blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
e0474dc4154f7f31e32d116f7155713af5ccd176
ae5eb1a38b4d22c82dfd67c86db73592094edc4b
/project44/src/main/java/org/gradle/test/performance/largejavamultiproject/project44/p224/Production4491.java
673300b81b6a34abaa6bc76ac3f2fcfacb168cba
[]
no_license
big-guy/largeJavaMultiProject
405cc7f55301e1fd87cee5878a165ec5d4a071aa
1cd6a3f9c59e9b13dffa35ad27d911114f253c33
refs/heads/main
2023-03-17T10:59:53.226128
2021-03-04T01:01:39
2021-03-04T01:01:39
344,307,977
0
0
null
null
null
null
UTF-8
Java
false
false
1,959
java
package org.gradle.test.performance.largejavamultiproject.project44.p224; public class Production4491 { private Production4488 property0; public Production4488 getProperty0() { return property0; } public void setProperty0(Production4488 value) { property0 = value; } private Production4489 property1; public Production4489 getProperty1() { return property1; } public void setProperty1(Production4489 value) { property1 = value; } private Production4490 property2; public Production4490 getProperty2() { return property2; } public void setProperty2(Production4490 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
[ "sterling.greene@gmail.com" ]
sterling.greene@gmail.com
f8b804699b0f813d313832c8fe957293d69ee5dc
8505c467459ad02f4b7e62193d3ab0587c09185c
/dev_oracle/src/com/procedure/Proc_emp_update2.java
1183111c29029069fa1d7d91c50e193a7b15f1ef
[]
no_license
mihyun510/resource-repo-java-kosmo
10501c2b2e62094d92c9ab34e932a8a2e8fd54e9
447ca4d5e0e8a798069e294694284be83bd68f58
refs/heads/master
2021-05-20T01:43:45.367788
2020-04-07T09:49:22
2020-04-07T09:49:22
252,133,318
0
0
null
null
null
null
UTF-8
Java
false
false
1,230
java
package com.procedure; import java.sql.CallableStatement; import java.sql.Connection; import javax.swing.JFrame; import javax.swing.JOptionPane; import com.util.DBConnectionMgr; public class Proc_emp_update2 extends JFrame{ DBConnectionMgr dbMgr = DBConnectionMgr.getInstance(); Connection con = null; //물리적으로 떨어져 있는 오라클 서버에 연결통로 만듬 CallableStatement cstmt = null; //저장 프로시저를 요청할 때 사용 public void empUpdate2() { String sdeptno = JOptionPane.showInputDialog("부서번호를 입력하세요."); int deptno = 0; int result = 0; //DB연동은 반드시 예외처리/ 네트워크 소켓 통신도 반드시 예외처리 try { con = dbMgr.getConnection(); con.setAutoCommit(false); //자동 커밋 해제 cstmt = con.prepareCall("{call Proc_emp_update2(?)}"); deptno = Integer.parseInt(sdeptno); cstmt.setInt(1, deptno); result = cstmt.executeUpdate(); System.out.println("result:"+result); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } finally { dbMgr.freeConnection(con, cstmt); } } public static void main(String[] args) { new Proc_emp_update2().empUpdate2(); } }
[ "k696366k@gmail.com" ]
k696366k@gmail.com
ec31374546bd597687b79f2d911d4755fcdee38d
d9eda5c6dfcd8a7db91d84389a387590dabc9032
/tiny-job-spring-cloud-adapter/src/main/java/com/tiny_job/TinyJobApplicaiton.java
155e089d655d3133400c44ca609913e5103530d9
[ "Apache-2.0" ]
permissive
yuhan0501/tiny-job
3f08a856df881e962c4918be619c9e4d8251888b
25553713b5b2ad95ffad5e4048ec068c146dde36
refs/heads/master
2023-08-11T07:38:05.614491
2021-09-22T02:00:04
2021-09-22T02:00:04
256,950,793
1
0
Apache-2.0
2021-09-22T02:00:05
2020-04-19T08:32:35
JavaScript
UTF-8
Java
false
false
390
java
package com.tiny_job; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: * @author: yuhan * @create: 2020-04-16 13:20 **/ @SpringBootApplication public class TinyJobApplicaiton { public static void main(String[] args) { SpringApplication.run(TinyJobApplicaiton.class, args); } }
[ "yu.han2@iwhalecloud.com" ]
yu.han2@iwhalecloud.com
e08202abc431e4a3503a685c2c41cbb53ea7c3c5
4bd019afa652a8481af5b206f69016dda8f69141
/src/main/java/org/serratec/projetoFinal/projetoFinalJava/exception/ExceptionController.java
724fdf81d7b40aa555f544eeb64190762519da54
[]
no_license
matheusmor/crud-java-residencia
4e0456ca7f3a08733357a931beb3470554c1babe
36b9b157b558b346476d62c8f845a9e0c4575ac3
refs/heads/master
2023-01-06T17:59:49.173005
2020-10-28T19:58:43
2020-10-28T19:58:43
308,126,685
0
0
null
null
null
null
UTF-8
Java
false
false
3,117
java
package org.serratec.projetoFinal.projetoFinalJava.exception; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ExceptionController { @ExceptionHandler(ProdutoNotFoundException.class) public ResponseEntity<String> trataProdutoNotFound(ProdutoNotFoundException exception) { String msg = String.format("O Produto com ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x mesg erro", msg).header("x codigo erro", "PRODUTO_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(ClienteNotFoundException.class) public ResponseEntity<String> trataClienteNotFound(ClienteNotFoundException exception) { String msg = String.format("O Cliente com ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x mesg erro", msg).header("x codigo erro", "CLIENTE_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(CategoriaNotFoundException.class) public ResponseEntity<String> trataCategoriaNotFound(CategoriaNotFoundException exception) { String msg = String.format("O Categoria com ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x mesg erro", msg).header("x codigo erro", "CATEGORIA_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(PedidoNotFoundException.class) public ResponseEntity<String> trataPedidoNotFound(PedidoNotFoundException exception) { String msg = String.format("O Pedido com ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x mesg erro", msg).header("x codigo erro", "PEDIDO_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(FuncionarioNotFoundException.class) public ResponseEntity<String> trataFuncionarioNotFound(FuncionarioNotFoundException exception) { String msg = String.format("O Funcionario com ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x mesg erro", msg).header("x codigo erro", "FUNCIONARIO_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(DataNotFoundException.class) public ResponseEntity<String> trataDataNotFound(DataNotFoundException exception) { String msg = String.format("O ID %d não foi encontrado", exception.getId()); return ResponseEntity.notFound().header("x msg erro", msg).header("x codigo erro", "DATA_NOT_FOUND") .header("x erro valor", exception.getId().toString()).build(); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<String> trataValidacao(MethodArgumentNotValidException e) { return ResponseEntity.badRequest().header("error-code", "REGISTRO_INVAIDO") .header("error-message", "NULL FOUND").build(); } }
[ "matieumor@hotmail.com" ]
matieumor@hotmail.com
643b4e3b7a1d334eacfb097dd21128127a1bcf8e
dc654f1fd11552b97fb062c0c7384017d9a96e66
/app/src/main/java/com/qlckh/chunlvv/adapter/RankAdapter.java
2460772a306a98174e02e8982db689b4f3ce5db1
[]
no_license
AndyAls/chulvv
efef7d09d8567d9dacfd091b8a86dc2aa0171f81
7b832883683195e8b25d684b984a902cc4a9dbcb
refs/heads/master
2021-06-20T01:33:21.591074
2019-10-11T02:52:02
2019-10-11T02:52:02
207,237,043
0
0
null
null
null
null
UTF-8
Java
false
false
2,289
java
package com.qlckh.chunlvv.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.qlckh.chunlvv.R; import com.qlckh.chunlvv.activity.NewsMoreActivity; import com.qlckh.chunlvv.activity.RankActivity; import com.qlckh.chunlvv.api.ApiService; import com.qlckh.chunlvv.dao.RankDao; import com.qlckh.chunlvv.http.utils.TimeUtil; import com.qlckh.chunlvv.utils.GlideUtil; import com.qlckh.chunlvv.view.richtextview.XRichText; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * @author Andy * @date 2018/9/7 17:28 * Desc: */ public class RankAdapter extends RecyclerView.Adapter<RankAdapter.VH> { private Context mContext; private List<RankDao.RankBean> mDatas; public RankAdapter(RankActivity newsMoreActivity, List<RankDao.RankBean> row) { this.mContext = newsMoreActivity; this.mDatas = row; } @NonNull @Override public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View inflate = LayoutInflater.from(mContext).inflate(R.layout.rank_list_item, parent, false); return new VH(inflate); } @Override public void onBindViewHolder(@NonNull VH holder, int position) { RankDao.RankBean rankBean = mDatas.get(position); GlideUtil.displayCircleImg(mContext, ApiService.IMG_URL + rankBean.getErimg(), holder.ivHead); holder.tvUser.setText(rankBean.getFullname()); holder.tvAddress.setText(rankBean.getWeight()); holder.tvJifen.setText(rankBean.getJifen()); } @Override public int getItemCount() { return mDatas.size(); } class VH extends RecyclerView.ViewHolder { @BindView(R.id.iv_head) ImageView ivHead; @BindView(R.id.tv_user) TextView tvUser; @BindView(R.id.tv_address) TextView tvAddress; @BindView(R.id.tv_jifen) TextView tvJifen; VH(View view) { super(view); ButterKnife.bind(this, view); } } }
[ "andy_als@163.com" ]
andy_als@163.com
3797b021f1c7c6b90210eff5e82b1856f909f636
7d096a926665217640f2ea8e8d003cd4de49041a
/src/main/java/com/ling/service/IDoctorService.java
ce98c1b6281a26a6cd395ac3cc5829c2fcfed7e6
[]
no_license
ZephyrusK/MER
5cc7af8265fb27c82f2894965a2a63b5ca2b321f
bb6fe73cca012ec93c402d92e7baa204e84a6d2c
refs/heads/master
2021-09-01T10:21:33.989259
2017-12-26T12:42:11
2017-12-26T12:42:11
115,010,337
1
0
null
null
null
null
UTF-8
Java
false
false
657
java
package com.ling.service; import java.util.List; import com.ling.entity.Doctor; import com.ling.entity.Patient; import com.baomidou.framework.service.ISuperService; /** * * Doctor 表数据服务层接口 * */ public interface IDoctorService extends ISuperService<Doctor> { public List<Doctor> selectAll(); public List<Doctor> select(int titleID,int departmentID); public List<Patient> choice(); public List<Patient> choice_select(String name); public List<Doctor> title(); public List<Doctor> department(); public List<Doctor> treatmentGroup(); public List<Doctor> medicalStaff(); public Doctor selectById(int doctorID); }
[ "849678350@qq.com" ]
849678350@qq.com
baa484c87c81421880c36bcb9ff5332e42586cab
4ad54a56ea1d1da711c1423c254b2b40b5619c9f
/citizen-intelligence-agency/src/test/java/com/hack23/cia/web/impl/ui/application/CitizenIntelligenceAgencyHealthCheckServletTest.java
74f098b3edbdef5bc86fd375af5fa45a511865ac
[ "Apache-2.0" ]
permissive
mushfiqur47/cia
1cc52cf2eb2bb96be7bd26822b5c3832fbc16905
3ddc99ffa278df6b479bf2df9cc59d7d6194cef8
refs/heads/master
2022-10-23T06:28:17.475685
2020-06-20T12:48:33
2020-06-20T12:48:33
273,761,227
1
0
Apache-2.0
2020-06-20T18:15:15
2020-06-20T18:15:14
null
UTF-8
Java
false
false
1,768
java
/* * Copyright 2010-2020 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.web.impl.ui.application; import java.io.IOException; import javax.servlet.ServletException; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import com.hack23.cia.testfoundation.AbstractUnitTest; /** * The Class CitizenIntelligenceAgencyHealthCheckServletTest. */ public class CitizenIntelligenceAgencyHealthCheckServletTest extends AbstractUnitTest { /** * Check health check test. * * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Test public void checkHealthCheckTest() throws ServletException, IOException { final CitizenIntelligenceAgencyHealthCheckServlet healthCheckServlet = new CitizenIntelligenceAgencyHealthCheckServlet(); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); healthCheckServlet.doGet(request, response); assertEquals("OK\n", response.getContentAsString()); } }
[ "pether.sorling@gmail.com" ]
pether.sorling@gmail.com
57cffce1a4e4faf5c877b2c307a841541c7cd996
a097daf47f5f5e7cf8bd7af80cac50622e6b05be
/src/main/java/tech/bts/javaexamples/classes/Stats.java
65587883af99070c62551cb93b4602ae5d8bcbbc
[]
no_license
vanessahigasi/java-examples
a9cefcedfbd1977842491e94e7adb42db06e97f8
a79e49bee49ea894e5dee2fd234c79b7dea07d6b
refs/heads/master
2020-03-30T22:55:56.217389
2018-10-10T10:33:02
2018-10-10T10:33:02
151,683,707
0
0
null
null
null
null
UTF-8
Java
false
false
933
java
package tech.bts.javaexamples.classes; public class Stats { //fields private double sum; private double count = 0; private double average; private double max = Double.MAX_VALUE; private double min = Double.MIN_VALUE; //constructor public Stats() { this.sum = getSum(); this.count = getCount(); this.average = getAverage(); } // method public void add(double x) { this.sum += x; this.count++; this.average = sum/count; if (x > max) { this.max = x; } if (x < min) { this.min = x; } } public double getSum() { return sum; } public double getCount() { return count; } public double getAverage() { return average; } public double getMax() { return max; } public double getMin() { return min; } }
[ "vanessahigasi@gmail.com" ]
vanessahigasi@gmail.com
c59131a3c69a30e9fcf93cef716049695de7b495
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Math/33/org/apache/commons/math3/stat/descriptive/SynchronizedSummaryStatistics_getSumsq_92.java
92fb93f9399738a74aaf84950d163003ebbfa99d
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
836
java
org apach common math3 stat descript implement link org apach common math3 stat descript summari statist summarystatist safe multithread environ multipl thread safe oper singl instanc caus runtim except due race condit effect implement make modif access method atom oper singl instanc thread comput statist instanc thread modifi instanc comput statist version synchron summari statist synchronizedsummarystatist summari statist summarystatist inherit doc inheritdoc overrid sumsq getsumsq sumsq getsumsq
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
7b2039dabdf5f559399c4db017f57f388d3986dc
cb8054d47e0d606f5d40dd5118b687ba8e49d4d4
/projekty/spring/10/Spring-lab1_05/src/main/java/altkom/model/Car.java
48fcc827c6fcf3a88669bd25c4ace680f8aae0c4
[]
no_license
Olakielbasa/it-love
75a17d1390208b0358afc70b7a70c8a168fa2809
86357761b79d30563228ae602f2a308b0dade541
refs/heads/master
2021-01-21T15:38:33.186337
2014-09-10T14:40:34
2014-09-10T14:40:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
921
java
/* * 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 altkom.model; import org.apache.commons.lang.builder.ToStringBuilder; public class Car { private String kolor; private String marka; public Car(String kolor, String marka) { this.kolor = kolor; this.marka = marka; } public Car(){ } @Override public String toString() { return ToStringBuilder.reflectionToString( this ); } public String getKolor() { return kolor; } public void setKolor(String kolor) { this.kolor = kolor; } public String getMarka() { return marka; } public void setMarka(String marka) { this.marka = marka; } }
[ "mgalgin@11a6dc57-d676-4505-b7dc-48ad575a0bd8" ]
mgalgin@11a6dc57-d676-4505-b7dc-48ad575a0bd8
36bde1dcd0bc5f720b4cfe50186320e58c546a78
6b997b11bdf9ea362ea57ff76547ccf9a7734f00
/Java01/src/j01_basic/OctHexEx.java
ce8c6dd575bc7838187aaf759ea1630dd81b7481
[]
no_license
ctho55/Java_Study
c9694df63a9c9f8d1780653794785f1536b8e54a
a497edb0973d6c29c24936371ed3ab5f7cb1348e
refs/heads/master
2023-08-24T22:57:00.661655
2021-09-28T11:44:52
2021-09-28T11:44:52
381,704,688
0
0
null
null
null
null
UTF-8
Java
false
false
861
java
package j01_basic; // ** 2진수, 8진수 , 16진수 표기 // => 2진수 : 0b 로시작 // => 8진수 : 0 // => 16진수: 0x public class OctHexEx { public static void main(String[] args) { int bin = 0b1111; // 1+2+4+8 int oct = 017 ; // 8+7 int hex = 0xf ; // 15 System.out.println("** binary => "+bin); System.out.println("** oct => "+oct); System.out.println("** hex => "+hex); // Integer to 2, 8, 16 진수로 출력하기 System.out.println("** binary => "+Integer.toBinaryString(bin)); System.out.println("** oct => "+Integer.toOctalString(oct)); System.out.println("** hex => "+Integer.toHexString(hex)); // Integer to String System.out.println("Integer to String => "+bin+oct+hex); // String to Integer String s="12345" ; System.out.println("String to Integer => "+ Integer.parseInt(s)*2); } //main } //class
[ "sk77424598@gmail.com" ]
sk77424598@gmail.com
1a5036236f5fe76efe02b30d5295bb027096caf8
97fd051782d21f254dfa739fd5b7d51194a7e536
/app/src/main/java/gachon/termproject/danggeun/Adapter/VerticalAdapter.java
01aa475fcea6e06805926127679386996cab60f1
[]
no_license
smpark0213/Dang-Geun-Bread
9740552231318fa895064c5cc79587a0ed0df2dc
2e8446394519119b784811ffab694edde9618613
refs/heads/master
2023-05-14T04:56:11.825885
2021-05-24T08:02:59
2021-05-24T08:02:59
367,282,933
0
0
null
null
null
null
UTF-8
Java
false
false
3,938
java
package gachon.termproject.danggeun.Adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import gachon.termproject.danggeun.Customer.BreadDTO; import gachon.termproject.danggeun.R; import gachon.termproject.danggeun.Util.Firebase; import gachon.termproject.danggeun.Util.Model.ReservatoinRequest; public class VerticalAdapter extends RecyclerView.Adapter<VerticalAdapter.VerticalViewHolder>{ private ArrayList<ReservatoinRequest> reservationRequest; private Context context; public VerticalAdapter(Context context, ArrayList<ReservatoinRequest> reservationRequest) { this.context = context; this.reservationRequest = reservationRequest; } public class VerticalViewHolder extends RecyclerView.ViewHolder{ protected RecyclerView recyclerView; protected TextView userName; protected TextView time; protected TextView Totalprice; public VerticalViewHolder(View view) { super(view); userName=view.findViewById(R.id.userName); time = view.findViewById(R.id.Time); Totalprice = view.findViewById(R.id.Totalprice); this.recyclerView = (RecyclerView)view.findViewById(R.id.recyclerViewVertical); } } @NonNull @Override public VerticalViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.reservationlist_manager2, null); return new VerticalAdapter.VerticalViewHolder(v); } @Override public void onBindViewHolder(@NonNull VerticalViewHolder verticalViewHolder, int position) { ReservatoinRequest currentReservation=reservationRequest.get(position); ArrayList<BreadDTO> breadList=currentReservation.getBreadArrayList(); FirebaseFirestore db = FirebaseFirestore.getInstance(); DocumentReference docRef = db.collection("users").document(currentReservation.getUserId()); docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { verticalViewHolder.userName.setText(documentSnapshot.get("nickname").toString()); } }); // verticalViewHolder.userName.setText(documentSnapshot.get("nickname")); SimpleDateFormat sdf = new SimpleDateFormat( "yy-MM-dd HH:mm:ss" , Locale.KOREA ); Date date = currentReservation.getTimestamp().toDate(); verticalViewHolder.time.setText(sdf.format(date)); int totalPrice=0; for(BreadDTO bread:breadList){ totalPrice=totalPrice+Integer.parseInt(bread.getTotalPrice()); } verticalViewHolder.Totalprice.setText("총 "+ Integer.toString(totalPrice)+"원"); HorizontalAdapter adapter = new HorizontalAdapter(breadList); verticalViewHolder.recyclerView.setHasFixedSize(true); verticalViewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(context , LinearLayoutManager.VERTICAL ,false)); verticalViewHolder.recyclerView.setAdapter(adapter); } @Override public int getItemCount() { return reservationRequest.size(); } }
[ "wooseokchoi0508@gmail.com" ]
wooseokchoi0508@gmail.com
fa8f5f4ed0d55ffd5a2bc0d67c64084ff1c06bfe
774ad58925938ca93ff6481f6fab22bcc711a76d
/src/Math/ConvertStrToInt.java
cd15f68251a05f773ba66ca1ca67758f6245203a
[]
no_license
leiwang8224/algorithm2
b26326bf6d851d5b3f30dd860e79bf02dc9a7ade
532fcd603cd1631af1468ecd5f9bffa353a25242
refs/heads/master
2022-06-12T05:55:56.635733
2022-06-03T23:10:41
2022-06-03T23:10:41
127,375,815
0
0
null
null
null
null
UTF-8
Java
false
false
453
java
package Math; /** * Created by leiwang on 4/6/18. */ public class ConvertStrToInt { public static void main(String args[]) { System.out.println(convertStrToInt("1")); } private static int convertStrToInt(String str) { int len = str.length(); int num = 0; for (int i = 0; i < len; i++) { num = num + (str.charAt(i) - '0') * (int)Math.pow(10,(len - i -1)); } return num; } }
[ "leiwang8224@gmail.com" ]
leiwang8224@gmail.com
ca22c742435d1c9597467e9c34343a2514b35220
6bc1a6b20ab386cdc3a8e113a3b04c324b6918b8
/T-carzy/HelloWei/src/com/eoe/pre/daytext04/Test12.java
dbed2eaebe847bb03bc44144ebfd8a0da28f0a14
[]
no_license
AmadaGS/eoeGeekCamp-201312
85d9785c0293ab5b7c522b28b54ce312cec72acd
aa02ca790528f0cad77e4d2878f107b2ab2db0b0
refs/heads/master
2021-01-21T20:19:20.928182
2014-02-20T13:25:29
2014-02-20T13:25:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package com.eoe.pre.daytext04; import java.util.Scanner; public class Test12 { public static void main(String[] args){ Scanner scanner=new Scanner(System.in); int score; do{ System.out.println("输入五分制的分数"); score=scanner.nextInt(); }while(score<0||score>5); System.out.println("OK"); } }
[ "596971957@qq.com" ]
596971957@qq.com
f7456be4826091790b4aec327442036eecc764b7
41df74f8295f3c90fcf12675c6b163955ec0c18a
/web/src/main/java/com/ozstrategy/webapp/spring/ConstrainedUrlPathHelper.java
319460d3bb7ca4ad397caf8fc742c99c74121976
[]
no_license
271387591/yjj
304368041037ace3bc22af7382304e28b9dc9fdc
d5e7979666f549130eb527e45e1cc6c91478dcfa
refs/heads/master
2021-01-13T00:37:20.885645
2015-12-07T09:16:22
2015-12-07T09:16:22
47,541,373
0
1
null
null
null
null
UTF-8
Java
false
false
4,131
java
package com.ozstrategy.webapp.spring; import org.springframework.util.StringUtils; import org.springframework.web.util.UrlPathHelper; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * Created by IntelliJ IDEA. User: Rojer Luo Date: Feb 25, 2010 Time: 11:55:12 AM To change this template use File | * Settings | File Templates. * * @author $author$ * @version $Revision$, $Date$ */ public class ConstrainedUrlPathHelper extends UrlPathHelper { //~ Static fields/initializers --------------------------------------------------------------------------------------- private static final String TRIGGER_404 = "NONEXISTING"; //~ Instance fields -------------------------------------------------------------------------------------------------- private Set<String> extensionToStrip = new LinkedHashSet<String>(); private Map<String, Set<String>> pathExtensionConstraint = new HashMap<String, Set<String>>(); private Set<String> refuseUrlEndsWith = new LinkedHashSet<String>(); private boolean stripConstraintedExtension = true; //~ Methods ---------------------------------------------------------------------------------------------------------- /** * This method looks at the pathExtensionConstraint (path, ext) and ensure the application only servers content for * those requests with matching path and extension. When path and extension match, this method will strip the * extension and return the result, otherwise a NONEXISTING view name is returned and triggers 404. * * <p>This class is injected into DefaultRequestToViewNameTranslator.</p> * * <p>Example: if pathExtensionConstraint = ("data", "js"), /data/someRes triggers 404 /data/someRes.abc triggers 404 * /data/someRes.js serves correct content.</p> * * @param request DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public String getLookupPathForRequest(HttpServletRequest request) { String result = super.getLookupPathForRequest(request); // perform validation String servletPath = super.getServletPath(request); String ext = StringUtils.getFilenameExtension(result); for (String end : refuseUrlEndsWith) { if (result.endsWith(end)) { return TRIGGER_404; } } Set<String> keys = pathExtensionConstraint.keySet(); for (String path : keys) { if (path.equals(servletPath)) { Set s = (Set) pathExtensionConstraint.get(path); if (!s.contains(ext)) { return TRIGGER_404; } else if (stripConstraintedExtension) { result = StringUtils.stripFilenameExtension(result); } } } // Only strip one extension - we will not strip extension recursively for (String e : extensionToStrip) { if (e.equals(ext)) { result = StringUtils.stripFilenameExtension(result); break; } } return result; } // end method getLookupPathForRequest //~ ------------------------------------------------------------------------------------------------------------------ /** * DOCUMENT ME! * * @param extensionToStrip DOCUMENT ME! */ public void setExtensionToStrip(Set<String> extensionToStrip) { this.extensionToStrip = extensionToStrip; } //~ ------------------------------------------------------------------------------------------------------------------ /** * DOCUMENT ME! * * @param pathExtensionConstraint DOCUMENT ME! */ public void setPathExtensionConstraint(Map<String, Set<String>> pathExtensionConstraint) { this.pathExtensionConstraint = pathExtensionConstraint; } //~ ------------------------------------------------------------------------------------------------------------------ /** * DOCUMENT ME! * * @param refuseUrlEndsWith DOCUMENT ME! */ public void setRefuseUrlEndsWith(Set<String> refuseUrlEndsWith) { this.refuseUrlEndsWith = refuseUrlEndsWith; } } // end class ConstrainedUrlPathHelper
[ "hao.li@ozstragety.com" ]
hao.li@ozstragety.com
7ccaea89e85824728018a343bef3d29a675aa28f
45f05c515e311d16eb48094b6d6617d6b6987397
/lucihunt-lucene4.10/src/test/java/org/apache/lucene/search/TestSimilarity.java
7c7b89b499ee22f1717ed33315019f1875971ec0
[ "Apache-2.0" ]
permissive
lemonJun/LuciHunt
5328dd270e891e302bf985a1a2517dcaa95def9d
08c71f80be580e5ebcbb519eb2aff1f3cfee55a8
refs/heads/master
2021-01-18T19:32:47.065466
2017-05-03T09:52:13
2017-05-03T09:52:13
86,899,911
1
0
null
null
null
null
UTF-8
Java
false
false
6,458
java
package org.apache.lucene.search; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ import org.apache.lucene.document.Field; import org.apache.lucene.util.LuceneTestCase; import java.io.IOException; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.FieldInvertState; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.store.Directory; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; /** Similarity unit test. * * */ public class TestSimilarity extends LuceneTestCase { public static class SimpleSimilarity extends DefaultSimilarity { @Override public float queryNorm(float sumOfSquaredWeights) { return 1.0f; } @Override public float coord(int overlap, int maxOverlap) { return 1.0f; } @Override public float lengthNorm(FieldInvertState state) { return state.getBoost(); } @Override public float tf(float freq) { return freq; } @Override public float sloppyFreq(int distance) { return 2.0f; } @Override public float idf(long docFreq, long numDocs) { return 1.0f; } @Override public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics[] stats) { return new Explanation(1.0f, "Inexplicable"); } } public void testSimilarity() throws Exception { Directory store = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), store, newIndexWriterConfig(new MockAnalyzer(random())).setSimilarity(new SimpleSimilarity())); Document d1 = new Document(); d1.add(newTextField("field", "a c", Field.Store.YES)); Document d2 = new Document(); d2.add(newTextField("field", "a b c", Field.Store.YES)); writer.addDocument(d1); writer.addDocument(d2); IndexReader reader = writer.getReader(); writer.close(); IndexSearcher searcher = newSearcher(reader); searcher.setSimilarity(new SimpleSimilarity()); Term a = new Term("field", "a"); Term b = new Term("field", "b"); Term c = new Term("field", "c"); searcher.search(new TermQuery(b), new Collector() { private Scorer scorer; @Override public void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { assertEquals(1.0f, scorer.score(), 0); } @Override public void setNextReader(AtomicReaderContext context) { } @Override public boolean acceptsDocsOutOfOrder() { return true; } }); BooleanQuery bq = new BooleanQuery(); bq.add(new TermQuery(a), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(b), BooleanClause.Occur.SHOULD); //System.out.println(bq.toString("field")); searcher.search(bq, new Collector() { private int base = 0; private Scorer scorer; @Override public void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Doc=" + doc + " score=" + score); assertEquals((float) doc + base + 1, scorer.score(), 0); } @Override public void setNextReader(AtomicReaderContext context) { base = context.docBase; } @Override public boolean acceptsDocsOutOfOrder() { return true; } }); PhraseQuery pq = new PhraseQuery(); pq.add(a); pq.add(c); //System.out.println(pq.toString("field")); searcher.search(pq, new Collector() { private Scorer scorer; @Override public void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Doc=" + doc + " score=" + score); assertEquals(1.0f, scorer.score(), 0); } @Override public void setNextReader(AtomicReaderContext context) { } @Override public boolean acceptsDocsOutOfOrder() { return true; } }); pq.setSlop(2); //System.out.println(pq.toString("field")); searcher.search(pq, new Collector() { private Scorer scorer; @Override public void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Doc=" + doc + " score=" + score); assertEquals(2.0f, scorer.score(), 0); } @Override public void setNextReader(AtomicReaderContext context) { } @Override public boolean acceptsDocsOutOfOrder() { return true; } }); reader.close(); store.close(); } }
[ "506526593@qq.com" ]
506526593@qq.com
5507626f78a5c37ebee3f9f42bdf0b90870e90a5
167a5c75426cb700e122a2743cbed6df88a4a9cf
/app/src/androidTest/java/com/example/yasmine/justjava/ExampleInstrumentedTest.java
5dfaf80aa047745dcc4d2537ed799078fae9d73f
[]
no_license
yasmine96/JustJava
8442307b8ef2b2e73d5797c7ab4fca9011733419
2d7512117b963cc3a14c445d366b4186e282f3a6
refs/heads/master
2020-04-09T20:26:50.073637
2019-04-25T16:08:34
2019-04-25T16:08:34
160,573,647
0
1
null
2019-04-25T15:41:04
2018-12-05T20:21:15
Java
UTF-8
Java
false
false
740
java
package com.example.yasmine.justjava; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.yasmine.justjava", appContext.getPackageName()); } }
[ "yasminemohamedelsayed@gmail.com" ]
yasminemohamedelsayed@gmail.com
857e43c2f3bdf7d1d6d349ef67ebad5368cd82d2
5234550b18e4c50310753e440b8cab16b523db48
/app/src/main/java/com/devsaidur/saidur/playnearn/ui/wallet/WalletFragment.java
1d3ac96a8a16869d154a7213d7b1ca1c0bfa7fdf
[]
no_license
SaidurRahmanfuad/playnearn
146a6b66afeffcfea8ac14fd08b71803e9767ac7
97bd3ba11eb26f045fed18e5bbf134e7e4fc06ec
refs/heads/main
2023-07-31T18:33:48.286909
2021-09-13T07:40:19
2021-09-13T07:40:19
405,877,553
0
0
null
null
null
null
UTF-8
Java
false
false
14,636
java
package com.devsaidur.saidur.playnearn.ui.wallet; import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.Toolbar; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.Navigation; import com.devsaidur.saidur.playnearn.Const; import com.devsaidur.saidur.playnearn.database.Spref; import com.devsaidur.saidur.playnearn.models.User; import com.devsaidur.saidur.playnearn.models.Withdraw; import com.devsaidur.saidur.playnearn.ui.logsing.Signup; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.material.textfield.TextInputEditText; import com.devsaidur.saidur.playnearn.R; import com.devsaidur.saidur.playnearn.databinding.FragmentWalletBinding; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; public class WalletFragment extends Fragment { FirebaseAuth mAuth; FirebaseDatabase fdb; DatabaseReference fdr, fdr2; Spref spref; private HashMap<String, String> getUserData; String savedMobile, saveuid; private WalletViewModel walletViewModel; private FragmentWalletBinding FWBind; Dialog popup_diposit, popup_withdraw; //diposit AutoCompleteTextView diposit_amount, pay_type; TextInputEditText diposit_number, ref_code; RelativeLayout btn_diposit; //withdraw AutoCompleteTextView withdraw_amount, withdraw_type; TextInputEditText withdraw_number, sec_code; RelativeLayout btn_withdraw; List<String> paytype = new ArrayList<>(); List<String> payamount = new ArrayList<>(); ArrayAdapter<String> paytypeAdapter; ArrayAdapter<String> payamountAdapter; String typeData, dipositData; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { walletViewModel = new ViewModelProvider(this).get(WalletViewModel.class); View root = inflater.inflate(R.layout.fragment_wallet, container, false); FWBind = FragmentWalletBinding.inflate(inflater, container, false); View v = FWBind.getRoot(); mAuth = FirebaseAuth.getInstance(); fdb = FirebaseDatabase.getInstance(); fdr = fdb.getReference(Const.adminDash); fdr2 = fdb.getReference(Const.userDash); spref = new Spref(getActivity()); getUserData = spref.getUserInfo(); savedMobile = getUserData.get(spref.UserMobile); /* walletViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { } });*/ /* FWBind.mbl.setAlpha(0.6f); FWBind.tops.setBackgroundColor(0);*/ rechargeData(); iniPopup(); iniWitdraw(); FWBind.cvRecharge.setOnClickListener(v1 -> { popup_diposit.show(); }); FWBind.cvWithdraw.setOnClickListener(v1 -> { popup_withdraw.show(); }); WithdrawTopData(); return v; } private void WithdrawTopData() { Toast.makeText(getActivity(), "Function call", Toast.LENGTH_SHORT).show(); //Withdraw req data fdr.child(Const.withdrawrequest).child(savedMobile).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { // Exist! Do whatever. String withdrawAmount = snapshot.child("withdrawAmount").getValue().toString(); String withdrawDate = snapshot.child("withdrawDate").getValue().toString(); String withdrawStatus = snapshot.child("withdrawStatus").getValue().toString(); FWBind.llwithdrawstatus.setVisibility(View.VISIBLE); FWBind.withdrawReqtk.setText(withdrawAmount); // FWBind.withdrawdate.setText(withdrawDate); if (withdrawStatus.equals("0")) { FWBind.withdrawstatus.setText("Pending..."); FWBind.withdrawdate.setText(withdrawDate); } else { FWBind.withdrawstatus.setText("Approved"); FWBind.withdrawdate.setText(withdrawDate); } } else { // Don't exist! Do something. FWBind.withdrawReqtk.setText("0"); FWBind.llwithdrawstatus.setVisibility(View.GONE); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); fdr2.child("Users").child(savedMobile).child("account").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot != null) { // Exist! Do whatever. String currentBal = snapshot.child("current_bal").getValue().toString(); FWBind.currentbal.setText(currentBal); } else { // Don't exist! Do something. FWBind.currentbal.setText("0"); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void diposit_ReqToDB() { //write database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!"); HashMap<Object, String> dipositreq = new HashMap<>(); dipositreq.put("user_name", "abc"); dipositreq.put("user_phon", "abc"); dipositreq.put("user_id", "abc"); dipositreq.put("diposit_amount", dipositData); dipositreq.put("diposit_type", typeData); dipositreq.put("diposit_number", "abc"); dipositreq.put("diposit_status", "req"); // Read from the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String value = dataSnapshot.getValue(String.class); Log.d("TAG", "Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("TAG", "Failed to read value.", error.toException()); } }); } private void rechargeData() { paytype.add("BKash"); paytype.add("Nagad"); paytype.add("Rocket"); paytypeAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, paytype); payamount.add("50 Tk"); payamount.add("100 Tk"); payamount.add("200 Tk"); payamount.add("500 Tk"); payamountAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, payamount); } private void iniPopup() { popup_diposit = new Dialog(getContext()); popup_diposit.setContentView(R.layout.popup_recharge); //popup_diposit.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // popup_diposit.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); popup_diposit.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT); popup_diposit.getWindow().getAttributes().gravity = Gravity.CENTER; // ini popup widgets diposit_amount = popup_diposit.findViewById(R.id.actv_dipositamount); pay_type = popup_diposit.findViewById(R.id.actv_paytype); diposit_number = popup_diposit.findViewById(R.id.actv_nmbr); ref_code = popup_diposit.findViewById(R.id.actv_refcode); btn_diposit = popup_diposit.findViewById(R.id.btn_diposit); pay_type.setAdapter(paytypeAdapter); pay_type.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { typeData = parent.getItemAtPosition(position).toString(); } }); diposit_amount.setAdapter(payamountAdapter); diposit_amount.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dipositData = parent.getItemAtPosition(position).toString(); } }); btn_diposit.setOnClickListener(v -> { popup_diposit.dismiss(); diposit_ReqToDB(); final NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment); navController.navigate(R.id.navigation_ldokngs); }); } private void iniWitdraw() { popup_withdraw = new Dialog(getContext()); popup_withdraw.setContentView(R.layout.popup_withdraw); //popup_diposit.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // popup_diposit.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); popup_withdraw.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT); popup_withdraw.getWindow().getAttributes().gravity = Gravity.CENTER; // ini popup widgets withdraw_amount = popup_withdraw.findViewById(R.id.actv_wamount); withdraw_type = popup_withdraw.findViewById(R.id.actv_wtype); withdraw_number = popup_withdraw.findViewById(R.id.actv_wnmbr); sec_code = popup_withdraw.findViewById(R.id.actv_seccode); btn_withdraw = popup_withdraw.findViewById(R.id.btn_withdraw); // rechargeData(); withdraw_type.setAdapter(paytypeAdapter); withdraw_type.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { typeData = parent.getItemAtPosition(position).toString(); } }); withdraw_amount.setAdapter(payamountAdapter); withdraw_amount.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dipositData = parent.getItemAtPosition(position).toString(); } }); withdraw_ReqToDB(); } private void withdraw_ReqToDB(/*Withdraw withdrawReq*/) { btn_withdraw.setOnClickListener(v -> { fdr2.child("Users").child(savedMobile).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot != null) { User instant_data = snapshot.getValue(User.class); String today = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()); Withdraw withdrawReq = new Withdraw(savedMobile, sec_code.getText().toString(), instant_data.getId(), instant_data.getUserName(), instant_data.getUserEmail(), withdraw_amount.getText().toString(), typeData, withdraw_number.getText().toString(), "0", today); popup_withdraw.dismiss(); FirebaseUser firebaseUser = mAuth.getCurrentUser(); if (firebaseUser != null) { fdr.child(Const.withdrawrequest).child(savedMobile).setValue(withdrawReq).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(), "With draw requestsend", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } Toast.makeText(getActivity(), "seccode "+sec_code.getText().toString(), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), "withdraw_amount "+withdraw_amount.getText().toString(), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), "typeData "+typeData, Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), "withdraw_number "+withdraw_number.getText().toString(), Toast.LENGTH_SHORT).show(); // withdraw_ReqToDB(withdrawReq); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); }); } @Override public void onStart() { super.onStart(); } }
[ "devsaidur@gmail.com" ]
devsaidur@gmail.com
72d43a8c219577b34e16d4b446a1044ff6116932
170d452b4651ccd610efe3eedeaad0f9d112a9a8
/src/com/sxh/history/factory/Dog.java
351f60fabdc99d169e5b5f3a63d45af2d466ec93
[]
no_license
JokerByrant/designPattern
76eaa04bc5f516f37c550e93326dc7a329e54c5e
9421181ce1bc67ebc12102e67317893a3a9de267
refs/heads/master
2020-07-30T17:02:12.322130
2020-06-17T08:49:01
2020-06-17T08:49:01
210,296,799
0
0
null
null
null
null
UTF-8
Java
false
false
220
java
package com.sxh.history.factory; /** * @author 一池春水倾半城 * @date 2019/9/23 */ public class Dog implements Animal { @Override public void show() { System.out.println("i'm a dog!"); } }
[ "sxhjoker@163.com" ]
sxhjoker@163.com
f9cb5d8cca85ae2f3c558ddb85b5aa6b2c9e95f0
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/java-inflector/generated/src/gen/java/org/openapitools/model/ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo.java
23b6c4b8bdfd9e2fbc77a2c602bd7044cfaa0273
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
Java
false
false
4,126
java
package org.openapitools.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckProperties; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaInflectorServerCodegen", date = "2019-08-05T00:53:46.291Z[GMT]") public class ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo { @JsonProperty("pid") private String pid = null; @JsonProperty("title") private String title = null; @JsonProperty("description") private String description = null; @JsonProperty("properties") private ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckProperties properties = null; /** **/ public ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo pid(String pid) { this.pid = pid; return this; } @ApiModelProperty(value = "") @JsonProperty("pid") public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } /** **/ public ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo title(String title) { this.title = title; return this; } @ApiModelProperty(value = "") @JsonProperty("title") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** **/ public ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo description(String description) { this.description = description; return this; } @ApiModelProperty(value = "") @JsonProperty("description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** **/ public ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo properties(ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckProperties properties) { this.properties = properties; return this; } @ApiModelProperty(value = "") @JsonProperty("properties") public ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckProperties getProperties() { return properties; } public void setProperties(ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckProperties properties) { this.properties = properties; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo comAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo = (ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo) o; return Objects.equals(pid, comAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo.pid) && Objects.equals(title, comAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo.title) && Objects.equals(description, comAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo.description) && Objects.equals(properties, comAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo.properties); } @Override public int hashCode() { return Objects.hash(pid, title, description, properties); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ComAdobeGraniteBundlesHcImplWebDavBundleHealthCheckInfo {\n"); sb.append(" pid: ").append(toIndentedString(pid)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
[ "cliffano@gmail.com" ]
cliffano@gmail.com
6e31cd64fc7cc514a08f2b1a2099be87d4e7d91d
fb4a8e9bbfb81ec18bdcf7dfacfd8ebb307995fb
/src/main/java/filius/gui/anwendungssicht/GUIInstallationsDialog.java
a2a9824befbcb73e441cfe23ff855c9c0e428fc8
[]
no_license
obutterwegge/filius_with_wannacry_simulation
5e9b7f8229794e43a40bd9242fe6f5dca5b390f9
702a02a5abace77f29aee16a34de9c10a14e676d
refs/heads/master
2023-04-14T14:48:02.616554
2020-12-31T11:32:56
2020-12-31T11:32:56
276,933,363
0
0
null
2021-04-26T20:26:47
2020-07-03T15:37:07
Java
UTF-8
Java
false
false
10,399
java
/* ** This file is part of Filius, a network construction and simulation software. ** ** Originally created at the University of Siegen, Institute "Didactics of ** Informatics and E-Learning" by a students' project group: ** members (2006-2007): ** André Asschoff, Johannes Bade, Carsten Dittich, Thomas Gerding, ** Nadja Haßler, Ernst Johannes Klebert, Michell Weyer ** supervisors: ** Stefan Freischlad (maintainer until 2009), Peer Stechert ** Project is maintained since 2010 by Christian Eibl <filius@c.fameibl.de> ** and Stefan Freischlad ** Filius is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 2 of the License, or ** (at your option) version 3. ** ** Filius is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied ** warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ** PURPOSE. See the GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Filius. If not, see <http://www.gnu.org/licenses/>. */ package filius.gui.anwendungssicht; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import filius.Main; import filius.rahmenprogramm.I18n; import filius.rahmenprogramm.Information; import filius.software.Anwendung; import filius.software.system.InternetKnotenBetriebssystem; public class GUIInstallationsDialog extends JInternalFrame implements I18n { private static final long serialVersionUID = 1L; private Container c; private JList softwareInstalliert; private JList softwareVerfuegbar; private JButton removeButton, addButton, confirmButton; private JLabel titleInstalled, titleAvailable; private DefaultListModel lmVerfuegbar; private DefaultListModel lmInstalliert; private GUIDesktopPanel dp; private List<Map<String, String>> programme = null; public GUIInstallationsDialog(GUIDesktopPanel dp) { super(); c = this.getContentPane(); this.dp = dp; try { programme = Information.getInformation().ladeProgrammListe(); } catch (IOException e) { e.printStackTrace(Main.debug); } initListen(); initButtons(); /* Title above lists */ titleInstalled = new JLabel(messages.getString("installationsdialog_msg3")); titleAvailable = new JLabel(messages.getString("installationsdialog_msg4")); /* Komponenten dem Panel hinzufügen */ Box gesamtBox = Box.createVerticalBox(); Box wrapperInstBox = Box.createVerticalBox(); Box wrapperAvailBox = Box.createVerticalBox(); wrapperInstBox.add(titleInstalled); wrapperInstBox.add(Box.createVerticalStrut(10)); Box listenBox = Box.createHorizontalBox(); listenBox.add(Box.createHorizontalStrut(10)); JScrollPane scrollAnwendungInstallieren = new JScrollPane(softwareInstalliert); scrollAnwendungInstallieren.setPreferredSize(new Dimension(170, 200)); wrapperInstBox.add(scrollAnwendungInstallieren); listenBox.add(wrapperInstBox); listenBox.add(Box.createHorizontalGlue()); Box topButtonBox = Box.createVerticalBox(); topButtonBox.add(addButton); topButtonBox.add(Box.createVerticalStrut(10)); topButtonBox.add(removeButton); listenBox.add(topButtonBox); wrapperAvailBox.add(titleAvailable); wrapperAvailBox.add(Box.createVerticalStrut(10)); JScrollPane scrollAnwendungVerfuegbar = new JScrollPane(softwareVerfuegbar); scrollAnwendungVerfuegbar.setPreferredSize(new Dimension(170, 200)); wrapperAvailBox.add(scrollAnwendungVerfuegbar); listenBox.add(wrapperAvailBox); listenBox.add(Box.createHorizontalStrut(10)); gesamtBox.add(Box.createVerticalStrut(10)); gesamtBox.add(listenBox); gesamtBox.add(Box.createVerticalStrut(10)); Box bottomButtonBox = Box.createVerticalBox(); bottomButtonBox.add(confirmButton); confirmButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); gesamtBox.add(bottomButtonBox); gesamtBox.add(Box.createVerticalStrut(10)); c.add(gesamtBox, BorderLayout.CENTER); this.setClosable(true); this.setMaximizable(true); this.setResizable(true); this.setBounds(0, 40, 480, 360); this.setTitle(messages.getString("installationsdialog_msg1")); this.setVisible(true); this.setAnwendungsIcon("gfx/desktop/icon_softwareinstallation.png"); } private GUIDesktopPanel getDesktopPanel() { return dp; } private void hinzufuegen() { Vector<String> vLoeschen = new Vector<String>(); int[] selektiertIndices = softwareVerfuegbar.getSelectedIndices(); for (int i : selektiertIndices) { lmInstalliert.addElement(lmVerfuegbar.get(i)); vLoeschen.add((String)lmVerfuegbar.get(i)); } // umständlich, aber wegen der Möglichkeit von Mehrfachselektion lassen // sich nicht einzelne Anwendungen sofort entfernen for (Enumeration<String> e = vLoeschen.elements(); e.hasMoreElements();) { String oZuLoeschen = e.nextElement(); lmVerfuegbar.removeElement(oZuLoeschen); } } private void entfernen() { int[] selektiertIndices = softwareInstalliert.getSelectedIndices(); Vector<String> hinzu = new Vector<String>(); for (int i : selektiertIndices) { lmVerfuegbar.addElement(lmInstalliert.getElementAt(i)); hinzu.add((String)lmInstalliert.getElementAt(i)); } // umständlich, aber wegen der Möglichkeit von Mehrfachselektion lassen // sich nicht einzelne Anwendungen sofort entfernen for (Enumeration<String> e = hinzu.elements(); e.hasMoreElements();) { String hinzuObjekt = e.nextElement(); lmInstalliert.removeElement(hinzuObjekt); } } private void aenderungenSpeichern() { InternetKnotenBetriebssystem bs = getDesktopPanel().getBetriebssystem(); Anwendung anwendung; for (Map<String, String> appInfo : programme) { for (int i = 0; i < lmInstalliert.getSize(); i++) { if (lmInstalliert.getElementAt(i).equals(appInfo.get("Anwendung")) && bs.holeSoftware(appInfo.get("Klasse").toString()) == null) { bs.installiereSoftware(appInfo.get("Klasse").toString()); anwendung = bs.holeSoftware(appInfo.get("Klasse").toString()); anwendung.starten(); } } for (int i = 0; i < lmVerfuegbar.getSize(); i++) { if (lmVerfuegbar.getElementAt(i).equals(appInfo.get("Anwendung"))) { anwendung = bs.holeSoftware(appInfo.get("Klasse").toString()); if (anwendung != null) { anwendung.beenden(); bs.entferneSoftware(appInfo.get("Klasse").toString()); } } } } dp.updateAnwendungen(); } private void initButtons() { /* ActionListener */ ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (arg0.getActionCommand().equals(addButton.getActionCommand())) { hinzufuegen(); } else if (arg0.getActionCommand().equals(removeButton.getActionCommand())) { entfernen(); } else if (arg0.getActionCommand() == confirmButton.getText()) { aenderungenSpeichern(); setVisible(false); } } }; /* Buttons */ removeButton = new JButton(new ImageIcon(getClass().getResource("/gfx/allgemein/pfeil_rechts.png"))); removeButton.setMargin(new Insets(2, 2, 2, 2)); removeButton.setActionCommand("remove"); removeButton.addActionListener(al); addButton = new JButton(new ImageIcon(getClass().getResource("/gfx/allgemein/pfeil_links.png"))); addButton.setMargin(new Insets(2, 2, 2, 2)); addButton.setActionCommand("add"); addButton.addActionListener(al); confirmButton = new JButton(messages.getString("installationsdialog_msg2")); confirmButton.addActionListener(al); } private void initListen() { Anwendung[] anwendungen; String awKlasse; InternetKnotenBetriebssystem bs; lmInstalliert = new DefaultListModel(); lmVerfuegbar = new DefaultListModel(); bs = dp.getBetriebssystem(); /* Installierte Anwendung auslesen */ anwendungen = bs.holeArrayInstallierteSoftware(); for (int i = 0; i < anwendungen.length; i++) { if (anwendungen[i] != null) { lmInstalliert.addElement(anwendungen[i].holeAnwendungsName()); } } if (programme != null) { for (Map<String, String> programmInfo : programme) { awKlasse = (String) programmInfo.get("Klasse"); if (dp.getBetriebssystem().holeSoftware(awKlasse) == null) { lmVerfuegbar.addElement(programmInfo.get("Anwendung")); } } } /* Listen */ softwareInstalliert = new JList(); softwareInstalliert.setModel(lmInstalliert); softwareInstalliert.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { GUIInstallationsDialog.this.entfernen(); } } }); softwareVerfuegbar = new JList(); softwareVerfuegbar.setModel(lmVerfuegbar); softwareVerfuegbar.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { GUIInstallationsDialog.this.hinzufuegen(); } } }); } public void setAnwendungsIcon(String datei) { ImageIcon image = new ImageIcon(getClass().getResource("/" + datei)); image.setImage(image.getImage().getScaledInstance(16, 16, Image.SCALE_AREA_AVERAGING)); this.setFrameIcon(image); } }
[ "auralprovide@gmail.com" ]
auralprovide@gmail.com
0815e302a25ba18c42eec7ae6ff93a65c65d7e65
ad4d42fc974fa6cb92fe05b24e52ba13d5956f44
/src/main/java/com/tiozao/config/SecurityConfig.java
23580edd7dc367d4449ed3ceeb3e549dba8b2c4d
[ "Apache-2.0" ]
permissive
marco-aurelioo/MindStruture
4b031fe540b711c1e134a1050c55f1d4892b54cc
7f48a20dcedb1b3141ca08e960048c5549b53ca8
refs/heads/master
2023-08-02T12:08:08.557300
2021-09-19T22:06:54
2021-09-19T22:06:54
197,982,160
0
0
null
null
null
null
UTF-8
Java
false
false
2,533
java
package com.tiozao.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().disable(); http .csrf() .disable() .authorizeRequests() .antMatchers( "/cadastro**", "/static/**", "/css/**", "/js/**", "/img/**", "/h2/*", "/vendor/**", "/webjars/**", "/admin/**", "/favicon.ico", "/resources/**", "/auth/**", "/signin/**", "/signup/**", "/disconnect/facebook" ) .permitAll() .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/usuario",true) .permitAll() .and() .logout().permitAll(); } @Bean public AuthenticationManager customAuthenticationManager() throws Exception { return authenticationManager(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } }
[ "marco_aurelioo@yahoo.com.br" ]
marco_aurelioo@yahoo.com.br
15b7a08075fcb04ad62b2d6878b7de312fa1076f
ef8cb084e87de0bc2abdbb822f60644bafa4ca19
/pay-startup/src/test/java/com/github/tiger/pay/test/concurrent/VolatileTest.java
f5d84fdf735d5e322d58ac37211bbf22fe22b09e
[]
no_license
lisycn/pay-1
b514f8fc552d64956d4e99d47e9f2a360f6cef70
011e4a76ba0059315abf764d6ffb10b60c6b952c
refs/heads/master
2020-04-04T22:44:50.564634
2017-12-27T02:17:26
2017-12-27T02:17:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
869
java
package com.github.tiger.pay.test.concurrent; /** * volatile对变量的操作非原子性,不能保证一致性 */ public class VolatileTest { private volatile int race = 0; public void increase() { race++; } public static final int THREAD_COUNT = 10; public static void main(String[] args) { final VolatileTest test = new VolatileTest(); for (int i = 0; i < THREAD_COUNT; i++) { new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 1000; j++) { test.increase(); } } }).start(); } // 等待所有累加线程都结束 while (Thread.activeCount() > 1) Thread.yield(); System.out.println(test.race); } }
[ "jason.liuhongming@gmail.com" ]
jason.liuhongming@gmail.com
56fe0597dcd9f10c0ed26d05d378d212e8309088
b5956cba852ce96a01110fa253baed17992a70d4
/fbspackage/new_package/javafbs/friendpack/T_FRIEND_LIST_RS.java
d4ac2e8982842a25219733f7b57e208d25c48bed
[]
no_license
phoenix-team1/communicate
7fa4d3d9f80b15b0c3d2d3716e3c1d254d96ae1d
6a2bedec1c22dc5e0974622d18f2f10284edd93b
refs/heads/master
2021-05-11T17:35:38.980652
2018-02-07T19:49:37
2018-02-07T19:49:37
117,801,069
0
0
null
null
null
null
UTF-8
Java
false
false
2,743
java
// automatically generated by the FlatBuffers compiler, do not modify package friendpack; import java.nio.*; import java.lang.*; import java.util.*; import com.google.flatbuffers.*; @SuppressWarnings("unused") public final class T_FRIEND_LIST_RS extends Table { public static T_FRIEND_LIST_RS getRootAsT_FRIEND_LIST_RS(ByteBuffer _bb) { return getRootAsT_FRIEND_LIST_RS(_bb, new T_FRIEND_LIST_RS()); } public static T_FRIEND_LIST_RS getRootAsT_FRIEND_LIST_RS(ByteBuffer _bb, T_FRIEND_LIST_RS obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; } public T_FRIEND_LIST_RS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public commonpack.S_RS_HEAD sRsHead() { return sRsHead(new commonpack.S_RS_HEAD()); } public commonpack.S_RS_HEAD sRsHead(commonpack.S_RS_HEAD obj) { int o = __offset(4); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; } public friendpack.T_FREIND_INFO friendList(int j) { return friendList(new friendpack.T_FREIND_INFO(), j); } public friendpack.T_FREIND_INFO friendList(friendpack.T_FREIND_INFO obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } public int friendListLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } public long token() { int o = __offset(8); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } public int msgSource() { int o = __offset(10); return o != 0 ? bb.getInt(o + bb_pos) : 0; } public static void startT_FRIEND_LIST_RS(FlatBufferBuilder builder) { builder.startObject(4); } public static void addSRsHead(FlatBufferBuilder builder, int sRsHeadOffset) { builder.addStruct(0, sRsHeadOffset, 0); } public static void addFriendList(FlatBufferBuilder builder, int friendListOffset) { builder.addOffset(1, friendListOffset, 0); } public static int createFriendListVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } public static void startFriendListVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static void addToken(FlatBufferBuilder builder, long token) { builder.addLong(2, token, 0L); } public static void addMsgSource(FlatBufferBuilder builder, int msgSource) { builder.addInt(3, msgSource, 0); } public static int endT_FRIEND_LIST_RS(FlatBufferBuilder builder) { int o = builder.endObject(); return o; } public static void finishT_FRIEND_LIST_RSBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } }
[ "shiyunjie@qbao.com" ]
shiyunjie@qbao.com
a1d639882a641be5b4688fac8f2513a9c36f5542
f6e5c2a87c6ed3d9b2684f9546babc694b0c36ff
/src/main/java/com/volvo/webapp/controllers/DepartmentController.java
05f4f187bcd6b1bd40e4f53fbb87d41a4c248f55
[]
no_license
Archana516/volvotest
8d19e38b4c0ff064e637840ff0916306c18bdbb9
174a393374592a089c5c6367841f500acce40a02
refs/heads/master
2021-04-06T20:51:53.721337
2018-03-16T04:06:49
2018-03-16T04:06:49
125,416,018
0
0
null
null
null
null
UTF-8
Java
false
false
993
java
/** * */ package com.volvo.webapp.controllers; /** * */ import org.ocpsoft.rewrite.annotation.Join; import org.ocpsoft.rewrite.el.ELBeanName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.volvo.webapp.entites.Department; import com.volvo.webapp.repository.DepartmentRepository; @Scope(value = "session") @Component(value = "departmentController") @ELBeanName(value = "departmentController") @Join(path = "/department", to = "/department-form.jsf") public class DepartmentController { @Autowired private DepartmentRepository departmentRepository; private Department department = new Department(); public String save() { departmentRepository.save(department); return "/department-list.xhtml?faces-redirect=true"; } public Department getdepartment() { return department; } }
[ "aravind.rapuru@gmail.com" ]
aravind.rapuru@gmail.com
192d98549bdef502fe6b29a54eff0c25e0a0316e
a534a0960d9d3d73bba9e3bd53c5ab2f431f7f4c
/app/src/main/java/com/yuan/mymusic/utils/IntentLink.java
f8e8fa45b5fbe0db36a2ce53633070e80cfdb7d9
[]
no_license
ypping/Music
976df36453ea46128b818a007f47b1b53fba9959
1e4352424f905c2df02bb7b00364914ca826d08f
refs/heads/master
2020-12-24T07:53:46.393787
2016-11-10T07:49:42
2016-11-10T07:49:42
73,357,872
1
0
null
null
null
null
UTF-8
Java
false
false
1,755
java
package com.yuan.mymusic.utils; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; import android.util.Log; /** * Created by YUAN on 2016/9/8. */ public class IntentLink { /** * 判断是否有网络 * * @return */ public static boolean isInternet(Context context) { ConnectivityManager connection = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connection.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnectedOrConnecting(); } /** * 判断网络的类型 * * @return */ public static int getInternetType(Context context) { int netType = 0; ConnectivityManager connection = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connection.getActiveNetworkInfo(); if (networkInfo == null) { context.startActivity(new Intent(Settings.ACTION_SETTINGS)); return netType; } int nType = networkInfo.getType(); if (nType == ConnectivityManager.TYPE_MOBILE) { String info = networkInfo.getExtraInfo(); if (info.toLowerCase().equals("3gnet")) { netType = 3; Log.i("infoto", "info:" + info.toLowerCase().toLowerCase()); } else { netType = 2; Log.i("infoto", "info:" + info.toLowerCase().toLowerCase()); } } else if (nType == ConnectivityManager.TYPE_WIFI) { netType = 1; } return netType; } }
[ "yuanping@hyrt.com.cn" ]
yuanping@hyrt.com.cn
1d1bec5d8fb4b46184e85fd4a9a0315615d374cd
680f7d92cc608cc6850cd5c150226aacbb419c06
/andEngineLib/src/main/java/org/andengine/util/adt/data/operator/CharOperator.java
a5b4663b4ffac06bbfc510c8016381768217a5e2
[]
no_license
mnafian/IsometricMapExample
e002b3e165abb5e52ec13fb4f541de155688bbc0
9dc08b462f5ad02cf70eab16328437fe5c8ad141
refs/heads/master
2021-01-22T06:58:51.347531
2015-08-19T08:27:05
2015-08-19T08:27:05
35,424,784
1
0
null
null
null
null
UTF-8
Java
false
false
2,499
java
package org.andengine.util.adt.data.operator; /** * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich <ngramlich@zynga.com> * @since 14:24:15 - 02.02.2012 */ public enum CharOperator { // =========================================================== // Elements // =========================================================== EQUALS() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA == pCharB; } }, NOT_EQUALS() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA != pCharB; } }, LESS_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA < pCharB; } }, LESS_OR_EQUAL_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA <= pCharB; } }, MORE_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA > pCharB; } }, MORE_OR_EQUAL_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA >= pCharB; } }; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public abstract boolean check(final char pCharA, final char pCharB); // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
[ "mnafian@icloud.com" ]
mnafian@icloud.com
151c06f7500fea35678d513238a1c2286ef00878
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
/src/number_of_direct_superinterfaces/i5140.java
2fb261e9aa2ceab3a41ee92a7de923e90e2e46d9
[]
no_license
vincentclee/jvm-limits
b72a2f2dcc18caa458f1e77924221d585f23316b
2fd1c26d1f7984ea8163bc103ad14b6d72282281
refs/heads/master
2020-05-18T11:18:41.711400
2014-09-14T04:25:18
2014-09-14T04:25:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
68
java
package number_of_direct_superinterfaces; public interface i5140 {}
[ "vincentlee.dolbydigital@yahoo.com" ]
vincentlee.dolbydigital@yahoo.com
1993820f1b8ab8468882af11420add8ecc335148
20b26eaeb2f5b025ed989cdeed51014f4225c50a
/Digital Signal Processing/src/charts/Chart_Generator.java
37ff929a4871e7af80086d3c197a8872a9d963a1
[]
no_license
hiagomb/mestrado
893f0a58797019572708c28fac6ece8f3a005564
db0973d3d84c4b8a9b430d23cbf9562ef4ebc9b1
refs/heads/master
2023-03-02T09:11:30.509993
2021-02-10T14:29:38
2021-02-10T14:29:38
326,781,020
0
0
null
null
null
null
UTF-8
Java
false
false
7,144
java
/* * 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 charts; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYShapeAnnotation; import org.jfree.chart.axis.AxisLabelLocation; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RefineryUtilities; import org.jfree.ui.TextAnchor; /** * * @author hiago */ public class Chart_Generator{ /*Resumidamente, a construção de gráficos com o JFreeChart é feita em quatro etapas: 1. Definição do conjunto de dados a serem plotados (o dataset) 2. Criação do modelo do gráfico (representado por um objeto da classe JFreeChart) 3. (Opcional) Alteração de propriedades de plotagem (fazendo modificações no objeto Plot obtido a partir do objeto JFreeChart) 4. Geração da imagem do gráfico a partir do seu modelo (ou de um componente visual, como um painel Swing)*/ public Chart_Generator() { } public JFreeChart createChart(ArrayList<Double> list, String xlabel, String ylabel, double lower_range, double upper_range) { //creating the chart JFreeChart xylineChart= ChartFactory.createXYLineChart("", xlabel, ylabel, createDataset(list, ylabel), PlotOrientation.VERTICAL, true, true, false); //setting some options final XYPlot plot= xylineChart.getXYPlot(); plot.getDomainAxis().setAutoRange(true); plot.setBackgroundPaint(Color.white); plot.setRangeGridlinePaint(Color.GRAY); plot.getRenderer().setSeriesPaint(0, Color.red); //changing the range of Y axis NumberAxis range= (NumberAxis) plot.getRangeAxis(); range.setRange(lower_range, upper_range); return xylineChart; } public JFreeChart createEarlyStoppingChart(ArrayList<Double> train, ArrayList<Double> test, String xlabel, String ylabel, double lower_range, double upper_range){ JFreeChart xyChart= ChartFactory.createXYLineChart("", xlabel, ylabel, createDoubleDataSet(train, test), PlotOrientation.VERTICAL, true, true, false); final XYPlot plot= xyChart.getXYPlot(); plot.getDomainAxis().setAutoRange(true); plot.setBackgroundPaint(Color.white); plot.setRangeGridlinePaint(Color.GRAY); plot.getRenderer().setSeriesPaint(0, Color.black); plot.getRenderer().setSeriesPaint(1, Color.red); NumberAxis range= (NumberAxis) plot.getRangeAxis(); range.setRange(lower_range, upper_range); return xyChart; } private XYDataset createDoubleDataSet(ArrayList<Double> train, ArrayList<Double> test){ final XYSeries training= new XYSeries("Treinamento"); for(int i=0; i<train.size(); i++){ training.add(i, train.get(i)); } final XYSeries testing= new XYSeries("Teste"); for(int i=0; i<test.size(); i++){ testing.add(i, test.get(i)); } final XYSeriesCollection dataset= new XYSeriesCollection(); dataset.addSeries(training); dataset.addSeries(testing); return dataset; } private XYDataset createDataset(ArrayList<Double> list, String serie_name) { final XYSeries distance_1_0= new XYSeries(serie_name); for(int i=0; i<list.size(); i++){ distance_1_0.add(i, list.get(i)); } final XYSeriesCollection dataset= new XYSeriesCollection(); dataset.addSeries(distance_1_0); return dataset; } public void plotChart(JFreeChart chart, String path){ try{ File file= new File(path); ChartUtilities.saveChartAsPNG(file, chart, 500, 400); }catch(Exception error){ System.out.println(error.getMessage()); } } public JFreeChart createParaconsistentChart(ArrayList<Double> list){ final XYSeries all_features= new XYSeries("Ponto P (Todas características)"); all_features.add(list.get(0), list.get(1)); final XYSeries selected_features= new XYSeries("Ponto P (Características selecionadas)"); selected_features.add(list.get(2), list.get(3)); final XYSeriesCollection dataset= new XYSeriesCollection(); dataset.addSeries(all_features); dataset.addSeries(selected_features); JFreeChart scatter_chart= ChartFactory.createScatterPlot("", "", "", dataset, PlotOrientation.VERTICAL, true, true, false); //setting some options final XYPlot plot= scatter_chart.getXYPlot(); plot.setBackgroundPaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.getRenderer().setSeriesPaint(0, Color.red); plot.getRenderer().setSeriesPaint(1, Color.blue); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); plot.setOutlineVisible(false); //changing the ranges NumberAxis domain= (NumberAxis) plot.getDomainAxis(); domain.setRange(-1.0, 1.0); NumberAxis range= (NumberAxis) plot.getRangeAxis(); range.setRange(-1.0, 1.0); //setting a diamond shape Polygon polygon= new Polygon(); polygon.addPoint(0, -1); polygon.addPoint(-1, 0); polygon.addPoint(0, 1); polygon.addPoint(1, 0); XYShapeAnnotation area= new XYShapeAnnotation(polygon, new BasicStroke(), Color.BLACK); plot.addAnnotation(area); //custom label G1 and G2 final Marker g1= new ValueMarker(0.15); g1.setPaint(Color.white); g1.setLabel("G1"); g1.setLabelAnchor(RectangleAnchor.RIGHT); g1.setLabelTextAnchor(TextAnchor.TOP_RIGHT); plot.addRangeMarker(g1); final Marker g2= new ValueMarker(0.15); g2.setPaint(Color.white); g2.setLabel("G2"); g2.setLabelAnchor(RectangleAnchor.TOP_LEFT); g2.setLabelTextAnchor(TextAnchor.TOP_RIGHT); plot.addDomainMarker(g2); return scatter_chart; } }
[ "hiagobrajato123@gmail.com" ]
hiagobrajato123@gmail.com
cd71465bb0151a764bb69d09ac85e5dfc5c860c3
09d59158e1573e9651837e942c7f7bed6fcaa38f
/InterestCalculator/src/main/java/CleanCode/InterestCalculator/Main.java
9568cba3854a53ba61fcf453957414860952e141
[]
no_license
seshasai-VVIT539/CleanCode
9f5e10b98fe29376a5b4f5ea4d63dbdc539cc357
8b256ab871e69698d8623f2b71be745c2da81b9d
refs/heads/master
2021-01-07T09:22:29.987957
2020-02-19T15:00:55
2020-02-19T15:00:55
241,647,828
0
0
null
2020-10-13T19:40:18
2020-02-19T14:51:04
Java
UTF-8
Java
false
false
917
java
package CleanCode.InterestCalculator; import java.util.Scanner; public class Main { public static void main(String[] args) { Interest obj; Scanner sc=new Scanner(System.in); int choice; float principalAmount,timePeriod,rateOfInterest; System.out.printf("Enter principal amount:"); principalAmount=sc.nextFloat(); System.out.printf("Enter time:"); timePeriod=sc.nextFloat(); System.out.printf("Enter rate:"); rateOfInterest=sc.nextFloat(); obj=new Interest(principalAmount,timePeriod,rateOfInterest); System.out.printf("Enter choice\n1.Simple Interest\t2.Compound Interest\n"); choice=sc.nextInt(); if(choice!=1 && choice!=2) { System.out.printf("Invalid choice\n"); } else if(choice==1) { System.out.printf("Simple interest is: %.2f",obj.calculateSimpleInterest()); } else { System.out.printf("Compound interest is: %.2f",obj.calculateCompoundInterest()); } } }
[ "seshasai8121@gmail.com" ]
seshasai8121@gmail.com
1cb30fbec1f3975a76dc8db018008e12c10aa7e9
c474b03758be154e43758220e47b3403eb7fc1fc
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/settings/presenter/ax.java
c7f988641acdb3c12df23c82c9c5a48a93176732
[]
no_license
EstebanDalelR/tinderAnalysis
f80fe1f43b3b9dba283b5db1781189a0dd592c24
941e2c634c40e5dbf5585c6876ef33f2a578b65c
refs/heads/master
2020-04-04T09:03:32.659099
2018-11-23T20:41:28
2018-11-23T20:41:28
155,805,042
0
0
null
2018-11-18T16:02:45
2018-11-02T02:44:34
null
UTF-8
Java
false
false
366
java
package com.tinder.settings.presenter; import com.tinder.settings.targets.SettingsTarget; import rx.functions.Action1; final /* synthetic */ class ax implements Action1 { /* renamed from: a */ static final Action1 f58428a = new ax(); private ax() { } public void call(Object obj) { ((SettingsTarget) obj).showEmailSettings(); } }
[ "jdguzmans@hotmail.com" ]
jdguzmans@hotmail.com
b8ba38f29ce1d248189ff68a4c1a38fa0043f4c3
0d9867aeebb24617471ab68c6d486bfff9f2ec5a
/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
281d59233c412eb11eb2f5550ce32b67da492688
[]
no_license
zhangdongjava/springioc
02cb2f0680462b233c542ecf04bf7254585246aa
d08620b8008a8e05620330667ebd3abe8f44138e
refs/heads/master
2021-01-20T18:48:03.007864
2017-11-06T10:33:39
2017-11-06T10:33:39
62,283,510
0
0
null
null
null
null
UTF-8
Java
false
false
37,534
java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import java.beans.ConstructorProperties; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.BeanMetadataElement; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.core.GenericTypeResolver; import org.springframework.core.MethodParameter; import org.springframework.core.NamedThreadLocal; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.util.ClassUtils; import org.springframework.util.MethodInvoker; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** * Delegate for resolving constructors and factory methods. * Performs constructor resolution through argument matching. * * @author Juergen Hoeller * @author Rob Harrop * @author Mark Fisher * @author Costin Leau * @since 2.0 * @see #autowireConstructor * @see #instantiateUsingFactoryMethod * @see AbstractAutowireCapableBeanFactory */ class ConstructorResolver { private static final NamedThreadLocal<InjectionPoint> currentInjectionPoint = new NamedThreadLocal<InjectionPoint>("Current injection point"); private final AbstractAutowireCapableBeanFactory beanFactory; /** * Create a new ConstructorResolver for the given factory and instantiation strategy. * @param beanFactory the BeanFactory to work with */ public ConstructorResolver(AbstractAutowireCapableBeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * "autowire constructor" (with constructor arguments by type) behavior. * Also applied if explicit constructor argument values are specified, * matching all remaining arguments with beans from the bean factory. * <p>This corresponds to constructor injection: In this mode, a Spring * bean factory is able to host components that expect constructor-based * dependency resolution. * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param chosenCtors chosen candidate constructors (or {@code null} if none) * @param explicitArgs argument values passed in programmatically via the getBean method, * or {@code null} if none (-> use constructor argument values from bean definition) * @return a BeanWrapper for the new instance */ public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, Constructor<?>[] chosenCtors, final Object[] explicitArgs) { BeanWrapperImpl bw = new BeanWrapperImpl(); this.beanFactory.initBeanWrapper(bw); Constructor<?> constructorToUse = null; ArgumentsHolder argsHolderToUse = null; Object[] argsToUse = null; if (explicitArgs != null) { argsToUse = explicitArgs; } else { //如果getBean方法没有指定方法参数则尝试从配置文件中解析 Object[] argsToResolve = null; synchronized (mbd.constructorArgumentLock) { constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod; if (constructorToUse != null && mbd.constructorArgumentsResolved) { // Found a cached constructor... //从缓存中获取 argsToUse = mbd.resolvedConstructorArguments; if (argsToUse == null) { //配置的构造函数参数 argsToResolve = mbd.preparedConstructorArguments; } } } //如果缓存中存在 if (argsToResolve != null) { //解析类型 如给定的构造方法是(int,int) 则通过此方法后将("1","1")转化为(1,1) argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve); } } //没有被缓存 if (constructorToUse == null) { // Need to resolve the constructor. boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); ConstructorArgumentValues resolvedValues = null; int minNrOfArgs; if (explicitArgs != null) { minNrOfArgs = explicitArgs.length; } else { //提取配置文件中配置的参数 ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); //用于解析后承载构造参数的值 resolvedValues = new ConstructorArgumentValues(); minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); } // Take specified constructors, if any. Constructor<?>[] candidates = chosenCtors; if (candidates == null) { Class<?> beanClass = mbd.getBeanClass(); try { candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors()); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex); } } AutowireUtils.sortConstructors(candidates); int minTypeDiffWeight = Integer.MAX_VALUE; Set<Constructor<?>> ambiguousConstructors = null; LinkedList<UnsatisfiedDependencyException> causes = null; for (Constructor<?> candidate : candidates) { Class<?>[] paramTypes = candidate.getParameterTypes(); if (constructorToUse != null && argsToUse.length > paramTypes.length) { // Already found greedy constructor that can be satisfied -> // do not look any further, there are only less greedy constructors left. break; } if (paramTypes.length < minNrOfArgs) { continue; } ArgumentsHolder argsHolder; if (resolvedValues != null) { try { String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length); if (paramNames == null) { ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer(); if (pnd != null) { paramNames = pnd.getParameterNames(candidate); } } argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring); } catch (UnsatisfiedDependencyException ex) { if (this.beanFactory.logger.isTraceEnabled()) { this.beanFactory.logger.trace( "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex); } // Swallow and try next constructor. if (causes == null) { causes = new LinkedList<UnsatisfiedDependencyException>(); } causes.add(ex); continue; } } else { // Explicit arguments given -> arguments length must match exactly. if (paramTypes.length != explicitArgs.length) { continue; } argsHolder = new ArgumentsHolder(explicitArgs); } int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes)); // Choose this constructor if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { constructorToUse = candidate; argsHolderToUse = argsHolder; argsToUse = argsHolder.arguments; minTypeDiffWeight = typeDiffWeight; ambiguousConstructors = null; } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) { if (ambiguousConstructors == null) { ambiguousConstructors = new LinkedHashSet<Constructor<?>>(); ambiguousConstructors.add(constructorToUse); } ambiguousConstructors.add(candidate); } } if (constructorToUse == null) { if (causes != null) { UnsatisfiedDependencyException ex = causes.removeLast(); for (Exception cause : causes) { this.beanFactory.onSuppressedException(cause); } throw ex; } throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"); } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean '" + beanName + "' " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors); } if (explicitArgs == null) { argsHolderToUse.storeCache(mbd, constructorToUse); } } try { Object beanInstance; if (System.getSecurityManager() != null) { final Constructor<?> ctorToUse = constructorToUse; final Object[] argumentsToUse = argsToUse; beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return beanFactory.getInstantiationStrategy().instantiate( mbd, beanName, beanFactory, ctorToUse, argumentsToUse); } }, beanFactory.getAccessControlContext()); } else { beanInstance = this.beanFactory.getInstantiationStrategy().instantiate( mbd, beanName, this.beanFactory, constructorToUse, argsToUse); } bw.setBeanInstance(beanInstance); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", ex); } } /** * Resolve the factory method in the specified bean definition, if possible. * {@link RootBeanDefinition#getResolvedFactoryMethod()} can be checked for the result. * @param mbd the bean definition to check */ public void resolveFactoryMethodIfPossible(RootBeanDefinition mbd) { Class<?> factoryClass; boolean isStatic; if (mbd.getFactoryBeanName() != null) { factoryClass = this.beanFactory.getType(mbd.getFactoryBeanName()); isStatic = false; } else { factoryClass = mbd.getBeanClass(); isStatic = true; } factoryClass = ClassUtils.getUserClass(factoryClass); Method[] candidates = getCandidateMethods(factoryClass, mbd); Method uniqueCandidate = null; for (Method candidate : candidates) { if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) { if (uniqueCandidate == null) { uniqueCandidate = candidate; } else if (!Arrays.equals(uniqueCandidate.getParameterTypes(), candidate.getParameterTypes())) { uniqueCandidate = null; break; } } } synchronized (mbd.constructorArgumentLock) { mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate; } } /** * Retrieve all candidate methods for the given class, considering * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag. * Called as the starting point for factory method determination. */ private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction<Method[]>() { @Override public Method[] run() { return (mbd.isNonPublicAccessAllowed() ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } }); } else { return (mbd.isNonPublicAccessAllowed() ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } } /** * Instantiate the bean using a named factory method. The method may be static, if the * bean definition parameter specifies a class, rather than a "factory-bean", or * an instance variable on a factory object itself configured using Dependency Injection. * <p>Implementation requires iterating over the static or instance methods with the * name specified in the RootBeanDefinition (the method may be overloaded) and trying * to match with the parameters. We don't have the types attached to constructor args, * so trial and error is the only way to go here. The explicitArgs array may contain * argument values passed in programmatically via the corresponding getBean method. * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param explicitArgs argument values passed in programmatically via the getBean * method, or {@code null} if none (-> use constructor argument values from bean definition) * @return a BeanWrapper for the new instance */ public BeanWrapper instantiateUsingFactoryMethod( final String beanName, final RootBeanDefinition mbd, final Object[] explicitArgs) { BeanWrapperImpl bw = new BeanWrapperImpl(); this.beanFactory.initBeanWrapper(bw); Object factoryBean; Class<?> factoryClass; boolean isStatic; String factoryBeanName = mbd.getFactoryBeanName(); if (factoryBeanName != null) { if (factoryBeanName.equals(beanName)) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } factoryBean = this.beanFactory.getBean(factoryBeanName); if (factoryBean == null) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "factory-bean '" + factoryBeanName + "' (or a BeanPostProcessor involved) returned null"); } if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) { throw new IllegalStateException("About-to-be-created singleton instance implicitly appeared " + "through the creation of the factory bean that its bean definition points to"); } factoryClass = factoryBean.getClass(); isStatic = false; } else { // It's a static factory method on the bean class. if (!mbd.hasBeanClass()) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "bean definition declares neither a bean class nor a factory-bean reference"); } factoryBean = null; factoryClass = mbd.getBeanClass(); isStatic = true; } Method factoryMethodToUse = null; ArgumentsHolder argsHolderToUse = null; Object[] argsToUse = null; if (explicitArgs != null) { argsToUse = explicitArgs; } else { Object[] argsToResolve = null; synchronized (mbd.constructorArgumentLock) { factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod; if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) { // Found a cached factory method... argsToUse = mbd.resolvedConstructorArguments; if (argsToUse == null) { argsToResolve = mbd.preparedConstructorArguments; } } } if (argsToResolve != null) { argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve); } } if (factoryMethodToUse == null || argsToUse == null) { // Need to determine the factory method... // Try all methods with this name to see if they match the given arguments. factoryClass = ClassUtils.getUserClass(factoryClass); Method[] rawCandidates = getCandidateMethods(factoryClass, mbd); List<Method> candidateSet = new ArrayList<Method>(); for (Method candidate : rawCandidates) { if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) { candidateSet.add(candidate); } } Method[] candidates = candidateSet.toArray(new Method[candidateSet.size()]); AutowireUtils.sortFactoryMethods(candidates); ConstructorArgumentValues resolvedValues = null; boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); int minTypeDiffWeight = Integer.MAX_VALUE; Set<Method> ambiguousFactoryMethods = null; int minNrOfArgs; if (explicitArgs != null) { minNrOfArgs = explicitArgs.length; } else { // We don't have arguments passed in programmatically, so we need to resolve the // arguments specified in the constructor arguments held in the bean definition. ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); resolvedValues = new ConstructorArgumentValues(); minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); } LinkedList<UnsatisfiedDependencyException> causes = null; for (Method candidate : candidates) { Class<?>[] paramTypes = candidate.getParameterTypes(); if (paramTypes.length >= minNrOfArgs) { ArgumentsHolder argsHolder; if (resolvedValues != null) { // Resolved constructor arguments: type conversion and/or autowiring necessary. try { String[] paramNames = null; ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer(); if (pnd != null) { paramNames = pnd.getParameterNames(candidate); } argsHolder = createArgumentArray( beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring); } catch (UnsatisfiedDependencyException ex) { if (this.beanFactory.logger.isTraceEnabled()) { this.beanFactory.logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName + "': " + ex); } // Swallow and try next overloaded factory method. if (causes == null) { causes = new LinkedList<UnsatisfiedDependencyException>(); } causes.add(ex); continue; } } else { // Explicit arguments given -> arguments length must match exactly. if (paramTypes.length != explicitArgs.length) { continue; } argsHolder = new ArgumentsHolder(explicitArgs); } int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes)); // Choose this factory method if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { factoryMethodToUse = candidate; argsHolderToUse = argsHolder; argsToUse = argsHolder.arguments; minTypeDiffWeight = typeDiffWeight; ambiguousFactoryMethods = null; } // Find out about ambiguity: In case of the same type difference weight // for methods with the same number of parameters, collect such candidates // and eventually raise an ambiguity exception. // However, only perform that check in non-lenient constructor resolution mode, // and explicitly ignore overridden methods (with the same parameter signature). else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight && !mbd.isLenientConstructorResolution() && paramTypes.length == factoryMethodToUse.getParameterTypes().length && !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) { if (ambiguousFactoryMethods == null) { ambiguousFactoryMethods = new LinkedHashSet<Method>(); ambiguousFactoryMethods.add(factoryMethodToUse); } ambiguousFactoryMethods.add(candidate); } } } if (factoryMethodToUse == null) { if (causes != null) { UnsatisfiedDependencyException ex = causes.removeLast(); for (Exception cause : causes) { this.beanFactory.onSuppressedException(cause); } throw ex; } List<String> argTypes = new ArrayList<String>(minNrOfArgs); if (explicitArgs != null) { for (Object arg : explicitArgs) { argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null"); } } else { Set<ValueHolder> valueHolders = new LinkedHashSet<ValueHolder>(resolvedValues.getArgumentCount()); valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values()); valueHolders.addAll(resolvedValues.getGenericArgumentValues()); for (ValueHolder value : valueHolders) { String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) : (value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null")); argTypes.add(argType); } } String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes); throw new BeanCreationException(mbd.getResourceDescription(), beanName, "No matching factory method found: " + (mbd.getFactoryBeanName() != null ? "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") + "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. " + "Check that a method with the specified name " + (minNrOfArgs > 0 ? "and arguments " : "") + "exists and that it is " + (isStatic ? "static" : "non-static") + "."); } else if (void.class == factoryMethodToUse.getReturnType()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid factory method '" + mbd.getFactoryMethodName() + "': needs to have a non-void return type!"); } else if (ambiguousFactoryMethods != null) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous factory method matches found in bean '" + beanName + "' " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousFactoryMethods); } if (explicitArgs == null && argsHolderToUse != null) { argsHolderToUse.storeCache(mbd, factoryMethodToUse); } } try { Object beanInstance; if (System.getSecurityManager() != null) { final Object fb = factoryBean; final Method factoryMethod = factoryMethodToUse; final Object[] args = argsToUse; beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return beanFactory.getInstantiationStrategy().instantiate( mbd, beanName, beanFactory, fb, factoryMethod, args); } }, beanFactory.getAccessControlContext()); } else { beanInstance = this.beanFactory.getInstantiationStrategy().instantiate( mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse); } if (beanInstance == null) { return null; } bw.setBeanInstance(beanInstance); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via factory method failed", ex); } } /** * Resolve the constructor arguments for this bean into the resolvedValues object. * This may involve looking up other beans. * <p>This method is also used for handling invocations of static factory methods. */ private int resolveConstructorArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) { TypeConverter customConverter = this.beanFactory.getCustomTypeConverter(); TypeConverter converter = (customConverter != null ? customConverter : bw); BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter); int minNrOfArgs = cargs.getArgumentCount(); for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cargs.getIndexedArgumentValues().entrySet()) { int index = entry.getKey(); if (index < 0) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid constructor argument index: " + index); } if (index > minNrOfArgs) { minNrOfArgs = index + 1; } ConstructorArgumentValues.ValueHolder valueHolder = entry.getValue(); if (valueHolder.isConverted()) { resolvedValues.addIndexedArgumentValue(index, valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder); } } for (ConstructorArgumentValues.ValueHolder valueHolder : cargs.getGenericArgumentValues()) { if (valueHolder.isConverted()) { resolvedValues.addGenericArgumentValue(valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addGenericArgumentValue(resolvedValueHolder); } } return minNrOfArgs; } /** * Create an array of arguments to invoke a constructor or factory method, * given the resolved constructor argument values. */ private ArgumentsHolder createArgumentArray( String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class<?>[] paramTypes, String[] paramNames, Object methodOrCtor, boolean autowiring) throws UnsatisfiedDependencyException { TypeConverter customConverter = this.beanFactory.getCustomTypeConverter(); TypeConverter converter = (customConverter != null ? customConverter : bw); ArgumentsHolder args = new ArgumentsHolder(paramTypes.length); Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<ConstructorArgumentValues.ValueHolder>(paramTypes.length); Set<String> autowiredBeanNames = new LinkedHashSet<String>(4); for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) { Class<?> paramType = paramTypes[paramIndex]; String paramName = (paramNames != null ? paramNames[paramIndex] : ""); // Try to find matching constructor argument value, either indexed or generic. ConstructorArgumentValues.ValueHolder valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders); // If we couldn't find a direct match and are not supposed to autowire, // let's try the next generic, untyped argument value as fallback: // it could match after type conversion (for example, String -> int). if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) { valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders); } if (valueHolder != null) { // We found a potential match - let's give it a try. // Do not consider the same value definition multiple times! usedValueHolders.add(valueHolder); Object originalValue = valueHolder.getValue(); Object convertedValue; if (valueHolder.isConverted()) { convertedValue = valueHolder.getConvertedValue(); args.preparedArguments[paramIndex] = convertedValue; } else { ConstructorArgumentValues.ValueHolder sourceHolder = (ConstructorArgumentValues.ValueHolder) valueHolder.getSource(); Object sourceValue = sourceHolder.getValue(); MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex); try { convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam); // TODO re-enable once race condition has been found (SPR-7423) /* if (originalValue == sourceValue || sourceValue instanceof TypedStringValue) { // Either a converted value or still the original one: store converted value. sourceHolder.setConvertedValue(convertedValue); args.preparedArguments[paramIndex] = convertedValue; } else { */ args.resolveNecessary = true; args.preparedArguments[paramIndex] = sourceValue; // } } catch (TypeMismatchException ex) { throw new UnsatisfiedDependencyException( mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage()); } } args.arguments[paramIndex] = convertedValue; args.rawArguments[paramIndex] = originalValue; } else { MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex); // No explicit match found: we're either supposed to autowire or // have to fail creating an argument array for the given constructor. if (!autowiring) { throw new UnsatisfiedDependencyException( mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?"); } try { Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); args.resolveNecessary = true; } catch (BeansException ex) { throw new UnsatisfiedDependencyException( mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex); } } } for (String autowiredBeanName : autowiredBeanNames) { this.beanFactory.registerDependentBean(autowiredBeanName, beanName); if (this.beanFactory.logger.isDebugEnabled()) { this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName + "' via " + (methodOrCtor instanceof Constructor ? "constructor" : "factory method") + " to bean named '" + autowiredBeanName + "'"); } } return args; } /** * Resolve the prepared arguments stored in the given bean definition. */ private Object[] resolvePreparedArguments( String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) { TypeConverter customConverter = this.beanFactory.getCustomTypeConverter(); TypeConverter converter = (customConverter != null ? customConverter : bw); BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter); Class<?>[] paramTypes = (methodOrCtor instanceof Method ? ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes()); Object[] resolvedArgs = new Object[argsToResolve.length]; for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) { Object argValue = argsToResolve[argIndex]; MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex); GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass()); if (argValue instanceof AutowiredArgumentMarker) { argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); } else if (argValue instanceof BeanMetadataElement) { argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue); } else if (argValue instanceof String) { argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd); } Class<?> paramType = paramTypes[argIndex]; try { resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam); } catch (TypeMismatchException ex) { throw new UnsatisfiedDependencyException( mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage()); } } return resolvedArgs; } protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) { Class<?> declaringClass = constructor.getDeclaringClass(); Class<?> userClass = ClassUtils.getUserClass(declaringClass); if (userClass != declaringClass) { try { return userClass.getDeclaredConstructor(constructor.getParameterTypes()); } catch (NoSuchMethodException ex) { // No equivalent constructor on user class (superclass)... // Let's proceed with the given constructor as we usually would. } } return constructor; } /** * Template method for resolving the specified argument which is supposed to be autowired. */ protected Object resolveAutowiredArgument( MethodParameter param, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) { if (InjectionPoint.class.isAssignableFrom(param.getParameterType())) { InjectionPoint injectionPoint = currentInjectionPoint.get(); if (injectionPoint == null) { throw new IllegalStateException("No current InjectionPoint available for " + param); } return injectionPoint; } return this.beanFactory.resolveDependency( new DependencyDescriptor(param, true), beanName, autowiredBeanNames, typeConverter); } static InjectionPoint setCurrentInjectionPoint(InjectionPoint injectionPoint) { InjectionPoint old = currentInjectionPoint.get(); if (injectionPoint != null) { currentInjectionPoint.set(injectionPoint); } else { currentInjectionPoint.remove(); } return old; } /** * Private inner class for holding argument combinations. */ private static class ArgumentsHolder { public final Object rawArguments[]; public final Object arguments[]; public final Object preparedArguments[]; public boolean resolveNecessary = false; public ArgumentsHolder(int size) { this.rawArguments = new Object[size]; this.arguments = new Object[size]; this.preparedArguments = new Object[size]; } public ArgumentsHolder(Object[] args) { this.rawArguments = args; this.arguments = args; this.preparedArguments = args; } public int getTypeDifferenceWeight(Class<?>[] paramTypes) { // If valid arguments found, determine type difference weight. // Try type difference weight on both the converted arguments and // the raw arguments. If the raw weight is better, use it. // Decrease raw weight by 1024 to prefer it over equal converted weight. int typeDiffWeight = MethodInvoker.getTypeDifferenceWeight(paramTypes, this.arguments); int rawTypeDiffWeight = MethodInvoker.getTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024; return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight); } public int getAssignabilityWeight(Class<?>[] paramTypes) { for (int i = 0; i < paramTypes.length; i++) { if (!ClassUtils.isAssignableValue(paramTypes[i], this.arguments[i])) { return Integer.MAX_VALUE; } } for (int i = 0; i < paramTypes.length; i++) { if (!ClassUtils.isAssignableValue(paramTypes[i], this.rawArguments[i])) { return Integer.MAX_VALUE - 512; } } return Integer.MAX_VALUE - 1024; } public void storeCache(RootBeanDefinition mbd, Object constructorOrFactoryMethod) { synchronized (mbd.constructorArgumentLock) { mbd.resolvedConstructorOrFactoryMethod = constructorOrFactoryMethod; mbd.constructorArgumentsResolved = true; if (this.resolveNecessary) { mbd.preparedConstructorArguments = this.preparedArguments; } else { mbd.resolvedConstructorArguments = this.arguments; } } } } /** * Marker for autowired arguments in a cached argument array. */ private static class AutowiredArgumentMarker { } /** * Delegate for checking Java 6's {@link ConstructorProperties} annotation. */ private static class ConstructorPropertiesChecker { public static String[] evaluate(Constructor<?> candidate, int paramCount) { ConstructorProperties cp = candidate.getAnnotation(ConstructorProperties.class); if (cp != null) { String[] names = cp.value(); if (names.length != paramCount) { throw new IllegalStateException("Constructor annotated with @ConstructorProperties but not " + "corresponding to actual number of parameters (" + paramCount + "): " + candidate); } return names; } else { return null; } } } }
[ "787395919@qq.com" ]
787395919@qq.com
bea2776e9baa2c9382a19dc2845cb7e1a183888f
8d81f02590d84bc39ad663ae2e7666a711ed9d3e
/PrincetonA/src/com/pekoto/challenges/TreeCodec.java
637ec29ef7dc56d647bb7fa9e1fa4f8e0fc43ad2
[]
no_license
pekoto-zz/PrincetonA
bd43cbb71906167db74d24ec36a2dfcdacf02d9c
bdd8e5d5e288594808aef8121519949603435556
refs/heads/master
2022-09-26T08:24:20.328761
2019-03-23T08:37:52
2019-03-23T08:37:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,446
java
package com.pekoto.challenges; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; /* * Serialize and deserialize a binary tree to/from a String */ public class TreeCodec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuffer sb = new StringBuffer(); serialize(root, sb); return sb.toString(); } /* * Basic in-order traversal */ private void serialize(TreeNode root, StringBuffer sb) { if(root == null) { // \0 = null character marker sb.append("X").append(","); return; } sb.append(root.val).append(","); serialize(root.left, sb); serialize(root.right, sb); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { Deque<String> nodes = new LinkedList<String>(); nodes.addAll(Arrays.asList(data.split(","))); return buildTree(nodes); } private TreeNode buildTree(Deque<String> nodes) { String val = nodes.remove(); if(val.equals("X")) { return null; } TreeNode node = new TreeNode(Integer.valueOf(val)); node.left = buildTree(nodes); node.right = buildTree(nodes); return node; } }
[ "graham20@gmail.com" ]
graham20@gmail.com
a8727c6f7e75ad3ba8132d7fd71188433705a8f9
27511a2f9b0abe76e3fcef6d70e66647dd15da96
/src/com/instagram/android/directsharev2/b/cr.java
02416bee0c259cae97509c28d8a8a30cd6a0876d
[]
no_license
biaolv/com.instagram.android
7edde43d5a909ae2563cf104acfc6891f2a39ebe
3fcd3db2c3823a6d29a31ec0f6abcf5ceca995de
refs/heads/master
2022-05-09T15:05:05.412227
2016-07-21T03:48:36
2016-07-21T03:48:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
314
java
package com.instagram.android.directsharev2.b; import com.instagram.common.p.d; import com.instagram.direct.d.k; final class cr implements d<k> { cr(dq paramdq) {} } /* Location: * Qualified Name: com.instagram.android.directsharev2.b.cr * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
edeb198382470998c19a7eecb7d99d7745f907a2
f99b204f67c83840d762c6328c0b0a2654c4824f
/aliyun-java-sdk-ecs/src/main/java/com/aliyuncs/ecs/model/v20140526/DescribeClustersRequest.java
0f26f72320d213880b13512c495dd2f713cb24fb
[ "Apache-2.0" ]
permissive
huanmengmie/aliyun-openapi-java-sdk
1182efee7ef06751427e46f89edbc79f527e3676
0ee6d4d975fb2e51984c9e0423f304d044b0f445
refs/heads/master
2021-01-02T08:55:05.600370
2017-08-01T07:53:54
2017-08-01T07:53:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,326
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.ecs.model.v20140526; import com.aliyuncs.RpcAcsRequest; /** * @author auto create * @version */ public class DescribeClustersRequest extends RpcAcsRequest<DescribeClustersResponse> { public DescribeClustersRequest() { super("Ecs", "2014-05-26", "DescribeClusters", "ecs"); } private Long ownerId; private String resourceOwnerAccount; private Long resourceOwnerId; private String ownerAccount; public Long getOwnerId() { return this.ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; putQueryParameter("OwnerId", ownerId); } public String getResourceOwnerAccount() { return this.resourceOwnerAccount; } public void setResourceOwnerAccount(String resourceOwnerAccount) { this.resourceOwnerAccount = resourceOwnerAccount; putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount); } public Long getResourceOwnerId() { return this.resourceOwnerId; } public void setResourceOwnerId(Long resourceOwnerId) { this.resourceOwnerId = resourceOwnerId; putQueryParameter("ResourceOwnerId", resourceOwnerId); } public String getOwnerAccount() { return this.ownerAccount; } public void setOwnerAccount(String ownerAccount) { this.ownerAccount = ownerAccount; putQueryParameter("OwnerAccount", ownerAccount); } @Override public Class<DescribeClustersResponse> getResponseClass() { return DescribeClustersResponse.class; } }
[ "ling.wu@alibaba-inc.com" ]
ling.wu@alibaba-inc.com
6934d614738b48cdbbc676ad616c0e173b18b795
aa68bd7ebe3f2620c4c87ca0c3f087b2376646fd
/org.jage.platform-component/src/main/java/org/jage/platform/component/definition/ConfigurationException.java
9b010b794f28b36f3efa69b93f6ef8439e0c66e9
[]
no_license
agh-miss/ResourceMonitor
274374cf69647cd0f9a711d36e3990f22ea8bcdf
105238010b84af11231e2033a37bb9793b48a06c
refs/heads/master
2021-01-25T07:39:35.760487
2012-06-04T21:49:33
2012-06-04T21:49:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,532
java
/** * Copyright (C) 2006 - 2010 * Pawel Kedzior * Tomasz Kmiecik * Kamil Pietak * Krzysztof Sikora * Adam Wos * and other students of AGH University of Science and Technology * as indicated in each file separately. * * This file is part of jAgE. * * jAgE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jAgE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jAgE. If not, see http://www.gnu.org/licenses/ */ /* * File: ConfigurationException.java * Created: 2008-10-07 * Author: awos * $Id: ConfigurationException.java 4 2011-12-22 15:10:04Z faber $ */ package org.jage.platform.component.definition; /** * * @author AGH AgE Team */ public class ConfigurationException extends Exception { private static final long serialVersionUID = 1L; public ConfigurationException(String message, Throwable cause) { super(message, cause); } public ConfigurationException(String message) { super(message); } public ConfigurationException(Throwable cause) { super(cause); } }
[ "Radzio@Radzio-Lapek" ]
Radzio@Radzio-Lapek
ff8008fecfb9cd169062f95cd96d96c7198f70fe
7510960e0a6aea5206de97081fce823e282d6ca8
/monitorstat-assign/src/main/java/com/taobao/csp/assign/packet/RequestPacket.java
114bec55d684f3fd8b1751bd0a3fa449ec115824
[]
no_license
sjywying/csp
ef8e348e2866643562edefc8b190e4994f3308ce
c4c858dd0b91dc41be4dd00b639601d23db8fd3a
refs/heads/master
2021-01-18T10:01:02.744898
2013-08-05T06:36:38
2013-08-05T06:36:38
null
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
998
java
package com.taobao.csp.assign.packet; import java.util.UUID; /** * * @author xiaodu * @version 2011-8-8 ÏÂÎç03:59:13 */ public class RequestPacket extends BasePacket{ /** * */ private static final long serialVersionUID = -2848878390462813040L; public RequestPacket(String id,Object name,PacketType key){ super(key); this.requestId = id; this.resource = name; } public RequestPacket(PacketType key){ super(key); } public RequestPacket(Object name,PacketType key){ this(UUID.randomUUID().toString(),name,key); } private String requestId; private Object resource; public Object getResource() { return resource; } public void setResource(Object resource) { this.resource = resource; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public String toString() { return "requestId="+this.requestId+"resource="+this.resource; } }
[ "zunyan.zb@taobao.com" ]
zunyan.zb@taobao.com
f41b1542df696c536d818ddf85a08314263b2ece
91730688d4db6a80b44d73193afafff49b62dd3b
/rure-common/src/main/java/com/bdth/common/util/RedisUtil.java
45338529d75081ad68b088f480447f02633b3795
[ "MIT" ]
permissive
lgpzjp/rure
adaca12a941fd656d6d599063b2afe8413373cff
d25da3aaec65ff3e0d42c71206182e184d1c2a3e
refs/heads/master
2021-01-23T16:05:04.982506
2017-11-06T06:54:51
2017-11-06T06:54:51
102,720,083
1
0
null
null
null
null
UTF-8
Java
false
false
7,430
java
package com.bdth.common.util; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.concurrent.locks.ReentrantLock; /** * Redis 工具类 * Created by shuzheng on 2016/11/26. */ public class RedisUtil { protected static ReentrantLock lockPool = new ReentrantLock(); protected static ReentrantLock lockJedis = new ReentrantLock(); private static Logger _log = LoggerFactory.getLogger(RedisUtil.class); // Redis服务器IP private static String IP = PropertiesFileUtil.getInstance("redis").get("master.redis.ip"); // Redis的端口号 private static int PORT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.port"); // 访问密码 private static String PASSWORD = AESUtil.AESDecode(PropertiesFileUtil.getInstance("redis").get("master.redis.password")); // 可用连接实例的最大数目,默认值为8; // 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 private static int MAX_ACTIVE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_active"); // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 private static int MAX_IDLE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_idle"); // 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; private static int MAX_WAIT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_wait"); // 超时时间 private static int TIMEOUT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.timeout"); // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; private static boolean TEST_ON_BORROW = false; private static JedisPool jedisPool = null; /** * redis过期时间,以秒为单位 */ public final static int EXRP_HOUR = 60 * 60; //一小时 public final static int EXRP_DAY = 60 * 60 * 24; //一天 public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月 /** * 初始化Redis连接池 */ private static void initialPool() { try { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(MAX_ACTIVE); config.setMaxIdle(MAX_IDLE); config.setMaxWaitMillis(MAX_WAIT); config.setTestOnBorrow(TEST_ON_BORROW); jedisPool = new JedisPool(config, IP, PORT, TIMEOUT); } catch (Exception e) { _log.error("First create JedisPool error : " + e); } } /** * 在多线程环境同步初始化 */ private static synchronized void poolInit() { if (null == jedisPool) { initialPool(); } } /** * 同步获取Jedis实例 * @return Jedis */ public synchronized static Jedis getJedis() { poolInit(); Jedis jedis = null; try { if (null != jedisPool) { jedis = jedisPool.getResource(); try { jedis.auth(PASSWORD); } catch (Exception e) { } } } catch (Exception e) { _log.error("Get jedis error : " + e); } return jedis; } /** * 设置 String * @param key * @param value */ public synchronized static void set(String key, String value) { try { value = StringUtils.isBlank(value) ? "" : value; Jedis jedis = getJedis(); jedis.set(key, value); jedis.close(); } catch (Exception e) { _log.error("Set key error : " + e); } } /** * 设置 byte[] * @param key * @param value */ public synchronized static void set(byte[] key, byte[] value) { try { Jedis jedis = getJedis(); jedis.set(key, value); jedis.close(); } catch (Exception e) { _log.error("Set key error : " + e); } } /** * 设置 String 过期时间 * @param key * @param value * @param seconds 以秒为单位 */ public synchronized static void set(String key, String value, int seconds) { try { value = StringUtils.isBlank(value) ? "" : value; Jedis jedis = getJedis(); jedis.setex(key, seconds, value); jedis.close(); } catch (Exception e) { _log.error("Set keyex error : " + e); } } /** * 设置 byte[] 过期时间 * @param key * @param value * @param seconds 以秒为单位 */ public synchronized static void set(byte[] key, byte[] value, int seconds) { try { Jedis jedis = getJedis(); jedis.set(key, value); jedis.expire(key, seconds); jedis.close(); } catch (Exception e) { _log.error("Set key error : " + e); } } /** * 获取String值 * @param key * @return value */ public synchronized static String get(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } String value = jedis.get(key); jedis.close(); return value; } /** * 获取byte[]值 * @param key * @return value */ public synchronized static byte[] get(byte[] key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } byte[] value = jedis.get(key); jedis.close(); return value; } /** * 删除值 * @param key */ public synchronized static void remove(String key) { try { Jedis jedis = getJedis(); jedis.del(key); jedis.close(); } catch (Exception e) { _log.error("Remove keyex error : " + e); } } /** * 删除值 * @param key */ public synchronized static void remove(byte[] key) { try { Jedis jedis = getJedis(); jedis.del(key); jedis.close(); } catch (Exception e) { _log.error("Remove keyex error : " + e); } } /** * lpush * @param key * @param key */ public synchronized static void lpush(String key, String... strings) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lpush(key, strings); jedis.close(); } catch (Exception e) { _log.error("lpush error : " + e); } } /** * lrem * @param key * @param count * @param value */ public synchronized static void lrem(String key, long count, String value) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lrem(key, count, value); jedis.close(); } catch (Exception e) { _log.error("lpush error : " + e); } } /** * sadd * @param key * @param value * @param seconds */ public synchronized static void sadd(String key, String value, int seconds) { try { Jedis jedis = RedisUtil.getJedis(); jedis.sadd(key, value); jedis.expire(key, seconds); jedis.close(); } catch (Exception e) { _log.error("sadd error : " + e); } } /** * incr * @param key * @return value */ public synchronized static Long incr(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } long value = jedis.incr(key); jedis.close(); return value; } /** * decr * @param key * @return value */ public synchronized static Long decr(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } long value = jedis.decr(key); jedis.close(); return value; } }
[ "93340606@qq.com" ]
93340606@qq.com
75e9ea49e7ba7c0520de5e543c116b82efebb9e6
3c4ff31445bf57e4c23e4b74603fa81e395f3c49
/source/com.rockwellcollins.atc.limp/src/com/rockwellcollins/atc/limp/utils/LimpConstructors.java
07968991f601661c08a6db5ec4383d1446656e34
[]
no_license
lgwagner/SIMPAL
083b1245d485f7bba3a9bffe0171c2516af3720b
fce10b4fa780362033014585f85949c32f066ac5
refs/heads/master
2021-01-23T03:12:09.254682
2016-01-19T20:29:16
2016-01-19T20:29:16
35,894,301
3
1
null
null
null
null
UTF-8
Java
false
false
13,295
java
package com.rockwellcollins.atc.limp.utils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.xtext.EcoreUtil2; import com.rockwellcollins.atc.limp.ArrayAccessExpr; import com.rockwellcollins.atc.limp.ArrayExpr; import com.rockwellcollins.atc.limp.ArrayType; import com.rockwellcollins.atc.limp.ArrayTypeDef; import com.rockwellcollins.atc.limp.ArrayUpdateExpr; import com.rockwellcollins.atc.limp.Attribute; import com.rockwellcollins.atc.limp.BinaryExpr; import com.rockwellcollins.atc.limp.BoolType; import com.rockwellcollins.atc.limp.ChoiceExpr; import com.rockwellcollins.atc.limp.Expr; import com.rockwellcollins.atc.limp.GlobalDeclaration; import com.rockwellcollins.atc.limp.IdExpr; import com.rockwellcollins.atc.limp.IdList; import com.rockwellcollins.atc.limp.IfThenElseExpr; import com.rockwellcollins.atc.limp.InitExpr; import com.rockwellcollins.atc.limp.InputArg; import com.rockwellcollins.atc.limp.IntegerLiteralExpr; import com.rockwellcollins.atc.limp.IntegerType; import com.rockwellcollins.atc.limp.IntegerWildCardExpr; import com.rockwellcollins.atc.limp.LimpFactory; import com.rockwellcollins.atc.limp.OutputArg; import com.rockwellcollins.atc.limp.Postcondition; import com.rockwellcollins.atc.limp.Precondition; import com.rockwellcollins.atc.limp.RealLiteralExpr; import com.rockwellcollins.atc.limp.RecordAccessExpr; import com.rockwellcollins.atc.limp.RecordExpr; import com.rockwellcollins.atc.limp.RecordFieldExpr; import com.rockwellcollins.atc.limp.RecordType; import com.rockwellcollins.atc.limp.RecordTypeDef; import com.rockwellcollins.atc.limp.RecordUpdateExpr; import com.rockwellcollins.atc.limp.SecondInit; import com.rockwellcollins.atc.limp.SomeAttributeBlock; import com.rockwellcollins.atc.limp.StringLiteralExpr; import com.rockwellcollins.atc.limp.Type; import com.rockwellcollins.atc.limp.UnaryMinusExpr; import com.rockwellcollins.atc.limp.UnaryNegationExpr; import com.rockwellcollins.atc.limp.VariableRef; //////////////////////////////////////////////////////////////////////////////// // This class includes several methods to construct LimpExprs from components. // Using the methods in this class rather than the LimpFactory directly should // help avoid bugs related to forgetting to copy Limp Exprs before using them // to build other Limp Exprs. //////////////////////////////////////////////////////////////////////////////// public class LimpConstructors { static LimpFactory f = LimpFactory.eINSTANCE; public static IntegerWildCardExpr makeAny() { return makeIntegerWildCardExpr(); } public static SecondInit makeSecondInit(VariableRef vref) { SecondInit secondInit = f.createSecondInit(); secondInit.setId(vref); return secondInit; } public static IntegerWildCardExpr makeIntegerWildCardExpr() { return f.createIntegerWildCardExpr(); } public static SomeAttributeBlock makeSomeAttributeBlock(EList<Attribute> attributeList) { SomeAttributeBlock someAttrBlock = f.createSomeAttributeBlock(); EList<Attribute> newAttrList = someAttrBlock.getAttributeList(); newAttrList.clear(); newAttrList.addAll(attributeList); return someAttrBlock; } public static SomeAttributeBlock makeSomeAttributeBlock() { SomeAttributeBlock someAttrBlock = f.createSomeAttributeBlock(); EList<Attribute> newAttrList = someAttrBlock.getAttributeList(); //Ensure the attribute list is empty newAttrList.clear(); return someAttrBlock; } public static Precondition makePrecondition(String precondName, Expr inputPrecondExpr) { Precondition precond = f.createPrecondition(); precond.setName(precondName); precond.setExpr(EcoreUtil2.copy(inputPrecondExpr)); return precond; } public static IfThenElseExpr makeITEEWithNullElse(Expr cond, Expr thenExpr) { IfThenElseExpr itee = f.createIfThenElseExpr(); itee.setCondExpr(EcoreUtil2.copy(cond)); itee.setThenExpr(EcoreUtil2.copy(thenExpr)); return itee; } public static RecordFieldExpr makeRecordFieldExprWithNullExpr(String fieldName) { RecordFieldExpr rfe = f.createRecordFieldExpr(); rfe.setFieldName(fieldName); return rfe; } public static RecordExpr makeRecordExprFromRecordTypeDef(RecordTypeDef inputRecordTypeDef) { RecordExpr re = f.createRecordExpr(); re.setRecordDefinition(EcoreUtil2.copy(inputRecordTypeDef)); return re; } public static ArrayExpr makeArrayExprFromArrayTypeDef(ArrayTypeDef inputArrayTypeDef) { ArrayExpr ae = f.createArrayExpr(); ae.setArrayDefinition(EcoreUtil2.copy(inputArrayTypeDef)); return ae; } public static UnaryNegationExpr makeUnaryNegationExpr(Expr e) { UnaryNegationExpr une = f.createUnaryNegationExpr(); une.setExpr(EcoreUtil.copy(e)); return une; } public static BinaryExpr makeBinaryExpr(Expr lhs, Expr rhs, String op) { BinaryExpr re = f.createBinaryExpr(); re.setLeft(EcoreUtil.copy(lhs)); re.setRight(EcoreUtil.copy(rhs)); re.setOp(op); return re; } public static IdExpr makeBooleanIdExpr(String name) { BoolType t = f.createBoolType(); GlobalDeclaration g = makeGlobalDeclaration(name, t); IdExpr ie = f.createIdExpr(); ie.setId(EcoreUtil.copy(g)); //IdExpr ie = name (global boolean) return ie; } public static InitExpr makeIntegerInitExpr(String name) { GlobalDeclaration g = makeGlobalDeclarationOfIntegerType(name); InitExpr ie = f.createInitExpr(); ie.setId(EcoreUtil.copy(g)); return ie; } public static GlobalDeclaration makeGlobalDeclarationOfIntegerType(String name) { IntegerType it = f.createIntegerType(); return makeGlobalDeclaration(name, it); } public static GlobalDeclaration makeGlobalDeclaration(String name, Type T) { GlobalDeclaration g = f.createGlobalDeclaration(); g.setName(name); g.setType(EcoreUtil2.copy(T)); return g; } public static IdExpr makeIntegerIdExpr(String name) { GlobalDeclaration g = makeGlobalDeclarationOfIntegerType(name); //Create an IdExpr ie referring to name IdExpr ie = f.createIdExpr(); ie.setId(EcoreUtil2.copy(g)); return ie; } public static ArrayTypeDef makeIntegerArrayTypeDef(String arrayName, BigInteger size) { ArrayTypeDef atd = f.createArrayTypeDef(); IntegerType it = f.createIntegerType(); atd.setBaseType(EcoreUtil.copy(it)); atd.setName(arrayName); atd.setSize(size); return atd; } public static IdExpr makeArrayIdExpr(String arrayName) { //Create a global variable with name arrayName for the array ArrayType at = f.createArrayType(); //This is a magic number for the array size. I just needed something here for testing examples. BigInteger SIZE = BigInteger.valueOf(10); at.setArrayDef(makeIntegerArrayTypeDef(arrayName, SIZE)); GlobalDeclaration g2 = makeGlobalDeclaration(arrayName, at); //Create an IdExpr aie referring to arrayName IdExpr ie = f.createIdExpr(); ie.setId(EcoreUtil2.copy(g2)); return ie; } public static IdExpr makeRecordIdExpr(String recordName) { //Create a global variable with name recordName for the record RecordType rt = f.createRecordType(); GlobalDeclaration g2 = makeGlobalDeclaration(recordName, rt); //Create an IdExpr ie referring to recordName IdExpr ie = f.createIdExpr(); ie.setId(EcoreUtil2.copy(g2)); return ie; } public static ArrayAccessExpr makeArrayAccessExpr(Expr array, Expr index) { //Define the ArrayAccessExpr array[index] ArrayAccessExpr aae = f.createArrayAccessExpr(); aae.setArray(EcoreUtil2.copy(array)); aae.setIndex(EcoreUtil2.copy(index)); return aae; } public static ArrayAccessExpr makeArrayAccessExpr(String arrayName, Expr index) { return makeArrayAccessExpr(makeArrayIdExpr(arrayName), index); } public static ArrayAccessExpr makeArrayAccessExpr(Expr array, String arrayIndex) { return makeArrayAccessExpr(array, makeIntegerIdExpr(arrayIndex)); } public static ArrayAccessExpr makeArrayAccessExpr(String arrayName, String arrayIndex) { return makeArrayAccessExpr(makeArrayIdExpr(arrayName), makeIntegerIdExpr(arrayIndex)); } public static ArrayAccessExpr makeArrayAccessExpr(String arrayName, int i) { return makeArrayAccessExpr(makeArrayIdExpr(arrayName), makeIntegerLiteralExpr(i)); } public static RecordAccessExpr makeRecordAccessExpr(Expr record, String fieldname) { //Define the RecordAccessExpr record.fieldName RecordAccessExpr rae = f.createRecordAccessExpr(); rae.setRecord(EcoreUtil2.copy(record)); rae.setField(fieldname); return rae; } public static RecordAccessExpr makeRecordAccessExpr(String recordName, String fieldName) { return makeRecordAccessExpr(makeRecordIdExpr(recordName), fieldName); } public static RecordUpdateExpr makeRecordUpdateExpr(String recordName, String fieldName, Expr value) { IdExpr myRecord = makeRecordIdExpr(recordName); RecordUpdateExpr myRecordUpdateExpr = f.createRecordUpdateExpr(); myRecordUpdateExpr.setRecord(EcoreUtil.copy(myRecord)); myRecordUpdateExpr.setField(fieldName); myRecordUpdateExpr.setValue(EcoreUtil.copy(value)); return myRecordUpdateExpr; } public static ArrayUpdateExpr makeArrayUpdateExpr(String arrayName, int index, Expr value) { ArrayAccessExpr myArrayAccessExpr = makeArrayAccessExpr(arrayName, index); return makeArrayUpdateExpr(myArrayAccessExpr, value); } public static ArrayUpdateExpr makeArrayUpdateExpr(ArrayAccessExpr inputArrayAccessExpr, Expr inputExpr) { ArrayUpdateExpr myArrayUpdateExpr = f.createArrayUpdateExpr(); myArrayUpdateExpr.setAccess(EcoreUtil.copy(inputArrayAccessExpr)); myArrayUpdateExpr.setValue(EcoreUtil.copy(inputExpr)); return myArrayUpdateExpr; } public static IfThenElseExpr makeITEE(Expr cond, Expr thenExpr, Expr elseExpr) { IfThenElseExpr itee = f.createIfThenElseExpr(); itee.setCondExpr(EcoreUtil2.copy(cond)); itee.setThenExpr(EcoreUtil2.copy(thenExpr)); itee.setElseExpr(EcoreUtil2.copy(elseExpr)); return itee; } public static StringLiteralExpr makeSLE(String s) { StringLiteralExpr sle = f.createStringLiteralExpr(); sle.setStringVal(s); return sle; } public static IdExpr makeIdExpr(InputArg inputArg) { IdExpr ide = f.createIdExpr(); ide.setId(EcoreUtil.copy(inputArg)); return ide; } public static IdExpr makeIdExpr(OutputArg outputArg) { IdExpr ide = f.createIdExpr(); ide.setId(EcoreUtil.copy(outputArg)); return ide; } public static IdExpr makeIdExpr(VariableRef id) { IdExpr ide = f.createIdExpr(); ide.setId(id); return ide; } public static IdExpr makeIdExpr(String name) { IdExpr ide = f.createIdExpr(); ide.setId(makeVariableRef(name)); return ide; } public static VariableRef makeVariableRef(String name) { VariableRef vref = f.createVariableRef(); vref.setName(name); return vref; } public static IdList makeIdList(List<VariableRef> ids) { IdList idList = f.createIdList(); List<VariableRef> idsOrig = idList.getIds(); idsOrig.addAll(ids); return idList; } public static IdList makeIdList(VariableRef id) { IdList idList = f.createIdList(); List<VariableRef> idsOrig = idList.getIds(); idsOrig.add(id); return idList; } public static ChoiceExpr makeChoiceExpr(Expr expr1, Expr expr2) { ChoiceExpr choiceExpr = f.createChoiceExpr(); choiceExpr.setFirst(EcoreUtil.copy(expr1)); choiceExpr.setSecond(EcoreUtil.copy(expr2)); return choiceExpr; } public static InitExpr makeInitExpr(InputArg inputArg) { InitExpr initExpr = f.createInitExpr(); initExpr.setId(EcoreUtil.copy(inputArg)); return initExpr; } public static InitExpr makeInitExpr(VariableRef id) { InitExpr initExpr = f.createInitExpr(); initExpr.setId(EcoreUtil.copy(id)); return initExpr; } public static IntegerLiteralExpr makeIntegerLiteralExpr(int i) { return makeIntegerLiteralExpr(BigInteger.valueOf(i)); } public static IntegerLiteralExpr makeIntegerLiteralExpr(BigInteger bi) { //Create an IntegerLiteralExpr ile for the array index i IntegerLiteralExpr ile = f.createIntegerLiteralExpr(); ile.setIntVal(bi); return ile; } public static IntegerLiteralExpr intZero() { return makeIntegerLiteralExpr(0); } public static IntegerLiteralExpr intOne() { return makeIntegerLiteralExpr(1); } public static RealLiteralExpr realZero() { return makeRealLiteralExpr(0.0); } public static RealLiteralExpr realOne() { return makeRealLiteralExpr(1.0); } public static RealLiteralExpr makeRealLiteralExpr(BigDecimal bd) { RealLiteralExpr realLiteralExpr = f.createRealLiteralExpr(); realLiteralExpr.setRealVal(bd.toPlainString()); return realLiteralExpr; } public static RealLiteralExpr makeRealLiteralExpr(double d) { return makeRealLiteralExpr(BigDecimal.valueOf(d)); } public static UnaryMinusExpr makeUnaryMinusExpr(Expr inputExpr) { UnaryMinusExpr unaryMinusExpr = f.createUnaryMinusExpr(); unaryMinusExpr.setExpr(EcoreUtil.copy(inputExpr)); return unaryMinusExpr; } public static Postcondition makePostcondition(String postcondName, Expr inputPostcondExpr) { Postcondition postcond = f.createPostcondition(); postcond.setName(postcondName); postcond.setExpr(EcoreUtil2.copy(inputPostcondExpr)); return postcond; } }
[ "lgwagner@gmail.com" ]
lgwagner@gmail.com
978ee3257b3cdb7e7550ae16d524fa7117c93b86
b508f87d88f20a3901e6f1d10522a59a5d8918fc
/src/main/java/com/nibiru/opengldemo/sample5/sample5_16/MySurfaceView.java
17425c2dbd6fe7d9d9a8a1fe7501bdef3f2b6efc
[]
no_license
zkuokuo/OpenGl3ES
692175e07b49e11a3fa59d50ac787d26afeac841
f8c1242b766310c1f6309fe23bf5d832ac13360b
refs/heads/master
2020-05-02T17:27:11.328966
2019-04-10T10:53:26
2019-04-10T10:53:26
178,098,834
0
0
null
null
null
null
UTF-8
Java
false
false
3,564
java
package com.nibiru.opengldemo.sample5.sample5_16; import android.content.Context; import android.opengl.GLES30; import android.opengl.GLSurfaceView; import com.nibiru.opengldemo.utils.Constant; import com.nibiru.opengldemo.utils.MatrixState; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * 作者:dick * 公司:nibiru * 时间:2019-03-27 * 描述: */ public class MySurfaceView extends GLSurfaceView { private SceneRenderer mRenderer;//场景渲染器 public MySurfaceView(Context context) { super(context); this.setEGLContextClientVersion(3);//使用opengl es 3.0 需要设置该值为3 mRenderer = new SceneRenderer(); //创建render this.setRenderer(mRenderer); //设置渲染器 this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); //设置渲染模式为主动渲染 } boolean cullFaceFlag = false;//是否开启背面剪裁的标志位 //设置是否开启背面剪裁的标志位 public void setCullFace(boolean flag) { cullFaceFlag = flag; } boolean cwCcwFlag = false;//是否打开自定义卷绕的标志位 //设置是否打开自定义卷绕的标志位 public void setCwOrCcw(boolean flag) { cwCcwFlag = flag; } private class SceneRenderer implements Renderer { TrianglePair tp;//三角形对对象引用 @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //设置屏幕背景色RGBA GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); //创建三角形对对象 tp = new TrianglePair(MySurfaceView.this); //打开深度检测 GLES30.glEnable(GLES30.GL_DEPTH_TEST); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { //设置视口的大小及位置 GLES30.glViewport(0, 0, width, height); //计算视口的宽高比 Constant.ratio = (float) width / height; // 调用此方法计算产生透视投影矩阵 MatrixState.setProjectFrustum(-Constant.ratio, Constant.ratio, -1, 1, 10, 100); // 调用此方法产生摄像机矩阵 MatrixState.setCamera(0, 0f, 20, 0f, 0f, 0f, 0f, 1.0f, 0.0f); //初始化变换矩阵 MatrixState.setInitStack(); } @Override public void onDrawFrame(GL10 gl) { if (cullFaceFlag) { //判断是否要打开背面剪裁 GLES30.glEnable(GLES30.GL_CULL_FACE); //打开背面剪裁 } else { GLES30.glDisable(GLES30.GL_CULL_FACE); //关闭背面剪裁 } if (cwCcwFlag) { //判断是否需要打开顺时针卷绕 GLES30.glFrontFace(GLES30.GL_CCW); //使用逆时针卷绕 } else { GLES30.glFrontFace(GLES30.GL_CW); //使用顺时针卷绕 } GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);//清除深度缓冲与颜色缓冲 MatrixState.pushMatrix(); //保护现场 MatrixState.translate(0, -1.4f, 0); //沿y轴负方向平移 tp.drawSelf(); //绘制三角形对 MatrixState.popMatrix(); } } }
[ "1216819573@qq.com" ]
1216819573@qq.com
fd88a9f80bdb0e12f0ecfd195ea564b0e4cc3e5a
3ab1337c8abcdf3fe312d9470a939ae70a74bea5
/src/com/qirunde/demo8.java
a53af785a268f5d7b2cb433c46837aae31555ef7
[ "Apache-2.0" ]
permissive
huangcan1/proj1
32b50478f1dfcf1316452333c08597b3dfe11b4a
5194da46d512f579c5be4fb297464d7966839ae5
refs/heads/master
2020-03-27T08:14:52.438379
2018-08-27T06:52:58
2018-08-27T06:52:58
146,236,176
0
0
null
null
null
null
UTF-8
Java
false
false
674
java
package com.qirunde; public class demo8 { public static void main(String[] args) { int H=7,W=7; for(int i=0;i<(H+1)/2;i++){ for (int j=0;j<W/2-i;j++){ System.out.print(" "); } for (int k=1;k<(i+1)*2;k++){ System.out.print("*"); } System.out.println(); } for (int i=1;i<=H/2;i++){ for (int j=1;j<=i;j++){ System.out.print(" "); } for (int k=1;k<=W-2*i;k++){ System.out.print("*"); } System.out.println(); } } }
[ "1345756375@qq.com" ]
1345756375@qq.com
62fe06749ac0abd44a266d6a080f9a2f6e053471
bc362ac5e759ce1507d70f4a8f8c24f647d2e838
/src/main/java/com/dao/system/UserMsgMapper.java
ba9577252ef387fd9741249b1fd5fe3ab31941a0
[]
no_license
The-Tomeless-Cat/crm
a1f434e0eb47b6dc6472bb4377c9eca04d5bf1ac
2c556d531d9f5c8e679e8c31066848edb4b303f4
refs/heads/master
2022-12-04T01:11:20.018516
2019-01-22T03:16:23
2019-01-22T03:16:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package com.dao.system; import java.util.List; import com.model.system.UserMsg; public interface UserMsgMapper { int deleteByPrimaryKey(String userMsgId); int insert(UserMsg record); int insertSelective(UserMsg record); UserMsg selectByPrimaryKey(String userMsgId); int updateByPrimaryKeySelective(UserMsg record); int updateByPrimaryKey(UserMsg record); List<UserMsg> selectAlluserMsg(); }
[ "15182361101@163.com" ]
15182361101@163.com
c91f50f10edd55fcc95dd11cb6d51a3f1ecc4a42
f5c1d0c1d790ef2e0e7f17bff7a705bfd180c33a
/src/frame2/src/main/java/com/dc/frame2/util/OptimisticLockCheckUtil.java
e5826b9d2157bc706fb063586645ae2580f362c0
[]
no_license
jueshimuye/frame2
53c2d4416f9ddcbb287dfb1d6574794e26e1e0e3
cf538ee780177381d5b355785c56fb8a0d10f0aa
refs/heads/master
2022-02-23T18:18:57.003417
2019-10-28T03:05:15
2019-10-28T03:05:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package com.dc.frame2.util; import com.dc.frame2.core.domain.BaseConfigEntity; import javax.persistence.OptimisticLockException; import java.util.Objects; /** * <p>Descriptions... * * @author Diamon.Cheng * @date 2018/12/5. */ public class OptimisticLockCheckUtil { public static void checkOptimisticLock(BaseConfigEntity dbEntity, BaseConfigEntity incomeEntity) { if (!Objects.equals(dbEntity.getVersion(), incomeEntity.getVersion())) { throw new OptimisticLockException("You have an old entity version to update."); } } }
[ "dcphone33@live.com" ]
dcphone33@live.com
5c5d9b1aeacfe741e54d56999bf202314c94abe4
0f2572ac1633f8b88595a4d88f3450c90b247f0f
/src/datastructure/array/Scoreboard.java
369e4e2f3822061ed64d714f2f6f4755b7a58a33
[]
no_license
quangctkm9207/cs
a0c4b330df2324532bd6d2d4edc0d53138fe592a
884689d1c12bed3e0ff88b86f2f71be638817138
refs/heads/master
2021-01-19T19:24:28.259900
2017-04-18T05:10:44
2017-04-18T05:10:44
88,416,292
0
0
null
null
null
null
UTF-8
Java
false
false
1,728
java
package datastructure.array; /** * Created by user on 3/11/17. */ public class Scoreboard { private int numEntries = 0; //number of actual entries private GameEntry[] board; //array of game entries (name and scores) public Scoreboard(int capacity) { board = new GameEntry[capacity]; } /**Attempts to add a new score to the collection (if it is high enough).*/ public void add(GameEntry e) { int newScore = e.getScore(); //is the new entry a really a high score if (numEntries < board.length || newScore > board[numEntries - 1].getScore()) { if (numEntries < board.length) //no score drops from the board numEntries ++; //so overall number increases //shift any lower score rightward to make room for the new entry int j = numEntries - 1; while (j > 0 && board[j-1].getScore() < newScore) { board[j] = board [j - 1]; j--; } board[j] = e; } } /**Attempts to remove an existing score from the collection*/ public GameEntry remove(int i) throws IndexOutOfBoundsException{ if (i < 0 || i >= numEntries) { throw new IndexOutOfBoundsException("score index is invalid"); } GameEntry temp = board[i]; //save the object to be removed numEntries --; //overall number decrease //Shifts all right items to the left from the index i + 1 int j = i; while (j < numEntries) { board[j] = board [j+ 1]; j++; } board[j] = null; //Remove the last one to make it empty place return temp; } }
[ "quang.bme.hust.55@gmail.com" ]
quang.bme.hust.55@gmail.com
2a8bf360f949fea1d9659cc5def44ae3381bcaf0
26486aa936e93f6b41d3e0fbd1d246bbf2a7cf34
/src/main/java/it/unict/dmi/netmatchstar/graph/GraphLoader.java
25034066bdb51ad19748a62deb230911ebcadfbc
[]
no_license
fabiorinnone/NetMatchStar
2bf5c2a15e4f2cca0fe62abb245d1ced54d75b1b
cb1dafa173c17e1715e52184a42d8130627db65f
refs/heads/master
2021-07-09T01:46:53.705783
2021-01-29T16:20:44
2021-01-29T16:20:44
38,106,325
3
1
null
2021-04-26T18:04:23
2015-06-26T10:54:16
Java
UTF-8
Java
false
false
9,544
java
/* * Copyright (c) 2015, Rosalba Giugno. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the <organization>. * 4. Neither the name of the University of Catania nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROSALBA GIUGNO ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ROSALBA GIUGNO BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package it.unict.dmi.netmatchstar.graph; import javax.swing.JOptionPane; import javax.swing.JPanel; import it.unict.dmi.netmatchstar.CyActivator; import it.unict.dmi.netmatchstar.MenuAction; import it.unict.dmi.netmatchstar.utils.Common; public class GraphLoader { private int count; private Node nodes; private Node lastNode; private Edge lastEdge; private CyActivator activator; private JPanel frame; public GraphLoader(CyActivator activator, JPanel frame) { this.activator = activator; initializeComponents(frame); } public GraphLoader(JPanel frame) { initializeComponents(frame); } private void initializeComponents(JPanel frame) { count = 0; nodes = null; lastNode = null; lastEdge = null; this.frame = frame; } //Returns the number of nodes public int nodeCount() { return count; } //Returns the attr of a node public Object getNodeAttr(int id) { Node n = nodes; if(lastNode != null && lastNode.id <= id) n = lastNode; while(n != null && n.id != id) n = n.next; if(n == null) { if(frame != null) JOptionPane.showMessageDialog( activator.getCySwingApplication().getJFrame(), Common.APP_NAME + " Error. Inconsistent data!", Common.APP_NAME + "Error", JOptionPane.ERROR_MESSAGE); else System.err.println(Common.APP_NAME + " Error. Inconsistent data!"); return null; } return n.attr; } public int getCyNetworkID(int id) { Node n = nodes; if(lastNode != null && lastNode.id <= id) n = lastNode; while(n != null && n.id != id) n = n.next; if(n == null) { if(frame != null) JOptionPane.showMessageDialog( activator.getCySwingApplication().getJFrame(), Common.APP_NAME + " Error. Inconsistent data!", Common.APP_NAME + "Error", JOptionPane.ERROR_MESSAGE); else System.err.println(Common.APP_NAME + " Error. Inconsistent data!"); return -1; } return n.networkIndex; } //Returns the number of edges coming out of a node. public int outEdgeCount(int id) { Node n = nodes; if(lastNode != null && lastNode.id <= id) n = lastNode; while(n != null && n.id != id) n = n.next; if(n == null) { if(frame != null) JOptionPane.showMessageDialog( activator.getCySwingApplication().getJFrame(), Common.APP_NAME + "Error. Inconsistent data!", Common.APP_NAME + "Error", JOptionPane.ERROR_MESSAGE); else System.err.println(Common.APP_NAME + "Error. Inconsistent data!"); return -1; } return n.count; } //Returns an edge public int getOutEdge(int id, int i, Object[][] pattr) { Node n = nodes; if(lastNode != null && lastNode.id <= id) n = lastNode; while(n != null && n.id != id) n = n.next; if(n == null) { if(frame != null) JOptionPane.showMessageDialog( activator.getCySwingApplication().getJFrame(), Common.APP_NAME + "Error. Inconsistent data!", Common.APP_NAME + "Error", JOptionPane.ERROR_MESSAGE); else System.err.println(Common.APP_NAME + "Error. Inconsistent data!"); return -1; } Edge e = n.edges; int pos = 0; if(lastEdge != null && lastEdge.from == id && lastEdge.pos >= 0 && lastEdge.pos <= i) { e = lastEdge; pos = e.pos; } while(e != null && pos < i) { e.pos = pos; e = e.next; pos++; } if(e == null) { if(frame != null) JOptionPane.showMessageDialog(activator.getCySwingApplication().getJFrame(), Common.APP_NAME + "Error. Inconsistent data!", Common.APP_NAME + "Error", JOptionPane.ERROR_MESSAGE); else System.err.println(Common.APP_NAME + "Error. Inconsistent data!"); return -1; } if(pattr != null) pattr[id][i] = e.attr; lastNode = n; lastEdge = e; return e.to; } //Creates a new node public int insertNode(Object attr, boolean isSelfEdge) { Node n = new Node(); int id = n.id = count++; n.attr = attr; n.edges = null; n.count = 0; n.isSelfEdge = isSelfEdge; Node p = nodes, p0 = null; if(lastNode != null && lastNode.id < id) { p0 = lastNode; p = lastNode.next; } while(p != null && p.id < id) { p0 = p; p = p.next; } if(p0 == null) { n.next = nodes; nodes = n; } else { n.next = p0.next; p0.next = n; } lastNode = n; return n.id; } public int insertNode(Object attr, int networkIndex, boolean isSelfEdge) { Node n = new Node(); int id = n.id = count++; n.attr = attr; n.edges = null; n.count = 0; n.networkIndex = networkIndex; n.isSelfEdge = isSelfEdge; Node p = nodes, p0 = null; if(lastNode != null && lastNode.id < id) { p0 = lastNode; p = lastNode.next; } while(p != null && p.id < id) { p0 = p; p = p.next; } if(p0 == null) { n.next = nodes; nodes = n; } else { n.next = p0.next; p0.next = n; } lastNode = n; return n.id; } //Creates a new edge public void insertEdge(int id1, int id2, Object attr, boolean isSelfEdge) { //System.out.println("DENTRO INSERT EDGE"); Node pn = nodes; if(lastNode != null && lastNode.id <= id1) pn = lastNode; while(pn != null && pn.id < id1) pn = pn.next; if(pn == null || pn.id != id1) if(frame != null) JOptionPane.showMessageDialog( activator.getCySwingApplication().getJFrame(), Common.APP_NAME + "Warning. Bad param 1 in GraphLoader - InsertEdge: " + id1 + " " + id2, Common.APP_NAME + "Warning", JOptionPane.WARNING_MESSAGE); else System.err.println(Common.APP_NAME + "Warning. Bad param 1 in GraphLoader - InsertEdge: " + id1 + " " + id2); else { Edge p = pn.edges, p0 = null; if(lastEdge != null && lastEdge.from == id1 && lastEdge.to < id2) { p0 = lastEdge; p = lastEdge.next; } while(p != null && p.to < id2) { p0 = p; p = p.next; } if(p != null && p.to == id2) p.update(attr); else { Edge e = new Edge(id1, id2, attr, isSelfEdge); if(p0 == null) { e.next = pn.edges; pn.edges = e; } else { e.next = p0.next; p0.next = e; } pn.count++; lastNode = pn; lastEdge = e; } } } }
[ "fabio.rinnone0@gmail.com" ]
fabio.rinnone0@gmail.com
e2c44f56807ee4c3c56f1b62788461d0f715c73a
fd2860cae671b8b5485adc2ae5d2c563c2c5301e
/app/src/main/java/com/example/codingtest/HandlerTestActivity.java
678cffbc1a4d61878f9582ec3e1137898d7dc74c
[]
no_license
gidools/CodingTest
cfb4e7537c0c5ba812ac2fac178bf71cd8e8802c
ca76844e908fbf558d2449ace62f6381ccfbb306
refs/heads/master
2020-12-05T03:37:59.930347
2020-01-06T01:19:36
2020-01-06T01:19:36
231,999,418
0
0
null
null
null
null
UTF-8
Java
false
false
945
java
package com.example.codingtest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Toast; public class HandlerTestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_test); new WorkerThread(this).run(); } private void callFromHandler() { Toast.makeText(this, "Call from handler in thread", Toast.LENGTH_LONG).show(); } private class WorkerThread extends Thread { private Handler handler; private HandlerTestActivity activity; WorkerThread(HandlerTestActivity activity) { this.activity = activity; } @Override public void run() { handler = new Handler(); handler.post(new Runnable() { @Override public void run() { activity.callFromHandler(); } }); } } }
[ "gskwon@maxst.com" ]
gskwon@maxst.com
460086302c7a80ee6c5b2e4486dcbe947dbda83e
afc42afb7832c28e95156ba9bdfc6bdf894ba1f3
/src/main/java/com/hc/service/impl/TbShortMessFollowServiceImpl.java
1833fe6bae9d381e2a2d16195b98c7dde3b7a4fc
[]
no_license
HanChenFu/nest_lot_demo
cf4a1071b0c13613ae08ec6da7d8519bfa1b3abe
405f09636b5d45b9f155c9651f14e497026fbf7b
refs/heads/master
2022-10-06T13:54:24.641106
2020-01-08T07:17:19
2020-01-08T07:17:19
227,021,263
0
1
null
2022-09-01T23:17:17
2019-12-10T03:29:40
JavaScript
UTF-8
Java
false
false
1,782
java
package com.hc.service.impl; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hc.common.exception.CustomException; import com.hc.common.param_checkd.annotation.ParamCheck; import com.hc.common.redis.RedisUtil; import com.hc.common.result.ResultBase; import com.hc.mapper.shortMessFollow.TbShortMessFollowMapper; import com.hc.pojo.shortMessFollow.TbShortMessFollow; import com.hc.service.TbShortMessFollowService; import com.hc.utils.redis.LoginUserUtil; import com.hc.utils.result.ResultUtil; @Service("tbShortMessFollowService") public class TbShortMessFollowServiceImpl implements TbShortMessFollowService{ @Autowired RedisUtil redis; @Autowired TbShortMessFollowMapper tbShortMessFollowMapper; @Autowired LoginUserUtil loginUserUtil; @Override @ParamCheck(names = {"tbShortMessId","tbAdminId"}) public ResultBase insertSelective(TbShortMessFollow follow, HttpServletRequest request) throws Exception, CustomException { String s = tbShortMessFollowMapper.isFollow(follow); if (s==null) { int size = tbShortMessFollowMapper.insertSelective(follow); if (size>0) { return ResultUtil.getResultBase("操作成功!"); } } return ResultUtil.getResultBase("操作失败!"); } @Override @ParamCheck(names = {"tbShortMessId","tbAdminId"}) public ResultBase deleteFollow(TbShortMessFollow follow, HttpServletRequest request) throws Exception, CustomException { int size = tbShortMessFollowMapper.deleteFollow(follow); if (size>0) { return ResultUtil.getResultBase("操作成功!"); } return ResultUtil.getResultBase("操作失败!"); } }
[ "Administrator@PC-20191122SYUK" ]
Administrator@PC-20191122SYUK
584a8570d6a513259039e7ed5499e40197fcf38a
65089d2152913b08348777acd289ff31a8eb0d88
/src/homework2/task7.java
4bc9b42a428a47f78ceb022780411c8f2754cbbc
[]
no_license
YuriiNikulin/YuriiHomework
57d57ffa0c645aa394196624898c5978675f8d05
f24cb243e5c715d3e3e7b49e19d04d209972ae9f
refs/heads/master
2021-01-17T17:25:38.524210
2016-07-25T09:08:48
2016-07-25T09:08:48
64,087,495
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package homework2; import method.methodsForString; /** * Created by yurii on 22.07.2016. */ public class task7 { public static void main(String[] args) { String line = methodsForString.enter() + " "; int f = 0; String[] slova = new String[line.length()]; int indexProb = 0; while (line.length() != 0) { indexProb = line.indexOf(" "); slova[f] = line.substring(0, indexProb); line = line.substring(indexProb + 1); f++; } int maxSlovo = 0; for (int i = 0; i < f; i++) { if (slova[maxSlovo].length() < slova[i].length()) { maxSlovo = i; } } System.out.println(); System.out.println(slova[maxSlovo]); } }
[ "yuriy11111111111@gmail.com" ]
yuriy11111111111@gmail.com
7934a58a86cfd0cfd7ed651abe746e2100489a39
9786d7ad3ffc6ce574d5971345065e2d97a15ddc
/src/main/java/com/basicauthdemo1/demo/PatchUserDTO.java
0ad5479457413a9d6e9074b4d1754e8bf99223b9
[]
no_license
marcin007/basicAuthDemo1
23b606aedf0f9fe720c804157535f8818fc91f87
66999c9e4882dc29966a56cf7df3ba2a0f612227
refs/heads/master
2022-07-14T09:02:36.485513
2020-05-17T08:46:48
2020-05-17T08:46:48
264,619,184
0
0
null
null
null
null
UTF-8
Java
false
false
540
java
package com.basicauthdemo1.demo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.Size; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class PatchUserDTO { @Size(min = 2, max = 10, message = "Edit first name.") private String firstName; @Size(min = 2, max = 10, message = "Edit last name.") private String lastName; @Size(min = 2, max = 10, message = "Edit password.") private String password; }
[ "marcin007wojciechowski@gmail.com" ]
marcin007wojciechowski@gmail.com
6b587c56bd8cbe11a503fb5c54a7c6ff23c27e2f
872f30ad7fe0e89404b27ce582564e4abb51b00c
/judicature/java/com/thinkgem/jeesite/modules/questionlib/entity/SchoolQuestionlib.java
4e27f82ec1eb00c110f268f6044c59177216811f
[]
no_license
lijiaxing1234/wuming
b845d7adfa183439417c74d9c571d0f6ae732e8e
2193a990d03ebba40f16ab57cbdacf93ded8cab9
refs/heads/master
2022-09-21T19:19:05.297235
2020-06-03T02:14:20
2020-06-03T02:14:20
262,944,504
0
0
null
null
null
null
UTF-8
Java
false
false
4,287
java
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.questionlib.entity; import java.util.Date; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.annotation.JsonFormat; import com.thinkgem.jeesite.common.persistence.DataEntity; import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField; import com.thinkgem.jeesite.modules.sys.entity.Office; /** * 学校数据库Entity * * @author ryz * @version 2016-09-14 */ public class SchoolQuestionlib extends DataEntity<SchoolQuestionlib> { private static final long serialVersionUID = 1L; private String schoolId; // 学校id private String questionlibId; // 题库id private Office school; // 学校 @ExcelField(title = "学校名称", align = 2) private String schoolName; // @ExcelField(title = "学校负责人",align = 2) private String master;// 学校负责人姓名 private CourseQuestionlib courseQuestionlib; // 题库 @ExcelField(title = "题库名称", align = 2) private String questionLibName; @ExcelField(title = "授权开始时间",align = 2) private Date validStartDate; // 有效期开始时间 @ExcelField(title = "授权结束时间",align = 2) private Date validEndDate; // 有效期结束时间 @ExcelField(title = "状态",align = 2) private String state; // 使用状态 1.试用 2.购买 3.过期 private Specialty specialty; private Course course; private CourseVesion courseVesion; private String ownerType; // 所属类型 public String getOwnerType() { return ownerType; } public void setOwnerType(String ownerType) { this.ownerType = ownerType; } private String questionlibOwner; // 题库所有者 public String getQuestionlibOwner() { return questionlibOwner; } public void setQuestionlibOwner(String questionlibOwner) { this.questionlibOwner = questionlibOwner; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public String getMaster() { return master; } public void setMaster(String master) { this.master = master; } public String getQuestionLibName() { return questionLibName; } public void setQuestionLibName(String questionLibName) { this.questionLibName = questionLibName; } public SchoolQuestionlib() { super(); } public SchoolQuestionlib(String id) { super(id); } @Length(min = 0, max = 32, message = "学校长度必须介于 0 和 32 之间") public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } @Length(min = 0, max = 32, message = "题库长度必须介于 0 和 32 之间") public String getQuestionlibId() { return questionlibId; } public void setQuestionlibId(String questionlibId) { this.questionlibId = questionlibId; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getValidStartDate() { return validStartDate; } public void setValidStartDate(Date validStartDate) { this.validStartDate = validStartDate; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getValidEndDate() { return validEndDate; } public void setValidEndDate(Date validEndDate) { this.validEndDate = validEndDate; } @Length(min = 0, max = 32, message = "使用状态长度必须介于 0 和 32 之间") public String getState() { return state; } public void setState(String state) { this.state = state; } public Office getSchool() { return school; } public void setSchool(Office school) { this.school = school; } public CourseQuestionlib getCourseQuestionlib() { return courseQuestionlib; } public void setCourseQuestionlib(CourseQuestionlib courseQuestionlib) { this.courseQuestionlib = courseQuestionlib; } public Specialty getSpecialty() { return specialty; } public void setSpecialty(Specialty specialty) { this.specialty = specialty; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public CourseVesion getCourseVesion() { return courseVesion; } public void setCourseVesion(CourseVesion courseVesion) { this.courseVesion = courseVesion; } }
[ "1216240145@qq.ocm" ]
1216240145@qq.ocm
f09a85d5fdd5706690a2710875fe84b87ac84f3f
6e18807e7c473d728b16ea7d3bf33a681e8df506
/src/test/java/com/shaojiexu/www/service/NumberEncodingServiceTest.java
f49c768677418ddb5b17a7eee9579f9376dd47fd
[]
no_license
shaojie-xu-kp/NumberEncoding
2d60fa4f00df9d73e87ef026720fc3182658982f
e401098d02e6ea150c0a47f85c1d8d2c87d7212b
refs/heads/master
2021-01-10T04:19:35.109890
2015-12-01T07:52:07
2015-12-01T07:52:07
46,225,536
0
0
null
null
null
null
UTF-8
Java
false
false
1,616
java
package com.shaojiexu.www.service; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.shaojiexu.www.NumberEncodingApplication; import com.shaojiexu.www.util.NumberEncodingUtil; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NumberEncodingApplication.class) @ActiveProfiles("dev") public class NumberEncodingServiceTest { @Autowired NumberEncodingService encodingService; @Test public void testEncoding(){ assertTrue(this.encodingService.encodeAsWhole(NumberEncodingUtil.cleanDashAndSlash("56-2"),false).contains("mir")); assertTrue(this.encodingService.encodeAsWhole(NumberEncodingUtil.cleanDashAndSlash("4824"),false).contains("Torf")); assertTrue(this.encodingService.encodeAsWhole(NumberEncodingUtil.cleanDashAndSlash("482"),false).contains("Tor")); assertTrue(this.encodingService.encodeAsWhole(NumberEncodingUtil.cleanDashAndSlash("10/7"),false).contains("neu")); } @Test public void testEncodingSearch(){ List<String> encodings = this.encodingService.encode("5624-82"); List<String> encodingsExpected = Arrays.asList("mir Tor", "Mix Tor"); assertThat(encodings, is(encodingsExpected)); } }
[ "shaojie.xu@infinitagroup.it" ]
shaojie.xu@infinitagroup.it
e5f8d13be99f46ea418ee85219136679a6555d0a
fa2d04e6a221437acc99b860f7565d21b0f3f456
/src/_307_Range_Sum_Query_Mutable.java
ad271bd4012f8412b398a70a325d3246ce68f2c0
[]
no_license
ravireddy76/Algorithm
9f010caa9f6389f6658b73a2f593b7b61a368814
7531301fc2e8ac6983e1ec9b4b6e815d71b5ccda
refs/heads/master
2021-09-10T20:01:01.379434
2018-04-01T06:10:02
2018-04-01T06:10:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
920
java
/** * * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. * * The update(i, val) function modifies nums by updating the element at index i to val. * Example: * Given nums = [1, 3, 5] * * sumRange(0, 2) -> 9 * update(1, 2) * sumRange(0, 2) -> 8 * Note: * The array is only modifiable by the update function. * You may assume the number of calls to update and sumRange function is distributed evenly. * @author Shengyi * */ public class _307_Range_Sum_Query_Mutable { public NumArray(int[] nums) { } public void update(int i, int val) { } public int sumRange(int i, int j) { } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * obj.update(i,val); * int param_2 = obj.sumRange(i,j); */
[ "Shengyi@DESKTOP-KUV4R69" ]
Shengyi@DESKTOP-KUV4R69
7c6156db47189173e9ca5246ca963af8ab38d34f
b3b7114ad49f99f839ab2bfcee55d564bdc395a4
/app/src/androidTest/java/com/example/feelman_museum/ExampleInstrumentedTest.java
40a59d2499fade15b2230af195485410cd724ea6
[]
no_license
Feelloooo/kwongiung_mu
9f2b9954f08a6e16f8a1a7ef6b0b22b21d961a03
6cf8394ba963af51d31cd565406db88720d166c5
refs/heads/master
2023-06-15T06:41:01.210309
2021-07-19T09:59:03
2021-07-19T09:59:03
379,560,044
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package com.example.feelman_museum; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.feelman_museum", appContext.getPackageName()); } }
[ "giung5311@hanmail.net" ]
giung5311@hanmail.net
c69e582742898fe4f502762d7ef3a6b03ed32bbb
c46cea34e4cbbe9ad6ec8315cc0a996491f3980c
/core/src/main/java/org/yes/cart/promotion/impl/PromotionTesterImpl.java
41fd80237c9a79397aaa6f79f7d6fb4422c1ab53
[ "Apache-2.0" ]
permissive
omge/yes-cart
cd1531664d49b28bf715b5eb3925de4966757c08
6ebba6ceb9243ddae3463da8f704919111da9f78
refs/heads/master
2020-08-28T20:11:45.802359
2019-10-24T15:42:11
2019-10-24T15:42:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,103
java
/* * Copyright 2009 Denys Pavlov, Igor Azarnyi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yes.cart.promotion.impl; import org.apache.commons.lang.StringUtils; import org.yes.cart.domain.entity.CarrierSla; import org.yes.cart.domain.entity.Shop; import org.yes.cart.promotion.PromotionContextFactory; import org.yes.cart.promotion.PromotionTester; import org.yes.cart.service.domain.CarrierSlaService; import org.yes.cart.service.domain.PriceService; import org.yes.cart.service.domain.ShopService; import org.yes.cart.shoppingcart.AmountCalculationStrategy; import org.yes.cart.shoppingcart.ShoppingCart; import org.yes.cart.shoppingcart.ShoppingCartCommand; import org.yes.cart.shoppingcart.ShoppingCartCommandFactory; import org.yes.cart.shoppingcart.impl.ShoppingCartImpl; import org.yes.cart.utils.TimeContext; import java.math.BigDecimal; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User: denispavlov * Date: 10/04/2018 * Time: 18:55 */ public class PromotionTesterImpl implements PromotionTester { private final ShopService shopService; private final PriceService priceService; private final PromotionContextFactory factory; private final CarrierSlaService carrierSlaService; private final AmountCalculationStrategy calculationStrategy; private final ShoppingCartCommandFactory cartCommandFactory; public PromotionTesterImpl(final ShopService shopService, final PriceService priceService, final PromotionContextFactory factory, final CarrierSlaService carrierSlaService, final AmountCalculationStrategy calculationStrategy, final ShoppingCartCommandFactory cartCommandFactory) { this.shopService = shopService; this.priceService = priceService; this.factory = factory; this.carrierSlaService = carrierSlaService; this.calculationStrategy = calculationStrategy; this.cartCommandFactory = cartCommandFactory; } /** {@inheritDoc} */ @Override public ShoppingCart testPromotions(final String shopCode, final String currency, final String language, final String customer, final String supplier, final Map<String, BigDecimal> products, final String shipping, final List<String> coupons, final Instant time) { boolean setTime = time != null; try { if (setTime) { TimeContext.setTime(time); } final Shop shop = this.shopService.getShopByCode(shopCode); ensureNoCache(shop, currency); final ShoppingCartImpl cart = new ShoppingCartImpl(); cart.initialise(calculationStrategy); prepareDefaults(cart, shop.getMaster() != null ? shop.getMaster() : shop, currency, language); loginCustomer(cart, customer); addProductsToCart(cart, supplier, products); addCouponsToCart(cart, coupons); prepareShipping(cart); setShippingMethod(cart, shipping); return cart; } finally { if (setTime) { TimeContext.clear(); } } } private void ensureNoCache(final Shop shop, final String currency) { // Ensure no cache factory.refresh(shop.getCode(), currency); priceService.refresh(shop.getCode(), currency); if (shop.getMaster() != null) { factory.refresh(shop.getMaster().getCode(), currency); priceService.refresh(shop.getMaster().getCode(), currency); } } private void prepareDefaults(final ShoppingCart cart, final Shop shop, final String currency, final String language) { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_SETSHOP, shop.getShopId()); params.put(ShoppingCartCommand.CMD_CHANGECURRENCY, currency); params.put(ShoppingCartCommand.CMD_CHANGELOCALE, language); params.put(ShoppingCartCommand.CMD_INTERNAL_SETIP, "127.0.0.1"); cartCommandFactory.execute(cart, params); } private void loginCustomer(final ShoppingCart cart, final String customer) { if (StringUtils.isNotBlank(customer)) { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_LOGIN_P_EMAIL, customer); params.put(ShoppingCartCommand.CMD_LOGIN_P_PASS, "promotest"); params.put("promoTestLoginCmd", "1"); cartCommandFactory.execute("promoTestLoginCmd", cart, params); } } private void addProductsToCart(final ShoppingCart cart, final String supplier, final Map<String, BigDecimal> products) { if (products != null) { for (final Map.Entry<String, BigDecimal> product : products.entrySet()) { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_ADDTOCART, product.getKey()); if (product.getValue() != null) { if (StringUtils.isNotBlank(supplier)) { params.put(ShoppingCartCommand.CMD_P_SUPPLIER, supplier); } params.put(ShoppingCartCommand.CMD_P_QTY, product.getValue().toPlainString()); } cartCommandFactory.execute(ShoppingCartCommand.CMD_ADDTOCART, cart, params); } } } private void addCouponsToCart(final ShoppingCart cart, final List<String> coupons) { if (coupons != null) { for (final String coupon : coupons) { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_ADDCOUPON, coupon); cartCommandFactory.execute(ShoppingCartCommand.CMD_ADDCOUPON, cart, params); } } } private void prepareShipping(final ShoppingCart cart) { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_SPLITCARTITEMS, ShoppingCartCommand.CMD_SPLITCARTITEMS); cartCommandFactory.execute(ShoppingCartCommand.CMD_SPLITCARTITEMS, cart, params); } private void setShippingMethod(final ShoppingCart cart, final String shipping) { if (StringUtils.isNotBlank(shipping)) { final CarrierSla carrierSla = carrierSlaService.findSingleByCriteria(" where e.guid = ?1", shipping); if (carrierSla != null) { final Map<String, Object> params = new HashMap<>(); final StringBuilder sla = new StringBuilder(); for (final String supplier : cart.getCartItemsSuppliers()) { if (sla.length() > 0) { sla.append('|'); } sla.append(String.valueOf(carrierSla.getCarrierslaId())).append('-').append(supplier); } params.put(ShoppingCartCommand.CMD_SETCARRIERSLA, sla.toString()); cartCommandFactory.execute(ShoppingCartCommand.CMD_SETCARRIERSLA, cart, params); } } } }
[ "denis.v.pavlov@gmail.com" ]
denis.v.pavlov@gmail.com
5d6fcb5dda1c79deda8c9b7adf3c2d5c943d018b
d9584a071ed65ef95f004eed88dedb6458e9cdee
/Pyramid Full Stack Projects/Student-Catalog-Project/backend/src/main/java/com/example/demo/rest/LoginController.java
aea2e7eecf2bc66cd7e5cdd463859d6965d61d70
[]
no_license
kunxinlin/Pyramid-Academy
f27e8941fe49525cf30f2b96f3e6a3f27b9822bf
1b583f5ac3f74c2218f3f807308da65b13fec95b
refs/heads/master
2021-07-13T03:51:10.765916
2021-05-12T08:20:34
2021-05-12T08:20:34
244,686,749
0
0
null
null
null
null
UTF-8
Java
false
false
2,169
java
package com.example.demo.rest; import com.example.demo.dao.UserLoginDAO; import com.example.demo.dao.UserLoginDAOImpl; import com.example.demo.entity.UserLogin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin(origins = {"http://localhost:3000"}) @RestController public class LoginController { private final UserLoginDAOImpl loginDAO; @Autowired public LoginController(UserLoginDAOImpl loginDAO) { this.loginDAO = loginDAO; } //http://localhost:8080/getAllUsers @GetMapping("/getAllUsers") public List<UserLogin> findAll(){ return loginDAO.findAll(); } @GetMapping("/getUser/{id}") public UserLogin findById(@PathVariable int id){ return loginDAO.findById(id); } @GetMapping("/getPassword/{email}") public String getPassword(@PathVariable("email") String email){ UserLogin user = loginDAO.findLoginByEmail(email); if(user == null){ throw new RuntimeException("Email is not found: " + email); } return user.getPassword(); } @GetMapping("/professor/{email}") public boolean isProfessor(@PathVariable("email") String email) { UserLogin user = loginDAO.findLoginByEmail(email); if(user == null){ throw new RuntimeException("User is not found: " + email); } return user.isProfessor(); } @PostMapping("/addUser") public UserLogin addUser(@RequestBody UserLogin user){ user.setId(0); //incase a id is passed in loginDAO.save(user); return user; } @PutMapping("/updateUser") public UserLogin updateUserLogin(@RequestBody UserLogin user){ loginDAO.save(user); return user; } @DeleteMapping("/deleteUser/{id}") public String deleteUser(@PathVariable int id){ UserLogin user = loginDAO.findById(id); if(user == null){ throw new RuntimeException("User does not exist with id: " + id); } loginDAO.deleteById(id); return "Deleted user with id: " + id; } }
[ "kunxinlin@gmail.com" ]
kunxinlin@gmail.com
3e8222ce1d92c91aa01817ab24dc611391e86764
169887de4b4a493cdca6aaf60eb8b11c05f08648
/FoxStorage/src/main/java/model/Image.java
7a2310feba792a549b41f447b49a50786bfd86ea
[]
no_license
bettirsch/degree-work
903f196429b3c2e15eefba9b30a4ecc3518f0b39
3e8e13d0ac0533e7b73d71f10dcad4896c256174
refs/heads/master
2021-06-21T10:19:05.577977
2020-12-06T15:53:48
2020-12-06T15:53:48
184,482,703
0
0
null
2021-06-07T18:58:30
2019-05-01T21:16:20
Java
UTF-8
Java
false
false
2,144
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * * @author spdue4cb */ @Entity @Table(name = "image") public class Image extends BaseModel implements Serializable{ private static final long serialVersionUID = -6086097595120063602L; @Column(name = "image_name") private String imageName; @Lob @Column(name = "doc") @Basic(fetch = FetchType.LAZY) private byte[] doc; @Column(name = "note") private String note; @Column(name = "inactive") private Boolean inactive; @ManyToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "product_ID") private Product product; public Image() { } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public byte[] getDoc() { return doc; } public void setDoc(byte[] doc) { this.doc = doc; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Boolean getInactive() { return inactive; } public void setInactive(Boolean inactive) { this.inactive = inactive; } @Override public String toString() { return "Image{" + "imageId=" + super.getId() + ", imageName=" + imageName + ", note=" + note + ", product=" + product.getProductEan() + '}'; } }
[ "36169595+bettirsch@users.noreply.github.com" ]
36169595+bettirsch@users.noreply.github.com
a0aca0e23c23c12ad8797a89e843f96a2d3ebeb5
acb951eab39213c740cc73f9fcb05b3032d9071a
/mogu_admin/src/main/java/com/moxi/mogublog/admin/security/WebSecurityConfig.java
a7da106996115f8decff765e13d7c91e42415d70
[ "Apache-2.0" ]
permissive
houfanghai/mogu_blog_v2
81e68a63974f0cb948e462c1239e9ebb16e5b9dd
071429dd8ef9ce38eca0ee246a5b4689b4a1e8ae
refs/heads/master
2023-08-18T05:13:04.342008
2021-09-14T10:04:02
2021-09-14T10:04:02
405,905,696
0
0
null
null
null
null
UTF-8
Java
false
false
5,351
java
package com.moxi.mogublog.admin.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * SpringSecurity配置文件 * 用于配置哪些请求被拦截,哪些请求可以匿名访问 * * @author 陌溪 * @date 2020年9月19日10:05:40 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Autowired private UserDetailsService userDetailsService; @Autowired public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder // 设置UserDetailsService .userDetailsService(this.userDetailsService) // 使用BCrypt进行密码的hash .passwordEncoder(passwordEncoder()); //remember me authenticationManagerBuilder.eraseCredentials(false); } /** * 装载BCrypt密码编码器 * * @return */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception { return new JwtAuthenticationTokenFilter(); } @Bean public FilterRegistrationBean registrationBean(JwtAuthenticationTokenFilter filter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setEnabled(false); return registrationBean; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { //因为SpringSecurity使用X-Frame-Options防止网页被Frame。所以需要关闭为了让后端的接口管理的swagger页面正常显示 httpSecurity.headers().frameOptions().disable(); httpSecurity //新加入,允许跨域 .cors() .and() // 由于使用的是JWT,我们这里不需要csrf .csrf().disable() // 异常的处理器,将执行未鉴权的处理方法 .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // 基于token,所以不需要session【但禁用后,将导致UserDetailsService每次都会执行,无法缓存用户信息】 //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许对于网站静态资源的无授权访问 .antMatchers( "/swagger-ui.html", "/swagger-ui/*", "/swagger-resources/**", "/v2/api-docs", "/v3/api-docs", "/webjars/**", "/actuator/**", "/druid/**" ).permitAll() // 对于获取token的RestApi要允许匿名访问 .antMatchers("/auth/**", "/creatCode/**", "/file/**" ).permitAll() // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated(); // 添加两个过滤器 // JwtAuthenticationTokenFilter: JWT认证过滤器,验证token有效性 // UsernamePasswordAuthenticationFilter: 认证操作全靠这个过滤器 httpSecurity.addFilterBefore(registrationBean(new JwtAuthenticationTokenFilter()).getFilter(), UsernamePasswordAuthenticationFilter.class); // 禁用缓存 httpSecurity.headers().cacheControl(); } }
[ "houfanghaidxy@163.com" ]
houfanghaidxy@163.com
696d4473e58bf96874c4a16c009ae9ae94ba45e3
7756a4077f71b27c9b47fa0096e8ed1557823dd7
/src/main/java/org/CustomRealm.java
9f38bbb2a0c748a9b77af7d3d7388bcd462a56b9
[]
no_license
20158711/shiro
cebaf77e4d516fb8b942838ed78955a329c531e9
363c96366e2b487f52c85925cd496393b34ca324
refs/heads/master
2020-03-23T18:06:51.847655
2018-07-22T11:32:33
2018-07-22T11:32:33
141,890,187
0
0
null
null
null
null
UTF-8
Java
false
false
2,870
java
package org; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.Md5Hash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * 自定义realm */ public class CustomRealm extends AuthorizingRealm { Map<String,String> userMap=new HashMap<>(); { userMap.put("yanbing1025","202cb962ac59075b964b07152d234b70"); super.setName("customRealm"); } @Override /** * 授权 */ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String userName= (String) principals.getPrimaryPrincipal(); Set<String> roles=getRolesByUsername(userName); Set<String> permissions=getPermissionByUserName(userName); SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo(); authorizationInfo.setStringPermissions(permissions); authorizationInfo.setRoles(roles); return authorizationInfo; } public static void main(String[] args) { Md5Hash md5Hash=new Md5Hash("123"); System.out.println(md5Hash.toString()); } @Override /** * 认证 */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //1,从主体传过来的认证信息中获取用户名 String username= (String) token.getPrincipal(); //2,到数据库中获取凭证 String password=getPasswordByUserName(username); if (password == null) { return null; } SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo("yanbing1025",password,"customRealm"); return authenticationInfo; } /** * 模拟数据库获取用户认证数据 * @param userName * @return */ private String getPasswordByUserName(String userName){ return userMap.get(userName); } /** * 模拟数据库获取角色数据 * @param username * @return */ private Set<String> getRolesByUsername(String username){ Set<String> set=new HashSet<>(); set.add("admin"); return set; } /** * 模拟数据库获取权限数据 * @param username * @return */ private Set<String> getPermissionByUserName(String username){ Set<String> set=new HashSet<>(); set.add("user:delete"); set.add("user:add"); return set; } }
[ "1280334378@qq.com" ]
1280334378@qq.com
53d30a07adeb731ab516f490c800219aab413f3d
7cb43b74c14017a48fcfd9429accb34661b87763
/moderatorservice/src/main/java/com/imadelfetouh/moderatorservice/dal/queryexecuter/DeleteUserExecuter.java
8862886d1a8f0af9e830c092efaae6d210652da5
[]
no_license
imadfetouh/moderatorservice
0dda587c6094a71c8ee9765a4cd57e4c2b4de9ab
c0590ba8f028faf8160a3c17946f9e4c1080b32c
refs/heads/main
2023-04-25T12:32:56.735038
2021-05-24T11:29:39
2021-05-24T11:29:39
358,835,242
0
0
null
null
null
null
UTF-8
Java
false
false
1,090
java
package com.imadelfetouh.moderatorservice.dal.queryexecuter; import com.imadelfetouh.moderatorservice.dal.configuration.QueryExecuter; import com.imadelfetouh.moderatorservice.dal.ormmodel.User; import com.imadelfetouh.moderatorservice.model.response.ResponseModel; import com.imadelfetouh.moderatorservice.model.response.ResponseType; import org.hibernate.Session; import javax.persistence.Query; public class DeleteUserExecuter implements QueryExecuter<Void> { private String userId; public DeleteUserExecuter(String userId) { this.userId = userId; } @Override public ResponseModel<Void> executeQuery(Session session) { ResponseModel<Void> responseModel = new ResponseModel<>(); Query query = session.createQuery("SELECT u FROM User u WHERE u.userId = :userId"); query.setParameter("userId", userId); User user = (User) query.getSingleResult(); session.delete(user); session.getTransaction().commit(); responseModel.setResponseType(ResponseType.CORRECT); return responseModel; } }
[ "imad.elfetouh@hotmail.com" ]
imad.elfetouh@hotmail.com
45161551d36d499a7b148c2ae025dfd15983ace5
d3a02c373be1e5f56cc82843aca5b7af18c9e662
/src/util/CurveEquation.java
48f78726ea37a5282db821d472c4ca9e1ec595b6
[]
no_license
harrypurba/rsaandecc
23766e5b6ad2f0b013c7b5d6a2f685283971fe41
37e5d1c58d4e2cf656e32d211042256faaf0d8c7
refs/heads/master
2021-04-18T22:23:26.469993
2018-03-27T17:34:50
2018-03-27T17:34:50
126,470,678
0
0
null
null
null
null
UTF-8
Java
false
false
2,693
java
package util; import java.util.ArrayList; import java.util.List; public class CurveEquation { // equation that follows y^2 = x^3 + ax + b mod p // where 4a^3+27b^2≠0 public int a; public int b; public int p; public CurveEquation(int a, int b, int p) throws Exception { if (4*Math.pow(a,3)+27*Math.pow(b,2)==0) throw new Exception("a and b singular"); if (!Util.isPrime(p)) throw new Exception("p is not prime"); this.a = a; this.b = b; this.p = p; } public boolean isXSolvable(int x){ int mod = ((x*x*x)+a*x+b) % p; // y^2 congruence with mod%p for(int y=0;y<p;y++){ if((y*y%p)==mod) return true; } return false; } public List<Point> getAllPossiblePoints(){ List<Point> points = new ArrayList<>(); for(int x=0;x<p;x++){ int mod = ((x*x*x)+a*x+b) % p; // y^2 congruence with mod%p for(int y=0;y<p;y++){ if((y*y%p)==mod) points.add(new Point(x,y)); } } return points; } public int getPointsCount(){ return getAllPossiblePoints().size(); } public boolean isInCurve(Point p){ int y2 = (p.x*p.x*p.x)+(a*p.x)+b; int mod = Math.floorMod(y2,this.p); return (Math.floorMod(p.y*p.y,this.p)==mod); } public Point addPoint(Point p1, Point p2){ if(p1.equals(p2)){ if(p1.y==0) return null; int divisor = Math.abs(2*p1.y); int invMod = Util.modInverse(divisor,p); int m = Math.floorMod((((3*p1.x*p1.x+a))*invMod),p); int xr = (m*m-2*p1.x); xr = Math.floorMod(xr,this.p); Point ret = new Point(xr, Math.floorMod((m*(p1.x-xr)-p1.y),p)); return (isInCurve(ret)?ret:null); } int divisor = (p1.x-p2.x); int invMod = Util.modInverse(divisor,p); int m = ((p1.y-p2.y)*invMod); m = Math.floorMod(m,p); int xr = (int) (m*m-p1.x-p2.x); xr = Math.floorMod(xr,p); Point ret = new Point(xr,(int)Math.floorMod((m*(p1.x-xr)-p1.y),p)); return (isInCurve(ret)?ret:null); } public Point multiplyPoint(Point p, int n){ --n; if(n==0){ return p; } Point r = addPoint(p,p); --n; for(int i=0;i<n;++i){ r = addPoint(p,r); } return r; } public Point subtractPoint(Point p, Point q){ Point negQ = new Point(q.x,Math.floorMod(-1*q.y,this.p)); return addPoint(p,negQ); } }
[ "massatriya@gmail.com" ]
massatriya@gmail.com
7bfc3a123ed94b54302f3b9b17f4b71300dd2400
0c3c07d64468c375613cf80064eb273192be35f6
/portlets/YejinTestOauth-portlet/docroot/WEB-INF/src/com/test/oauth/OAuthTest.java
72ba7060035dba53df621eac5e2fd9b9ea533f62
[]
no_license
jerryhseo/OSP
032d270c76f8410482efafabc68641fdb95f7f0e
509307f9207b4d4c2ce80805998a53e6a5b340fa
refs/heads/devel
2021-07-13T02:51:45.676311
2020-06-16T02:18:48
2020-06-16T02:18:48
157,665,981
0
0
null
2020-06-16T02:19:55
2018-11-15T06:53:56
HTML
UTF-8
Java
false
false
184
java
package com.test.oauth; import com.liferay.util.bridges.mvc.MVCPortlet; /** * Portlet implementation class OAuthTest */ public class OAuthTest extends MVCPortlet { }
[ "yejinkwon@kisti.re.kr" ]
yejinkwon@kisti.re.kr
5482296efb9b5b7acb1d3a8203aa382123c148ba
96fad468533d392c9de03fa253bcab2b1bda9c70
/src/com/jiubang/goscreenlock/theme/cjpcardcool/weather/util/BrowseCityActivity.java
161f65b4f693c088aca4a73a4f58a8e4e7bca430
[ "Apache-2.0" ]
permissive
chenjianping99/CradCool
3d57c46ee027fa7724b9edf0696a58cb08e16eb3
a7a70ee031cd64d6426b9b8bec7ffb5c7f7de802
refs/heads/master
2020-04-05T05:47:55.903328
2015-01-16T08:46:53
2015-01-16T08:46:53
29,339,013
0
0
null
null
null
null
UTF-8
Java
false
false
36,047
java
package com.jiubang.goscreenlock.theme.cjpcardcool.weather.util; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.jiubang.goscreenlock.theme.cjpcardcool.util.Global; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.CityBean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.ContinentBean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.CountryBean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.StateBean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.CommonConstants; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.LocationConstants; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.Util; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.HttpExecutor; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.HttpExecutorContext; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.HttpRequestStatus; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.Request; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.Result; import com.jiubang.goscreenlock.theme.cjpcardcool.R; /** * * <br>类描述: * <br>功能详细描述: * * @date [2012-9-5] */ public class BrowseCityActivity extends Activity implements OnClickListener, OnItemClickListener, OnDismissListener { private LayoutInflater mInflater; private ListView mList; private ListAdapter mListAdapter; private ImageView mBackImg; private TextView mTitleTV; /** 用以存放ListView中显示内容的List*/ private ArrayList<String> mLabelList; /** 大洲List*/ private ArrayList<ContinentBean> mContinents; /** 当前大洲*/ private ContinentBean mCurContinent; /** 当前国家*/ private CountryBean mCurCountry; /** 当前州*/ private StateBean mCurState; private TextView mGridTip; private GridView mGrid; private GridAdapter mGridAdapter; private static final int CONTINENT_LEVEL = 0x01; private static final int COUNTRY_LEVEL = 0x02; private static final int STATE_LEVEL = 0x03; private static final int CITY_LEVEL = 0x04; /** 当前的查询层次*/ private int mCurLevel; private final static String[] ALPHABET = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; private ProgressDialog mLoadingDialog; private LocationQueryHandler mLocationQueryHandler; /** 浏览城市界面是否已销毁 */ private boolean mIsDestroy = false; /** 是否正在执行数据库的查询和添加城市操作。true,是;false,否 */ private boolean mDBOperating = false; /*****服务器返回的状态码********/ private static final String STATUS_SERVER_ERROR = "-1"; private static final String STATUS_SERVER_DONE = "1"; private static final String STATUS_SERVER_EMPTY_DATA = "0"; /**查询将要添加的城市是否已经存在**/ private static final int TOKEN_QUERY_ADD_CITY = 0x01; /**查询动态壁纸绑定的城市id**/ private static final int TOKEN_QUERY_LIVE_WALLPAPER_CITY_ID = 0x02; /**更新壁纸绑定的城市**/ private final static int TOKEN_UPDATE_LIVE_WALLPAPER_CITY_ID = 0x03; View mV; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // 初始化UI对象 mInflater = getLayoutInflater(); setContentView(R.layout.weather_browsecity_layout); mBackImg = (ImageView) findViewById(R.id.add_city_title_back); mBackImg.setOnClickListener(this); mList = (ListView) findViewById(R.id.add_city_browse_list); mTitleTV = (TextView) findViewById(R.id.browse_title_label); mTitleTV.setText(R.string.addcity_browse_city_label); mGridTip = (TextView) findViewById(R.id.browse_alphabet_tip); mGrid = (GridView) findViewById(R.id.browse_city_alphabet_grid); mGridAdapter = new GridAdapter(); mGrid.setAdapter(mGridAdapter); mGrid.setOnItemClickListener(this); mLabelList = new ArrayList<String>(); mContinents = new ArrayList<ContinentBean>(); mListAdapter = new ListAdapter(); mList.setAdapter(mListAdapter); mList.setOnItemClickListener(this); if (mLoadingDialog == null) { mLoadingDialog = createLoadingDialog(this, this.getResources().getString(R.string.browse_locations_title), this .getResources().getString(R.string.addcity_serach_dialog_content), this); } mLocationQueryHandler = new LocationQueryHandler(getContentResolver()); Intent intent = getIntent(); // 请求大洲数据 mCurLevel = CONTINENT_LEVEL; BrowseLocation browseContinent = new BrowseLocation(); // 第一个参数可以传null和-10000之外的所有整型数字,这一层它不会被用到url中,仅用作有效判断。 browseContinent.execute(0, null); if (!mIsDestroy && mLoadingDialog != null) { mLoadingDialog.show(); } mV = findViewById(R.id.weather_guanggao_browser); mV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean result = Global.gotoMarket(BrowseCityActivity.this, Global.SURISTRING); if (!result) { Global.gotoBrowser(BrowseCityActivity.this, Global.SPATHSTRING); } } }); } @Override protected void onResume() { super.onResume(); if (mV != null && Global.isAppExist(this, Global.SWEATHERPACK)) { mV.setVisibility(View.GONE); } } public ProgressDialog createLoadingDialog(Context context, String title, String msg, OnDismissListener listener) { ProgressDialog loadingDialog = new ProgressDialog(context); loadingDialog.setTitle(title); loadingDialog.setMessage(msg); loadingDialog.setOnDismissListener(listener); return loadingDialog; } private void selectCity(CityBean city) { WeatherSettingUtil.setCity(this, city); finish(); // if (!mDBOperating) { // mDBOperating = true; // // TODO:执行插入操作之前先检查要插入的城市在数据库中是否存在 // /* // mLocationQueryHandler.startQuery(TOKEN_QUERY_ADD_CITY, city, // WeatherContentProvider.TABLE_CITYNOW_URI, // new String[] { CityNowTable.CITY_ID }, // CityNowTable.CITY_ID + "='" + city.getCityId() + "' and " // + CityNowTable.MY_LOCATION + " = '" + Constants.FLAG_CITY_ADDED + "'", // null, null); // */ // } } @Override public void onClick(View v) { // 基本和onKeyDown相同,但是不需要处理return if (mBackImg == v) { /** * 点击返回键的流程: * 1.若有对话框,隐藏它 * 2.若在最顶层,finish * 3.否则清空当前层的数据,返回上一层并释放内存 * 4.设置标题 */ if (mLoadingDialog != null) { if (mLoadingDialog.isShowing()) { mLoadingDialog.dismiss(); } } mLabelList.clear(); switch (mCurLevel) { case CONTINENT_LEVEL : finish(); break; case COUNTRY_LEVEL : mCurLevel = CONTINENT_LEVEL; if (mCurContinent != null) { mCurContinent.getCounties().clear(); mCurCountry = null; for (ContinentBean continent : mContinents) { mLabelList.add(continent.getLabel()); } mTitleTV.setText(R.string.addcity_browse_city_label); } break; case STATE_LEVEL : mCurLevel = COUNTRY_LEVEL; if (mCurCountry != null) { mCurCountry.getStates().clear(); mCurState = null; for (CountryBean country : mCurContinent.getCounties()) { mLabelList.add(country.getLabel()); } mTitleTV.setText(mCurContinent.getContinentName()); } break; case CITY_LEVEL : mCurLevel = STATE_LEVEL; if (mCurState != null) { mGrid.setVisibility(View.GONE); mGridTip.setVisibility(View.GONE); mCurState.getCities().clear(); mCurState.getAlphabet().clear(); for (StateBean state : mCurCountry.getStates()) { mLabelList.add(state.getLabel()); } mTitleTV.setText(mCurCountry.getCountryName()); mGridAdapter.mIsInitized = false; } break; default : break; } mListAdapter.notifyDataSetChanged(); mList.setSelection(0); } } @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { if (l instanceof ListView) { /** * 前三层点击列表项的操作步骤: * 1.进入下一个操作层次 * 2.更新当前操作层的执行对象(如mCurContient) * 3.获取当前操作层的数据 * 4.设置Title * 5.显示Dialog * * 后两层的操作步骤: * 1.获取选中的城市 * 2.将这个城市插入数据库 * 3.finish */ switch (mCurLevel) { case CONTINENT_LEVEL : if (mContinents != null && position >= 0 && position < mContinents.size()) { mCurLevel = COUNTRY_LEVEL; mCurContinent = mContinents.get(position); BrowseLocation browseCountries = new BrowseLocation(); browseCountries.execute(mCurContinent.getContinentId(), null); mTitleTV.setText(mCurContinent.getLabel()); if (!mIsDestroy && mLoadingDialog != null) { mLoadingDialog.show(); } } break; case COUNTRY_LEVEL : if (mCurContinent != null && position >= 0 && position < mCurContinent.getCounties().size()) { mCurLevel = STATE_LEVEL; mCurCountry = mCurContinent.getCounties().get(position); BrowseLocation browseStates = new BrowseLocation(); browseStates.execute(mCurCountry.getCountryId(), null); mTitleTV.setText(mCurCountry.getLabel()); if (!mIsDestroy && mLoadingDialog != null) { mLoadingDialog.show(); } } break; case STATE_LEVEL : if (mCurCountry != null && position >= 0 && position < mCurCountry.getStates().size()) { mCurLevel = CITY_LEVEL; mCurState = mCurCountry.getStates().get(position); BrowseLocation browseCities = new BrowseLocation(); browseCities.execute(mCurState.getStateId(), null); mTitleTV.setText(mCurState.getLabel()); if (!mIsDestroy && mLoadingDialog != null) { mLoadingDialog.show(); } } break; case CITY_LEVEL : if (mCurState != null && position >= 0 && position < mCurState.getCities().size()) { CityBean city = mCurState.getCities().get(position); selectCity(city); } break; default : break; } } // 不需要判断现在处于哪个操作层,因为这个操作只能在字母表层被触发 /** * 操作流程: * 1.找到用户选择的字母 * 2.更新当前字母 * 3.用州Id和这个字母请求数据 */ else if (l instanceof GridView) { if (mCurState != null && position >= 0 && position < ALPHABET.length) { String selectedLetter = ALPHABET[position]; // 向服务器请求这个字母下的城市 BrowseLocation browseCities = new BrowseLocation(); browseCities.execute(mCurState.getStateId(), selectedLetter); if (!mIsDestroy && mLoadingDialog != null) { mLoadingDialog.show(); } } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean bHandled = false; /** * 点击返回键的流程: * 1.若有对话框,隐藏它 * 2.若在最顶层,finish * 3.否则清空当前层的数据,返回上一层并释放内存;如果是字母表层,隐藏GridView * 4.设置标题 */ if (keyCode == KeyEvent.KEYCODE_BACK) { bHandled = true; if (mLoadingDialog != null) { if (mLoadingDialog.isShowing()) { mLoadingDialog.dismiss(); } } mLabelList.clear(); switch (mCurLevel) { case CONTINENT_LEVEL : bHandled = false; break; case COUNTRY_LEVEL : mCurLevel = CONTINENT_LEVEL; if (mCurContinent != null) { mCurContinent.getCounties().clear(); mCurCountry = null; for (ContinentBean continent : mContinents) { mLabelList.add(continent.getLabel()); } mTitleTV.setText(R.string.addcity_browse_city_label); } break; case STATE_LEVEL : mCurLevel = COUNTRY_LEVEL; if (mCurCountry != null) { mCurCountry.getStates().clear(); mCurState = null; for (CountryBean country : mCurContinent.getCounties()) { mLabelList.add(country.getLabel()); } mTitleTV.setText(mCurContinent.getContinentName()); } break; case CITY_LEVEL : mCurLevel = STATE_LEVEL; if (mCurState != null) { mGrid.setVisibility(View.GONE); mGridTip.setVisibility(View.GONE); mGridAdapter.mIsInitized = false; mCurState.getCities().clear(); mCurState.getAlphabet().clear(); for (StateBean state : mCurCountry.getStates()) { mLabelList.add(state.getLabel()); } mTitleTV.setText(mCurCountry.getCountryName()); } break; default : break; } mListAdapter.notifyDataSetChanged(); mList.setSelection(0); } if (!bHandled) { finish(); return super.onKeyDown(keyCode, event); } else { return true; } } protected void onDestroy() { mIsDestroy = true; super.onDestroy(); } /** * * <br>类描述: * <br>功能详细描述: * * @date [2012-9-5] */ private class ListAdapter extends BaseAdapter { @Override public int getCount() { return mLabelList.size(); } @Override public Object getItem(int position) { if (position >= 0 && position < mLabelList.size()) { return mLabelList.get(position); } else { return 0; } } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; View item = null; if (convertView == null) { item = mInflater.inflate(R.layout.weather_addcity_list_item_layout, parent, false); holder = new ViewHolder(); holder.mTextView = (TextView) item.findViewById(R.id.addcity_list_item_title); holder.mImageView = (ImageView) item.findViewById(R.id.addcity_list_item_more); item.setTag(holder); } else { item = convertView; holder = (ViewHolder) item.getTag(); } if (position >= 0 && position < mLabelList.size()) { holder.mTextView.setText(mLabelList.get(position)); if (mCurLevel == CITY_LEVEL) { holder.mImageView.setVisibility(View.GONE); } else { holder.mImageView.setVisibility(View.VISIBLE); } } return item; } } /** * * 类描述: * 功能详细描述: * * @author chenyuning * @date [2012-11-5] */ class ViewHolder { TextView mTextView; ImageView mImageView; } /** * * <br>类描述: * <br>功能详细描述: * * @date [2012-9-5] */ private class GridAdapter extends BaseAdapter { public boolean mIsInitized = false; private boolean[] mIsEnabledArray = new boolean[26]; @Override public int getCount() { return ALPHABET.length; } @Override public Object getItem(int position) { return ALPHABET[position]; } @Override public long getItemId(int position) { return position; } @Override public boolean isEnabled(int position) { // 未被初始化则遍历当前州的字母表,过滤不存在的字母 // isisEnabled在点击的时候被调用,加在这里仅作保护 if (!mIsInitized) { for (int i = 0; i < 26; i++) { mIsEnabledArray[i] = false; } for (int i = 0; i < 26; i++) { for (String letter : mCurState.getAlphabet()) { if (letter.equals(ALPHABET[i])) { mIsEnabledArray[i] = true; } } } } return mIsEnabledArray[position]; } @Override public View getView(int position, View convertView, ViewGroup parent) { View item; TextView tv; if (!mIsInitized) { for (int i = 0; i < 26; i++) { mIsEnabledArray[i] = false; } for (int i = 0; i < 26; i++) { for (String letter : mCurState.getAlphabet()) { if (letter.equals(ALPHABET[i])) { mIsEnabledArray[i] = true; } } } } if (convertView == null) { item = mInflater.inflate(R.layout.weather_grid_city_item, parent, false); tv = (TextView) item.findViewById(R.id.text); item.setTag(tv); } else { item = convertView; tv = (TextView) item.getTag(); } if (mIsEnabledArray[position]) { tv.setTextColor(Color.BLACK); } else { tv.setTextColor(Color.GRAY); } tv.setText(ALPHABET[position]); return item; } } /** * * <br>类描述: * <br>功能详细描述: * * @date [2012-9-5] */ class LocationQueryHandler extends AsyncQueryHandler { public LocationQueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { super.onQueryComplete(token, cookie, cursor); switch (token) { case TOKEN_QUERY_ADD_CITY : CityBean city = (CityBean) cookie; // 添加的城市是否已经存在 boolean isExist = false; if (cursor != null) { try { if (cursor.getCount() > 0) { Toast toast = Toast.makeText(BrowseCityActivity.this, R.string.cityexists, Toast.LENGTH_SHORT); toast.show(); mDBOperating = false; isExist = true; } } catch (Exception e) { e.printStackTrace(); // 数据库操作异常,终止本次添加城市,更新数据库操作 mDBOperating = false; } finally { cursor.close(); } if (mDBOperating && !isExist) { // 数据库操作正常,并且添加的城市不存在数据库中 // TODO:这里将所得到的城市插入到数据库中,插入完成后会调用onInsertComplete方法 /* ContentValues values = new ContentValues(); values.put(CityNowTable.CITY_ID, city.getCityId()); values.put(CityNowTable.OLD_CITY_ID, city.getCityId()); values.put(CityNowTable.CITY_NAME, city.getCityName()); values.put(CityNowTable.STATE, city.getStateName()); values.put(CityNowTable.COUNTRY, city.getCountryName()); values.put(CityNowTable.TZ_OFFSET, city.getTimeZone()); values.put(CityNowTable.MY_LOCATION, Constants.FLAG_CITY_ADDED); values.put(CityNowTable.WIND_DIRECTION, Constants.UNKNOWN_VALUE_STRING); values.put(CityNowTable.WIND_STRENGTH, Constants.UNKNOWN_VALUE_STRING); values.put(CityNowTable.WIND_TYPE, Constants.UNKNOWN_WIND_TYPE); values.put(CityNowTable.SUNRISE, Constants.UNKNOWN_VALUE_STRING); values.put(CityNowTable.SUNSET, Constants.UNKNOWN_VALUE_STRING); values.put(CityNowTable.TYPE, Constants.UNKNOWN_WEATHER_TYPE); // 未知天气类型 values.put(CityNowTable.NOW_DESP, Constants.UNKNOWN_VALUE_STRING); values.put(CityNowTable.SEQUENCE, mLargestSeqNum); values.put(CityNowTable.POP, Constants.WEATHER_MIN_VALUE); values.put(CityNowTable.CITY_TYPE, PlaceInfo.WORLDWIDE); values.put(CityNowTable.FEELSLIKE_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.BAROMETER_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.DEWPOINT_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.HIGH_TEMP_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.LOW_TEMP_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.WIND_STRENGTH_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.NOW_TEMP_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.TIMESTAMP, Constants.UNKNOWN_VALUE_INT); values.put(CityNowTable.UVINDEX_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.HUMIDITY_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.VISIBILITY_VALUE, Constants.UNKNOWN_VALUE_FLOAT); values.put(CityNowTable.UPDATE_TIME, Constants.UNKNOWN_VALUE_INT); mLocationQueryHandler.startInsert(0, city, WeatherContentProvider.TABLE_CITYNOW_URI, values); */ } } else { mDBOperating = false; } break; default : break; } } @Override protected void onInsertComplete(int token, Object cookie, Uri uri) { super.onInsertComplete(token, cookie, uri); mDBOperating = false; CityBean city = (CityBean) cookie; Toast.makeText( BrowseCityActivity.this, BrowseCityActivity.this.getString(R.string.add_city_successfully, city.getCityName()), Toast.LENGTH_SHORT).show(); setResult(0, new Intent()); // TODO:到这里插入城市操作完成,可以处理一些插入完成后的操作,例如请求天气 BrowseCityActivity.this.finish(); } } @Override public void onDismiss(DialogInterface arg0) { } /** * * <br>类描述: * <br>功能详细描述: * * @date [2012-9-5] */ class BrowseLocation extends AsyncTask<Object, Object, Result> { @Override protected Result doInBackground(Object... params) { int id = CommonConstants.UNKNOWN_VALUE_INT; String letter = null; if (params.length > 0) { id = (Integer) params[0]; } if (params.length > 1) { letter = (String) params[1]; } Result result = new Result(); result.setStatus(HttpRequestStatus.REQUEST_HTTP_FAILED); if (id != CommonConstants.UNKNOWN_VALUE_INT) { Request request = getRequest(id, letter); getData(request, result); } return result; } @Override protected void onPostExecute(Result result) { super.onPostExecute(result); if (!mIsDestroy && mLoadingDialog != null) { if (mLoadingDialog.isShowing()) { mLoadingDialog.dismiss(); } } mLabelList.clear(); switch (result.getStatus()) { case HttpRequestStatus.REQUEST_SUCCESS : processDataReady(); break; /**doInBackground * 错误处理流程: * 1.将当前操作层回滚 * 2.弹对应的toast */ case HttpRequestStatus.REQUEST_NO_DATA : Toast toast = Toast.makeText(BrowseCityActivity.this, R.string.no_result_list, Toast.LENGTH_SHORT); toast.show(); break; case HttpRequestStatus.REQUEST_NETWORK_UNAVAILABLE : Toast toast2 = Toast.makeText(BrowseCityActivity.this, R.string.network_excepiton, Toast.LENGTH_SHORT); toast2.setGravity(Gravity.CENTER, 0, 0); toast2.show(); break; case HttpRequestStatus.REQUEST_TIMEOUT : Toast toast3 = Toast.makeText(BrowseCityActivity.this, R.string.network_timeout, Toast.LENGTH_SHORT); toast3.setGravity(Gravity.CENTER, 0, 0); toast3.show(); break; // 其他结果都认为是网络错误 default : Toast toast4 = Toast.makeText(BrowseCityActivity.this, R.string.server_error_result, Toast.LENGTH_SHORT); toast4.setGravity(Gravity.CENTER, 0, 0); toast4.show(); break; } mListAdapter.notifyDataSetChanged(); mList.setSelection(0); } private Request getRequest(int id, String letter) { /** * url例子: * 大洲: * http://goweatherex.3g.cn/goweatherex/guide/continent?lang=en&sys=4.0.4&ps=2.0 * 国家: * http://goweatherex.3g.cn/goweatherex/guide/country?continentid=1&lang=en&sys=4.0.4&ps=2.0 * 州: * http://goweatherex.3g.cn/goweatherex/guide/state?countryid=1&lang=en&sys=4.0.4&ps=2.0 * 城市: * http://goweatherex.3g.cn/goweatherex/guide/cities?stateid=1&lang=en&sys=4.0.4&ps=2.0 * 字母: * http://goweatherex.3g.cn/goweatherex/guide/cities?stateid=1&alphabet=a&lang=en&sys=4.0.4&ps=2.0 */ Request request = null; StringBuilder path = new StringBuilder(); path.append(LocationConstants.STR_HTTP).append(LocationConstants.LOCATION_SERVER_HOST); switch (mCurLevel) { case CONTINENT_LEVEL : path.append(LocationConstants.STR_API_GET_CONTINENTS); request = new Request(path.toString()); break; case COUNTRY_LEVEL : path.append(LocationConstants.STR_API_GET_COUNTRIES); request = new Request(path.toString()); request.addHeader(LocationConstants.STR_API_EXTRA_CONTINENTID, String.valueOf(id)); break; case STATE_LEVEL : path.append(LocationConstants.STR_API_GET_STATES); request = new Request(path.toString()); request.addHeader(LocationConstants.STR_API_EXTRA_COUNTRYID, String.valueOf(id)); break; case CITY_LEVEL : path.append(LocationConstants.STR_API_GET_CITIES); request = new Request(path.toString()); request.addHeader(LocationConstants.STR_API_EXTRA_STATEID, String.valueOf(id)); if (letter != null) { request.addHeader(LocationConstants.STR_API_EXTRA_ALPHABET, letter); } break; default : // 程序不应该执行到这里 request = new Request(path.toString()); break; } // 加上lang,sys,ps if (request != null) { request.addDefaultHeader(BrowseCityActivity.this, Util.getCurLanguage(BrowseCityActivity.this)); } return request; } } /** * 请求服务器获取列表数据 * @param request * @param result */ private void getData(Request request, Result result) { // 检查网络情况,附带标识网络类型 HttpExecutor httpExecutor = HttpExecutorContext.getHttpExecutor(); if (!httpExecutor.checkNetwork(result, BrowseCityActivity.this)) { result.setStatus(HttpRequestStatus.REQUEST_NETWORK_UNAVAILABLE); } else { InputStream inputStream = null; try { String url = request.composeCompleteURL(); result.setRequestStartTime(SystemClock.elapsedRealtime()); inputStream = httpExecutor.doRefresh(url, request, result); } catch (UnsupportedEncodingException e1) { // 请求URL不合法 result.setStatus(HttpRequestStatus.REQUEST_HTTP_FAILED); e1.printStackTrace(); } if (inputStream != null) { try { String json = Util.readInputStream(inputStream); String serverResult = parseInputStream(json); if (serverResult.equals(STATUS_SERVER_DONE)) { // 置浏览城市请求结束时间 result.setRequestEndTime(SystemClock.elapsedRealtime()); result.setStatus(HttpRequestStatus.REQUEST_SUCCESS); } else if (serverResult.equals(STATUS_SERVER_EMPTY_DATA)) { result.setStatus(HttpRequestStatus.REQUEST_NO_DATA); } else { result.setStatus(HttpRequestStatus.REQUEST_NO_DATA); } } catch (IOException e) { e.printStackTrace(); result.setStatus(HttpRequestStatus.REQUEST_IO_EXCEPTION); } catch (JSONException e) { e.printStackTrace(); result.setStatus(HttpRequestStatus.REQUEST_IO_EXCEPTION); } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } httpExecutor.release(); } } /** * 功能简述: 将Json解析后存入内存 * 功能详细描述: * 解析JSON的步骤: * 1.读head字段,读出result,若不为1,则直接返回 * 2.判断当前操作层,先把当前操作对象的下级数组清空 * 3.从JSONObject中读出JSONARRAY,解析后加入数组 * 4.若第三步成功,则发生消息通知当前操作成功,否则通知当前操作失败 * * 注意: * @param json * @return 服务器返回的状态码:-1 服务器错误;1 正常;0 无数据 * @throws JSONException */ private String parseInputStream(String json) throws JSONException { // -1表示服务器错误 String result = "-1"; // 解析JSON JSONObject rootObject = new JSONObject(json); // 读response头 JSONObject head = rootObject.getJSONObject("head"); result = head.getString("result"); if (result.equalsIgnoreCase("1")) { // 不同操作层次需要解析的字段不同 switch (mCurLevel) { case CONTINENT_LEVEL : parseContinents(rootObject); break; case COUNTRY_LEVEL : parseCountries(rootObject); break; case STATE_LEVEL : parseStates(rootObject); break; case CITY_LEVEL : parseCities(rootObject); break; default : break; } } return result; } private void parseContinents(JSONObject rootObject) throws JSONException { JSONArray continents; continents = rootObject.getJSONArray("continents"); if (!mContinents.isEmpty()) { mContinents.clear(); } for (int i = 0; i < continents.length(); i++) { JSONObject continent = continents.getJSONObject(i); String name = continent.getString("continent"); int id = continent.getInt("continentId"); if (mContinents != null) { mContinents.add(new ContinentBean(id, name, name)); } } } private void parseCountries(JSONObject rootObject) throws JSONException { JSONArray countries; countries = rootObject.getJSONArray("countries"); if (!mCurContinent.getCounties().isEmpty()) { mCurContinent.getCounties().clear(); } for (int i = 0; i < countries.length(); i++) { JSONObject country = countries.getJSONObject(i); String name = country.getString("country"); int id = country.getInt("countryId"); if (mCurContinent != null) { mCurContinent.getCounties().add(new CountryBean(id, name, name)); } } } private void parseStates(JSONObject rootObject) throws JSONException { JSONArray states; states = rootObject.getJSONArray("states"); if (!mCurCountry.getStates().isEmpty()) { mCurCountry.getStates().clear(); } for (int i = 0; i < states.length(); i++) { JSONObject state = states.getJSONObject(i); String name = state.getString("state"); int id = state.getInt("stateId"); if (mCurCountry != null) { mCurCountry.getStates().add(new StateBean(id, name, name)); } } } private void parseCities(JSONObject rootObject) throws JSONException { String alphabet = rootObject.getString("filterList"); /** * filter_list和cities必有一个为空,可以通过判断alphabet是否为空来判断是否需要显示字母表 * 显示字母表需要做的事: * 1.使GridView可以见 * 2.GridiewAdapter的初始化标志位置为false; */ if (!TextUtils.isEmpty(alphabet) && !alphabet.equalsIgnoreCase("null")) { String[] letterList = alphabet.split(", "); int length = letterList.length; mCurState.setIsAlphabet(true); // 清空 if (!mCurState.getAlphabet().isEmpty()) { mCurState.getAlphabet().clear(); } // 当前String是否为字母 boolean isLetter = false; /** * 如果有一个不是字母,则认为JSON解析错误,将操作回滚,并抛出异常 */ for (int i = 0; i < length; i++) { isLetter = false; for (int j = 0; j < 26; j++) { if (letterList[i].equalsIgnoreCase(ALPHABET[j])) { isLetter = true; } } if (isLetter) { mCurState.getAlphabet().add(letterList[i]); } else { if (!mCurState.getAlphabet().isEmpty()) { mCurState.getAlphabet().clear(); } mCurState.setIsAlphabet(false); throw new JSONException("字母表格式不正确: " + alphabet); } } } else { JSONArray cities = rootObject.getJSONArray("cities"); if (!mCurState.getCities().isEmpty()) { mCurState.getCities().clear(); } for (int i = 0; i < cities.length(); i++) { JSONObject city = cities.getJSONObject(i); String cityName = city.getString("city"); String id = city.getString("cityId"); String stateName = city.getString("state"); String countryName = city.getString("country"); String timeZone = city.getString("timeZone"); if (mCurState != null) { mCurState.getCities().add( new CityBean(id, cityName, stateName, countryName, timeZone, cityName)); } } } } /** * 1.清空LabelList * 2.将搜索结果装载入Labelist * 3.若有字母表,则显示GridView * 4.通知ListView刷新 * 5.若LabelList为空,提示 */ private void processDataReady() { switch (mCurLevel) { case CONTINENT_LEVEL : for (ContinentBean continent : mContinents) { mLabelList.add(continent.getLabel()); } break; case COUNTRY_LEVEL : for (CountryBean country : mCurContinent.getCounties()) { mLabelList.add(country.getLabel()); } break; case STATE_LEVEL : for (StateBean state : mCurCountry.getStates()) { mLabelList.add(state.getLabel()); } break; case CITY_LEVEL : for (CityBean city : mCurState.getCities()) { mLabelList.add(city.getLabel()); } if (mCurState.isAlphabet()) { mGrid.setVisibility(View.VISIBLE); mGridTip.setVisibility(View.VISIBLE); mGridAdapter.notifyDataSetChanged(); } else { mGrid.setVisibility(View.GONE); } break; } if (mLabelList.isEmpty() && !mCurState.isAlphabet() && mCurLevel == CITY_LEVEL) { Toast toast = Toast.makeText(BrowseCityActivity.this, R.string.no_result_list, Toast.LENGTH_SHORT); toast.show(); } } }
[ "=" ]
=
ab1d2533d8eff946f1826135f967f69775d0d1c4
53c67c897192a52b21622fbc4744453a41539e84
/src/main/java/com/liuchikit/constant/ResponseMsg.java
fd77cd41da9afa2e445bbca3fdc6a788a123b689
[]
no_license
zhumian/oa1.0
fd3a37e332537d0552130977516c4b4eaf2b4114
5cd3b3b099a16d6209403cb93ba58d40c0a426a8
refs/heads/master
2021-09-06T01:53:23.080855
2017-12-16T08:25:54
2017-12-16T08:25:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
529
java
package com.liuchikit.constant; /** * {类说明} * * @author liaozijie * @date 2017/11/15 */ public enum ResponseMsg { SAVE_SUCCESS("保存成功"), SAVE_FAIL("保存失败"), DEL_SUCCESS("删除成功"), DEL_FAIL("删除失败"), UPDATE_SUCCESS("更新成功"), UPDATE_FAIL("更新失败"), GET_SUCCESS("获取成功"), GET_FAIL("获取失败"); private String msg; ResponseMsg(String msg){ this.msg = msg; } public String getMsg() { return msg; } }
[ "liuchikit@foxmail.com" ]
liuchikit@foxmail.com
ba29e7e02659a9cffacb5cc2b9245d0b3d63d82f
773f6b270f5782d9da80b6f41f63040276a2f829
/src/main/java/io/sinistral/proteus/server/swagger/ServerParameterExtension.java
dbf1e70cba8c291344efab2897b8454cf3701ff5
[ "Apache-2.0" ]
permissive
SeanMollet/proteus
2fa6c5778336c1b03080ca3b2db8396cb6e01f6a
c28771d7757f44b0e7dca022f92ad20fd5316c8c
refs/heads/master
2020-03-30T13:11:15.220324
2018-10-02T21:16:02
2018-10-02T21:16:02
151,261,678
0
0
Apache-2.0
2018-10-02T13:46:38
2018-10-02T13:46:37
null
UTF-8
Java
false
false
1,756
java
/** * */ package io.sinistral.proteus.server.swagger; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Iterator; import java.util.List; import java.util.Set; import com.fasterxml.jackson.databind.JavaType; import io.swagger.jaxrs.DefaultParameterExtension; import io.swagger.jaxrs.ext.SwaggerExtension; import io.swagger.models.parameters.Parameter; /** * @author jbauer * */ public class ServerParameterExtension extends DefaultParameterExtension { public ServerParameterExtension() { super(); } @Override public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) { if(type.getTypeName().contains("java.nio.ByteBuffer") || type.getTypeName().contains("java.nio.file.Path")) { type = java.io.File.class; } return super.extractParameters(annotations, type, typesToSkip, chain); } @Override protected boolean shouldIgnoreType(Type type, Set<Type> typesToSkip) { if( type.getTypeName().contains("io.sinistral.proteus.server.ServerRequest") || type.getTypeName().contains("HttpServerExchange") || type.getTypeName().contains("HttpHandler") || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse") || type.getTypeName().contains("io.undertow.server.session") ) { return true; } return super.shouldIgnoreType(type, typesToSkip); } @Override protected JavaType constructType(Type type) { if(type.getTypeName().contains("java.nio.ByteBuffer") || type.getTypeName().contains("java.nio.file.Path")) { type = java.io.File.class; } return super.constructType(type); } }
[ "josh@wurrly.com" ]
josh@wurrly.com
80c1b88acc8c6e5ef5dbb3337da98d43cad46211
6379630846831b6bac51b6752f391be570876af4
/src/main/java/com/avit/itdap/mock/LookBackMock.java
bd34ed9736fd0a4dd2cb3e22d4d61ee8f85173f1
[]
no_license
binggu1993/springBoot-bo
890d67379d7d16b0d9ffc075747de2eba5422c90
44642bd7fa6332c8b1f5190c8cdde38144ad6401
refs/heads/master
2021-04-12T03:23:31.977785
2018-04-19T12:08:21
2018-04-19T12:08:21
125,945,687
0
0
null
null
null
null
UTF-8
Java
false
false
4,953
java
package com.avit.itdap.mock; import java.util.Random; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; import com.avit.itdap.task.ChannelEnum; public class LookBackMock { private static String getAreaName(String areaCode) { switch(areaCode) { case "01": return "合肥"; case "02": return "黄山"; case "03": return "潢川"; case "04": return "芜湖"; case "05": return "马鞍山"; case "06": return "滁州"; case "07": return "淮北"; case "08": return "安庆"; case "09": return "宿州"; default: return "合肥"; } } private static String getEpgName(int random){ switch(random){ case 1: return "模拟节目1"; case 2: return "模拟节目2"; case 3: return "模拟节目3"; default: return "模拟节目"; } } private static ChannelEnum getServiceId() { int enumCase=0; enumCase = new Random().nextInt(20) + 1; switch(enumCase) { case 1: return ChannelEnum.CCTV1; case 2: return ChannelEnum.CCTV2; case 3: return ChannelEnum.CCTV3; case 4: return ChannelEnum.CCTV4; case 5: return ChannelEnum.CCTV5; case 6: return ChannelEnum.CCTV6; case 7: return ChannelEnum.CCTV7; case 8: return ChannelEnum.CCTV8; case 9: return ChannelEnum.BJWS; case 10: return ChannelEnum.ZJWS; case 11: return ChannelEnum.HBWS; case 12: return ChannelEnum.HNWS; case 13: return ChannelEnum.JXWS; case 14: return ChannelEnum.AHWS; case 15: return ChannelEnum.LNWS; case 16: return ChannelEnum.SZWS; default: return ChannelEnum.CCTV1; } } public static void main(String[] args) throws InterruptedException { while(true){ Random random = new Random(); // Long startTime = System.currentTimeMillis(); //随机生成一个5-10分钟的切出 Long endTime = System.currentTimeMillis()+900000+random.nextInt(300000); //间隔 Long duringTime = (endTime - startTime)/1000; //随机生成一个1-2000的TVN String tvn = random.nextInt(2000)+""; //随机生成一个1-100的serviceId //String serviceId = random.nextInt(100)+""; String aeraCode ="0"+ random.nextInt(9); String areaName = getAreaName(aeraCode); //随机生成nodeId Integer nodeId = random.nextInt(10); //随机生成一个提供商 //String opName = operatorEnum.getValue(random.nextInt(3)); int epgid = random.nextInt(3); String epgName = getEpgName(epgid); ChannelEnum channel=getServiceId(); String serviceId = channel.getKey()+""; String serviceName=channel.getValue(); // String jsonTemplate = "{\"user_code\":\""+tvn+"\",\"start_time\":"+startTime+",\"area_code\":\""+aeraCode+"\",\"end_time\":"+endTime+",\"duration_time\":"+duringTime+",\"live\":{\"service_id\":\""+serviceId+"\",\"action_type\":\"DVB\"}}"; String jsonTemplate = "{\"user_code\":\""+tvn+"\",\"area_code\":\""+aeraCode+"\",\"area_name\":\""+areaName+"\",\"start_time\":"+startTime+",\"end_time\":"+endTime+",\"duration\":"+duringTime+",\"service_id\":"+serviceId+",\"service_name\":\""+serviceName+"\",\"epg_id\":\""+epgid+"\",\"epg_name\":\""+serviceId+epgName+"\"}"; String jsonTemplate2 = "{\"user_code\":\""+tvn+"\",\"area_code\":\""+aeraCode+"\",\"area_name\":\""+areaName+"\",\"start_time\":"+startTime+",\"duration\":"+duringTime+",\"service_id\":"+serviceId+",\"service_name\":\""+serviceName+"\",\"epg_id\":\""+epgid+"\",\"epg_name\":\""+serviceId+epgName+"\"}"; System.out.println(jsonTemplate); //使用RestTemplate发送请求 RestTemplate restTemplate=new RestTemplate(); // String url="http://192.168.2.202:9200/demand_index/data/"+startTime+tvn; String url="http://192.168.2.202:9200/playback_index/data/"+startTime+tvn; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity entity = new HttpEntity(jsonTemplate, headers); System.out.println(restTemplate.exchange(url, HttpMethod.POST, entity, String.class).toString()); RestTemplate restTemplate2=new RestTemplate(); String url2="http://192.168.2.202:9200/playback_index/data/"+tvn+startTime; HttpEntity entity2 = new HttpEntity(jsonTemplate2, headers); System.out.println(restTemplate2.exchange(url2, HttpMethod.POST, entity2, String.class).toString()); Thread.sleep(1000); } } }
[ "1321269617@qq.com" ]
1321269617@qq.com
08af1677ad60cb80d74cf10805e42a0de5ea26a5
35f58a12c03e3dc622c08a56db5f7541a5301a87
/src/http/HttpServletRequest.java
5af4da716a1d905b03493c35f855d2306d821ed3
[]
no_license
hejiying/hjy
aa70d9dd9d6139de69820a6ace544e6131860c2c
03e5f0e96e753ca6135f89d6f7bc4a3fd1a44fc4
refs/heads/master
2020-08-27T22:51:22.559465
2019-10-25T11:33:19
2019-10-25T11:33:19
217,511,195
0
0
null
null
null
null
UTF-8
Java
false
false
1,207
java
package http; import java.util.HashMap; public class HttpServletRequest { private String method; private String requestURL; private String protocol; private HashMap<String, String> headerMaps = new HashMap<>(); /** * request.getRequestURL();E:\workspaces202\plants\WebContent * request.getMethod();//请求的方法 * request.getProtocol();//请求的协议版本编号 * request.getHeader("Host");//返回头域的指定的字段值 */ public HttpServletRequest (String content) { //解析请求报文 String[] lines = content.split("\r\n"); for(int i=0;i<lines.length;i++){ if(i==0){ //解析投行,以空格为间隔符 String[] topLines = lines[i].split("\\s"); method = topLines[0]; requestURL = topLines[1]; protocol =topLines[2]; }else{ String[] headerLines = lines[i].split(":\\s"); headerMaps.put(headerLines[0],headerLines[1]); } } } public String getRequestURL() { return requestURL; } public String getMethod() { return method; } public String getProtocol(){ return protocol; } public String getHeader(String header){ return headerMaps.get(header); } }
[ "BD-DELL@DESKTOP-7FU39I3" ]
BD-DELL@DESKTOP-7FU39I3
e8c4636ffd7a6e393d256309e1d7120f2efb95c0
c6637d397ef1a21b8d812bcfb63a85c628dc5700
/pta-intelligent-search-metadata-extractor/src/main/java/fi/maanmittauslaitos/pta/search/metadata/model/MetadataDownloadLink.java
ef0f756e705caf644700f5ab8c83699499828982
[ "CC-BY-4.0" ]
permissive
nlsfi/pta-intelligent-search
610bf8f7da63be18eca83b5322f91e98502ebfd8
194588904345ddaee284a8b8846c23dedbc1cc2c
refs/heads/master
2022-11-23T16:04:30.629191
2020-12-02T06:32:12
2020-12-02T06:32:12
112,617,376
2
3
null
2022-11-16T04:32:03
2017-11-30T13:54:57
Java
UTF-8
Java
false
false
744
java
package fi.maanmittauslaitos.pta.search.metadata.model; public class MetadataDownloadLink { private String title; private String protocol; private String url; private String desc; public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
[ "nils.stenholm@nls.fi" ]
nils.stenholm@nls.fi
14444047b7063e3d2ec5f3b4afb601f69ac274dc
07d789d9fa4c28f0960600cb0ae38f8757bab7a6
/src/behavioral/command/CommandDemo.java
92322a9058b9a6b22f6a6adbace37d950df81e58
[]
no_license
HugoLiconV/Design-Patterns-Java
c859eabdee2df6096c3d0c58f1e0a63c0216b459
f043f631ae13403828d4155b6d3f02e90d7d0ea3
refs/heads/master
2020-03-28T23:59:43.537579
2018-09-24T01:34:00
2018-09-24T01:34:00
149,319,336
0
0
null
null
null
null
UTF-8
Java
false
false
4,162
java
//package behavioral.command; // //import java.awt.FlowLayout; //import java.awt.event.ActionEvent; //import java.awt.event.ActionListener; //import java.util.Stack; //import javax.swing.BoxLayout; //import javax.swing.JButton; //import javax.swing.JFrame; //import javax.swing.JPanel; //import javax.swing.JTextArea; //import javax.swing.WindowConstants; // //public class CommandDemo { // // public static void main(String[] args) { // Editor editor = new Editor(); // editor.init(); // } //} // //abstract class Command { // // public Editor editor; // private String backup; // // Command(Editor editor) { // this.editor = editor; // } // // void backup() { // backup = editor.textField.getText(); // } // // public void undo() { // editor.textField.setText(backup); // } // // public abstract boolean execute(); //} // //class CopyCommand extends Command { // // public CopyCommand(Editor editor) { // super(editor); // } // // @Override // public boolean execute() { // editor.clipboard = editor.textField.getSelectedText(); // return false; // } //} // //class PasteCommand extends Command { // // public PasteCommand(Editor editor) { // super(editor); // } // // @Override // public boolean execute() { // if (editor.clipboard == null || editor.clipboard.isEmpty()) { // return false; // } // // backup(); // editor.textField.insert(editor.clipboard, editor.textField.getCaretPosition()); // return true; // } //} // //class CutCommand extends Command { // // public CutCommand(Editor editor) { // super(editor); // } // // @Override // public boolean execute() { // if (editor.textField.getSelectedText().isEmpty()) { // return false; // } // // backup(); // String source = editor.textField.getText(); // editor.clipboard = editor.textField.getSelectedText(); // editor.textField.setText(cutString(source)); // return true; // } // // private String cutString(String source) { // String start = source.substring(0, editor.textField.getSelectionStart()); // String end = source.substring(editor.textField.getSelectionEnd(), source.length()); // return start + end; // } //} // //class CommandHistory { // // private Stack<Command> history = new Stack<>(); // // public void push(Command c) { // history.push(c); // } // // public Command pop() { // return history.pop(); // } // // public boolean isEmpty() { // return history.isEmpty(); // } //} // //class Editor { // // public JTextArea textField; // public String clipboard; // private CommandHistory history = new CommandHistory(); // // public void init() { // JFrame frame = new JFrame("Text editor (type & use buttons, Luke!)"); // JPanel content = new JPanel(); // frame.setContentPane(content); // frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); // textField = new JTextArea(); // textField.setLineWrap(true); // content.add(textField); // JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER)); // JButton ctrlC = new JButton("Ctrl+C"); // JButton ctrlX = new JButton("Ctrl+X"); // JButton ctrlV = new JButton("Ctrl+V"); // JButton ctrlZ = new JButton("Ctrl+Z"); // Editor editor = this; // ctrlC.addActionListener(e -> executeCommand(new CopyCommand(editor))); // ctrlX.addActionListener(e -> executeCommand(new CutCommand(editor))); // ctrlV.addActionListener(e -> executeCommand(new PasteCommand(editor))); // ctrlZ.addActionListener(e -> undo()); // buttons.add(ctrlC); // buttons.add(ctrlX); // buttons.add(ctrlV); // buttons.add(ctrlZ); // content.add(buttons); // frame.setSize(450, 200); // frame.setLocationRelativeTo(null); // frame.setVisible(true); // } // // private void executeCommand(Command command) { // if (command.execute()) { // history.push(command); // } // } // // private void undo() { // if (history.isEmpty()) { // return; // } // // Command command = history.pop(); // if (command != null) { // command.undo(); // } // } //}
[ "hugo_val28@hotmail.com" ]
hugo_val28@hotmail.com
bdbde7d78c4a6ccb8f59bafd5f4f8d7c52a7f9e0
b1be13a237515b5597ee20cc3a4c322343f08e8e
/multiplayer/ClientPlayer2.java
6896f6eacccb5d4bf9ee4af642882a35d194ac50
[]
no_license
ujjawal22/Ping-Pong
ccf246c9bdf1a1e4bccca29250f3d73c113a99d4
cdcb750d927b017aef7dc40f2a74202cf416792d
refs/heads/master
2016-09-12T22:12:56.236445
2016-05-02T16:40:49
2016-05-02T16:40:49
57,902,815
0
0
null
null
null
null
UTF-8
Java
false
false
13,263
java
package multiplayer; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JOptionPane; import singleplayer.AI_; import singleplayer.PingPong; public class ClientPlayer2 extends Canvas implements Runnable, KeyListener { private static final long serialVersionUID = 1L; public Ball b1 ; double speed; public final boolean diff = PingPong.diff_level; //DatagramPacket sendPacket; public static int connected; AI_ ai1, ai2; DatagramSocket clientSocket; Rectangle serverRect; Rectangle client1Rect , client2Rect, client3Rect; int player1,player2,player3,player4; //Connection info String serverIP; int serverPort; Socket socket; int a,b,c,d,e; //Frame JFrame frame; int width = 500; int height = 500; public final Dimension gameDim = new Dimension(width,height); String received; //Screen BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //Game info int pWidth1,pWidth2,pWidth3,pWidth4; int pHeight1,pHeight2,pHeight3,pHeight4; int xPos; int yPos; int sXPos; static int sYPos; int port1,port2,port3,position1,position2,position3; int c2XPos , c3XPos; int c2YPos , c3YPos; int loop; // Booleans for movement boolean moveRight = false; boolean moveLeft = false; public static boolean c2; InetAddress IPAddress, IPAddress1, IPAddress2, IPAddress3; // Scores int serverScore = 0; int client1Score = 0; int client2Score = 0; int client3Score = 0; // Ball info public int bX; public int bY; int bSize = 16; // For run private int ticks = 0; private int frames = 0; private int FPS = 0; private int UPS = 0; public double delta; // Used in the "run" method to limit the frame rate to the UPS boolean limitFrameRate = false; boolean shouldRender; private String username; //private int userid = 1; public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D / 60D; long lastTimer = System.currentTimeMillis(); delta = 0D; try { clientSocket = new DatagramSocket(); } catch (Exception e1) { e1.printStackTrace(); } while (true) { long now = System.nanoTime(); delta += (now - lastTime) / nsPerTick; lastTime = now; // If you want to limit frame rate, shouldRender = false shouldRender = false; // If the time between ticks = 1, then various things (shouldRender = true, keeps FPS locked at UPS) while (delta >= 1) { ticks++; try { tick(); render(); } catch (IOException e) { e.printStackTrace(); } delta -= 1; shouldRender = true; } if (!limitFrameRate && ticks > 0) shouldRender = true; // If you should render, render! if (shouldRender) { frames++; //render(); } // Reset stuff every second for the new "FPS" and "UPS" if (System.currentTimeMillis() - lastTimer >= 1000) { lastTimer += 1000; FPS = frames; UPS = ticks; frames = 0; ticks = 0; } } } // End run private void requestInformation() { serverIP = JOptionPane.showInputDialog("What is the IP of the server you are connecting to?"); serverPort = Integer.parseInt(JOptionPane.showInputDialog("What is the port you are connecting through?")); username = JOptionPane.showInputDialog("Enter username:"); } private void createFrame() { // Frame stuff setMinimumSize(gameDim); setMaximumSize(gameDim); setPreferredSize(gameDim); frame = new JFrame("Pong Multiplayer : "+ username ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(this, BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); if(diff == true){ pWidth1 = pWidth2 = pWidth3 = pWidth4 = 15; pHeight1 = pHeight2 = pHeight3 = pHeight4 = 40; speed=3; } else{ pWidth1 = pWidth2 = pWidth3 = pWidth4 = 15; pHeight1 = pHeight2 = pHeight3 = pHeight4 = 60; speed=4; } // Players initializing xPos = frame.getWidth()-20; yPos = 60; sXPos = 1; sYPos = 60; c2XPos = 200; c2YPos = 0; c3XPos = 200; c3YPos = 492; serverRect = new Rectangle(sXPos, sYPos, pWidth1, pHeight1); client1Rect = new Rectangle(xPos, yPos, pWidth2, pHeight2); client2Rect = new Rectangle(c2XPos, c2YPos,pHeight3,pWidth3); client3Rect = new Rectangle(c3XPos,c3YPos,pHeight4,pWidth4); b1 = new Ball(this.getWidth()/2 - 16, this.getHeight()/2 - 16); /*if(PingPong.players==3 && CreateServer.ainumber==1){ ai1 = new AI_(height-26,1); } else if(PingPong.players==4 && CreateServer.ainumber==2){ ai1 = new AI_(height-26,1); ai2 = new AI_(height-26,494); }*/ addKeyListener(this); requestFocus(); Thread thread = new Thread(this); thread.start(); } public ClientPlayer2() throws Exception { requestInformation(); //handShake(); createFrame(); c2=true; } private void movement() { if (moveLeft && c2XPos > 0) { c2XPos -= speed; } if (moveRight && ((c2XPos + pHeight3 < getWidth())) ) { c2XPos += speed; } } private void tick() throws IOException { IPAddress = InetAddress.getByName(serverIP); byte[] receiveData = new byte[1024]; byte[] sendData1 = new byte[1024]; byte[] sendData2 = new byte[1024]; byte[] sendData3 = new byte[1024]; String sentence = "2," + Integer.toString(c2XPos)+","+"0"; sendData1 = sentence.getBytes(); System.out.println(sentence); DatagramPacket sendPacket = new DatagramPacket(sendData1, sendData1.length,IPAddress, serverPort); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); System.out.println("recieve packet.."); clientSocket.receive(receivePacket); //receiveData = receivePacket.getData(); String delims = "[,]+"; received = new String(receivePacket.getData()); String[] tokens = received.split(delims); System.out.println(tokens[0] + "," ); int c = Integer.parseInt(tokens[0]); System.out.println(c + "," + tokens[2]); if (c==0){ loop++; position1 = Integer.parseInt(tokens[1]); if (loop==1){ port1 =Integer.parseInt(tokens[3]); tokens[2] = tokens[2].startsWith("/") ? tokens[2].substring(1) : tokens[2]; IPAddress1 = InetAddress.getByName(tokens[2]); System.out.println(IPAddress1 + "," + position1 + "," + port1); if((PingPong.players==3||PingPong.players==4)){ port2 =Integer.parseInt(tokens[5]); tokens[4] = tokens[4].startsWith("/") ? tokens[4].substring(1) : tokens[4]; IPAddress2 = InetAddress.getByName(tokens[4]); } if((PingPong.players==4)){ port3 =Integer.parseInt(tokens[7]); tokens[6] = tokens[6].startsWith("/") ? tokens[6].substring(1) : tokens[6]; IPAddress3 = InetAddress.getByName(tokens[6]); } } } else if (Integer.parseInt(tokens[0])==1) { position2 = Integer.parseInt(tokens[1]); } else if (Integer.parseInt(tokens[0])==3) { position3 = Integer.parseInt(tokens[1]); } if((PingPong.players==3||PingPong.players==4)){ sendData2 = sentence.getBytes(); DatagramPacket sendPacket2 = new DatagramPacket(sendData2, sendData2.length, IPAddress1, port1); clientSocket.send(sendPacket2); } if(PingPong.players==4){ sendData3 = sentence.getBytes(); DatagramPacket sendPacket3 = new DatagramPacket(sendData3, sendData3.length, IPAddress3, port3); clientSocket.send(sendPacket3); } serverRect.setBounds(sXPos, sYPos, pWidth1, pHeight1); client1Rect.setBounds(xPos, yPos, pWidth2, pHeight2); client2Rect.setBounds(c2XPos,c2YPos,pHeight3,pWidth3); client3Rect.setBounds(c3XPos,c3YPos,pHeight4,pWidth4); sYPos = position1; c3XPos = position3; yPos = position2; System.out.println(a+" "+b); movement(); b1.tick_1(this, delta); /* if(PingPong.players==3 && CreateServer.ainumber==1){ ai1.tick_1(this,delta); } else if(PingPong.players==4 && CreateServer.ainumber==2){ ai1.tick_1(this,delta); ai2.tick_1(this,delta); }*/ } private void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.setColor(Color.RED); g.fillRect(sXPos, sYPos, pWidth1, pHeight1); g.fillRect(xPos, yPos, pWidth2, pHeight2); if(PingPong.players==3||PingPong.players==4){ g.fillRect(c2XPos,c2YPos,pHeight3,pWidth3); } if(PingPong.players==4){ g.fillRect(c3XPos,c3YPos,pHeight4,pWidth4); } //g.fillRect(c2XPos,c2YPos,pHeight,pWidth); b1.render(g); // Draw scores g.setColor(Color.WHITE); if(serverScore<3){ g.drawString("Player1 : "+serverScore,5,10); } else{ g.drawString("Player1 : Lost",5,10); pWidth1 = 0; pHeight1 = 0; player1=1; } if(client1Score<3){ g.drawString("Player2 : "+client1Score,width-69,10); } else{ g.drawString("Player2 :Lost",width-78,10); pWidth2 = 0; pHeight2 = 0; player2=1; } if(PingPong.players==3){ g.setColor(Color.WHITE); if(client2Score<3){ g.drawString("Player3 : "+client2Score,(width-69)/2,10); } else{ g.drawString("Player3 : Lost",(width-69)/2,10); pWidth3=0; pHeight3=0; player3=1; } } else if(PingPong.players==4){ g.setColor(Color.WHITE); if(client2Score<3){ g.drawString("Player3 : "+client2Score,5,492); } else{ g.drawString("Player3 : Lost",5,492); pWidth3=0; pHeight3=0; player3=1; } if(client3Score<3){ g.drawString("Player4 : "+client3Score,width-69,492); } else{ g.drawString("Player4 :Lost",width-78,492); pWidth4=0; pHeight4=0; player4=1; } } if(PingPong.players==2){ if (player1==1 && player2==0){ g.drawString("Player2 wins",200,200); b1.remove(); } else if (player2==1 && player1==0){ g.drawString("Player1 wins",200,200); b1.remove(); } } else if(PingPong.players==3){ if (player1==1 && player3==1 && player2==0){ g.drawString("Player2 wins",200,200); b1.remove(); } if (player2==1 && player3==1 && player1==0){ g.drawString("Player1 wins",200,200); b1.remove(); } if(player1==1 && player2==1 && player3==0) { g.drawString("Player3 wins",200,200); b1.remove(); } } else if(PingPong.players==4){ if (player1==1 && player3==1 && player4==1 && player2==0){ g.drawString("Player2 wins",200,200); b1.remove(); } if (player2==1 && player3==1 && player4==1 && player1==0){ g.drawString("Player1 wins",200,200); b1.remove(); } if(player1==1 && player2==1 && player4==1 && player3==0) { g.drawString("Player3 wins",200,200); b1.remove(); } if(player1==1 && player2==1 && player3==1 && player4==0) { g.drawString("Player4 wins",200,200); b1.remove(); } } /*if((PingPong.players==3 || PingPong.players==4) && ainumber==1){ ai1.render(g); } else if(PingPong.players==4 && ainumber==2){ ai1.render(g); ai2.render(g); }*/ //g.drawString("P3 score: " + client2Score, getWidth()-125, 20); g.dispose(); bs.show(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT) { moveRight = true; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { moveLeft = true; } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT) { moveRight = false; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { moveLeft = false; } } public void keyTyped(KeyEvent e) { //nothing to be done here } }
[ "ujjawal22malik@gmail.com" ]
ujjawal22malik@gmail.com
9a41f824959a290570fade9e3b6d38b82df45a72
9c64d1f7ae7422aa8028802003e1845c095e2e34
/jesse04-case08-mongodb/src/main/java/com/jesse04/case08/mongodb/SpringbootMongodbApplication.java
4a9fb25ba6d4167cb4832f4a21876ad0c09ed033
[]
no_license
zhoudirui/jesse04
e6a1fcddc6005cd374e43fb5cc4beab95979ff7d
1da954450749a5d4e4cc224f4d67871251f900c7
refs/heads/master
2021-05-14T15:05:30.795570
2018-01-03T09:03:02
2018-01-03T09:03:02
115,985,123
1
0
null
null
null
null
UTF-8
Java
false
false
2,320
java
package com.jesse04.case08.mongodb; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.jesse04.case08.mongodb.dao.CustomerRepository; import com.jesse04.case08.mongodb.entity.Customer; /** * 启动mongodb * C:\Program Files\MongoDB\Server\3.4\bin * mongod.exe --dbpath E:\mongdb\data\db */ @SpringBootApplication public class SpringbootMongodbApplication implements CommandLineRunner { @Autowired private CustomerRepository repository; public static void main(String[] args) { SpringApplication.run(SpringbootMongodbApplication.class, args); } @Override public void run(String... args) throws Exception { repository.deleteAll(); // save a couple of customers repository.save(new Customer("Alice", "Smith")); repository.save(new Customer("Bob", "Smith")); // fetch all customers System.out.println("Customers found with findAll():"); System.out.println("-------------------------------"); for (Customer customer : repository.findAll()) { System.out.println(customer); } System.out.println(); // fetch an individual customer System.out.println("Customer found with findByFirstName('Alice'):"); System.out.println("--------------------------------"); System.out.println(repository.findByFirstName("Alice")); System.out.println("Customers found with findByLastName('Smith'):"); System.out.println("--------------------------------"); for (Customer customer : repository.findByLastName("Smith")) { System.out.println(customer); } } /** * Customers found with findAll(): ------------------------------- Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith'] Customer[id=58f880f589ffb696b8a6077f, firstName='Bob', lastName='Smith'] Customer found with findByFirstName('Alice'): -------------------------------- Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith'] Customers found with findByLastName('Smith'): -------------------------------- Customer[id=58f880f589ffb696b8a6077e, firstName='Alice', lastName='Smith'] Customer[id=58f880f589ffb696b8a6077f, firstName='Bob', lastName='Smith'] */ }
[ "2011zhouhang@gmail.com" ]
2011zhouhang@gmail.com
010831f16b29be8e722cc134ebb94d02e8c16a4d
ac2230a69b2088aa22436c369652db13090acef6
/src/dao/FetchproviderDao.java
b6bea1851c7a0b44aab63b058aed8dc68af13a01
[]
no_license
Virtusa15/Team-8-Car_Pooling
e37c8e9fcaa37fe76241f1107c56ec0a4c9c39ab
d5f45de97fa2261bc1e5065e7580c59e4d77aa55
refs/heads/master
2020-07-20T00:21:15.300780
2019-09-05T10:36:34
2019-09-05T10:36:34
206,538,608
0
0
null
null
null
null
UTF-8
Java
false
false
2,318
java
package dao; import java.sql.*; import java.util.ArrayList; import bean.ProviderRegisterBean; import util.DBConnection; public class FetchproviderDao { public ArrayList<ProviderRegisterBean> Fetchdata(ProviderRegisterBean p) { String origin=p.getOrigin(); String destination=p.getDestination(); ArrayList<ProviderRegisterBean> arrayList = new ArrayList<ProviderRegisterBean>(); try { Connection con=DBConnection.createConnection(); PreparedStatement ps=con.prepareStatement("SELECT * FROM V_PROVIDER WHERE origin=? AND destination=? and AVAILABLE_SEATS>0"); ps.setString(1,origin); ps.setString(2,destination); ResultSet rs=ps.executeQuery(); while(rs.next()) { ProviderRegisterBean providerRegisterBean = new ProviderRegisterBean(); providerRegisterBean.setId(rs.getString(1)); providerRegisterBean.setName(rs.getString(2)); providerRegisterBean.setStart_time(rs.getString(7)); providerRegisterBean.setReturn_time(rs.getString(8)); providerRegisterBean.setAvailable_seats(rs.getString(12)); providerRegisterBean.setMobile(rs.getString(4)); providerRegisterBean.setEmail(rs.getString(10)); arrayList.add(providerRegisterBean); } } catch(Exception e) { e.printStackTrace(); } return arrayList; } public ArrayList<ProviderRegisterBean> Fetchproviderdata(ProviderRegisterBean p) { String id=p.getId(); int pid=Integer.parseInt(id); ArrayList<ProviderRegisterBean> arrayList = new ArrayList<ProviderRegisterBean>(); try { Connection con=DBConnection.createConnection(); PreparedStatement ps=con.prepareStatement("SELECT * FROM V_PROVIDER WHERE provider_id=?"); ps.setInt(1,pid); ResultSet rs=ps.executeQuery(); while(rs.next()) { ProviderRegisterBean providerRegisterBean = new ProviderRegisterBean(); providerRegisterBean.setId(rs.getString(1)); providerRegisterBean.setName(rs.getString(2)); providerRegisterBean.setMobile(rs.getString(4)); providerRegisterBean.setEmail(rs.getString(10)); providerRegisterBean.setAvailable_seats(rs.getString(12)); arrayList.add(providerRegisterBean); } } catch(Exception e) { e.printStackTrace(); } return arrayList; } }
[ "Admin@DESKTOP-D9ST29R" ]
Admin@DESKTOP-D9ST29R
8360980e877785175462f0473eabf4912d6db7e4
19f3e4df408f56e7f4fe20c8cdecedbd71d9887e
/37_java/classes-dex2jar/net/youmi/android/banner/g.java
3b478b3cbb1f7bb160ec07f810763d3b9af6a5f7
[]
no_license
XuGuangHuiGit/softwareSecurity
5ed6dfe1316672a061dbe03bf235c452342b296f
9f1eb53d3e06751fe17dbf43a5d7a5fa95051313
refs/heads/master
2020-04-08T01:42:39.467579
2018-11-24T05:46:28
2018-11-24T05:46:28
158,906,469
0
0
null
null
null
null
UTF-8
Java
false
false
747
java
package net.youmi.android.banner; import android.os.Handler; import android.os.Message; class g extends Handler { g(e parame) {} public void handleMessage(Message paramMessage) { switch (paramMessage.what) { } for (;;) { super.handleMessage(paramMessage); return; h localh = BannerManager.getBannerObject(e.a(this.a)); String str = localh.g(); if ((str == null) || (str.equals(""))) { this.a.a(localh); } else { e.a(this.a, localh); } } } } /* Location: C:\Users\guanghui\Desktop\软件安全\37\classes-dex2jar.jar * Qualified Name: net.youmi.android.banner.g * JD-Core Version: 0.7.0.1 */
[ "xgh.bupt@gmail.com" ]
xgh.bupt@gmail.com
8f686ab3b710b803335803e465a82ce174894144
72a95cb8368e22381170e37525071875dc5a2cca
/app/src/main/java/com/pixels/Gestion/ofertas_aplicadas.java
fddce36896f05bcee78fe6f4dc40e09d5a3c7d18
[]
no_license
Raynor119/Gestion-engresados
d34c43fe59add293629286ac2817524db26d3678
055646cf40edb0f0de3dfa6f8c140745043a4077
refs/heads/master
2020-06-05T09:07:29.927972
2019-08-07T01:22:42
2019-08-07T01:22:42
192,384,401
0
0
null
null
null
null
UTF-8
Java
false
false
4,161
java
package com.pixels.Gestion; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ofertas_aplicadas extends AppCompatActivity { private ExpandableListView expandableListView; private ExpandableListAdapter expandableListAdapter; private List<String> expandableListNombres; private HashMap<String, tbofertas> listaContactos; private int lastExpandedPosition = -1; private Activity activity; private List<tbofertas> ofert=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ofertas_aplicadas); ip ccc=new ip(); activity=this; this.expandableListView = findViewById(R.id.expandableListView); final String ipt=ccc.ip(); String Url="http://"+ipt+":80/AppAndroid/ofertalist.php"; JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { JSONObject jo = null; //Toast.makeText(getApplicationContext(), "entro2",Toast.LENGTH_LONG).show(); for (int i = 0; i < response.length(); i++) { try { //Toast.makeText(getApplicationContext(), "entro3",Toast.LENGTH_LONG).show(); jo = response.getJSONObject(i); ofert.add(new tbofertas(jo.getString("titulo"), jo.getString("descrip"), jo.getString("link"),jo.getString("Rango"))); } catch (JSONException e) { Toast.makeText(getApplicationContext(), "puta", Toast.LENGTH_LONG).show(); } } HashMap<String, tbofertas> listaC = new HashMap<>(); for(int i=0;i<ofert.size();i++){ listaC.put(ofert.get(i).getTitulo(), new tbofertas(ofert.get(i).getTitulo(),ofert.get(i).getDescrip(),ofert.get(i).getLink(),ofert.get(i).getRango())); } listaContactos = listaC; expandableListNombres = new ArrayList<>(listaContactos.keySet()); expandableListAdapter = new CustomExpandableListAdapter(getApplicationContext(), expandableListNombres, listaContactos); ((CustomExpandableListAdapter) expandableListAdapter).setInflater(activity); expandableListView.setAdapter(expandableListAdapter); expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { if(lastExpandedPosition != -1 && groupPosition != lastExpandedPosition){ expandableListView.collapseGroup(lastExpandedPosition); } lastExpandedPosition = groupPosition; } }); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "errorConexion",Toast.LENGTH_LONG).show(); } }); RequestQueue requestQueue; requestQueue= Volley.newRequestQueue(getApplicationContext()); requestQueue.add(jsonArrayRequest); } }
[ "saibod15@hotmail.es" ]
saibod15@hotmail.es
4ecf086c2477b147dd60cdbf5d54985924a5b6f5
37e6e35f93320c1335a5aa77d54730000565eb51
/7Week/CatService/src/main/java/com/revature/remote/UserClient.java
32c147ab0dba764d33dd83586749af23adc4521b
[]
no_license
1910javareact/Demos
618431f484ce708804a0165d8fd1a6f21aa06b50
9a04e3a035441b416caf053950fe2775f641de20
refs/heads/master
2022-12-13T02:03:57.050305
2020-01-05T21:37:16
2020-01-05T21:37:16
218,315,309
2
3
null
2022-12-11T15:06:59
2019-10-29T15:06:47
Java
UTF-8
Java
false
false
429
java
package com.revature.remote; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import com.revature.models.User; @FeignClient(name = "user-service", fallback = UserClientFallback.class) public interface UserClient { //inside this interface, I write methods like in a controller and it will generate the impls @GetMapping("users") public User getAllUser(); }
[ "abatson94@gmail.com" ]
abatson94@gmail.com
a3065b01cba4d8a63feff327e18638661405a653
b1cd7a0934d863f4c8ded4b731d8ab85937116cf
/WeatherFunny/app/src/main/java/com/techkids/weatherfunny/models/json/api_apixu/Current.java
9590521c976c5cbdf97af2c295feb846d8b6b028
[]
no_license
tranthanhtu/hackathonAD5_Weather
6b24d104d73c9af9f25e2c4d70212f08b0901486
8a3cb2e22ad9a5960ea25f330c0e891e3e8bfec0
refs/heads/master
2021-01-12T07:28:35.163811
2017-01-15T18:31:37
2017-01-15T18:31:37
76,967,528
0
1
null
null
null
null
UTF-8
Java
false
false
3,456
java
package com.techkids.weatherfunny.models.json.api_apixu; import com.google.gson.annotations.SerializedName; import io.realm.RealmObject; /** * Created by Hau on 08/01/2017. */ public class Current extends RealmObject { @SerializedName("last_updated_epoch") private String lastUpdateEpoch; @SerializedName("last_updated") private String lastUpdate; @SerializedName("temp_c") private String tempC; @SerializedName("temp_f") private String tempF; @SerializedName("is_day") private String isDay; @SerializedName("condition") private Condition condition; @SerializedName("wind_mph") private String windMph; @SerializedName("wind_kph") private String windKph; @SerializedName("wind_degree") private String windDegree; @SerializedName("wind_dir") private String windDir; @SerializedName("pressure_mb") private String pressureMb; @SerializedName("pressure_in") private String pressureIn; @SerializedName("precip_mm") private String precipMM; @SerializedName("precip_in") private String precipIn; @SerializedName("humidity") private String humidity; @SerializedName("cloud") private String cloud; @SerializedName("feelslike_c") private String feelslikeC; @SerializedName("feelslike_f") private String feelslikeF; public String getLastUpdateEpoch() { return lastUpdateEpoch; } public String getLastUpdate() { return lastUpdate; } public String getTempC() { return tempC; } public String getTempF() { return tempF; } public String getIsDay() { return isDay; } public Condition getCondition() { return condition; } public String getWindMph() { return windMph; } public String getWindKph() { return windKph; } public String getWindDegree() { return windDegree; } public String getWindDir() { return windDir; } public String getPressureMb() { return pressureMb; } public String getPressureIn() { return pressureIn; } public String getPrecipMM() { return precipMM; } public String getPrecipIn() { return precipIn; } public String getHumidity() { return humidity; } public String getCloud() { return cloud; } public String getFeelslikeC() { return feelslikeC; } public String getFeelslikeF() { return feelslikeF; } @Override public String toString() { return "Current{" + "lastUpdateEpoch=" + lastUpdateEpoch + ", lastUpdate='" + lastUpdate + '\'' + ", tempC=" + tempC + ", tempF=" + tempF + ", isDay=" + isDay + ", condition=" + condition + ", windMph=" + windMph + ", windKph=" + windKph + ", windDegree=" + windDegree + ", windDir='" + windDir + '\'' + ", pressureMb=" + pressureMb + ", pressureIn=" + pressureIn + ", precipMM=" + precipMM + ", precipIn=" + precipIn + ", humidity=" + humidity + ", cloud=" + cloud + ", feelslikeC=" + feelslikeC + ", feelslikeF=" + feelslikeF + '}'; } }
[ "hauchu1196@gmail.com" ]
hauchu1196@gmail.com
06c1d297cfb46d38745c2f5aaae796f64abdf6f3
7c9da4aa06bfe1acee4eeff7ea285277809ca800
/src/test/java/OCRTest.java
488817f651bf40007916f042f59111bc0921b611
[]
no_license
qq484480806/baidu-ocr
f25166bc05ff1bcddc4aac0b6d56d9d72f77c3b8
6ff204317d68d59aaa9baaf5fd7f65bcb603285f
refs/heads/master
2023-04-20T04:22:44.158806
2017-08-12T07:03:09
2017-08-12T07:03:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,734
java
import com.baidu.aip.ocr.AipOcr; import com.luckysweetheart.ocr.dto.IdentityInfo; import com.luckysweetheart.ocr.exception.OCRException; import com.luckysweetheart.ocr.service.BaiduOCRService; import com.luckysweetheart.ocr.util.ThumbnailUtilService; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.io.File; import java.io.IOException; /** * Created by yangxin on 2017/8/11. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:/spring/spring-context.xml"}) public class OCRTest { String imagePath = "C:\\Users\\dp\\Desktop\\证件识别\\IMG_4541.JPG"; //String imagePath = "C:\\Users\\dp\\Desktop\\lucky-web.png"; String bankImg = "C:\\Users\\dp\\Desktop\\证件识别\\IMG_4536.JPG"; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private AipOcr aipOcr; @Resource private ThumbnailUtilService thumbnailUtilService; @Resource private BaiduOCRService baiduOCRService; @Test public void test1() throws IOException, OCRException { byte[] bytes = FileUtils.readFileToByteArray(new File(imagePath)); IdentityInfo identityInfo = baiduOCRService.getIdentityInfo(bytes,true); System.out.println(identityInfo); } @Test public void test2() throws Exception{ byte[] bytes = FileUtils.readFileToByteArray(new File(bankImg)); System.out.println(baiduOCRService.getBankCardInfo(bytes)); } }
[ "981987024@qq.com" ]
981987024@qq.com
bd623a7a5055e09823f3f64b826c4ce8f3a05aef
1d04e828191505f259184c1ecb825108a43223a5
/app/src/main/java/com/critics/taste/MainActivity.java
940af19159cda3f2a94c07914ee33b08a9aaf10c
[]
no_license
seyedjafariy/Taste
36b75a0327d07a1b0db42576388b8f4635781b67
88e662ff57eacb9527db1100c2304e7731e96edd
refs/heads/master
2022-01-09T15:01:22.429691
2019-04-23T14:29:39
2019-04-23T14:29:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,994
java
package com.critics.taste; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProvider; import android.arch.lifecycle.ViewModelProviders; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.critics.taste.MainActivityFeature.DaggerMainActivityComponent; import com.critics.taste.MainActivityFeature.MainActivityComponent; import com.critics.taste.MainActivityFeature.MainActivityModule; import com.critics.taste.adapter.SearchResultAdapter; import com.critics.taste.application.TasteApplication; import com.critics.taste.database.entity.Result; import com.critics.taste.database.entity.SearchResultEntity; import com.critics.taste.interfaces.TasteDiveWebservice; import com.critics.taste.repositories.SearchRepository; import com.critics.taste.view_models.SearchViewModel; import java.util.List; import javax.inject.Inject; public class MainActivity extends AppCompatActivity { private List<Result> mResults; private View.OnClickListener onItemClickListener = new View.OnClickListener() { @Override public void onClick(View view) { RecyclerView.ViewHolder viewHolder = (RecyclerView.ViewHolder) view.getTag(); int position = viewHolder.getAdapterPosition(); Result resultItem = mResults.get(position); Toast.makeText(MainActivity.this, "You Clicked: " + resultItem.getName(), Toast.LENGTH_LONG).show(); } }; @Inject SearchRepository searchRepository; @Inject TasteDiveWebservice tasteDiveWebservice; @Inject SearchResultAdapter searchResultAdapter; @Inject ViewModelProvider.Factory viewModelFactory; private SearchViewModel viewModel; EditText searchEditText; Spinner searchTypeSpinner; Spinner searchLimitSpinner; Button searchLiveButton; Button searchOfflineButton; RecyclerView recyclerView; String userSearchQuery; String userSearchType; String userSearchLimit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //INITIALIZE DAGGER COMPONENT MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder() .mainActivityModule(new MainActivityModule(this)) .appComponent(TasteApplication.get(this).getAppComponent()) .build(); mainActivityComponent.injectMainActivity(this); //INITIALIZE VIEWS searchEditText = findViewById(R.id.search_editText); searchTypeSpinner = findViewById(R.id.type_spinner); searchLimitSpinner = findViewById(R.id.limit_spinner); initializeSpinners(); searchLiveButton = findViewById(R.id.search_live_button); searchOfflineButton = findViewById(R.id.search_offline_button); recyclerView = findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(searchResultAdapter); searchResultAdapter.setOnItemClickListener(onItemClickListener); //INITIALIZE VIEWMODEL viewModel = ViewModelProviders.of(this, this.viewModelFactory).get(SearchViewModel.class); searchLiveButton.setOnClickListener((View view) -> { userSearchQuery = searchEditText.getText().toString(); userSearchType = searchTypeSpinner.getSelectedItem().toString(); userSearchLimit = searchLimitSpinner.getSelectedItem().toString(); viewModel.init(userSearchQuery, userSearchType, userSearchLimit); viewModel.getSearchResultEntityLiveData() .observe(MainActivity.this, searchResultEntities -> searchResultAdapter.setItems(searchResultEntities)); }); } public void initializeSpinners() { ArrayAdapter<CharSequence> typeSpinnerAdapter = ArrayAdapter .createFromResource(this, R.array.search_result_type , android.R.layout.simple_spinner_item); typeSpinnerAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); searchTypeSpinner.setAdapter(typeSpinnerAdapter); ArrayAdapter<CharSequence> limitSpinnerAdapter = ArrayAdapter .createFromResource(this, R.array.search_result_limit , android.R.layout.simple_spinner_item); limitSpinnerAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); searchLimitSpinner.setAdapter(limitSpinnerAdapter); } }
[ "shayansakhaeidev@gmail.com" ]
shayansakhaeidev@gmail.com
3696b1c495ade19303bcbe7c03d902bcf3e4ec1b
1302a788aa73d8da772c6431b083ddd76eef937f
/WORKING_DIRECTORY/frameworks/support/v7/recyclerview/tests/src/android/support/v7/widget/StaggeredGridLayoutManagerWrapContentTest.java
5021ecb7872bf6a714e87cd2b2e28bd39b059c04
[]
no_license
rockduan/androidN-android-7.1.1_r28
b3c1bcb734225aa7813ab70639af60c06d658bf6
10bab435cd61ffa2e93a20c082624954c757999d
refs/heads/master
2021-01-23T03:54:32.510867
2017-03-30T07:17:08
2017-03-30T07:17:08
86,135,431
2
1
null
null
null
null
UTF-8
Java
false
false
6,328
java
/* * Copyright (C) 2016 The Android Open Source Project * * 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 android.support.v7.widget; import static android.support.v7.widget.BaseWrapContentWithAspectRatioTest.MeasureBehavior; import static android.support.v7.widget.BaseWrapContentWithAspectRatioTest.WrapContentAdapter; import static android.support.v7.widget.StaggeredGridLayoutManager.HORIZONTAL; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import android.graphics.Rect; import android.os.Build; import android.support.test.filters.SdkSuppress; import android.test.suitebuilder.annotation.MediumTest; import android.view.Gravity; import android.view.View; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.List; @MediumTest @RunWith(Parameterized.class) public class StaggeredGridLayoutManagerWrapContentTest extends BaseWrapContentTest { int mOrientation = StaggeredGridLayoutManager.VERTICAL; public StaggeredGridLayoutManagerWrapContentTest(Rect padding) { super(new WrapContentConfig(false, false, padding)); } @Parameterized.Parameters(name = "paddingRect={0}") public static List<Rect> params() { return Arrays.asList( new Rect(0, 0, 0, 0), new Rect(5, 0, 0, 0), new Rect(0, 3, 0, 0), new Rect(0, 0, 2, 0), new Rect(0, 0, 0, 7), new Rect(3, 5, 7, 11) ); } @SdkSuppress(minSdkVersion = Build.VERSION_CODES.M) @Test public void testUnspecifiedWithHint() throws Throwable { unspecifiedWithHintTest(mOrientation == StaggeredGridLayoutManager.HORIZONTAL); } @Test public void testSimple() throws Throwable { TestedFrameLayout.FullControlLayoutParams lp = mWrapContentConfig.toLayoutParams(WRAP_CONTENT, WRAP_CONTENT); WrapContentAdapter adapter = new WrapContentAdapter( new MeasureBehavior(10, 10, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(10, 15, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(10, 20, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(20, 10, WRAP_CONTENT, WRAP_CONTENT) ); Rect[] expected = new Rect[] { new Rect(0, 0, 10, 10), new Rect(20, 0, 30, 15), new Rect(40, 0, 50, 20), new Rect(0, 10, 20, 20) }; layoutAndCheck(lp, adapter, expected, 60, 20); } @Test public void testSimpleHorizontal() throws Throwable { mOrientation = HORIZONTAL; TestedFrameLayout.FullControlLayoutParams lp = mWrapContentConfig.toLayoutParams(WRAP_CONTENT, WRAP_CONTENT); WrapContentAdapter adapter = new WrapContentAdapter( new MeasureBehavior(10, 10, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(15, 10, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(20, 10, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(10, 20, WRAP_CONTENT, WRAP_CONTENT) ); Rect[] expected = new Rect[] { new Rect(0, 0, 10, 10), new Rect(0, 20, 15, 30), new Rect(0, 40, 20, 50), new Rect(10, 0, 20, 20) }; layoutAndCheck(lp, adapter, expected, 20, 60); } @Test public void testUnspecifiedWidth() throws Throwable { TestedFrameLayout.FullControlLayoutParams lp = mWrapContentConfig.toLayoutParams(WRAP_CONTENT, WRAP_CONTENT); lp.wSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); WrapContentAdapter adapter = new WrapContentAdapter( new MeasureBehavior(2000, 10, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(500, 15, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(400, 20, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(50, 10, MATCH_PARENT, WRAP_CONTENT) ); Rect[] expected = new Rect[] { new Rect(0, 0, 2000, 10), new Rect(2000, 0, 2500, 15), new Rect(4000, 0, 4400, 20), new Rect(0, 10, 2000, 20) }; layoutAndCheck(lp, adapter, expected, 6000, 20); } @Test public void testUnspecifiedHeight() throws Throwable { TestedFrameLayout.FullControlLayoutParams lp = mWrapContentConfig.toLayoutParams(WRAP_CONTENT, WRAP_CONTENT); lp.hSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); WrapContentAdapter adapter = new WrapContentAdapter( new MeasureBehavior(10, 4000, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(10, 5500, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(10, 3000, WRAP_CONTENT, WRAP_CONTENT), new MeasureBehavior(20, 100, WRAP_CONTENT, WRAP_CONTENT) ); Rect[] expected = new Rect[] { new Rect(0, 0, 10, 4000), new Rect(20, 0, 30, 5500), new Rect(40, 0, 50, 3000), new Rect(40, 3000, 60, 3100) }; layoutAndCheck(lp, adapter, expected, 60, 5500); } @Override RecyclerView.LayoutManager createLayoutManager() { return new StaggeredGridLayoutManager(3, mOrientation); } @Override protected int getVerticalGravity(RecyclerView.LayoutManager layoutManager) { return Gravity.TOP; } @Override protected int getHorizontalGravity(RecyclerView.LayoutManager layoutManager) { return Gravity.LEFT; } }
[ "duanliangsilence@gmail.com" ]
duanliangsilence@gmail.com
a6d65998291ffc646cb1e8f4dcc8bb2f6aac7c6f
65a09e9f4450c6133e6de337dbba373a5510160f
/naifg28/src/main/java/co/simasoft/models/GroupIdsTypes.java
68455b1332bb136dbc6f66160b91b49f8f18e3d7
[]
no_license
nelsonjava/simasoft
c0136cdf0c208a5e8d01ab72080330e4a15b1261
be83eb8ef67758be82bbd811b672572eff1910ee
refs/heads/master
2021-01-23T15:21:01.981277
2017-04-27T12:46:16
2017-04-27T12:46:16
27,980,384
0
0
null
null
null
null
UTF-8
Java
false
false
3,162
java
package co.simasoft.models; import java.io.Serializable; import java.util.Set; import java.util.HashSet; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; import javax.persistence.GenerationType; import javax.persistence.GeneratedValue; import javax.persistence.FetchType; import javax.persistence.Column; import javax.persistence.Lob; import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import javax.persistence.OneToOne; import javax.persistence.OneToMany; import javax.persistence.ManyToOne; import javax.persistence.ManyToMany; import co.simasoft.models.*; import org.hibernate.search.annotations.Resolution; import org.hibernate.search.annotations.DateBridge; import javax.persistence.Temporal; import javax.persistence.TemporalType; // @Indexed @Entity @XmlRootElement public class GroupIdsTypes implements Serializable { private static final long serialVersionUID = 1L; @Id @DocumentId @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Version private Integer optlock; private double orden; @Lob @Column(nullable = true, unique = false) // @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO) private String observations; @Column(nullable = false, unique = true) // @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO) private String name; @OneToMany(mappedBy = "groupIdsTypes") private Set<GroupIds> groupIds = new HashSet<GroupIds>(); public GroupIdsTypes() { } public GroupIdsTypes(String name) { this.name = name; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Integer getOptlock() { return this.optlock; } public void setOptlock(Integer optlock) { this.optlock = optlock; } public double getOrden() { return this.orden; } public void setOrden(double orden) { this.orden = orden; } public String getObservations() { return observations; } public void setObservations(String observations) { this.observations = observations; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<GroupIds> getGroupIds() { return groupIds; } public void setGroupIds(Set<GroupIds> groupIds) { this.groupIds = groupIds; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object ojt) { if (this == ojt) return true; if (ojt == null) return false; if (getClass() != ojt.getClass()) return false; GroupIdsTypes other = (GroupIdsTypes) ojt; if (id == null) { if (other.id != null) { return false; } } else { if (!id.equals(other.id)) { return false; } } return true; } } // entity
[ "nelsonjava@gmail.com" ]
nelsonjava@gmail.com
1d9d55befa87de3d9ba7a2f8c85ff83e3dd66bc9
b0aced10eb6a2df660c3196aafbca92ccbdf49f4
/xueZhuLi10/src/main/java/com/jsy_jiaobao/main/personalcenter/QiuZhiSuggestShowRecommentActivity.java
80bb219e51cd03e021d1b74dff4d1d81adbc25e6
[]
no_license
JinShiYe-Admin/JiaoBao1.0-andr
7f1be969d72471f2666126c414d027d9247cc5bf
566d9b1d395159615b5b0bcc3fc02570357eb1ec
refs/heads/master
2023-02-06T16:28:24.754755
2020-12-29T02:42:24
2020-12-29T02:42:24
64,978,678
0
0
null
null
null
null
UTF-8
Java
false
false
12,254
java
package com.jsy_jiaobao.main.personalcenter; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.jsy.xuezhuli.utils.ACache; import com.jsy.xuezhuli.utils.Constant; import com.jsy.xuezhuli.utils.EventBusUtil; import com.jsy.xuezhuli.utils.StringUtils; import com.jsy.xuezhuli.utils.ToastUtil; import com.jsy.xuezhuli.utils.WebSetUtils; import com.jsy_jiaobao.customview.CusListView; import com.jsy_jiaobao.main.BaseActivity; import com.jsy_jiaobao.main.R; import com.jsy_jiaobao.po.qiuzhi.AnswerItem; import com.jsy_jiaobao.po.qiuzhi.QuestionIndexItem; import com.jsy_jiaobao.po.qiuzhi.RecommentDetails; import com.jsy_jiaobao.po.qiuzhi.RecommentIndexItem; import com.jsy_jiaobao.po.qiuzhi.WatchedEntityIndexItem; import com.jsy_jiaobao.po.qiuzhi.Watcher; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.HashMap; /** * 推荐详情页面 * * @author admin */ public class QiuZhiSuggestShowRecommentActivity extends BaseActivity implements OnRefreshListener2<ScrollView>, OnClickListener, Watcher, OnItemClickListener { public static HashMap<String, Drawable> cache = new HashMap<>(); private PullToRefreshScrollView mPullRefreshScrollView; private RecommentIndexItem recomment;// 回答 private Context mContext; private TextView tv_question;// 问题标题 private TextView tv_topic;// 所属话题 private TextView tv_answernum;// 回答数量 private TextView tv_attnum;// 关注数量 private TextView tv_clicknum;// 点击数量 private LinearLayout layout_deal; private QiuZhiSuggestAnswerListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { if (savedInstanceState.getSerializable("QuestionIndexItem") instanceof RecommentIndexItem) { recomment = (RecommentIndexItem) savedInstanceState .getSerializable("QuestionIndexItem"); } } else { initPassData(); } initViews(); } /** * @method 自定义方法 * @功能 获取Intent 携带数据 */ public void initPassData() { Intent getPass = getIntent(); if (getPass != null) { Bundle bundle = getPass.getExtras(); if (bundle != null) { if (bundle.getSerializable("QuestionIndexItem") instanceof RecommentIndexItem) { recomment = (RecommentIndexItem) bundle .getSerializable("QuestionIndexItem"); } } } } /** * @功能 保存可能意外销毁的数据 */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("QuestionIndexItem", recomment); } /** * @功能 初始化界面 注册监听 等 */ private void initViews() { setContentLayout(R.layout.activity_qiuzhi_question_answerlist); mContext = this; getWindow().setBackgroundDrawable(null); QiuZhiQuestionAnswerListActivityController.getInstance().setContext( this); WatchedEntityIndexItem.getInstance().addWatcher(this); mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview); tv_question = (TextView) findViewById(R.id.qiuzhi_question_tv_question); tv_topic = (TextView) findViewById(R.id.qiuzhi_question_tv_topic); tv_answernum = (TextView) findViewById(R.id.qiuzhi_question_tv_answernum); tv_attnum = (TextView) findViewById(R.id.qiuzhi_question_tv_attnum); tv_clicknum = (TextView) findViewById(R.id.qiuzhi_question_tv_clicknum); CusListView listView;// listView listView = (CusListView) findViewById(R.id.qiuzhi_question_listview); TextView tv_yuanwen = (TextView) findViewById(R.id.qiuzhi_question_tv_details); LinearLayout layout_tab = (LinearLayout) findViewById(R.id.qiuzhi_question_layout_chose); layout_deal = (LinearLayout) findViewById(R.id.qiuzhi_question_layout_deal); layout_tab.setVisibility(View.GONE); layout_deal.removeAllViews(); tv_yuanwen.setText(getResources().getString(R.string.sourse_text)); tv_yuanwen.setOnClickListener(this); tv_question.setOnClickListener(this); listView.setOnItemClickListener(this); mPullRefreshScrollView.setMode(Mode.BOTH); mPullRefreshScrollView.setOnRefreshListener(this); adapter = new QiuZhiSuggestAnswerListAdapter(mContext, listView); listView.setAdapter(adapter); if (null != recomment) { adapter.setQuestion(recomment); setActionBarTitle(recomment.getQuestion().getTitle()); tv_question.setText(recomment.getQuestion().getTitle()); tv_topic.setText(recomment.getQuestion().getCategorySuject()); tv_attnum.setText(String.valueOf(recomment.getQuestion() .getAttCount())); tv_answernum.setText(String.valueOf(recomment.getQuestion() .getAnswersCount())); tv_clicknum.setText(String.valueOf(recomment.getQuestion() .getViewCount())); QiuZhiQuestionAnswerListActivityController.getInstance() .ShowRecomment(recomment.getTabid()); } } @Override public void onResume() { EventBusUtil.register(this); super.onResume(); } @Override public void onPause() { EventBusUtil.unregister(this); super.onPause(); } @Override protected void onDestroy() { layout_deal.removeAllViews(); adapter.Destroy(); adapter = null; cache.clear(); super.onDestroy(); WatchedEntityIndexItem.getInstance().removeWatcher(this); } /** * EventBus 功能模块 * * @param list list * @功能 获取网络请求返回的数据 并处理 */ @Subscribe public void onEventMainThread(ArrayList<Object> list) { int tag = (Integer) list.get(0); switch (tag) { case Constant.msgcenter_qiuzhi_ShowRecomment: mPullRefreshScrollView.onRefreshComplete(); RecommentDetails recomment1 = (RecommentDetails) list.get(1); if (null != recomment1) { // 回答不为空 if (null != recomment1.getQuestion()) { // 回答的问题部位空 tv_question.setText(recomment1.getQuestion().getTitle()); tv_topic.setText(recomment1.getQuestion() .getCategorySuject()); tv_attnum.setText(String.valueOf(recomment1.getQuestion() .getAttCount())); tv_answernum.setText(String.valueOf(recomment1 .getQuestion().getAnswersCount())); tv_clicknum.setText(String.valueOf(recomment1.getQuestion() .getViewCount())); layout_deal.removeAllViews(); layout_deal.setPadding(10, 0, 10, 0); final WebView content = new WebView(this); // 设置webView属性 WebSetUtils.getWebSetting(this, content); String url = recomment1.getQuestion() .getKnContent(); // 判断回复内容是否为空,不为空则加载url if (url != null && url.length() > 0) { content.loadDataWithBaseURL( null, StringUtils.xml2webview(url.replaceAll("width", "").replaceAll("height", "")), "text/html", "utf-8", null); layout_deal.addView(content); } } else { ACache.get(getApplicationContext(), "qiuzhi").put("isOld", "false"); ToastUtil.showMessage(mContext, R.string.this_question_deleted); mPullRefreshScrollView.setVisibility(View.GONE); } adapter.setData(recomment1.getAnswers()); adapter.notifyDataSetChanged(); } else { ACache.get(getApplicationContext(), "qiuzhi").put("isOld", "false"); ToastUtil.showMessage(mContext, R.string.this_question_deleted); mPullRefreshScrollView.setVisibility(View.GONE); } break; default: break; } } /** * 覆写接口 * * @功能 各种点击事件 */ @Override public void onClick(View v) { switch (v.getId()) { // 详情 问题标题的点击事件 case R.id.qiuzhi_question_tv_details: case R.id.qiuzhi_question_tv_question: Intent intent = new Intent(mContext, QiuZhiQuestionAnswerListActivity.class); intent.putExtra("QuestionIndexItem", recomment.getQuestion()); startActivity(intent); break; default: break; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } /** * 系统返回按键 结束当前Activity */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); return true; } return super.onKeyDown(keyCode, event); } /** * 下拉刷新 * * @功能 重新请求数据 */ @Override public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) { if (null != recomment) { QiuZhiQuestionAnswerListActivityController.getInstance() .ShowRecomment(recomment.getTabid()); } } /** * 上拉加载 ,一样重新加载 */ @Override public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) { if (null != recomment) { QiuZhiQuestionAnswerListActivityController.getInstance() .ShowRecomment(recomment.getTabid()); } else { mPullRefreshScrollView.onRefreshComplete(); } } @Override public void update(QuestionIndexItem qEntity) { if (qEntity != null) { if (recomment.getQuestion().getTabID() == qEntity.getTabID()) { tv_attnum.setText(String.valueOf(qEntity.getAttCount())); tv_answernum.setText(String.valueOf(qEntity.getAnswersCount())); tv_clicknum.setText(String.valueOf(qEntity.getViewCount())); } } } @Override public void update(AnswerItem answer) { // TODO Auto-generated method stub } @Override public void onPullPageChanging(boolean isChanging) { // TODO Auto-generated method stub } }
[ "rockan007@gmail.com" ]
rockan007@gmail.com
f8694936ab17dfcb1b37680df8f7484121810034
be2f95ab1069ca92d796c17ce5fd126e152953f3
/src/org/gotpike/pdt/PikeValidationThread.java
f6cc9f4965a87154ef0f70336d4a8261c855f926
[]
no_license
hww3/pdt
540be30daf363e2114970373e7204372e091700c
80b5f2e9cd3aa70a1bf9d0d417af0decf3d092ff
refs/heads/master
2016-09-09T17:07:16.232646
2010-04-05T22:43:55
2010-04-05T22:43:55
2,464,249
0
0
null
null
null
null
UTF-8
Java
false
false
65
java
package org.gotpike.pdt; public class PikeValidationThread { }
[ "bill@welliver.org" ]
bill@welliver.org
3d41fd08f885588f308036836f9c96abba1f1e98
ddabfa543d9cafe470232817ea6c2d2db09f8ce5
/algorithm/src/test/java/yanglifan/learn/algorithm/codility/lesson/time_complexity/TapeEquilibriumTest.java
907d68348d714132e42de6e9b572396c780dc90e
[]
no_license
yanglifan/learn
b0425792889afebe6927355a2f91e1f6dbed7de9
6488a9bc5030fe9591298cfd312b864c997dca4c
refs/heads/master
2022-12-25T09:46:38.269753
2019-11-05T08:26:19
2019-11-05T08:26:19
31,022,451
0
0
null
2022-12-10T02:44:45
2015-02-19T15:45:58
Java
UTF-8
Java
false
false
1,296
java
package yanglifan.learn.algorithm.codility.lesson.time_complexity; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class TapeEquilibriumTest { private TapeEquilibrium tapeEquilibrium = new TapeEquilibrium(); private int[] input; private int result; public TapeEquilibriumTest(List<Integer> input, int result) { this.input = new int[input.size()]; for (int i = 0; i < input.size(); i++) { this.input[i] = input.get(i); } this.result = result; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {Arrays.<Integer>asList(0, 0), 0}, {Arrays.<Integer>asList(0, 0, 0), 0}, {Arrays.<Integer>asList(1, 0, 1), 0}, {Arrays.<Integer>asList(1, 0, 0), 1}, {Arrays.<Integer>asList(-1000, 1000), 2000}, {Arrays.<Integer>asList(3, 1, 2, 4, 3), 1} }); } @Test public void test() { assertEquals(result, tapeEquilibrium.run(input)); } }
[ "yanglifan@gmail.com" ]
yanglifan@gmail.com
b4086d6f841c87a453f1ded06e75b54dc0ade31a
7a07ceafd824a77a2f1bd4f941e857e06bc7b504
/src/main/java/de/uni_passau/fim/se2/sa_examples/agent/SimpleClassTransformer.java
31b5ae1b406ef707e4ec4b33f397700e6525f360
[]
no_license
se2p/asm-example
a7e3b752d2bd0cd9c71bb7dfb53a6adc0f742757
ae8a752583095242417b046b360a903995e19c49
refs/heads/main
2023-04-10T23:45:32.836023
2021-04-23T06:55:48
2021-04-23T06:55:48
360,791,958
0
0
null
null
null
null
UTF-8
Java
false
false
1,383
java
package de.uni_passau.fim.se2.sa_examples.agent; import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.NotFoundException; public class SimpleClassTransformer implements ClassFileTransformer { @Override public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className.endsWith("sun/net/www/protocol/http/HttpURLConnection")) { final ClassPool classPool = ClassPool.getDefault(); try { final CtClass clazz = classPool.get("sun.net.www.protocol.http.HttpURLConnection"); for (final CtConstructor constructor : clazz.getConstructors()) { constructor.insertAfter("System.out.println(this.getURL());"); } byte[] byteCode = clazz.toBytecode(); clazz.detach(); return byteCode; } catch (NotFoundException | CannotCompileException | IOException pE) { pE.printStackTrace(); } } return null; } } // java -javaagent:build/libs/foo.jar=foobarbaz
[ "stephan.lukasczyk@uni-passau.de" ]
stephan.lukasczyk@uni-passau.de
7a60744810824ba9d79e8b47b5afb665225ad293
221ae276848ea422578b02d8e729376e8f8bb0ce
/src/com/tanishk/commonthings/SwapValues.java
c7a7d6885a7a9cb8bd7a8f0b81801e28389ba4f3
[]
no_license
kchhipa4u/HotelBooking
f24a082b2b30665fa35519f73b9ed4aa01626ecd
123c0903b52eade9dc1bff34a44a05e1a244a0b4
refs/heads/master
2021-01-11T15:45:21.839980
2017-05-17T06:55:53
2017-05-17T06:55:53
79,922,865
0
0
null
null
null
null
UTF-8
Java
false
false
223
java
package com.tanishk.commonthings; public class SwapValues { public static void main(String[] args) { int x=10; int y = 20; int z = 0; z=x; x=y; y=z; System.out.println(x); System.out.println(y); } }
[ "kchhipa4u@gmail.com" ]
kchhipa4u@gmail.com
89becb628dd4aad542cd93d9c2eaffee0e2354d0
9218f59b1d4b17b809da5288f81a9ee81d447bdf
/FP1516-josprimen/src/fp/grados/tipos/NotaImpl.java
ea9c105124b37e90b8ffe9ad66dbcfb93739881d
[]
no_license
josprimen/FundamentosDeProgramacion
b9b39937a2603b78e67d555800d6578d429e09cf
0ff4ae622a3f21fcf4a8ceec834bef5335e0f002
refs/heads/master
2020-04-23T03:04:00.730964
2019-02-15T13:10:03
2019-02-15T13:10:03
170,866,548
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
3,038
java
package fp.grados.tipos; import fp.grados.excepciones.ExcepcionNotaNoValida; public class NotaImpl implements Nota{ private Asignatura asignatura; private Integer cursoAcademico; private Convocatoria convocatoria; private Double valor; private Boolean mencionHonor; public NotaImpl(Asignatura asignatura, Integer cursoAcademico, Convocatoria convocatoria, Double valor, Boolean mencionHonor){ checkValor(valor); checkMencionDeHonor(mencionHonor,valor); this.asignatura=asignatura; this.cursoAcademico=cursoAcademico; this.convocatoria=convocatoria; this.valor=valor; this.mencionHonor=mencionHonor; } public NotaImpl(Asignatura asignatura, Integer cursoAcademico, Convocatoria convocatoria, Double valor){ //ESTO LO QUE ESTÁ HACIENDO ES LLAMAR AL CONSTRUCTOR DE ARRIBA, POR ESO NO PONEMOS CHECKS, SE USAN LOS DE ARRIBA this (asignatura, cursoAcademico, convocatoria, valor,false); } private void checkValor(Double valor2){ if(valor2<0 || valor2>10){ throw new ExcepcionNotaNoValida("La nota tiene que estar entre 0 y 10"); } } private void checkMencionDeHonor(Boolean mencionDeHonor, Double valor){ if(mencionDeHonor && valor<9){ throw new ExcepcionNotaNoValida("La mención de honor se obtiene con nota superior o igual a 9"); } } public boolean equals (Object o){ boolean res = false; if (o instanceof Nota){ Nota n = (Nota) o; res = getCursoAcademico().equals(n.getCursoAcademico())&& getAsignatura().equals(n.getAsignatura())&& getConvocatoria().equals(n.getConvocatoria()); } return res; } public int hashCode(){ return getCursoAcademico().hashCode() + getAsignatura().hashCode()*31 + getConvocatoria().hashCode()*31*31; } public int compareTo(Nota n){ int res = getCursoAcademico().compareTo(n.getCursoAcademico()); if (res == 0){ res = getAsignatura().compareTo(n.getAsignatura()); if (res == 0){ res = getConvocatoria().compareTo(n.getConvocatoria()); } } return res; } @Override public Asignatura getAsignatura() { return asignatura; } @Override public Integer getCursoAcademico() { return cursoAcademico; } @Override public Convocatoria getConvocatoria() { return convocatoria; } @Override public Double getValor() { return valor; } @Override public Boolean getMencionHonor() { return mencionHonor; } public Calificacion getCalificacion() { Calificacion nota = Calificacion.SOBRESALIENTE; if(valor<5){ nota = Calificacion.SUSPENSO; } else if (valor>=5 && valor<7){ nota = Calificacion.APROBADO; } else if (valor>=7 && valor<9 ){ nota = Calificacion.NOTABLE; } else if (getMencionHonor()){ nota = Calificacion.MATRICULA_DE_HONOR; } return nota; } public String toString(){ Integer g = getCursoAcademico() +1; String cadena; cadena=String.valueOf(g).substring(2); //cadena=g.toString().substring(2, 4); return getAsignatura()+","+getCursoAcademico()+"-"+ cadena +","+getConvocatoria()+","+getValor()+","+getCalificacion(); } }
[ "jose9@10.100.60.10" ]
jose9@10.100.60.10
0b97f6123429c4152cd8ec014eb9faf5a8b443a1
184b4b538ce5e7be0973a385e498931e8fc2772a
/src/com/spoonner/alex/appkit/core/undo/RedoAction.java
9eeed0a89fb925a1cd80c82654072668ed347690
[]
no_license
Spoonner/algoVisualization
4058053b1469d08419fb086f7045066252c361f8
9d67cd4c496184931cc060865c202175cb5f5d38
refs/heads/master
2021-03-16T05:44:11.703693
2018-04-07T09:05:55
2018-04-07T09:05:55
112,342,790
0
0
null
null
null
null
UTF-8
Java
false
false
2,548
java
/* [The "BSD licence"] Copyright (c) 2005 Jean Bovet All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.spoonner.alex.appkit.core.undo; import javax.swing.*; import javax.swing.undo.CannotRedoException; import javax.swing.undo.UndoManager; import java.awt.event.ActionEvent; public class RedoAction extends AbstractAction { protected UndoManager undoManager; protected UndoAction undoAction; public RedoAction(UndoManager manager) { super("Redo"); setEnabled(false); this.undoManager = manager; } public void setUndoAction(UndoAction action) { this.undoAction = action; } public void actionPerformed(ActionEvent e) { if(!undoManager.canRedo()) return; try { undoManager.redo(); } catch (CannotRedoException ex) { ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undoManager.canRedo()) { setEnabled(true); putValue(Action.NAME, undoManager.getRedoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Redo"); } } }
[ "spoonner12@gmail.com" ]
spoonner12@gmail.com
693afb3dcc9e67950db4b88062553c9be27137fa
bad63edbd06ac66b9cf7c68847155fd8630c32ff
/src/cavaliers/ClientJeu.java
f25d6cd52a02a383ae0354d63b9b6f580bb80d13
[]
no_license
rexbut/IA_CavaliersChinois
69be20c2f416a313bcfc81373edaca25bf8a52b2
6642bdef5d1452f8aa02e2a265f0ebbd084e83ba
refs/heads/master
2021-05-15T21:35:42.762218
2017-10-11T08:22:41
2017-10-11T08:22:41
106,524,197
0
0
null
null
null
null
UTF-8
Java
false
false
4,723
java
package cavaliers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.StringTokenizer; /** * Cette classe permet de charger dynamiquement une classe de joueur, qui doit obligatoirement * implanter l'interface IJoueur. Vous lui donnez aussi en argument le nom de la machine distante * (ou "localhost") sur laquelle le serveur de jeu est lanc�, ainsi que le port sur lequel la * machine �coute. * * Exemple: >java -cp . frontieres.ClientJeu frontieres.joueurProf localhost 1234 * * Le client s'occupe alors de tout en lan?ant les m�thodes implant�es de l'interface IJoueur. Toute * la gestion r�seau est donc cach�e. * * @author L. Simon (Univ. Paris-Sud)- 2006-2008 * @see IJoueur */ public class ClientJeu { // Mais pas lors de la conversation avec l'arbitre // Vous pouvez changer cela en interne si vous le souhaitez static final int BLANC = -1; static final int NOIR = 1; static final int VIDE = 0; /** * @param args * Dans l'ordre : NomClasseJoueur MachineServeur PortEcoute */ public static void main(String[] args) { if (args.length < 3) { System.err.println("ClientJeu Usage: NomClasseJoueur MachineServeur PortEcoute"); System.exit(1); } // Le nom de la classe joueur � charger dynamiquement String classeJoueur = args[0]; // Le nom de la machine serveur a �t� donn� en ligne de commande String serverMachine = args[1]; // Le num�ro du port sur lequel on se connecte a aussi �t� donn� int portNum = Integer.parseInt(args[2]); System.out.println("Le client se connectera sur " + serverMachine + ":" + portNum); Socket clientSocket = null; IJoueur joueur; String msg, firstToken; // permet d'analyser les chaines de caract?res lues StringTokenizer msgTokenizer; // C'est la couleur qui doit jouer le prochain coup int couleurAJouer; // C'est ma couleur (quand je joue) int maCouleur; boolean jeuTermine = false; try { // initialise la socket clientSocket = new Socket(serverMachine, portNum); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // ***************************************************** System.out.print("Chargement de la classe joueur " + classeJoueur + "... "); Class<?> cjoueur = Class.forName(classeJoueur); joueur = (IJoueur) cjoueur.newInstance(); System.out.println("Ok"); // **************************************************** // Envoie de l'identifiant de votre quadrinome. out.println(joueur.binoName()); System.out.println("Mon nom de quadrinome envoy� est " + joueur.binoName()); // R�cup?re le message sous forme de chaine de caract?res msg = in.readLine(); System.out.println(msg); // Lit le contenu du message, toutes les infos du message msgTokenizer = new StringTokenizer(msg, " \n\0"); if ((msgTokenizer.nextToken()).equals("Blanc")) { System.out.println("Je suis Blanc, c'est � moi de jouer."); maCouleur = BLANC; } else { // doit etre �gal � "Noir" System.out.println("Je suis Noir, j'attends le mouvement de Blanc."); maCouleur = NOIR; } // permet d'initialiser votre joueur avec sa couleur joueur.initJoueur(maCouleur); // boucle g�n�rale de jeu do { // Lire le msg � partir du serveur msg = in.readLine(); msgTokenizer = new StringTokenizer(msg, " \n\0"); firstToken = msgTokenizer.nextToken(); if (firstToken.equals("FIN!")) { jeuTermine = true; String theWinnerIs = msgTokenizer.nextToken(); if (theWinnerIs.equals("Blanc")) { couleurAJouer = BLANC; } else { if (theWinnerIs.equals("Noir")) couleurAJouer = NOIR; else couleurAJouer = VIDE; } if (couleurAJouer == maCouleur) System.out.println("J'ai gagn�!"); joueur.declareLeVainqueur(couleurAJouer); } else if (firstToken.equals("JOUEUR")) { // On demande au joueur de jouer if ((msgTokenizer.nextToken()).equals("Blanc")) { couleurAJouer = BLANC; } else { couleurAJouer = NOIR; } if (couleurAJouer == maCouleur) { // On appelle la classe du joueur pour choisir un mouvement msg = joueur.choixMouvement(); out.println(msg); } } else if (firstToken.equals("MOUVEMENT")) { // On lit ce que joue le joueur et on l'envoie � l'autre joueur.mouvementEnnemi(msgTokenizer.nextToken()); } } while (!jeuTermine); } catch (Exception e) { System.out.println(e); } } }
[ "butbutdu45@gmail.com" ]
butbutdu45@gmail.com
88e54f7c6cf0bf22ff98a359a91bd35fc034efef
94f21a0077f69d3fb26aeec379ec3e347bfe3c47
/src/Sorting/InsertionSort.java
7451c06438a991efb9cf0fb0be4f998519ba941c
[]
no_license
raiden8051/Java_IntelliJIdea
1858818318fe5e531f2abe48ff34664d420f7844
c29485759ba21c97d6a56490cd807c9ad83d8f48
refs/heads/master
2023-02-25T21:32:26.891049
2021-01-27T14:48:41
2021-01-27T14:48:41
289,179,159
0
1
null
2020-10-02T06:23:59
2020-08-21T04:43:39
Java
UTF-8
Java
false
false
508
java
package Sorting; public class InsertionSort { public static void main(String[] args) { sort(new int[]{64,25,12,22,11}); } private static void sort(int[] arr){ int n = arr.length; for(int i=1;i<n;i++){ int key = arr[i]; int j=i-1; while(j>=0 && arr[j]>key){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } for(int i:arr) System.out.print(i+" , "); } }
[ "www.sidharth.56@gmail.com" ]
www.sidharth.56@gmail.com
63e563ce3cb20275fcaeae5054d05c248ecfdb37
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/linkedmall-20180116/src/main/java/com/aliyun/linkedmall20180116/models/DeleteItemLimitRuleResponseBody.java
26361401e3c620f62d0b6b4bbfb50a6fe933ccfe
[ "Apache-2.0" ]
permissive
aliyun/alibabacloud-java-sdk
83a6036a33c7278bca6f1bafccb0180940d58b0b
008923f156adf2e4f4785a0419f60640273854ec
refs/heads/master
2023-09-01T04:10:33.640756
2023-09-01T02:40:45
2023-09-01T02:40:45
288,968,318
40
45
null
2023-06-13T02:47:13
2020-08-20T09:51:08
Java
UTF-8
Java
false
false
1,429
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.linkedmall20180116.models; import com.aliyun.tea.*; public class DeleteItemLimitRuleResponseBody extends TeaModel { @NameInMap("Code") public String code; @NameInMap("Message") public String message; @NameInMap("Model") public Boolean model; @NameInMap("RequestId") public String requestId; public static DeleteItemLimitRuleResponseBody build(java.util.Map<String, ?> map) throws Exception { DeleteItemLimitRuleResponseBody self = new DeleteItemLimitRuleResponseBody(); return TeaModel.build(map, self); } public DeleteItemLimitRuleResponseBody setCode(String code) { this.code = code; return this; } public String getCode() { return this.code; } public DeleteItemLimitRuleResponseBody setMessage(String message) { this.message = message; return this; } public String getMessage() { return this.message; } public DeleteItemLimitRuleResponseBody setModel(Boolean model) { this.model = model; return this; } public Boolean getModel() { return this.model; } public DeleteItemLimitRuleResponseBody setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
ba9aa64633e451a62546b08ee75d0844ef9e0789
828111a9183c38e87ba650b1fb09a2b2c98f6195
/Product/Production/Adapters/General/CONNECTAdapterWeb/src/main/java/gov/hhs/fha/nhinc/subdisc/entity/EntitySubjectDiscoveryImpl.java
6bf334f6f7f7250dd735f60554d6f877a7f9d56f
[]
no_license
sahilshaikh89/CONNECT-Legacy
6a7f080087bd17420e0716305a1231a7825e7d8d
9b3b820bd151be403ba5e165dbf560061ccc5d6f
refs/heads/master
2021-01-19T10:12:21.372914
2012-02-20T20:14:26
2012-02-20T20:14:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,113
java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2010(Year date of delivery) United States Government, as represented by the Secretary of Health and Human Services. All rights reserved. * */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gov.hhs.fha.nhinc.subdisc.entity; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache; import gov.hhs.fha.nhinc.entitysubjectdiscoverysecured.EntitySubjectDiscoverySecured; import gov.hhs.fha.nhinc.entitysubjectdiscoverysecured.EntitySubjectDiscoverySecuredPortType; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.saml.extraction.SamlTokenCreator; import java.util.Map; import javax.xml.ws.BindingProvider; import org.hl7.v3.MCCIIN000002UV01; import org.hl7.v3.PIXConsumerPRPAIN201301UVRequestType; import org.hl7.v3.PIXConsumerPRPAIN201301UVSecuredRequestType; import org.hl7.v3.PIXConsumerPRPAIN201302UVRequestType; import org.hl7.v3.PIXConsumerPRPAIN201302UVSecuredRequestType; import org.hl7.v3.PIXConsumerPRPAIN201304UVRequestType; import org.hl7.v3.PIXConsumerPRPAIN201309UVRequestType; import org.hl7.v3.PIXConsumerPRPAIN201309UVResponseType; import org.hl7.v3.PIXConsumerPRPAIN201309UVSecuredRequestType; /** * * @author jhoppesc */ public class EntitySubjectDiscoveryImpl { private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(EntitySubjectDiscoveryImpl.class); private static EntitySubjectDiscoverySecured service = new EntitySubjectDiscoverySecured(); public MCCIIN000002UV01 pixConsumerPRPAIN201301UV(PIXConsumerPRPAIN201301UVRequestType request) { MCCIIN000002UV01 ack = new MCCIIN000002UV01(); try { String url = ConnectionManagerCache.getLocalEndpointURLByServiceName(NhincConstants.ENTITY_SUBJECT_DISCOVERY_SECURED_SERVICE_NAME); EntitySubjectDiscoverySecuredPortType port = getPort(url); AssertionType assertIn = request.getAssertion(); SamlTokenCreator tokenCreator = new SamlTokenCreator(); Map requestContext = tokenCreator.CreateRequestContext(assertIn, url, NhincConstants.SUBJECT_DISCOVERY_ACTION); ((BindingProvider) port).getRequestContext().putAll(requestContext); PIXConsumerPRPAIN201301UVSecuredRequestType body = new PIXConsumerPRPAIN201301UVSecuredRequestType(); body.setPRPAIN201301UV02(request.getPRPAIN201301UV02()); body.setNhinTargetCommunities(request.getNhinTargetCommunities()); ack = port.pixConsumerPRPAIN201301UV(body); } catch (Exception ex) { log.error("Failed to send entity subject discovery from proxy EJB to secure interface: " + ex.getMessage(), ex); } return ack; } public MCCIIN000002UV01 pixConsumerPRPAIN201302UV(PIXConsumerPRPAIN201302UVRequestType request) { MCCIIN000002UV01 ack = new MCCIIN000002UV01(); try { String url = ConnectionManagerCache.getLocalEndpointURLByServiceName(NhincConstants.ENTITY_SUBJECT_DISCOVERY_SECURED_SERVICE_NAME); EntitySubjectDiscoverySecuredPortType port = getPort(url); AssertionType assertIn = request.getAssertion(); SamlTokenCreator tokenCreator = new SamlTokenCreator(); Map requestContext = tokenCreator.CreateRequestContext(assertIn, url, NhincConstants.SUBJECT_DISCOVERY_ACTION); ((BindingProvider) port).getRequestContext().putAll(requestContext); PIXConsumerPRPAIN201302UVSecuredRequestType body = new PIXConsumerPRPAIN201302UVSecuredRequestType(); body.setPRPAIN201302UV02(request.getPRPAIN201302UV02()); body.setNhinTargetCommunities(request.getNhinTargetCommunities()); ack = port.pixConsumerPRPAIN201302UV(body); } catch (Exception ex) { log.error("Failed to send entity subject discovery from proxy EJB to secure interface: " + ex.getMessage(), ex); } return ack; } public MCCIIN000002UV01 pixConsumerPRPAIN201304UV(PIXConsumerPRPAIN201304UVRequestType request) { //TODO implement this method throw new UnsupportedOperationException("Not implemented yet."); } public PIXConsumerPRPAIN201309UVResponseType pixConsumerPRPAIN201309UV(PIXConsumerPRPAIN201309UVRequestType request) { PIXConsumerPRPAIN201309UVResponseType response = new PIXConsumerPRPAIN201309UVResponseType(); try { String url = ConnectionManagerCache.getLocalEndpointURLByServiceName(NhincConstants.ENTITY_SUBJECT_DISCOVERY_SECURED_SERVICE_NAME); EntitySubjectDiscoverySecuredPortType port = getPort(url); AssertionType assertIn = request.getAssertion(); SamlTokenCreator tokenCreator = new SamlTokenCreator(); Map requestContext = tokenCreator.CreateRequestContext(assertIn, url, NhincConstants.SUBJECT_DISCOVERY_ACTION); ((BindingProvider) port).getRequestContext().putAll(requestContext); PIXConsumerPRPAIN201309UVSecuredRequestType body = new PIXConsumerPRPAIN201309UVSecuredRequestType(); body.setPRPAIN201309UV02(request.getPRPAIN201309UV02()); body.setNhinTargetCommunities(request.getNhinTargetCommunities()); response = port.pixConsumerPRPAIN201309UV(body); } catch (Exception ex) { log.error("Failed to send entity subject discovery from proxy EJB to secure interface: " + ex.getMessage(), ex); } return response; } private EntitySubjectDiscoverySecuredPortType getPort(String url) { EntitySubjectDiscoverySecuredPortType port = service.getEntitySubjectDiscoverySecuredPortSoap(); log.info("Setting endpoint address to Entity Subject Discovery Secured Service to " + url); ((BindingProvider) port).getRequestContext().put(javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); return port; } }
[ "sgirrinki@yahoo.com" ]
sgirrinki@yahoo.com
4e9777e6370e3612bcc7d8f5b5206f41ff8243f9
747a95ed9358dc825d0757e180e9242489d65be4
/tankWar/TankWar2.3/src/Missile.java
beb6f78b23b838a54ccf149be68fbbdccf8f9f3a
[]
no_license
kick-pixel/mashibing-teaching-source-code
19f955073e75d89d021508c2433b4cf4467b7db6
1747fa7e87f9ab5aa00eae2da2e834b0f9163635
refs/heads/master
2021-05-30T14:13:18.204638
2015-12-26T10:27:28
2015-12-26T10:27:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,178
java
import java.awt.*; import java.util.List; public class Missile { public static final int XSPEED = 10; public static final int YSPEED = 10; public static final int WIDTH = 10; public static final int HEIGHT = 10; int x, y; Tank.Direction dir; private boolean good; private boolean live = true; private TankClient tc; public Missile(int x, int y, Tank.Direction dir) { this.x = x; this.y = y; this.dir = dir; } public Missile(int x, int y, boolean good, Tank.Direction dir, TankClient tc) { this(x, y, dir); this.good = good; this.tc = tc; } public void draw(Graphics g) { if(!live) { tc.missiles.remove(this); return; } Color c = g.getColor(); g.setColor(Color.BLACK); g.fillOval(x, y, WIDTH, HEIGHT); g.setColor(c); move(); } private void move() { switch(dir) { case L: x -= XSPEED; break; case LU: x -= XSPEED; y -= YSPEED; break; case U: y -= YSPEED; break; case RU: x += XSPEED; y -= YSPEED; break; case R: x += XSPEED; break; case RD: x += XSPEED; y += YSPEED; break; case D: y += YSPEED; break; case LD: x -= XSPEED; y += YSPEED; break; case STOP: break; } if(x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y > TankClient.GAME_HEIGHT) { live = false; } } public boolean isLive() { return live; } public Rectangle getRect() { return new Rectangle(x, y, WIDTH, HEIGHT); } public boolean hitTank(Tank t) { if(this.live && this.getRect().intersects(t.getRect()) && t.isLive() && this.good != t.isGood()) { if(t.isGood()) { t.setLife(t.getLife()-20); if(t.getLife() <= 0) t.setLive(false); } else { t.setLive(false); } this.live = false; Explode e = new Explode(x, y, tc); tc.explodes.add(e); return true; } return false; } public boolean hitTanks(List<Tank> tanks) { for(int i=0; i<tanks.size(); i++) { if(hitTank(tanks.get(i))) { return true; } } return false; } public boolean hitWall(Wall w) { if(this.live && this.getRect().intersects(w.getRect())) { this.live = false; return true; } return false; } }
[ "winjayyu@gmail.com" ]
winjayyu@gmail.com
c06ba0b736d9dca5884ec40dc9153aa779f41a34
447f6028a2c2aed78e4229133b7b549c61331c57
/Bike Game/src/main/java/ch/epfl/cs107/play/game/actor/bike/Pendule.java
8eaec3442d958da4ad1c7c7d381fd4edf0df99f4
[]
no_license
Alvaro2112/Bike_Game
871af7a5d807bdac339501432c32dbb23938cfb9
0965f27e8299c0d5a435a76158019d0e94afcbe3
refs/heads/master
2020-08-07T22:16:04.148787
2019-10-08T09:45:54
2019-10-08T09:45:54
213,602,311
0
0
null
null
null
null
UTF-8
Java
false
false
1,333
java
package ch.epfl.cs107.play.game.actor.bike; import ch.epfl.cs107.play.game.actor.Actor; import ch.epfl.cs107.play.game.actor.ActorGame; import ch.epfl.cs107.play.game.actor.GameEntity; import ch.epfl.cs107.play.math.Entity; import ch.epfl.cs107.play.math.RopeConstraintBuilder; import ch.epfl.cs107.play.math.Transform; import ch.epfl.cs107.play.math.Vector; import ch.epfl.cs107.play.window.Canvas; public class Pendule extends GameEntity implements Actor{ public Pendule(ActorGame game, boolean fixed) { super(game, fixed); } void attachPendulum(Entity boite, Entity boule, float width1, float height1,Vector rayon) { RopeConstraintBuilder ropeConstraintBuilder = getActorGame().getRope() ; ropeConstraintBuilder.setFirstEntity(boite) ; ropeConstraintBuilder.setFirstAnchor(new Vector(width1,height1)); ropeConstraintBuilder.setSecondEntity(boule) ; ropeConstraintBuilder.setSecondAnchor(rayon) ; ropeConstraintBuilder.setMaxLength(3.0f) ; ropeConstraintBuilder.setInternalCollision(false) ; ropeConstraintBuilder.build() ; } @Override public void draw(Canvas canvas) { } @Override public Transform getTransform() { // TODO Auto-generated method stub return null; } @Override public Vector getVelocity() { // TODO Auto-generated method stub return null; } }
[ "alvarocauderan8515@gmail.com" ]
alvarocauderan8515@gmail.com
daa2a1c59ca76de465b5846543d258e94e11a4a2
3ca53c13d2953805c00406476ceda9684887a8ad
/src/com/iwxxm/taf/MDRangeDimensionType.java
7ccb5c7c7f3365f6c5e18628cfe922a2d5c3a62f
[]
no_license
yw2017051032/tac2iwxxm
ae93c12b08b7316cd59de032d4ae2e8082bc6c0b
5a08cb9ecd0833fd4435bf6db81a2b8126380ec1
refs/heads/master
2020-03-17T03:03:06.671868
2018-06-05T16:55:59
2018-06-05T17:06:03
133,217,637
3
0
null
null
null
null
GB18030
Java
false
false
2,973
java
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.8-b130911.1802 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2018.04.04 时间 07:08:22 PM CST // package com.iwxxm.taf; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * Set of adjacent wavelengths in the electro-magnetic spectrum with a common characteristic, such as the visible band * * <p>MD_RangeDimension_Type complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="MD_RangeDimension_Type"> * &lt;complexContent> * &lt;extension base="{http://www.isotc211.org/2005/gco}AbstractObject_Type"> * &lt;sequence> * &lt;element name="sequenceIdentifier" type="{http://www.isotc211.org/2005/gco}MemberName_PropertyType" minOccurs="0"/> * &lt;element name="descriptor" type="{http://www.isotc211.org/2005/gco}CharacterString_PropertyType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MD_RangeDimension_Type", namespace = "http://www.isotc211.org/2005/gmd", propOrder = { "sequenceIdentifier", "descriptor" }) @XmlSeeAlso({ MDBandType.class }) public class MDRangeDimensionType extends AbstractObjectType { protected MemberNamePropertyType sequenceIdentifier; protected CharacterStringPropertyType descriptor; /** * 获取sequenceIdentifier属性的值。 * * @return * possible object is * {@link MemberNamePropertyType } * */ public MemberNamePropertyType getSequenceIdentifier() { return sequenceIdentifier; } /** * 设置sequenceIdentifier属性的值。 * * @param value * allowed object is * {@link MemberNamePropertyType } * */ public void setSequenceIdentifier(MemberNamePropertyType value) { this.sequenceIdentifier = value; } /** * 获取descriptor属性的值。 * * @return * possible object is * {@link CharacterStringPropertyType } * */ public CharacterStringPropertyType getDescriptor() { return descriptor; } /** * 设置descriptor属性的值。 * * @param value * allowed object is * {@link CharacterStringPropertyType } * */ public void setDescriptor(CharacterStringPropertyType value) { this.descriptor = value; } }
[ "852406820@qq.com" ]
852406820@qq.com
b2c5d11e2b4dacfec30ac9cbba7a735007b47b1a
d45a48f7bbb7769bca8b7296404234cade391d21
/src/com/leetcode/DataStructure/array/replaceElementsSolution.java
e610cc2650f198a2a9ec4a6f86c99adf300f69a9
[]
no_license
fo878/CodingPractice
5b1833f4d29135cb57d5e174be9a7133ee477143
c84dd3cba7d4e080359a2b12dddb8c964e3f331a
refs/heads/master
2022-07-10T12:16:47.043993
2022-07-03T13:25:37
2022-07-03T13:25:37
244,250,936
0
2
null
null
null
null
UTF-8
Java
false
false
1,478
java
package com.leetcode.DataStructure.array; import java.util.Arrays; /* * 给你一个数组 arr ,请你将每个元素用它右边最大的元素替换,如果是最后一个元素,用 -1 替换。 完成所有替换操作后,请你返回这个数组。 * */ public class replaceElementsSolution { public int[] replaceElements(int[] arr) { for (int i = 0; i < arr.length-1; i++) { int max = 0; for (int j = i+1; j < arr.length; j++) { if (max<arr[j]){ max = arr[j]; } } arr[i] = max; } arr[arr.length-1] = -1; return arr; } /*精华题解*/ /* * 从右往左,并始终维护一个当前位置右边的最大值 rightMaxrightMax, * 这样一来我们只需要遍历一遍数组。这样问题就转化为从右往左找最大值了。 * */ public int[] replaceElements2(int[] arr) { int rightMax = -1; for (int i = arr.length-1; i >= 0; i--) { int temp = arr[i]; arr[i] = rightMax; if(temp > rightMax) rightMax = temp; } return arr; } public static void main(String[] args) { int[] arr = {17,18,5,4,6,1}; replaceElementsSolution foo = new replaceElementsSolution(); int[] array = foo.replaceElements(arr); System.out.println(Arrays.toString(array));//{18,6,6,6,1,-1} } }
[ "278241740@qq.com" ]
278241740@qq.com
f81733d4b8df3e2fb8278206dbb7f923da39b183
8f01b8893b9b3656cf6cd229e75718be8f5fcf5d
/com/amazon/exercises/chapter6_reusing_classes/ex10/Root.java
719b236462d91de8980d09c8239133ffefe3bfe3
[]
no_license
hailstone/thinking_in_java_homework
df61643466f981d1d69c20e0960990a08e4d8596
5996a8872c7d384a5fcd0648f3ed93279b9cfe92
refs/heads/master
2021-09-01T09:18:56.241198
2017-12-26T06:46:07
2017-12-26T06:46:07
108,838,671
0
0
null
null
null
null
UTF-8
Java
false
false
887
java
package exercises.chapter6_reusing_classes.ex10; public class Root { Component1 c1; Component2 c2; Component3 c3; Root(int i) { c1 = new Component1(22); c2 = new Component2(22); c3= new Component3(22); } public static void main(String[] args) { } } class Stem extends Root { Component1 c1; Component2 c2; Component3 c3; Stem(int i) { super(i); c1 = new Component1(11); c2 = new Component2(11); c3= new Component3(11); } public static void main(String[] args) { new Stem(11); } } class Component1 { Component1(int i) { System.out.println("compenent1"); } } class Component2 { Component2(int i) { System.out.println("compenent2"); } } class Component3 { Component3(int i) { System.out.println("compenent3"); } }
[ "lihaokai@amazon.com" ]
lihaokai@amazon.com
d9d57d30df8e8b79a15bb332d5caba60f1c9a7c6
c7e000e5c6549e095a8ffd032d33e0ca449c7ffd
/bin/platform/bootstrap/gensrc/de/hybris/platform/bmecat/model/PriceCopyModel.java
61404a4d03f0d88ae6c1585396db28c774c75f43
[]
no_license
J3ys/million
e80ff953e228e4bc43a1108a1c117ddf11cc4644
a97974b68b4adaf820f9024aa5181de635c60b4f
refs/heads/master
2021-03-09T22:59:35.115273
2015-05-19T02:47:29
2015-05-19T02:47:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,283
java
/* * ---------------------------------------------------------------- * --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! --- * --- Generated at 2015/05/18 13:25:55 --- * ---------------------------------------------------------------- * * [y] hybris Platform * * Copyright (c) 2000-2011 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of 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 hybris. * */ package de.hybris.platform.bmecat.model; import de.hybris.platform.core.HybrisEnumValue; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.core.model.c2l.CurrencyModel; import de.hybris.platform.core.model.product.UnitModel; import de.hybris.platform.servicelayer.model.ItemModelContext; import java.util.Date; /** * Generated model class for type PriceCopy first defined at extension bmecat. */ @SuppressWarnings("all") public class PriceCopyModel extends ItemModel { /**<i>Generated model type code constant.</i>*/ public final static String _TYPECODE = "PriceCopy"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.productCode</code> attribute defined at extension <code>bmecat</code>. */ public static final String PRODUCTCODE = "productCode"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.unit</code> attribute defined at extension <code>bmecat</code>. */ public static final String UNIT = "unit"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.unitFactor</code> attribute defined at extension <code>bmecat</code>. */ public static final String UNITFACTOR = "unitFactor"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.userPriceGroup</code> attribute defined at extension <code>bmecat</code>. */ public static final String USERPRICEGROUP = "userPriceGroup"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.minQuantity</code> attribute defined at extension <code>bmecat</code>. */ public static final String MINQUANTITY = "minQuantity"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.currency</code> attribute defined at extension <code>bmecat</code>. */ public static final String CURRENCY = "currency"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.net</code> attribute defined at extension <code>bmecat</code>. */ public static final String NET = "net"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.startDate</code> attribute defined at extension <code>bmecat</code>. */ public static final String STARTDATE = "startDate"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.endDate</code> attribute defined at extension <code>bmecat</code>. */ public static final String ENDDATE = "endDate"; /** <i>Generated constant</i> - Attribute key of <code>PriceCopy.priceValue</code> attribute defined at extension <code>bmecat</code>. */ public static final String PRICEVALUE = "priceValue"; /** <i>Generated variable</i> - Variable of <code>PriceCopy.productCode</code> attribute defined at extension <code>bmecat</code>. */ private String _productCode; /** <i>Generated variable</i> - Variable of <code>PriceCopy.unit</code> attribute defined at extension <code>bmecat</code>. */ private UnitModel _unit; /** <i>Generated variable</i> - Variable of <code>PriceCopy.unitFactor</code> attribute defined at extension <code>bmecat</code>. */ private Integer _unitFactor; /** <i>Generated variable</i> - Variable of <code>PriceCopy.userPriceGroup</code> attribute defined at extension <code>bmecat</code>. */ private HybrisEnumValue _userPriceGroup; /** <i>Generated variable</i> - Variable of <code>PriceCopy.minQuantity</code> attribute defined at extension <code>bmecat</code>. */ private Long _minQuantity; /** <i>Generated variable</i> - Variable of <code>PriceCopy.currency</code> attribute defined at extension <code>bmecat</code>. */ private CurrencyModel _currency; /** <i>Generated variable</i> - Variable of <code>PriceCopy.net</code> attribute defined at extension <code>bmecat</code>. */ private Boolean _net; /** <i>Generated variable</i> - Variable of <code>PriceCopy.startDate</code> attribute defined at extension <code>bmecat</code>. */ private Date _startDate; /** <i>Generated variable</i> - Variable of <code>PriceCopy.endDate</code> attribute defined at extension <code>bmecat</code>. */ private Date _endDate; /** <i>Generated variable</i> - Variable of <code>PriceCopy.priceValue</code> attribute defined at extension <code>bmecat</code>. */ private Double _priceValue; /** * <i>Generated constructor</i> - Default constructor for generic creation. */ public PriceCopyModel() { super(); } /** * <i>Generated constructor</i> - Default constructor for creation with existing context * @param ctx the model context to be injected, must not be null */ public PriceCopyModel(final ItemModelContext ctx) { super(ctx); } /** * <i>Generated constructor</i> - Constructor with all mandatory attributes. * @deprecated Since 4.1.1 Please use the default constructor without parameters * @param _endDate initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> * @param _net initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> * @param _startDate initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> */ @Deprecated public PriceCopyModel(final Date _endDate, final Boolean _net, final Date _startDate) { super(); setEndDate(_endDate); setNet(_net); setStartDate(_startDate); } /** * <i>Generated constructor</i> - for all mandatory and initial attributes. * @deprecated Since 4.1.1 Please use the default constructor without parameters * @param _endDate initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> * @param _net initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> * @param _owner initial attribute declared by type <code>Item</code> at extension <code>core</code> * @param _startDate initial attribute declared by type <code>PriceCopy</code> at extension <code>bmecat</code> */ @Deprecated public PriceCopyModel(final Date _endDate, final Boolean _net, final ItemModel _owner, final Date _startDate) { super(); setEndDate(_endDate); setNet(_net); setOwner(_owner); setStartDate(_startDate); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.currency</code> attribute defined at extension <code>bmecat</code>. * @return the currency - Currency */ public CurrencyModel getCurrency() { if (this._currency!=null) { return _currency; } return _currency = getPersistenceContext().getValue(CURRENCY, _currency); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.endDate</code> attribute defined at extension <code>bmecat</code>. * @return the endDate - EndDate */ public Date getEndDate() { if (this._endDate!=null) { return _endDate; } return _endDate = getPersistenceContext().getValue(ENDDATE, _endDate); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.minQuantity</code> attribute defined at extension <code>bmecat</code>. * @return the minQuantity - MinimumQuantity */ public Long getMinQuantity() { if (this._minQuantity!=null) { return _minQuantity; } return _minQuantity = getPersistenceContext().getValue(MINQUANTITY, _minQuantity); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.net</code> attribute defined at extension <code>bmecat</code>. * @return the net - Net */ public Boolean getNet() { if (this._net!=null) { return _net; } return _net = getPersistenceContext().getValue(NET, _net); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.priceValue</code> attribute defined at extension <code>bmecat</code>. * @return the priceValue */ public Double getPriceValue() { if (this._priceValue!=null) { return _priceValue; } return _priceValue = getPersistenceContext().getValue(PRICEVALUE, _priceValue); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.productCode</code> attribute defined at extension <code>bmecat</code>. * @return the productCode - ProductCode */ public String getProductCode() { if (this._productCode!=null) { return _productCode; } return _productCode = getPersistenceContext().getValue(PRODUCTCODE, _productCode); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.startDate</code> attribute defined at extension <code>bmecat</code>. * @return the startDate - StartDate */ public Date getStartDate() { if (this._startDate!=null) { return _startDate; } return _startDate = getPersistenceContext().getValue(STARTDATE, _startDate); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.unit</code> attribute defined at extension <code>bmecat</code>. * @return the unit - Unit */ public UnitModel getUnit() { if (this._unit!=null) { return _unit; } return _unit = getPersistenceContext().getValue(UNIT, _unit); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.unitFactor</code> attribute defined at extension <code>bmecat</code>. * @return the unitFactor - UnitFactor */ public Integer getUnitFactor() { if (this._unitFactor!=null) { return _unitFactor; } return _unitFactor = getPersistenceContext().getValue(UNITFACTOR, _unitFactor); } /** * <i>Generated method</i> - Getter of the <code>PriceCopy.userPriceGroup</code> attribute defined at extension <code>bmecat</code>. * @return the userPriceGroup - UserPriceGroup */ public HybrisEnumValue getUserPriceGroup() { if (this._userPriceGroup!=null) { return _userPriceGroup; } return _userPriceGroup = getPersistenceContext().getValue(USERPRICEGROUP, _userPriceGroup); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.currency</code> attribute defined at extension <code>bmecat</code>. * * @param value the currency - Currency */ public void setCurrency(final CurrencyModel value) { _currency = getPersistenceContext().setValue(CURRENCY, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.endDate</code> attribute defined at extension <code>bmecat</code>. * * @param value the endDate - EndDate */ public void setEndDate(final Date value) { _endDate = getPersistenceContext().setValue(ENDDATE, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.minQuantity</code> attribute defined at extension <code>bmecat</code>. * * @param value the minQuantity - MinimumQuantity */ public void setMinQuantity(final Long value) { _minQuantity = getPersistenceContext().setValue(MINQUANTITY, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.net</code> attribute defined at extension <code>bmecat</code>. * * @param value the net - Net */ public void setNet(final Boolean value) { _net = getPersistenceContext().setValue(NET, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.priceValue</code> attribute defined at extension <code>bmecat</code>. * * @param value the priceValue */ public void setPriceValue(final Double value) { _priceValue = getPersistenceContext().setValue(PRICEVALUE, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.productCode</code> attribute defined at extension <code>bmecat</code>. * * @param value the productCode - ProductCode */ public void setProductCode(final String value) { _productCode = getPersistenceContext().setValue(PRODUCTCODE, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.startDate</code> attribute defined at extension <code>bmecat</code>. * * @param value the startDate - StartDate */ public void setStartDate(final Date value) { _startDate = getPersistenceContext().setValue(STARTDATE, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.unit</code> attribute defined at extension <code>bmecat</code>. * * @param value the unit - Unit */ public void setUnit(final UnitModel value) { _unit = getPersistenceContext().setValue(UNIT, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.unitFactor</code> attribute defined at extension <code>bmecat</code>. * * @param value the unitFactor - UnitFactor */ public void setUnitFactor(final Integer value) { _unitFactor = getPersistenceContext().setValue(UNITFACTOR, value); } /** * <i>Generated method</i> - Setter of <code>PriceCopy.userPriceGroup</code> attribute defined at extension <code>bmecat</code>. * * @param value the userPriceGroup - UserPriceGroup */ public void setUserPriceGroup(final HybrisEnumValue value) { _userPriceGroup = getPersistenceContext().setValue(USERPRICEGROUP, value); } }
[ "yanagisawa@gotandadenshi.jp" ]
yanagisawa@gotandadenshi.jp
13c882285176c3209b7754ad5c3a0563456bddcd
8b4f81c21862f87df0421a8ee9424b2f79a85630
/src/com/james/Mammal.java
9d152cee90e7ac994d6fb724ac40c514f374a8ab
[]
no_license
vint-james207/Zoo
6f5553858c99a68a5bee1542d8401587443ac05f
c424ce771fd94f060592a2ff7ad3ba8964893bc9
refs/heads/master
2016-09-12T22:26:48.100489
2016-06-01T13:29:27
2016-06-01T13:29:27
59,580,792
0
0
null
null
null
null
UTF-8
Java
false
false
159
java
package com.james; /** * Created by jamesyburr on 5/24/16. */ public class Mammal extends Animal { public Mammal() { this.name = "Dog"; } }
[ "vint.james@gmail.com" ]
vint.james@gmail.com
36a91c413effab13e6109f4706ecf7e409d04c8f
a4c9e79782e87314af6b9e9b5d8a494b6e3a269b
/app/src/main/java/com/dylan/rxjavademo/ui/activity/create/RangeDemoActivity.java
3cbcf7d1ea1200762a6d927942d4fef869f8ace7
[]
no_license
DylanZhuang/RxJavaDemo
2c958804ec03bd67b3867dfc0532e178aafcbaf4
bae071ecdae61456c410fd94ae7d87df0d602fc9
refs/heads/master
2021-01-17T18:34:39.942490
2016-08-15T11:59:18
2016-08-15T11:59:18
65,728,435
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package com.dylan.rxjavademo.ui.activity.create; import com.dylan.rxjavademo.ui.activity.DemoActivity; import rx.Observable; /** * Description * author Dylan.zhuang * Date: 16/7/24-下午12:08 */ public class RangeDemoActivity extends DemoActivity { @Override protected void createObservable() { super.createObservable(); mObservable = Observable.range(0, 10); } }
[ "dylan.zhuang@uxin.com" ]
dylan.zhuang@uxin.com
abe56e89b3b08782061c30170f20a3638301aca2
02533ed4e8c8e15d4b60d9804a57a29c8c82825b
/scrati/common/src/main/java/com/hq/scrati/common/constants/trade/PayChannels.java
2087ceeb599b8dc952b6d5e5676620bae2ae5f7c
[]
no_license
douglashu/hq-forecast
804449d11c5e39f0cfa110214b6431d1d7ac8e23
7aa8d9c459d4aa1e62ed3827e1f951773ac249a9
refs/heads/master
2021-06-15T15:19:14.566905
2017-04-12T07:54:17
2017-04-12T07:54:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,356
java
package com.hq.scrati.common.constants.trade; import org.springframework.util.StringUtils; import java.util.regex.Pattern; /** * Created by zhaoyang on 10/5/16. */ public class PayChannels { public static final PayChannel WEIXIN_PAY = new PayChannel("微信支付", "WEIXIN_PAY", 1, 18, "13", "Wx"); public static final PayChannel ALI_PAY = new PayChannel("支付宝", "ALIPAY", 2, 18, "28", "Ali"); public static final PayChannel UNION_PAY = new PayChannel("银联钱包", "UNION_PAY", 4, 21, "1010", "Union"); public static final PayChannel TEN_PAY = new PayChannel("QQ钱包", "TEN_PAY", 8, 18, "91", "Ten"); public static final PayChannel BAIDU_WALLET = new PayChannel("百度钱包", "BAIDU_PAY", 16, 18, "31", "Baidu"); public static final PayChannel JD_PAY = new PayChannel("京东钱包", "JD_PAY", 32, 18, "18", "Jd"); public static final PayChannel[] ALL = new PayChannel[] { WEIXIN_PAY, ALI_PAY, UNION_PAY, TEN_PAY, BAIDU_WALLET, JD_PAY }; public static PayChannel fromAuthCode(String authCode) { if(!StringUtils.isEmpty(authCode)) { if (WEIXIN_PAY.checkPayCode(authCode)) return WEIXIN_PAY; if (ALI_PAY.checkPayCode(authCode)) return ALI_PAY; if (UNION_PAY.checkPayCode(authCode)) return UNION_PAY; if (TEN_PAY.checkPayCode(authCode)) return TEN_PAY; if (BAIDU_WALLET.checkPayCode(authCode)) return BAIDU_WALLET; if (JD_PAY.checkPayCode(authCode)) return JD_PAY; } return null; } public static PayChannel fromString(String string) { if(StringUtils.isEmpty(string)) return null; switch (string) { case "WEIXIN_PAY": return WEIXIN_PAY; case "ALIPAY": return ALI_PAY; case "UNION_PAY": return UNION_PAY; case "TEN_PAY": return TEN_PAY; case "BAIDU_PAY": return BAIDU_WALLET; case "JD_PAY": return JD_PAY; default: return null; } } public static PayChannel fromValue(Integer value) { if(value == null) return null; switch (value) { case 1: return WEIXIN_PAY; case 2: return ALI_PAY; case 4: return UNION_PAY; case 8: return TEN_PAY; case 16: return BAIDU_WALLET; case 32: return JD_PAY; default: return null; } } public static class PayChannel { private String name; private String code; private Integer value; private Integer payCodeLength; private String payCodeStartsWith; private String beanPrefix; @Override public String toString() { return getName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PayChannel that = (PayChannel) o; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } public PayChannel() { } public PayChannel(String name, String code, Integer value , Integer payCodeLength, String payCodeStartsWith, String beanPrefix) { this.name = name; this.code = code; this.value = value; this.payCodeLength = payCodeLength; this.payCodeStartsWith = payCodeStartsWith; this.beanPrefix = beanPrefix; } public boolean checkPayCode(String payCode) { if(!isSpecNumber(payCode, this.payCodeLength)) return false; return payCode.startsWith(this.payCodeStartsWith); } private static boolean isSpecNumber(String str, int specLen) { if(StringUtils.isEmpty(str)) return false; Pattern pattern = Pattern.compile(("^[0-9]{" + specLen + "}$")); return pattern.matcher(str).matches(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public Integer getPayCodeLength() { return payCodeLength; } public void setPayCodeLength(Integer payCodeLength) { this.payCodeLength = payCodeLength; } public String getPayCodeStartsWith() { return payCodeStartsWith; } public void setPayCodeStartsWith(String payCodeStartsWith) { this.payCodeStartsWith = payCodeStartsWith; } public String getBeanPrefix() { return beanPrefix; } public void setBeanPrefix(String beanPrefix) { this.beanPrefix = beanPrefix; } } }
[ "46773109@qq.com" ]
46773109@qq.com
897ba7a529512556b94eddc1721c129d28401ffd
91aded8e8d96765be7ab067d7bc40710317555af
/app/src/main/java/comt/dcm/legal/MainActivity.java
52c785061000c98b27c5468fc256f0e34d992edc
[]
no_license
vikash0439/Webview_Legal
3835d7d84e3cef6971bd436137843d92124c8441
22cadac8be6af925a4077d396da1b4b46cd33892
refs/heads/master
2020-04-15T15:19:58.296740
2019-01-10T06:55:20
2019-01-10T06:55:20
164,791,567
1
0
null
2019-01-27T07:41:20
2019-01-09T05:04:30
Java
UTF-8
Java
false
false
816
java
package comt.dcm.legal; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebSettings; import android.webkit.*; /** * Created by Vikash Kumar on 09-01-2019. */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl("http://192.168.1.2:8080/LegalApp/login"); //enter url or domain here with http/https MyWebViewClient wb =new MyWebViewClient(); webView.setWebViewClient(wb); } }
[ "vikash.k@dcmtech.com" ]
vikash.k@dcmtech.com