blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
5026dc3ed8ef8929d84580d42089d3a1f17b1b66
Java
DyadyaSasha/JavaProjects
/XmlRpc/src/main/java/Client.java
UTF-8
1,028
2.671875
3
[]
no_license
import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class Client { public void startClient(){ try { XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl(); clientConfig.setServerURL(new URL("http://127.0.0.1:8080/xmlrpc")); XmlRpcClient client = new XmlRpcClient(); client.setConfig(clientConfig); List<Integer> params = new ArrayList<Integer>(); params.add(new Integer(17)); params.add(new Integer(13)); Object result = client.execute("sample.sum", params); int sum = ((Integer) result).intValue(); System.out.println("Result of remote method: " + sum); } catch (MalformedURLException | XmlRpcException e) { e.printStackTrace(); } } }
true
cec52b3eb6d54c54eade2a22a8b8a48f48af1d36
Java
asimq74/PopularMovies
/app/src/main/java/com/example/popularmovies/task/ListMovieImagesAsyncTask.java
UTF-8
5,220
2.390625
2
[]
no_license
package com.example.popularmovies.task; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; import com.example.popularmovies.BuildConfig; import com.example.popularmovies.businessobjects.MovieImage; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Async Task to list all movie images for a specific movie id. * <p/> * Created by Asim Qureshi. */ public class ListMovieImagesAsyncTask extends AsyncTask<Integer, Void, MovieImage> { final String TAG = ListMovieImagesAsyncTask.class.getSimpleName(); private final ImageView imageView; private final Context context; public ListMovieImagesAsyncTask(Context context, ImageView imageView) { super(); this.context = context; this.imageView = imageView; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(MovieImage movieImage) { final String imageUrlPath = "http://image.tmdb.org/t/p/w" + movieImage.getWidth() + movieImage.getFilePath() + "?api_key=" + BuildConfig.THE_MOVIE_DB_API_KEY + "&language=en&include_image_language=en,null"; Log.i(TAG, String.format("imageUrlPath=%s", imageUrlPath)); Picasso.with(context).load(imageUrlPath).into(imageView); } @Override protected MovieImage doInBackground(Integer... params) { Integer id = params[0]; HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String moviesJsonString; MovieImage movieImage = new MovieImage(); try { // Construct the URL Uri.Builder builder = new Uri.Builder(); builder.scheme("http") .authority("api.themoviedb.org") .appendPath("3") .appendPath("movie") .appendPath(id.toString()) .appendPath("images") .appendQueryParameter("api_key", BuildConfig.THE_MOVIE_DB_API_KEY); final String urlString = builder.build().toString(); URL url = new URL(urlString); // Create the request and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } if (buffer.length() == 0) Log.d(TAG, "Stream was empty"); moviesJsonString = buffer.toString(); movieImage = formatJson(moviesJsonString); } catch (Exception e) { Log.e(TAG, "Error ", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(TAG, "Error closing stream", e); } } } return movieImage; } protected MovieImage formatJson(String json) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String ASPECT_RATIO = "aspect_ratio"; final String FILE_PATH = "file_path"; final String HEIGHT = "height"; final String WIDTH = "width"; final String BACKDROPS = "backdrops"; JSONObject moviePosterJson = new JSONObject(json); JSONArray moviesImageArray = moviePosterJson.getJSONArray(BACKDROPS); List<MovieImage> movieImages = new ArrayList<>(); for (int i = 0; i < moviesImageArray.length(); i++) { JSONObject moviesImageJSONObject = moviesImageArray.getJSONObject(i); MovieImage movieImage = new MovieImage(); movieImage.setAspectRatio(moviesImageJSONObject.getLong(ASPECT_RATIO)); movieImage.setFilePath(moviesImageJSONObject.getString(FILE_PATH)); movieImage.setHeight(moviesImageJSONObject.getInt(HEIGHT)); movieImage.setWidth(moviesImageJSONObject.getInt(WIDTH)); movieImages.add(movieImage); } return movieImages.get(random(movieImages.size() - 1)); } protected int random(int length) { Random rand = new Random(); return rand.nextInt(length); } }
true
a831a89b37a6dc8741bd71de70fc4f1134b9f2c8
Java
439ED537979D8E831561964DBBBD7413/LiaLia
/liangliang/app/src/main/java/cn/chono/yopper/Service/Http/DatingsList/DatingListRespBean.java
UTF-8
416
1.8125
2
[]
no_license
package cn.chono.yopper.Service.Http.DatingsList; import cn.chono.yopper.data.AppointListDto; import cn.chono.yopper.Service.Http.RespBean; /** * Created by zxb on 2015/11/21. */ public class DatingListRespBean extends RespBean { private AppointListDto resp; public AppointListDto getResp() { return resp; } public void setResp(AppointListDto resp) { this.resp = resp; } }
true
9e0c5ed7d7a587ff308f4e810230394ac23eb936
Java
seinecle/Eonydis
/src/eonydis/Transaction.java
UTF-8
3,834
2.875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eonydis; import java.util.ArrayList; import java.util.HashMap; import levallois.clement.utils.Pair; import levallois.clement.utils.Triple; import org.joda.time.LocalDate; /** * * @author dnb */ public class Transaction { private HashMap<String, String> mapTransFull = new HashMap(); static public ArrayList<Transaction> listTransactions = new ArrayList(); boolean nodekAddedLn = false; boolean nodeAddedBr = false; boolean nodeAddedAll = false; int year; int month; int day; int hour; int minute; String [] arrayTime; ArrayList <Integer> arrayListTime = new ArrayList(); private final LocalDate dt; //Beginning Constructor Transaction(String[] values) { for (int i = 0; i < Main.headers.length; i++) { mapTransFull.put(Main.headers[i], values[i]); //Bank bank = new Node(); } //adds the 2 banks of this current transaction // to the set all the banks are present in the dataset - simply referred by their BIC nodeAddedAll = Main.setNodes.add(mapTransFull.get(Main.source)); nodeAddedAll = Main.setNodes.add(mapTransFull.get(Main.target)); //add the pair of Nodes to a set of unique pairs of Nodes Main.setPairsNodes.add(mapTransFull.get(Main.source).concat(mapTransFull.get(Main.target))); // parse the field "ln_date" to format the time in a proper way // arrayTime = mapTransFull.get("ln_time").split("/"); // month = Integer.valueOf(arrayTime[0]); // System.out.println("value of Month with the usual method: "+month); // day = Integer.valueOf(arrayTime[1]); // year = Integer.valueOf(arrayTime[2].split(" ")[0]); String timeField = mapTransFull.get(Main.timeField); // System.out.println("timeField"+timeField); month = Integer.valueOf(timeField.replaceAll(Main.userDefinedTimeFormat, "$"+Main.mapOrderTimeFields.get("month"))); day = Integer.valueOf(timeField.replaceAll(Main.userDefinedTimeFormat, "$"+Main.mapOrderTimeFields.get("day"))); year = Integer.valueOf(timeField.replaceAll(Main.userDefinedTimeFormat, "$"+Main.mapOrderTimeFields.get("year"))); //stores the time in a dt object (using the Joda library) dt = new LocalDate(year,month,day); //creates an object "nodeSource" to store in a neat way the details of the lending bank of this transaction (see "Node" class to see the details) Node nodeSource = new Node(mapTransFull.get(Main.source)); //creates an object "nodeTarget" to store in a neat way the details of the borrowing bank of this transaction (see "Node" class to see the details) Node nodeTarget = new Node(mapTransFull.get(Main.target)); Main.listTransactionsAndDates.add(new Triple(mapTransFull,new Pair(nodeSource.getNodeId(),nodeTarget.getNodeId()),dt)); //adds pairs of the objects created above to a list storing these pairs Main.listNodesAndDates.add(new Triple(nodeSource,dt,mapTransFull)); Main.listNodesAndDates.add(new Triple(nodeTarget,dt,mapTransFull)); //System.out.println(Node.getlistBanksAndDates().size()); }//End Constructor public HashMap<String, String> getMapTransFull() { return mapTransFull; } public String getLnValue() { return mapTransFull.get("ln_value"); } public String getRate() { return mapTransFull.get("rate"); } } // End class Transaction
true
46280d51f61d3b6bd03dcfbb1c589dd0903a9110
Java
bigstar18/prjs
/prj/bank/web-pingan-b2bic/src/main/java/cn/com/agree/eteller/afa/persistence/AfaSubunitadmPK.java
UTF-8
1,878
2.140625
2
[ "Apache-2.0" ]
permissive
package cn.com.agree.eteller.afa.persistence; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; public class AfaSubunitadmPK implements Serializable { private String sysid; private String unitno; private String subunitno; public AfaSubunitadmPK(String sysid, String unitno, String subunitno) { this.sysid = sysid; this.unitno = unitno; this.subunitno = subunitno; } public AfaSubunitadmPK() {} public String getSysid() { return this.sysid; } public void setSysid(String sysid) { this.sysid = sysid; } public String getUnitno() { return this.unitno; } public void setUnitno(String unitno) { this.unitno = unitno; } public String getSubunitno() { return this.subunitno; } public void setSubunitno(String subunitno) { this.subunitno = subunitno; } public String toString() { return new ToStringBuilder(this).append("sysid", getSysid()).append("unitno", getUnitno()).append("subunitno", getSubunitno()).toString(); } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof AfaSubunitadmPK)) { return false; } AfaSubunitadmPK castOther = (AfaSubunitadmPK)other; return new EqualsBuilder() .append(getSysid(), castOther.getSysid()) .append(getUnitno(), castOther.getUnitno()) .append(getSubunitno(), castOther.getSubunitno()) .isEquals(); } public int hashCode() { return new HashCodeBuilder().append(getSysid()).append(getUnitno()).append(getSubunitno()).toHashCode(); } }
true
fc4e94c7ceb69fea80fb9d3a9edd7ef5233389a3
Java
kutaelee/2019.07.18_ShoppingMall_SpringBoot
/src/main/java/com/shop/www/main/MainDAO.java
UTF-8
1,038
2.1875
2
[]
no_license
package com.shop.www.main; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class MainDAO { @Autowired private JdbcTemplate template; public List<Map<String, Object>> getNewReview() { String SQL = "SELECT * FROM REVIEW" + " ORDER BY FRST_REG_DT DESC" + " LIMIT 3"; List<Map<String, Object>> list = template.queryForList(SQL); return list; } public List<Map<String, Object>> getBestReview() { String SQL = "SELECT * FROM REVIEW" + " WHERE FRST_REG_DT>DATE_SUB(NOW() , INTERVAL 100 DAY)" + " ORDER BY LIKE_CNT DESC" + " LIMIT 3"; return template.queryForList(SQL); } public List<Map<String, Object>> getProduct() { String SQL = "SELECT * FROM PRODUCT" + " WHERE FLAG=1" + " ORDER BY LAST_REG_DT DESC" + " LIMIT 10"; return template.queryForList(SQL); } }
true
06787571c33ab37d42f5881b632cacc6c1411997
Java
adgupta12/tridion-automation
/src/Allctr.java
UTF-8
1,655
3.265625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Allctr { public static void main(String[] args) throws Exception { int sz,opt; System.out.println("Enter the size of the stack"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); sz = Integer.parseInt(br.readLine()); Stack obj1 = new Stack(sz); do{ System.out.println("1. PUSH "); System.out.println("2. POP "); System.out.println("3. DISPLAY STACK "); System.out.println("4. EXIT "); System.out.println("\n Enter Your Option: "); opt = Integer.parseInt(br.readLine()); switch(opt) { case 1: obj1.push(); break; case 2: int j=obj1.pop(); if(j==-1000030) System.out.println("Stack has underflown"); else System.out.println("The element popped out is "+j); break; case 3: obj1.display(); break; case 4: System.exit(0); break; default:System.out.println("Invalid choice"); } }while(opt!=4); } }
true
59c51f230db4c5a27bfb163a98add4964dc862fe
Java
catheneos/Vending-Machine
/src/test/java/materials/AllProductTests.java
UTF-8
1,098
2.625
3
[]
no_license
package materials; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import org.junit.Test; public class AllProductTests { @Test public void code_is_correct() { Vendable test = new Chip("A1", "Lays", new BigDecimal(1.00)); String expectedResult = "A1"; String actualResult = test.getProductCode(); assertEquals(expectedResult, actualResult); } @Test public void name_is_correct() { Vendable test = new Chip("A1", "Lays", new BigDecimal(1.00)); String expectedResult = "Lays"; String actualResult = test.getProductName(); assertEquals(expectedResult, actualResult); } @Test public void price_is_correct() { Vendable test = new Chip("A1", "Lays", new BigDecimal(1.55)); BigDecimal expectedResult = new BigDecimal(1.55); BigDecimal actualResult = test.getPrice(); assertEquals(expectedResult, actualResult); } @Test public void quantity_is_correct() { Vendable test = new Chip("A1", "Lays", new BigDecimal(1.00)); int expectedResult = 5; int actualResult = test.getQuantity(); assertEquals(expectedResult, actualResult); } }
true
a124b1b0154a6197d3f6199c1ae2c4398e54a159
Java
qinhuangdaoStation/NongShangTong
/app/src/main/java/jmessage/example/com/nongshangtong/utils/BottomUtil.java
UTF-8
5,282
2.28125
2
[]
no_license
package jmessage.example.com.nongshangtong.utils; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import jmessage.example.com.nongshangtong.R; import jmessage.example.com.nongshangtong.homepage.HomePageUtil; import jmessage.example.com.nongshangtong.homepage.MainActivity; import jmessage.example.com.nongshangtong.more.MoreActivity; /** todo 待完善!!!!!!!!!!!!!!! * Created by ii on 2016/4/8. */ public class BottomUtil { //这里,主要是借助它的activity跳转方法 private HomePageUtil util; private Context context; private RadioGroup radioGroup; private RadioButton radbtn_homepage; private RadioButton radbtn_farmProduce; private RadioButton radbtn_IndustryInfo; private RadioButton radbtn_more; private LinearLayout layout_bottom; public boolean isFinish = false; //默认不关闭当前activity public BottomUtil(Context context) { this.context = context; util = new HomePageUtil(context); } /** * 初始化布局 */ public void init(RadioGroup radioGroup,RadioButton radbtn_farmProduce, RadioButton radbtn_homepage, RadioButton radbtn_IndustryInfo, RadioButton radbtn_more) { this.radioGroup = radioGroup; this.radbtn_more = radbtn_more; this.radbtn_IndustryInfo = radbtn_IndustryInfo; this.radbtn_homepage = radbtn_homepage; this.radbtn_farmProduce = radbtn_farmProduce; //设置为“更多”的选择界面 colorChange(4); isFinish = false; radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.radbtn_bottom_homepage: //首页 colorChange(1); isFinish = true; util.activityStart(MainActivity.class); break; case R.id.radbtn_bottom_farmProduce: //农产品 colorChange(2); isFinish = true; Toast.makeText(context, "农产品界面还在开发中~", Toast.LENGTH_SHORT).show(); break; case R.id.radbtn_bottom_industryInfo: //农贸商城 colorChange(3); isFinish = true; Toast.makeText(context,"农贸商城界面还在开发中~",Toast.LENGTH_SHORT).show(); break; case R.id.radbtn_bottom_more: //更多 colorChange(4); isFinish = true; util.activityStart(MoreActivity.class); break; default: break; } } }); } /** * 背景颜色变化 * @param num */ public void colorChange(int num) { switch (num) { case 1: //首页 radbtn_homepage.setBackgroundColor(Color.GREEN); radbtn_farmProduce.setBackgroundColor(Color.GRAY); radbtn_IndustryInfo.setBackgroundColor(Color.GRAY); radbtn_more.setBackgroundColor(Color.GRAY); break; case 2: //农产品 radbtn_homepage.setBackgroundColor(Color.GRAY); radbtn_farmProduce.setBackgroundColor(Color.GREEN); radbtn_IndustryInfo.setBackgroundColor(Color.GRAY); radbtn_more.setBackgroundColor(Color.GRAY); break; case 3: //农贸商城 radbtn_homepage.setBackgroundColor(Color.GRAY); radbtn_farmProduce.setBackgroundColor(Color.GRAY); radbtn_IndustryInfo.setBackgroundColor(Color.GREEN); radbtn_more.setBackgroundColor(Color.GRAY); break; case 4: //更多 radbtn_homepage.setBackgroundColor(Color.GRAY); radbtn_farmProduce.setBackgroundColor(Color.GRAY); radbtn_IndustryInfo.setBackgroundColor(Color.GRAY); radbtn_more.setBackgroundColor(Color.GREEN); break; default: //默认 radbtn_homepage.setBackgroundColor(Color.GRAY); radbtn_farmProduce.setBackgroundColor(Color.GRAY); radbtn_IndustryInfo.setBackgroundColor(Color.GRAY); radbtn_more.setBackgroundColor(Color.GRAY); break; } } }
true
e7f2c2358d17d18fa29de9e355d33dd1e8ab4c7c
Java
pealipala/Mybatis-airplane
/src/com/service/impl/AirplaneServiceImpl.java
UTF-8
426
1.867188
2
[]
no_license
package com.service.impl; import com.mapper.AirplaneMapper; import com.pojo.Airplane; import com.service.AirplaneService; import com.utils.MyBatisUtil; import java.util.List; public class AirplaneServiceImpl implements AirplaneService { @Override public List<Airplane> show(int takeid, int landid) { return MyBatisUtil.getSession().getMapper(AirplaneMapper.class).selByTakeidLandid(takeid, landid); } }
true
541fae3f2b315ffc6740e90d1ef0476fe6ade4c0
Java
zhanxu913/Demo
/Demo1.java
UTF-8
4,717
3.921875
4
[]
no_license
package com.wang.ref; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; /** * 反射机制。 * * 构造方法。 * */ public class Demo1 { /** * 获取构造方法。 */ public void test1(){ //Class对象 try { Class<?> c = Class.forName("com.wang.ref.Student"); //获取所有构造方法 Constructor<?>[] cons = c.getConstructors(); //构造方法个数 System.out.println("cons count:" + cons.length); //打印所有构造 for (Constructor<?> con : cons) { //名字 String name = con.getName(); System.out.println("name:" + name); //修饰符 int mod = con.getModifiers(); System.out.println("mod:" + Modifier.toString(mod)); //参数 int pcount = con.getParameterCount(); System.out.println("param count:" + pcount); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 调用构造方法。 */ public void test2(){ try { //Class对象 Class<?> c = Class.forName("com.wang.ref.Student"); //获取有参构造 Constructor<?> con = c.getConstructor(String.class, int.class); // 调用有参构造 Student s = (Student)con.newInstance("zhang", 20); s.intro(); s.study(); /** * 构造方法不仅仅通过new可以调用。 * 调用构造方法可以获得一个对象。 */ } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Constructor类研究。 * * 构造类。 * */ public void test3(){ /* * Constructor是构造方法的类形式。 * 构造方法也是方法,可从一般方法的基本格式入手研究。 * (1)修饰符 * (2)返回值 * (3)方法名 * (4)方法参数 * (5)方法异常 * (6)其他 */ Class<Student> c = Student.class; try { Constructor<?> con = c.getConstructor(String.class, int.class); //修饰符 int mod = con.getModifiers(); System.out.println("mod:" + Modifier.toString(mod)); //名字 String name = con.getName(); System.out.println("name:" + name); //参数 Parameter[] paras = con.getParameters(); System.out.println("para count:" + paras.length); //异常 Class<?>[] exceps = con.getExceptionTypes(); System.out.println("excps:" + exceps.length); //其他 //通过构造生成对象 Student s = (Student)con.newInstance("zhao", 30); s.intro(); s.study(); //判断访问性 boolean b1 = con.isAccessible(); System.out.println("accessable:" + b1); //设置访问性 con.setAccessible(true); boolean b2 = con.isAccessible(); System.out.println("accessable:" + b2); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Paremeter类研究。 * * 参数类。 * */ public void test4(){ Class<Student> c = Student.class; try { Constructor<Student> con = c.getConstructor(String.class,int.class); Parameter[] paras = con.getParameters(); for (Parameter para : paras) { //类型 Class<?> type = para.getType(); System.out.println("type:" + type); //名字 String name = para.getName(); System.out.println("name:" + name); //修饰符 int mod = para.getModifiers(); System.out.println("mod:" + Modifier.toString(mod)); } } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
d47ddb95dac5863cfe7455925cbf8cd41930ef1d
Java
GeorgyYakunin/StylishNameMaker
/app/src/main/java/com/Example/stylishnamemaker/ActivitySharing.java
UTF-8
8,087
1.882813
2
[]
no_license
package com.Example.stylishnamemaker; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.Example.stylishnamemaker.comman.BitmapScaler; import com.Example.stylishnamemaker.comman.PhotoConstant; import java.io.File; public class ActivitySharing extends Activity implements OnClickListener { public static boolean deleted = false; private ImageView deleteBtn; private String imgUrl = null; private ImageView instaBtn; private ImageView mainImageView; private ImageView shareBtn; private ImageView whatsappBtn; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(1); setContentView(R.layout.share_image); RelativeLayout adview=(RelativeLayout) findViewById(R.id.adlayout); // Banner(adview,ActivitySharing.this); this.mainImageView = (ImageView) findViewById(R.id.mainImageView); this.instaBtn = (ImageView) findViewById(R.id.instaBtn); this.whatsappBtn = (ImageView) findViewById(R.id.whatsappBtn); this.shareBtn = (ImageView) findViewById(R.id.shareBtn); this.deleteBtn = (ImageView) findViewById(R.id.deleteBtn); this.imgUrl = getIntent().getStringExtra("ImgUrl"); this.instaBtn.setOnClickListener(this); this.whatsappBtn.setOnClickListener(this); this.shareBtn.setOnClickListener(this); this.deleteBtn.setOnClickListener(this); ImageLoader.getInstance().loadImage(this.imgUrl, BitmapScaler.getDisplayImageOptions(true), new ImageLoadingListener() { public void onLoadingStarted(String arg0, View arg1) { } public void onLoadingFailed(String arg0, View arg1, FailReason arg2) { PhotoConstant.errorAlert(ActivitySharing.this); } public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) { ActivitySharing.this.mainImageView.setImageBitmap(arg2); } public void onLoadingCancelled(String arg0, View arg1) { } }); } public void onClick(View arg0) { switch (arg0.getId()) { case R.id.shareBtn: Intent share = new Intent("android.intent.action.SEND"); share.setType("image/jpeg"); share.putExtra("android.intent.extra.STREAM", Uri.parse(this.imgUrl)); startActivity(Intent.createChooser(share, "via")); return; case R.id.instaBtn: if (instagramappInstalledOrNot()) { try { Intent shareIntent = new Intent("android.intent.action.SEND"); shareIntent.setType("image/*"); shareIntent.putExtra("android.intent.extra.STREAM", Uri.parse(this.imgUrl)); shareIntent.setPackage("com.instagram.android"); startActivity(shareIntent); return; } catch (Exception e) { Toast.makeText(this, "Error", Toast.LENGTH_LONG).show(); return; } } Toast.makeText(this, getResources().getString(R.string.instaTxt), Toast.LENGTH_LONG).show(); startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=com.instagram.android"))); return; case R.id.whatsappBtn: shareOnWhatsApp(); return; case R.id.deleteBtn: deleted(); return; default: return; } } private void shareOnWhatsApp() { if (whatsappInstalledOrNot()) { Intent waIntent = new Intent("android.intent.action.SEND"); waIntent.setType("image/jpeg"); waIntent.setPackage("com.whatsapp"); if (waIntent != null) { waIntent.putExtra("android.intent.extra.STREAM", Uri.parse(this.imgUrl)); startActivity(Intent.createChooser(waIntent, getResources().getString(R.string.shareTxt))); return; } return; } Toast.makeText(this, getResources().getString(R.string.whatsappTxt), Toast.LENGTH_LONG).show(); startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp&hl=en"))); } private void deleted() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.removeOpt)); builder.setMessage(getResources().getString(R.string.removeTxt)); builder.setPositiveButton(getResources().getString(R.string.yestxt), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); if (new File(Uri.parse(ActivitySharing.this.imgUrl).getPath()).delete()) { ActivitySharing.this.setResult(-1); ActivitySharing.this.finish(); return; } Toast.makeText(ActivitySharing.this.getApplicationContext(), ActivitySharing.this.getResources().getString(R.string.errorImg), Toast.LENGTH_LONG).show(); } }); builder.setNegativeButton(getResources().getString(R.string.canceltxt), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } private boolean instagramappInstalledOrNot() { try { ApplicationInfo info = getPackageManager().getApplicationInfo("com.instagram.android", 0); return true; } catch (NameNotFoundException e) { return false; } } private boolean whatsappInstalledOrNot() { try { ApplicationInfo info = getPackageManager().getApplicationInfo("com.whatsapp", 0); return true; } catch (NameNotFoundException e) { return false; } } public void onPause() { super.onPause(); } public void onResume() { super.onResume(); } public void onDestroy() { super.onDestroy(); System.gc(); } @Override public void onBackPressed() { super.onBackPressed(); } // public void Banner(final RelativeLayout Ad_Layout, final Context context) { // // AdView mAdView = new AdView(context); // mAdView.setAdSize(AdSize.BANNER); // mAdView.setAdUnitId(getString(R.string.ads_bnr)); // AdRequest adre = new AdRequest.Builder().build(); // mAdView.loadAd(adre); // Ad_Layout.addView(mAdView); // // mAdView.setAdListener(new AdListener() { // // @Override // public void onAdLoaded() { // // TODO Auto-generated method stub // Ad_Layout.setVisibility(View.VISIBLE); // super.onAdLoaded(); // } // // @Override // public void onAdFailedToLoad(int errorCode) { // // TODO Auto-generated method stub // Ad_Layout.setVisibility(View.GONE); // // // } // }); // } }
true
d2711637b0a93ada8d47b1ad8b507268b8571413
Java
OfekSha/ICM
/Client/src/GUI/PopUpWindows/ApproveExtensionController.java
UTF-8
1,621
2.203125
2
[]
no_license
package GUI.PopUpWindows; import java.net.URL; import java.util.ResourceBundle; import Controllers.InspectorController; import WindowApp.IcmForm; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class ApproveExtensionController extends AbstractPopUp implements IcmForm { @FXML private Label title; @FXML private Button btnApprove; @FXML private Button btnDisapprove; @FXML private TextArea reactionReason; @FXML private TextArea extensionExplanation; @FXML private TextField extensionDueDate; @FXML void getApprove(ActionEvent event) { InspectorController.approveExtension(true, InspectorController.selectedRequest, reactionReason.getText()); getCancel(); } @FXML void getDisapprove(ActionEvent event) { InspectorController.approveExtension(false, InspectorController.selectedRequest, reactionReason.getText()); getCancel(); } @Override public void initialize(URL location, ResourceBundle resources) { title.setText("Do you approve extension for request " +InspectorController.selectedRequest.getRequestID()); extensionExplanation.setText(InspectorController.selectedRequest.getProcessStage().getExtensionExplanation()); extensionDueDate.setText(InspectorController.selectedRequest.getProcessStage().getExtensionRequestDate().toString()); } @Override public void getFromServer(Object message) { // TODO Auto-generated method stub } }
true
48b51dca598c4a0eaa067b5a6cd8017054512190
Java
ss-bak/lms-common
/security/CommonTestUserIdProvider.java
UTF-8
2,391
2.25
2
[]
no_license
package com.smoothstack.lms.common.security; import com.smoothstack.lms.common.util.Debug; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletRequest; @Controller public class CommonTestUserIdProvider { @Autowired private RestTemplate restTemplate; @GetMapping("/identityprovider/getuserdetails") public ResponseEntity<Object> anonymousIdProvider(HttpServletRequest request, @RequestHeader MultiValueMap<String, String> headers) { final String requestTokenHeader = request.getHeader("Proxy-Authorization"); String jwt = null; if (requestTokenHeader == null || !requestTokenHeader.startsWith("JWT ")) { return ResponseEntity.badRequest().body(requestTokenHeader == null?"<NULL>":request.getHeader("Proxy-Authorization")); } jwt = requestTokenHeader.substring(4); Debug.printf("JWT = %s\n",jwt); String testRole = null; /* TODO: 1. Validate JWT 2. Get subject from JWT, this will be the username (or use JwtUtils) 3. Query UserDetails from database by username 4. Construct UserDetails (build) or if UserObject from database is implements UserDetails, just use it as-is 5. Return UserDetails to IdentityTenant */ switch (jwt) { case "BORROWER": testRole = "BORROWER"; break; case "LIBRARIAN": testRole = "LIBRARIAN"; break; case "ADMIN": testRole = "ADMIN"; break; default: testRole = "GUEST"; } User.UserBuilder userBuilder = User.withUsername("test"); userBuilder.password(jwt); userBuilder.roles("TEST_USER", "TEST_"+testRole); return ResponseEntity.ok().body(userBuilder.build()); } }
true
bf06a822170e6c45a238d466108d230b1619986b
Java
lilit-nersisyan/tmm
/src/main/java/org/cytoscape/tmm/reports/SVM.java
UTF-8
15,749
2.234375
2
[]
no_license
package org.cytoscape.tmm.reports; import jsat.ARFFLoader; import jsat.DataSet; import jsat.classifiers.*; import jsat.classifiers.bayesian.NaiveBayes; import jsat.classifiers.linear.ALMA2; import jsat.classifiers.svm.DCD; import jsat.classifiers.svm.LSSVM; import jsat.datatransform.DataTransform; import jsat.datatransform.PCA; import jsat.datatransform.ZeroMeanTransform; import jsat.linear.DenseVector; import jsat.linear.Vec; import javax.swing.*; import javax.xml.crypto.Data; import java.io.*; import java.lang.reflect.Field; import java.util.*; /** * Created by Lilit Nersisyan on 4/8/2017. */ public class SVM { public static String ALTOPTION = "alt"; public static String NONALTOPTION = "non-alt"; public static String TELOMERASEOPTION = "telomerase"; public static String NONTELOMERASEOPTION = "non-telomerase"; private LSSVM classifier = new LSSVM(); private double[][] confusionMatrix; private boolean[][] predictionTable; // predicted phenotypes: colnames=isALT, isTelomerase private int classCount; private double h; private double v; private SummaryFileHandler summaryFileHandler; private TMMLabels tmmLabels; private Double accuracy = null; public SVM(SummaryFileHandler summaryFileHandler, TMMLabels tmmLabels) { this.summaryFileHandler = summaryFileHandler; this.tmmLabels = tmmLabels; this.predictionTable = new boolean[summaryFileHandler.getSamples().size()][2]; } public double getH() { return h; } public double getV() { return v; } public double[][] getConfusionMatrix() { return confusionMatrix; } public void runSVM() throws Exception { ClassificationDataSet altDataSet = null; try { altDataSet = generateDataSet(summaryFileHandler, TMMLabels.A); } catch (Exception e) { throw new Exception("Problem generating the ALT dataset. " + e.getMessage()); } printDataSet(altDataSet); classify(altDataSet); printConfusionMatrix(altDataSet); ClassificationDataSet telomeraseDataset = null; try { telomeraseDataset = generateDataSet(summaryFileHandler, TMMLabels.T); } catch (Exception e) { throw new Exception("Problem generating the ALT dataset. " + e.getMessage()); } printDataSet(telomeraseDataset); classify(telomeraseDataset); printConfusionMatrix(telomeraseDataset); printPredictionTable(); } /** * Reads the data from summaryFileHandler and the sample labels from tmmLabels. * Generates a one-coordinate classification dataset for the specified tmmReference * (ALT or Telomerase) * * @param summaryFileHandler * @param tmmReference the key specifying which TMM to separate: the ALT versus non-ALT cases, or Telomerase versus non-telomerase cases * @return returns the classification dataset * @throws Exception */ public ClassificationDataSet generateDataSet(SummaryFileHandler summaryFileHandler, String tmmReference) throws Exception { HashMap<String, HashMap<String, HashMap<String, Double>>> summaryMap = summaryFileHandler.getSummaryMap(); HashMap<String, Double> altScores = summaryMap.get(SummaryFileHandler.ALTKEY).get(SummaryFileHandler.SCORESKEY); HashMap<String, Double> telomeraseScores = summaryMap.get(SummaryFileHandler.TELOMERASEKEY).get(SummaryFileHandler.SCORESKEY); // 1 - means one dimension; new CategoricalData(2) means two categories CategoricalData[] categoricalDatas = new CategoricalData[1]; CategoricalData categoricalData = new CategoricalData(2); categoricalData.setCategoryName("tmmclass"); if (tmmReference.equals(TMMLabels.A)) { categoricalData.setOptionName(ALTOPTION, 1); categoricalData.setOptionName(NONALTOPTION, 0); } else { categoricalData.setOptionName(TELOMERASEOPTION, 1); categoricalData.setOptionName(NONTELOMERASEOPTION, 0); } categoricalDatas[0] = categoricalData; ClassificationDataSet tmmDataSet = new ClassificationDataSet(1, categoricalDatas, categoricalData); int ind = 0; for (String s : summaryFileHandler.getSamples()) { double score; if (tmmReference.equals(TMMLabels.A)) score = altScores.get(s); else score = telomeraseScores.get(s); Vec vec = DenseVector.toDenseVec(score); String tmm = tmmLabels.getSampleTMMLabelMap().get(s); int cat; if (tmmReference.equals(TMMLabels.A)) cat = (tmm.equals(TMMLabels.A) || tmm.equals(TMMLabels.AT)) ? 1 : 0; else cat = (tmm.equals(TMMLabels.T) || tmm.equals(TMMLabels.AT)) ? 1 : 0; DataPoint dp = new DataPoint(vec, new int[]{cat}, categoricalDatas); try { tmmDataSet.addDataPoint(dp, cat); } catch (Exception e) { throw new Exception("Could not add datapoint to the dataset: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage())); } } return tmmDataSet; } /** * Performs classification on the dataset with the default linear classifier * pre-initialized for the SVM object. * * @param dataSet - A one dimensional dataset containing PSF scores for either of the TMM networks */ public void classify(ClassificationDataSet dataSet) throws Exception { int errors = 0; classifier.trainC(dataSet); CategoricalData predicting = dataSet.getPredicting(); int numOfClasses = dataSet.getClassSize(); classCount = predicting.getNumOfCategories(); confusionMatrix = new double[numOfClasses][numOfClasses]; ArrayList<Double> values0 = new ArrayList<>(); // keep all the values with 0 prediction ArrayList<Double> values1 = new ArrayList<>(); // keep all the values with 1 prediction for (int i = 0; i < dataSet.getSampleSize(); i++) { DataPoint dataPoint = dataSet.getDataPoint(i); int truth = dataSet.getDataPointCategory(i); CategoricalResults predictionResults = classifier.classify(dataPoint); int predicted = predictionResults.mostLikely(); if (dataSet.getPredicting().getOptionName(1).equals(ALTOPTION)) predictionTable[i][0] = (predicted != 0); else predictionTable[i][1] = (predicted != 0); if (predicted == 0) values0.add(dataPoint.getNumericalValues().get(0)); else values1.add(dataPoint.getNumericalValues().get(0)); if (predicted != truth) { errors++; confusionMatrix[truth][1 - truth] += 1; } else { confusionMatrix[truth][truth] += 1; } System.out.println(i + "| True Class: " + truth + ", Predicted: " + predicted + ", Confidence: " + predictionResults.getProb(predicted)); } double low = 0; if (values0.size() > 0) { for (double value : values0) if (value > low) low = value; } double up = 0; if (values1.size() > 0) { up = Double.MAX_VALUE; for (double value : values1) if (value < up) up = value; } if (dataSet.getPredicting().getOptionName(1).equals(ALTOPTION)) h = (up + low) / 2; else v = (up + low) / 2; //After counting the h and v, we should re-iterate the classification, // since sometimes the SVM will classify points with low ALT values as ALT positive // and those with high ALT values as ALT negative. So we will switch in the following lines. for (int i = 0; i < dataSet.getSampleSize(); i++) { DataPoint dataPoint = dataSet.getDataPoint(i); int truth = dataSet.getDataPointCategory(i); int predicted; if (dataSet.getPredicting().getOptionName(1).equals(ALTOPTION)) predicted = classify(dataPoint, h); else predicted = classify(dataPoint, v); if (dataSet.getPredicting().getOptionName(1).equals(ALTOPTION)) predictionTable[i][0] = (predicted != 0); else predictionTable[i][1] = (predicted != 0); if (predicted == 0) values0.add(dataPoint.getNumericalValues().get(0)); else values1.add(dataPoint.getNumericalValues().get(0)); if (predicted != truth) { errors++; confusionMatrix[truth][1 - truth] += 1; } else { confusionMatrix[truth][truth] += 1; } System.out.println(i + "| True Class: " + truth + ", Predicted: " + predicted ); } System.out.println(errors + " errors were made, " + 100.0 * errors / dataSet.getSampleSize() + "% error rate"); // I don't know what this is: useless staff // if (dataSet.getPredicting().getOptionName(1).equals(ALTOPTION)) { // classifier.supportsWeightedData(); // } else // classifier.supportsWeightedData(); } private int classify(DataPoint datapoint, double threshold){ return datapoint.getNumericalValues().get(0) >= threshold? 1 : 0; } /** * Used to get access to the bias field in the classifier through reflection. * * @param clazz * @param fieldName * @return * @throws NoSuchFieldException */ private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } /** * Prints the dataset * * @param dataSet */ public void printDataSet(ClassificationDataSet dataSet) { System.out.println("There are " + dataSet.getNumFeatures() + " features for this data set."); System.out.println(dataSet.getNumCategoricalVars() + " categorical features"); System.out.println("They are:"); for (int i = 0; i < dataSet.getNumCategoricalVars(); i++) System.out.println("\t" + dataSet.getCategoryName(i)); System.out.println(dataSet.getNumNumericalVars() + " numerical features"); System.out.println("They are:"); for (int i = 0; i < dataSet.getNumNumericalVars(); i++) System.out.println("\t" + dataSet.getNumericName(i)); System.out.println("\nThe whole data set"); for (int i = 0; i < dataSet.getSampleSize(); i++) { DataPoint dataPoint = dataSet.getDataPoint(i); System.out.println(dataPoint); System.out.println("DataPointCategory: " + dataSet.getDataPointCategory(i)); } } /** * Prints the confusion matrix. The rows represent true categories, while the columns - predictions. * * @param dataSet */ public void printConfusionMatrix(ClassificationDataSet dataSet) { if (confusionMatrix == null) System.out.println("Confusion matrix not initialized"); CategoricalData predicting = dataSet.getPredicting(); int nameLength = 10; for (int pfx = 0; pfx < classCount; ++pfx) { nameLength = Math.max(nameLength, predicting.getOptionName(pfx).length() + 2); } String var7 = "%-" + nameLength; System.out.printf(var7 + "s ", "Matrix"); for (int c = classCount; c > 0; c--) { System.out.printf(var7 + "s\t", predicting.getOptionName(classCount - c).toUpperCase()); } System.out.println(); for (int i = 0; i < confusionMatrix.length; ++i) { System.out.printf(var7 + "s ", predicting.getOptionName(i).toUpperCase()); for (int j = 0; j < classCount - 1; ++j) { System.out.printf(var7 + "f ", confusionMatrix[i][j]); } System.out.printf(var7 + "f\n", confusionMatrix[i][classCount - 1]); } } public void printPredictionTable() { System.out.println("Sample\tTrue TMM\tALT pred\tTelomerase pred\n"); for (int i = 0; i < summaryFileHandler.getSamples().size(); i++) { String sample = summaryFileHandler.getSamples().get(i); String tmm = tmmLabels.getSampleTMMLabelMap().get(sample); String isALT = predictionTable[i][0] ? "+" : "-"; String isTelomerase = predictionTable[i][1] ? "+" : "-"; System.out.println(sample + "\t" + tmm + "\t" + isALT + "\t" + isTelomerase + "\n"); } } public static void main(String[] args) { File summaryFile = new File("c:\\Dropbox\\Bioinformatics_Group\\The_telomere_project\\telomere_network\\alt-tert-networks\\p9.cl.av\\alt-tert\\Untitled_iteration\\psf_summary.xls"); SummaryFileHandler summaryFileHandler = null; try { summaryFileHandler = new SummaryFileHandler(summaryFile); } catch (Exception e) { e.printStackTrace(); } File tmmLabelsFile = new File("c:\\Dropbox\\Bioinformatics_Group\\The_telomere_project\\telomere_network\\alt-tert-networks\\p9.cl.av\\tmm_labels.txt"); TMMLabels tmmLabels = null; try { tmmLabels = new TMMLabels(tmmLabelsFile); } catch (Exception e) { e.printStackTrace(); } try { SVM svm = new SVM(summaryFileHandler, tmmLabels); ClassificationDataSet dataSet = svm.generateDataSet(summaryFileHandler, TMMLabels.A); svm.printDataSet(dataSet); svm.classify(dataSet); svm.printConfusionMatrix(dataSet); dataSet = svm.generateDataSet(summaryFileHandler, TMMLabels.T); svm.printDataSet(dataSet); svm.classify(dataSet); svm.printConfusionMatrix(dataSet); System.out.println("h: " + svm.getH() + " v: " + svm.getV()); } catch (Exception e) { e.printStackTrace(); } } public double getAccuracy() { if(accuracy != null) return accuracy; int correct = 0; int wrong = 0; // A, T, N, AT //truth\prediction double[][] allConfusionMatrix = new double[4][4]; for (int i = 0; i < summaryFileHandler.getSamples().size(); i++) { String sample = summaryFileHandler.getSamples().get(i); String tmm = tmmLabels.getSampleTMMLabelMap().get(sample); String pred; if (predictionTable[i][0]) if (predictionTable[i][1]) pred = TMMLabels.AT; else pred = TMMLabels.A; else if (predictionTable[i][1]) pred = TMMLabels.T; else pred = TMMLabels.N; if (tmm.equals(pred)){ correct++; } else { wrong++; } } accuracy = ((double) correct) / (wrong + correct); return accuracy; } }
true
d328afb24f0c2fa78b97a5fd565848ee2476e714
Java
codeboxgit/Test2
/JavaTest/src/com/test/Ex45_Override.java
UTF-8
2,755
3.921875
4
[]
no_license
package com.test; import java.util.Date; import java.util.Random; public class Ex45_Override { public static void main(String[] args) { //Ex45_Override.java //메소드 오버로딩 // - 동일한 이름의 메소드를 여러개 만드는 기술 // - 상속 유무와 관계없이 발생 //메소드 오버라이딩 // - 상속할 때 발생 OverrideParent p = new OverrideParent(); p.hello(); OverrideChild c = new OverrideChild(); c.hello(); //c.hi(); //Override 실제 예 Date d1 = new Date(); System.out.println(d1);//출력 System.out.println(d1.toString());//실제 Time2 t1 = new Time2(5, 20); System.out.println(t1.getTime()); //** System.out.println(t1); System.out.println(t1.toString()); //** //com.test.Time2@7d4991ad //자료형@해시코드 MyRandom2 rnd = new MyRandom2(); System.out.println(rnd.nextInt()); rnd.test(); }//main } class MyRandom2 extends Random { //멤버 구성 //1. Random의 멤버 상속 //2. 자신 멤버 //사용 빈도 높음 -> nextInt() @Override public int nextInt() { Random rnd = new Random(); return rnd.nextInt(10) + 1; } public void test() { //this : 객체 접근 지정자(연산자), 현재 코드를 가지고 있는 객체(인스턴스)를 가르키는 예약어 //super : 부모 객체 접근 지정자 System.out.println(this.nextInt()); System.out.println(super.nextInt()); } } class Time2 { private int hour; private int min; public Time2(int hour, int min) { this.hour = hour; this.min = min; } public String getTime() { //시간 확인용 return String.format("%d:%d" , this.hour , this.min); } //부모가 물려준 toString()을 재정의(Overriding) @Override public String toString() { //내부구현은 내맘 // -> 주로.. toString() 메소드는 객체 자신이 가지고 있는 데이터를 문자열로 돌려주는 코드를 구현 return String.format("%d:%d" , this.hour , this.min); } } class OverrideParent { public String name; public void hello() { System.out.println("안녕하십니까~"); } } class OverrideChild extends OverrideParent { //public String name;//사용X //아빠의 인사 방식X -> 자신만의 인사 방식O /* public void hi() { System.out.println("하이~"); } */ //메소드 재정의, Method Overriding // -> 왜?? // -> 전세대에서 정의한 메소드가 후세대에서 내용을 변경할 일이 생겼을때.. // -> 제 3자의 입장에서는 메소드 내용이 바뀌어도 접근 방식을 동일하게 제공하고 싶을때.. public void hello() { System.out.println("하이~"); } }
true
8721adb080f19e3c97d21684b1f46f07f272b264
Java
Joabenman/VistoYNoVisto
/app/src/main/java/com/vynv/proyecto/vistoynovisto/MainActivity.java
UTF-8
17,719
1.84375
2
[]
no_license
package com.vynv.proyecto.vistoynovisto; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Locale; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class MainActivity extends Activity { Socket miCliente; String direccion = "192.168.56.1";//oJo suele cambiar int puerto = 6000; ArrayList<Libro> datoslibros = new ArrayList(); LibroAdaptador adaptador; EditText editsearch; String titulo=""; String imagen=""; String editorial=""; String autor=""; String nfichero="recibelibros.xml"; private ListView listlibros; private int selectedItem; private TextView lblEtiqueta; private ListView lstOpciones; String menusocket; //cuando se lanza la aplicacion @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lblEtiqueta = (TextView)findViewById(R.id.LblEtiqueta); lstOpciones = (ListView)findViewById(R.id.LstOpciones); //enables filtering for the contents of the given ListView lstOpciones.setTextFilterEnabled(true); //Log.d("tag",datoslibros.get(0).getTitulo()); adaptador = new LibroAdaptador(this, datoslibros); lstOpciones.setAdapter(adaptador); lstOpciones.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { //Alternativa 1: String opcionSeleccionada = ((Libro) a.getAdapter().getItem(position)).getTitulo(); lblEtiqueta.setText("Libro seleccionado: " + opcionSeleccionada); } }); // Locate the EditText in listview_main.xml editsearch = (EditText) findViewById(R.id.search); // Capture Text in EditText editsearch.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub String text = editsearch.getText().toString().toLowerCase(Locale.getDefault()); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } }); listlibros = (ListView) findViewById(R.id.LstOpciones); //filtro EditText myFilter = (EditText) findViewById(R.id.search); myFilter.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { adaptador.getFilter().filter(s.toString()); } }); } //cargamos el menu @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } public void onResume() { super.onResume(); if(datoslibros.size()==0){ cargarLibros(); } registerForContextMenu(listlibros); } @Override public void onStop() { super.onStop(); guardarLibrosSincronizado(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == 1) { if (data.hasExtra("titulo")) { // Toast.makeText(this, data.getExtras().getString("titulo"), Toast.LENGTH_SHORT).show(); titulo = data.getExtras().getString("titulo"); } if (data.hasExtra("imagen")) { // Toast.makeText(this, data.getExtras().getString("imagen"),Toast.LENGTH_SHORT).show(); imagen = data.getExtras().getString("imagen"); } if (data.hasExtra("editorial")) { // Toast.makeText(this, data.getExtras().getString("editorial"), Toast.LENGTH_SHORT).show(); editorial = data.getExtras().getString("editorial"); } if (data.hasExtra("autor")) { // Toast.makeText(this, data.getExtras().getString("autor"),Toast.LENGTH_SHORT).show(); autor = data.getExtras().getString("autor"); } Log.d("tag", titulo); datoslibros.add(new Libro(titulo, imagen , editorial, autor)); adaptador.notifyDataSetChanged(); } if (resultCode == RESULT_OK && requestCode == 3) { if (data.hasExtra("titulo")) { // Toast.makeText(this, data.getExtras().getString("titulo"), Toast.LENGTH_SHORT).show(); titulo = data.getExtras().getString("titulo"); } if (data.hasExtra("imagen")) { // Toast.makeText(this, data.getExtras().getString("imagen"), Toast.LENGTH_SHORT).show(); imagen = data.getExtras().getString("imagen"); } if (data.hasExtra("editorial")) { // Toast.makeText(this, data.getExtras().getString("editorial"), Toast.LENGTH_SHORT).show(); editorial = data.getExtras().getString("editorial"); } if (data.hasExtra("autor")) { // Toast.makeText(this, data.getExtras().getString("autor"), Toast.LENGTH_SHORT).show(); autor = data.getExtras().getString("autor"); } Log.d("titulo", "en el main" + titulo); Log.d("titulo", "en el main" + selectedItem); datoslibros.set(selectedItem, new Libro(titulo, imagen , editorial, autor)); adaptador.notifyDataSetChanged(); } } //opciones del menu de la barra de herramientas @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.insertar: Intent intent = new Intent(this, Insertar.class); startActivityForResult(intent, 1); break; case R.id.guardar: guardarLibrosSincronizado(); break; case R.id.cargar: cargarLibros(); break; case R.id.importar: //CargarXmlTask cargarxml = new CargarXmlTask(); //cargarxml.execute("http://192.168.42.235/libros.xml"); /*String direccion = "192.168.42.235";//oJo int puerto = 6000; relacionservidor cargamos = new relacionservidor(direccion, puerto); cargamos.execute();*/ menusocket="1"; // relacionservidor cargamos = new relacionservidor(direccion, puerto, menusocket); // cargamos.execute(); break; case R.id.exportar: //CargarXmlTask cargarxml = new CargarXmlTask(); //cargarxml.execute("http://192.168.42.235/libros.xml"); /*String direccion = "192.168.42.235";//oJo int puerto = 6000; relacionservidor cargamos = new relacionservidor(direccion, puerto); cargamos.execute();*/ menusocket="0"; // relacionservidor cargamos2 = new relacionservidor(direccion, puerto, menusocket); // cargamos2.execute(); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; selectedItem = info.position; menu.setHeaderTitle(datoslibros.get(info.position).getTitulo()); inflater.inflate(R.menu.popup_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.mnuVisualizar: Intent intentVisualiza = new Intent(this, Visualizar.class); titulo =(datoslibros.get(info.position).getTitulo()); imagen =(datoslibros.get(info.position).getRutaimagen()); editorial =(datoslibros.get(info.position).getEditorial()); autor =(datoslibros.get(info.position).getAutor()); intentVisualiza.putExtra("titulo",titulo); intentVisualiza.putExtra("imagen",imagen); intentVisualiza.putExtra("editorial", editorial); intentVisualiza.putExtra("autor", autor); startActivity(intentVisualiza); break; case R.id.mnuEditar: Intent intent = new Intent(this, Editar.class); titulo =(datoslibros.get(info.position).getTitulo()); imagen =(datoslibros.get(info.position).getRutaimagen()); editorial =(datoslibros.get(info.position).getEditorial()); autor =(datoslibros.get(info.position).getAutor()); Log.d("titulo", titulo); intent.putExtra("titulo",titulo); intent.putExtra("imagen",imagen); intent.putExtra("editorial",editorial); intent.putExtra("autor", autor); startActivityForResult(intent, 3); break; case R.id.mnuBorrar: //lo borramos de la base de datos borrar(info); //lo borramos del listview y lo actualizamos datoslibros.remove(selectedItem); adaptador.notifyDataSetChanged(); break; } return true; } private void guardarLibrosSincronizado() { //guardamos los libros en la base de datos LibrosSQLiteHelper Librosdbh = new LibrosSQLiteHelper(this, "DBLibros", null, 1); SQLiteDatabase db = Librosdbh.getWritableDatabase(); ArrayList<Libro> enviadatos = new ArrayList(); enviadatos = datoslibros; datoslibros=Librosdbh.saveSincronizado(enviadatos); db.close(); adaptador = new LibroAdaptador(this, datoslibros); //actualizamos el listview lstOpciones.setAdapter(adaptador); //adaptador.notifyDataSetChanged(); Toast.makeText(this, "datos guardados de forma sincronizada ", Toast.LENGTH_SHORT).show(); } private void cargarLibros() { //cargamos los libros desde la base de datos Log.d("socket", "cargamos datos"); LibrosSQLiteHelper Librosdbh = new LibrosSQLiteHelper(this, "DBLibros", null, 1); SQLiteDatabase db = Librosdbh.getReadableDatabase(); datoslibros= Librosdbh.load(); db.close(); adaptador = new LibroAdaptador(this, datoslibros); //actualizamos el listview lstOpciones.setAdapter(adaptador); // adaptador.notifyDataSetChanged(); Toast.makeText(this, "datos cargados ", Toast.LENGTH_SHORT).show(); } private void borrar(AdapterView.AdapterContextMenuInfo info){ //lo borramos de la base de datos LibrosSQLiteHelper Librosdbh = new LibrosSQLiteHelper(this, "DBLibros", null, 1); titulo =(datoslibros.get(info.position).getTitulo()); //pillamos el titulo del elemento seleccionado Librosdbh.delete(titulo); } /* //adaptador del listview class LibroAdaptador extends ArrayAdapter<Libro> { Activity context; private ArrayList<Libro> listalibrosoriginal; private ArrayList<Libro> listalibros; private FiltroLibros filter; public LibroAdaptador(Context context, ArrayList<Libro> datoslib) { super(context, R.layout.listitem_libro, datoslib); this.listalibrosoriginal = new ArrayList<Libro>(); this.listalibrosoriginal.addAll(datoslib); this.listalibros= new ArrayList<Libro>(); this.listalibros.addAll(datoslib); } @Override public Filter getFilter() { if (filter == null){ filter = new FiltroLibros(); } return filter; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(getContext()); View item = inflater.inflate(R.layout.listitem_libro, null); TextView LblTitulo = (TextView)item.findViewById(R.id.LblListaTitulo); LblTitulo.setText(datoslibros.get(position).getTitulo()); ImageView ImgLibro = (ImageView)item.findViewById(R.id.ImgListaLibro); Bitmap image = BitmapFactory.decodeFile(datoslibros.get(position).getRutaimagen()); ImgLibro.setImageBitmap(image); TextView LblEditorial = (TextView) item.findViewById(R.id.LblListaEditorial); LblEditorial.setText(datoslibros.get(position).getEditorial()); TextView LblAutor = (TextView) item.findViewById(R.id.LblListaAutor); LblAutor.setText(datoslibros.get(position).getAutor()); return(item); } private class FiltroLibros extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { constraint = constraint.toString().toLowerCase(); FilterResults result = new FilterResults(); if(constraint != null && constraint.toString().length() > 0) { ArrayList<Libro> filteredItems = new ArrayList<Libro>(); for(int i = 0, l = listalibrosoriginal.size(); i < l; i++) { Log.d("filtro", listalibrosoriginal.size() + " " + listalibrosoriginal.get(i) + " " + constraint); Libro libro = listalibrosoriginal.get(i); if(libro.getTitulo().toLowerCase().contains(constraint)) filteredItems.add(libro); } result.count = filteredItems.size(); result.values = filteredItems; } else { synchronized(this) { result.values = listalibrosoriginal; result.count = listalibrosoriginal.size(); } } return result; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { listalibros = (ArrayList<Libro>)results.values; notifyDataSetChanged(); clear(); for(int i = 0, l = listalibros.size(); i < l; i++) add(listalibros.get(i)); notifyDataSetInvalidated(); } } }*/ }
true
4bdf9f734d4dc95967d908443095afabe9187c1e
Java
Ericliu001/PlayMarkMurphy
/src/com/playmarkmurphy/alarm/PollReceiver.java
UTF-8
827
2.21875
2
[]
no_license
package com.playmarkmurphy.alarm; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class PollReceiver extends BroadcastReceiver { private static final int PERIOD = 3500; @Override public void onReceive(Context context, Intent intent) { scheduleAlarms(context); } static void scheduleAlarms(Context context) { AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, ScheduledService.class); PendingIntent pi = PendingIntent.getService(context, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi); } }
true
f42f24833480cbb28e3b830ced7577f4e0f2e875
Java
devil-yao/sso
/demo-stream-activemq/src/main/java/org/demo/yj/ActivemqChannel.java
UTF-8
1,103
1.84375
2
[]
no_license
package org.demo.yj; import org.springframework.cloud.stream.binder.*; import org.springframework.cloud.stream.provisioning.ConsumerDestination; import org.springframework.cloud.stream.provisioning.ProducerDestination; import org.springframework.integration.core.MessageProducer; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; public class ActivemqChannel extends AbstractMessageChannelBinder<ConsumerProperties,ProducerProperties,ActivemqProvisioningProvider> { public ActivemqChannel(String[] headersToEmbed, ActivemqProvisioningProvider provisioningProvider) { super(headersToEmbed, provisioningProvider); } @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ProducerProperties producerProperties, MessageChannel errorChannel) throws Exception { return null; } @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ConsumerProperties properties) throws Exception { return null; } }
true
904d3a3252310623c12f458c19458ffc454beb7e
Java
szaqal/AGHProjects
/Agh_Compute/ProcessComputation/src/computation/worker/NodeInvokerWorker.java
UTF-8
1,437
2.28125
2
[]
no_license
package computation.worker; import java.io.Serializable; import java.util.HashMap; import api.computation.ComputationContext; import computation.exceptions.ComputationRunTimeException; import computation.model.ComputingNode; import computation.model.PerformedComputation; /** * Handles core operations based. * @author malczyk.pawel@gmail.com * */ public interface NodeInvokerWorker { /** * Invokes operation on node server. * * @param node * registered computing node. * @param inputs * task inputs * @param outputs * task outputs * @param taskName * task name to be computed * @param performedComputation * needed in order to create computation log * @param computationContext * current compuation context. * @throws ComputationRunTimeException * that may be throwed * @return xml result. */ HashMap<String, Serializable> invoke(ComputingNode node, HashMap<String, Serializable> inputs, HashMap<String, Serializable> outputs, String taskName, PerformedComputation performedComputation, ComputationContext computationContext) throws ComputationRunTimeException; /** * Local interface. * @author malczyk.pawel@gmail.com * */ public interface NodeInvokerWorkerLocal extends NodeInvokerWorker { } /** * Remote interface. * @author malczyk.pawel@gmail.com * */ public interface NodeInvokerWorkerRemote extends NodeInvokerWorker { } }
true
d9dcd8ff9d2d8423e1ee02f8693ce241d8a102e7
Java
shuhui-csh/DataShow
/DShow/src/gd/dshow/ui/LoginActivity.java
UTF-8
2,684
2.125
2
[]
no_license
package gd.dshow.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import gd.dshow.R; import gd.dshow.http.MyAsyncTaskUtils; import gd.dshow.interfaces.IShowView; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import gd.dshow.http.*; public class LoginActivity extends Activity { private Button login, register, forget; private EditText account, password; private IShowView mishowview; private MyAsyncTaskUtils task; private Context context = LoginActivity.this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 隐藏标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login); account = (EditText) findViewById(R.id.et_account); password = (EditText) findViewById(R.id.et_password); login = (Button) findViewById(R.id.bt_login); register = (Button) findViewById(R.id.bt_register); forget = (Button) findViewById(R.id.bt_forget); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String admin = account.getText().toString(); String passwordstr = password.getText().toString(); mishowview = new MIshowview(); task = new MyAsyncTaskUtils(LoginActivity.this, mishowview); String[] str = { admin, passwordstr, HttpURL.Login }; task.execute(str); } }); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } class MIshowview implements IShowView { @Override public void showView(String str) { if (str.equals("601")) { Toast.makeText(context, "正常登陆", 1000).show(); Intent intent = new Intent(); intent.setClass(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } else if (str.equals("602")) { Toast.makeText(context, "用户不存在", 2000).show(); } else if (str.equals("603")) { Toast.makeText(context, "密码错误", 2000).show(); } // TODO Auto-generatedmethod stub Log.i("MainActivity", str); /* * String title = JsonTools.getString("title", str); List<String> * list = JsonTools.getList("data", str); * listview.setAdapter(MainActivity .setAdapter(MainActivity.this, * list)); textview.setText(title); */ } } }
true
dbb61536eeb8ba2935cee0b950ecd53d837d6a60
Java
trunkatree/numerical_analysis_1
/src/math2/Gauss.java
UTF-8
2,053
3.59375
4
[]
no_license
package math2; public class Gauss { // Gaussの消去法(前進消去過程) // Gaussの消去法(後退代入過程) public static void main(String[] args) { double A[][] = {{1, 2, 1, 2, 1}, {2, 3, 2, 3, 2}, {1, 2, 3, 4, 5}, {4, 3, 8, 1, 2}, {8, 2, 4, 1, 9}}; double b[] ={7, 7, 7, 7, 7}; /* ここで初期値をとっておいても なぜかbとともに変更されてしまうから 最期に初期値をもう一度入力することにする originA = A;では、結局同じ場所を参照することになってしまう? 配列のセルごとにコピーすればいい? double originA[][] = new double[A.length][A[0].length]; double originb[] = new double[b.length]; originA = A; originb = b; */ int n = A.length; double originA[][] = new double[n][n]; double originb[] = new double[n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { originA[i][j] = A[i][j]; } originb[i] = b[i]; } double α = 0.0; // 前進消去過程 for(int k=0; k<n-1; k++) { // 第k+1列目の消去を計算 for(int i=k+1; i<n; i++) { // i行 α = A[i][k]/A[k][k]; for(int j=k+1; j<n; j++) { // j列 A[i][j] = A[i][j] - α*A[k][j]; } b[i] = b[i] - α*b[k]; } } Calc.printMat(A); System.out.println(); Calc.printVec(b); System.out.println(); // 後退代入過程 /* int k = b.length-1; b[k] = b[k]/A[k][k]; for(int i=k-1; i>=0; i--) { α = 0.0; for(int j=k; j>i; j--) { α += A[i][j]*b[j]; } b[i] = (b[i]-α)/A[i][i]; } Calc.printVec(b); // 解 */ for(int i=n-1; i>=0; i--) { for(int j=n-1; j>i; j--) { b[i] -= A[i][j]*b[j]; } b[i] = b[i]/A[i][i]; } Calc.printVec(b); // 解 System.out.println(); // 残差2ノルムを求める System.out.println(Calc.vecNorm2(Calc.residual(originA, b, originb))); } }
true
284a4145f23317c63e9a0cc1333b3ba7084f6288
Java
andresrub10/parroquia_asuncion_del_senor
/WS/src/main/java/com/bezikee/DataAccessLayer/User/UserBean.java
UTF-8
2,299
2.46875
2
[]
no_license
package com.bezikee.DataAccessLayer.User; import java.sql.Date; import java.sql.Timestamp; public class UserBean { private int id; private String name; private String lastName; private String email; private String username; private String password; private String birthDate; private String sex; public UserBean(String name, String lastName, String email, String username, String password, String birthDate, String sex) { this.name = name; this.lastName = lastName; this.email = email; this.username = username; this.password = password; this.birthDate = birthDate; this.sex = sex; } public UserBean(int id, String name, String lastName, String email, String username, String password, String birthDate, String sex) { this.id = id; this.name = name; this.lastName = lastName; this.email = email; this.username = username; this.password = password; this.birthDate = birthDate; this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
true
9a856dcc92e3b35f1e57e7147834f531d6500bfe
Java
deveshsheth/HealthAssistAPI
/src/main/java/com/dao/OtpDao.java
UTF-8
440
2.0625
2
[]
no_license
package com.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class OtpDao { @Autowired JdbcTemplate stmt; public void updateOtp(String email, String otp) { // TODO Auto-generated method stub stmt.update("update users set otp = ? where email = ?", otp, email); } }
true
fb14170956ebc5745c092a4d51c73713a739399d
Java
helyho/Voovan
/Common/src/test/java/org/voovan/test/tools/json/JSONRunTimeTest.java
UTF-8
1,315
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package org.voovan.test.tools.json; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; public class JSONRunTimeTest { public static void main(String[] args) { TestObject testObject = new TestObject(); testObject.setString(null); testObject.setBint(32); testObject.getList().add("listitem1"); testObject.getList().add("listitem2 "); testObject.getList().add("listitem3"); testObject.getMap().put("mapitem1", "mapitem1"); testObject.getMap().put("mapitem2", "mapitem2"); testObject.getTb2().setString("bingo"); testObject.getTb2().setBint(56); testObject.getTb2().getList().add("tb2 list item"); testObject.getTb2().getMap().put("tb2 map item", "tb2 map item"); long start = System.currentTimeMillis(); String jsonString = JSON.toJSON(testObject); Logger.simple("----Serial Time:"+(System.currentTimeMillis()-start)); Logger.simple(jsonString); start = System.currentTimeMillis(); Object object = JSON.parse(jsonString); Logger.simple("\r\n----Deserial Map Time:"+(System.currentTimeMillis()-start)); Logger.simple(object); start = System.currentTimeMillis(); TestObject tObject = JSON.toObject(jsonString,TestObject.class); Logger.simple("\r\n----Deserial Object Time:"+(System.currentTimeMillis()-start)); Logger.simple(tObject); } }
true
9d5d816a17c68a3d8fb01e5707f7c1bff05d7086
Java
jmprathab/MyHome
/service/src/main/java/com/myhome/controllers/mapper/SchedulePaymentApiMapper.java
UTF-8
5,647
1.835938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Prathab Murugan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.myhome.controllers.mapper; import com.myhome.controllers.dto.PaymentDto; import com.myhome.controllers.dto.UserDto; import com.myhome.controllers.request.EnrichedSchedulePaymentRequest; import com.myhome.domain.Community; import com.myhome.domain.HouseMember; import com.myhome.domain.Payment; import com.myhome.domain.User; import com.myhome.model.AdminPayment; import com.myhome.model.HouseMemberDto; import com.myhome.model.MemberPayment; import com.myhome.model.SchedulePaymentRequest; import com.myhome.model.SchedulePaymentResponse; import java.util.Set; import java.util.stream.Collectors; import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.Mappings; import org.mapstruct.Named; @Mapper public interface SchedulePaymentApiMapper { @Named("adminIdToAdmin") static UserDto adminIdToAdminDto(String adminId) { return UserDto.builder() .userId(adminId) .build(); } @Named("memberIdToMember") static HouseMemberDto memberIdToMemberDto(String memberId) { return new HouseMemberDto() .memberId(memberId); } @Named("adminToAdminId") static String adminToAdminId(UserDto userDto) { return userDto.getUserId(); } @Named("memberToMemberId") static String memberToMemberId(HouseMemberDto houseMemberDto) { return houseMemberDto.getMemberId(); } @Mappings({ @Mapping(source = "adminId", target = "admin", qualifiedByName = "adminIdToAdmin"), @Mapping(source = "memberId", target = "member", qualifiedByName = "memberIdToMember") }) PaymentDto schedulePaymentRequestToPaymentDto(SchedulePaymentRequest schedulePaymentRequest); PaymentDto enrichedSchedulePaymentRequestToPaymentDto( EnrichedSchedulePaymentRequest enrichedSchedulePaymentRequest); @AfterMapping default void setUserFields(@MappingTarget PaymentDto.PaymentDtoBuilder paymentDto, EnrichedSchedulePaymentRequest enrichedSchedulePaymentRequest) { // MapStruct and Lombok requires you to pass in the Builder instance of the class if that class is annotated with @Builder, or else the AfterMapping method is not used. // required to use AfterMapping to convert the user details of the payment request to admin, and same with house member paymentDto.member(getEnrichedRequestMember(enrichedSchedulePaymentRequest)); paymentDto.admin(getEnrichedRequestAdmin(enrichedSchedulePaymentRequest)); } Set<MemberPayment> memberPaymentSetToRestApiResponseMemberPaymentSet( Set<Payment> memberPaymentSet); @Mapping(target = "memberId", expression = "java(payment.getMember().getMemberId())") MemberPayment paymentToMemberPayment(Payment payment); Set<AdminPayment> adminPaymentSetToRestApiResponseAdminPaymentSet( Set<Payment> memberPaymentSet); @Mapping(target = "adminId", expression = "java(payment.getAdmin().getUserId())") AdminPayment paymentToAdminPayment(Payment payment); @Mappings({ @Mapping(source = "admin", target = "adminId", qualifiedByName = "adminToAdminId"), @Mapping(source = "member", target = "memberId", qualifiedByName = "memberToMemberId") }) SchedulePaymentResponse paymentToSchedulePaymentResponse(PaymentDto payment); default EnrichedSchedulePaymentRequest enrichSchedulePaymentRequest( SchedulePaymentRequest request, User admin, HouseMember member) { Set<String> communityIds = admin.getCommunities() .stream() .map(Community::getCommunityId) .collect(Collectors.toSet()); return new EnrichedSchedulePaymentRequest(request.getType(), request.getDescription(), request.isRecurring(), request.getCharge(), request.getDueDate(), request.getAdminId(), admin.getId(), admin.getName(), admin.getEmail(), admin.getEncryptedPassword(), communityIds, member.getMemberId(), member.getId(), member.getHouseMemberDocument() != null ? member.getHouseMemberDocument() .getDocumentFilename() : "", member.getName(), member.getCommunityHouse() != null ? member.getCommunityHouse().getHouseId() : ""); } default UserDto getEnrichedRequestAdmin(EnrichedSchedulePaymentRequest enrichedSchedulePaymentRequest) { return UserDto.builder() .userId(enrichedSchedulePaymentRequest.getAdminId()) .id(enrichedSchedulePaymentRequest.getAdminEntityId()) .name(enrichedSchedulePaymentRequest.getAdminName()) .email(enrichedSchedulePaymentRequest.getAdminEmail()) .encryptedPassword(enrichedSchedulePaymentRequest.getAdminEncryptedPassword()) .build(); } default HouseMemberDto getEnrichedRequestMember(EnrichedSchedulePaymentRequest enrichedSchedulePaymentRequest) { return new HouseMemberDto() .id(enrichedSchedulePaymentRequest.getMemberEntityId()) .memberId(enrichedSchedulePaymentRequest.getMemberId()) .name(enrichedSchedulePaymentRequest.getHouseMemberName()); } }
true
540c0f893f72febd8f8c610784e0b1f7f5a65eab
Java
alfonso74/automart
/am-counterpoint/src/main/java/com/orendel/counterpoint/domain/InventoryPK.java
UTF-8
1,431
2.421875
2
[]
no_license
package com.orendel.counterpoint.domain; import java.io.Serializable; public class InventoryPK implements Serializable { private static final long serialVersionUID = 527884612930924245L; private String itemNo; private String locationId; public InventoryPK() { } public InventoryPK(String itemNo, String locationId) { super(); this.itemNo = itemNo; this.locationId = locationId; } public String getItemNo() { return itemNo; } public void setItemNo(String itemNo) { this.itemNo = itemNo; } public String getLocationId() { return locationId; } public void setLocationId(String locationId) { this.locationId = locationId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((itemNo == null) ? 0 : itemNo.hashCode()); result = prime * result + ((locationId == null) ? 0 : locationId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InventoryPK other = (InventoryPK) obj; if (itemNo == null) { if (other.itemNo != null) return false; } else if (!itemNo.equals(other.itemNo)) return false; if (locationId == null) { if (other.locationId != null) return false; } else if (!locationId.equals(other.locationId)) return false; return true; } }
true
78d534ac99942527c471fcee7536ae9c8912ed6c
Java
Layoomielie/design-power
/src/main/java/com/example/facade/Circle.java
UTF-8
282
2.328125
2
[]
no_license
package com.example.facade;/** * ${tag} * * @author zhanghongjian * @Date 2019/6/14 17:43 */ /** * @author:张鸿建 * @time:2019/6/14 * @desc: **/ public class Circle implements Shape { public void draw() { System.out.println("Circle::draw()"); } }
true
4a711d883743179f5af25a654d1555ffecd05e18
Java
Liammi/movie-recommend
/movie-recommend/src/main/java/me/quinn/movie/domain/Audience.java
UTF-8
468
1.734375
2
[ "MIT" ]
permissive
package me.quinn.movie.domain; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Data @Component public class Audience { @Value("${audience.clientId}") private String clientId; @Value("${audience.base64Secret}") private String base64Secret; @Value("${audience.name}") private String name; @Value("${audience.expiresSecond}") private int expiresSecond; }
true
118c8a55fa56e196e3eaf557df814d72db120666
Java
Adtx/PEI-GRUPO5
/dl4j-examples-master/Anansi/src/Servlet/CompanyProfile.java
UTF-8
4,084
2.40625
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
package Servlet; import bean.Context.ContextBeanLocal; import bean.Response.ResponseBeanLocal; import bean.util.AppConfigBeanLocal; import bean_lookup.AppConfigBeanLookup; import bean_lookup.ContextBeanLookup; import bean_lookup.ResponseBeanLookup; import hibernate.Company; import hibernate.Context; import hibernate.Context1; import hibernate.ContextDAO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.security.SecureRandom; @WebServlet(name = "companyProfile") public class CompanyProfile extends HttpServlet { static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static SecureRandom rnd = new SecureRandom(); String randomString( int len ){ StringBuilder sb = new StringBuilder( len ); for( int i = 0; i < len; i++ ) sb.append( AB.charAt( rnd.nextInt(AB.length()) ) ); return sb.toString(); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // --- BEANS AppConfigBeanLocal appConfig = AppConfigBeanLookup.getAppConfigBean(); ContextBeanLocal contextBeanLocal = ContextBeanLookup.getContextBean(); ResponseBeanLocal responseBeanLocal = ResponseBeanLookup.getResponserBean(); HttpSession httpSession = request.getSession(); Company c = (Company )httpSession.getAttribute("company"); try { String nome = request.getParameter("name"); String pw = request.getParameter("pass"); request.removeAttribute("name"); request.removeAttribute("pass"); if (nome != null && pw != null) { Context con = new Context(); con.setName(nome); con.setPassword(pw); con.setCompany(c); con.setCode(randomString(16)); while (contextBeanLocal.getContextByCode(con.getCode()) != null) { con.setCode(randomString(16)); } ContextDAO.save(con); } Context[] contexts = contextBeanLocal.getCompanyContexts(c.getID()); Context1[]context1s= new Context1[contexts.length]; for(int i=0;i<contexts.length;i++) { Context1 temp = new Context1(); temp.setName(contexts[i].getName()); temp.setCode(contexts[i].getCode()); temp.setID(contexts[i].getID()); temp.setPassword(contexts[i].getPassword()); temp.setStats(responseBeanLocal.getContextResponses(contexts[i].getID())); context1s[i] = temp; } httpSession.setAttribute("contexts",context1s); }catch (Exception e){ e.printStackTrace(); } // POST and GET String page = "companyProfile"; request.setAttribute("req_project_name", appConfig.getProject() ); request.setAttribute("req_page_title", appConfig.getPageTitle(page) ); request.setAttribute("req_page_jsp_files", appConfig.getPageTemplates(page) ); getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/template.jsp").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (Exception e) { e.printStackTrace(); } } }
true
565396af1e501ffcfde1fa3b8800568fe6a11260
Java
klimovm/code
/src/main/java/kurs2/week2/day2HomeWork/myArrayList/TestStudent.java
UTF-8
3,103
3.34375
3
[]
no_license
package kurs2.week2.day2HomeWork.myArrayList; import kurs2.week2.day2HomeWork.studArrayList.Student; import kurs2.utils.MyDate; /** * Created by miha on 02.06.2016. */ public class TestStudent { public static void main(String[] args) { /************************создаем студентов**********************************/ Student student1 = new Student("Саша", new MyDate(1989, 04, 20), 15.2, 180); Student student2 = new Student("Коля", new MyDate(1988, 04, 21), 11.2, 181); Student student3 = new Student("Олег", new MyDate(1988, 04, 22), 13.2, 182); Student student4 = new Student("Ваня", new MyDate(1988, 04, 23), 13.0, 182); Student student5 = new Student("Толя", new MyDate(1989, 04, 20), 10.2, 180); /************************создаем группу*************************************/ Group aco13 = new Group("aco13"); /************************добавляем студента группу*************************/ aco13.addStudent(student1); aco13.addStudent(student2); aco13.addStudent(student3); aco13.addStudent(student4); aco13.addStudent(student5); /************************добавляем студента по индексу*************************/ /* aco13.add(5,"Валентина");// ндексу у прупет метода добавления по ин aco13.add(5,"Ирина"); aco13.add(5,"Катерина");*/ /************************Смотрим что вышло*************************/ aco13.showGroup(); System.out.println(); /************************Удаляем студента по объекту*************************/ aco13.delStudentObject(student1); /************************Удаляем студента по индексу*************************/ //aco13.remove(6); нет метода у групе удаления по индексу /************************Смотрим что вышло*************************/ aco13.showGroup(); System.out.println(); /************ получения объекта по индексу*****************/ /// System.out.println(aco13.(1)); либо пишем гетеры и сметеры либо public System.out.println(); /********Заменяем объект новым объектом в позиции******/ /*aco13.set(0,"Барак Обама"); aco13.show(); System.out.println(); *//********Показываем сколько непустых елементов******//* System.out.println(aco13.size()); System.out.println(); *//********Проверяет есть ли объект в листе******//* System.out.println(aco13.contains("Слава")); System.out.println(); *//********Очищаем массив(заполняем null******//* aco13.clear(); aco13.show();*/ } }
true
a03fc743a89ca737c7b173f2d9af06fe8ada0523
Java
turbotobbe/swejug
/src/main/java/se/lingonskogen/gae/swejug/context/ServletContextVelocityListener.java
UTF-8
1,464
1.984375
2
[]
no_license
package se.lingonskogen.gae.swejug.context; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.tools.view.WebappResourceLoader; public class ServletContextVelocityListener implements ServletContextListener { private static final String CLASS = ServletContextVelocityListener.class.getName(); private static final Logger LOG = Logger.getLogger(CLASS); @Override public void contextInitialized(ServletContextEvent event) { LOG.log(Level.INFO, "Running velocity init ..."); ServletContext context = event.getServletContext(); VelocityEngine engine = new VelocityEngine(); engine.setApplicationAttribute("javax.servlet.ServletContext", context); Properties properties = new Properties(); properties.put("resource.loader", "webapp"); properties.put("webapp.resource.loader.class", WebappResourceLoader.class.getName()); properties.put("webapp.resource.loader.path", "/WEB-INF/velocity"); engine.init(properties); context.setAttribute("velocityEngine", engine); } @Override public void contextDestroyed(ServletContextEvent event) { // not run in GAE } }
true
dc6353ff54e70a011c69ebda1759af412d566cc4
Java
erderis/native_dapetfulus
/app/src/main/java/id/deris/dapetfulus/DBHelper.java
UTF-8
17,233
2.328125
2
[]
no_license
package id.deris.dapetfulus; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; import static android.content.ContentValues.TAG; public class DBHelper extends SQLiteOpenHelper { // Database Info private static final String DATABASE_NAME = "dapetfulusdb"; private static final int DATABASE_VERSION = 1; // Table Names private static final String TABLE_PAYMENT = "payments"; private static final String TABLE_QA = "qas"; private static final String TABLE_NOTIF = "notif"; private static final String TABLE_HISTORY = "histories"; // Payment Table Columns private static final String KEY_PAYMENT_ID = "id"; private static final String KEY_PAYMENT_VIA = "via"; private static final String KEY_PAYMENT_AMOUNT = "amount"; private static final String KEY_PAYMENT_STATUS = "status"; private static final String KEY_PAYMENT_TIME = "time"; // QA Table Columns private static final String KEY_QA_ID = "id"; private static final String KEY_QA_QUESTION = "question"; private static final String KEY_QA_ANSWER = "answer"; // Notif Table Columns private static final String KEY_NOTIF_ID = "id"; private static final String KEY_NOTIF_TITLE = "title"; private static final String KEY_NOTIF_DESCRIPTION = "description"; private static final String KEY_NOTIF_TIME = "time"; //History Table Column private static final String KEY_HISTORY_ID = "id"; private static final String KEY_HISTORY_TITLE = "title"; private static final String KEY_HISTORY_TIME = "time"; private static final String KEY_HISTORY_COIN = "coin"; private static DBHelper sInstance; public static synchronized DBHelper getInstance(Context context) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. // See this article for more information: http://bit.ly/6LRzfx if (sInstance == null) { sInstance = new DBHelper(context.getApplicationContext()); } return sInstance; } /** * Constructor should be private to prevent direct instantiation. * Make a call to the static method "getInstance()" instead. */ private DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Called when the database connection is being configured. // Configure database settings for things like foreign key support, write-ahead logging, etc. @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); db.setForeignKeyConstraintsEnabled(true); } // Called when the database is created for the FIRST time. // If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called. @Override public void onCreate(SQLiteDatabase db) { String CREATE_PAYMENT_TABLE = "CREATE TABLE " + TABLE_PAYMENT + "(" + KEY_PAYMENT_ID + " INTEGER PRIMARY KEY," + KEY_PAYMENT_VIA + " TEXT," + KEY_PAYMENT_AMOUNT + " TEXT," + KEY_PAYMENT_STATUS + " TEXT," + KEY_PAYMENT_TIME + " TEXT" + ")"; String CREATE_QA_TABLE = "CREATE TABLE " + TABLE_QA + "(" + KEY_QA_ID + " INTEGER PRIMARY KEY," + KEY_QA_QUESTION + " TEXT," + KEY_QA_ANSWER + " TEXT" + ")"; String CREATE_NOTIF_TABLE = "CREATE TABLE " + TABLE_NOTIF + "(" + KEY_NOTIF_ID+ " INTEGER PRIMARY KEY," + KEY_NOTIF_TITLE + " TEXT," + KEY_NOTIF_DESCRIPTION + " TEXT," + KEY_NOTIF_TIME + " TEXT" + ")"; String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "(" + KEY_HISTORY_ID + " INTEGER PRIMARY KEY," + KEY_HISTORY_TITLE + " TEXT," + KEY_HISTORY_TIME + " TEXT," + KEY_HISTORY_COIN + " TEXT" + ")"; db.execSQL(CREATE_PAYMENT_TABLE); db.execSQL(CREATE_QA_TABLE); db.execSQL(CREATE_NOTIF_TABLE); db.execSQL(CREATE_HISTORY_TABLE); } // Called when the database needs to be upgraded. // This method will only be called if a database already exists on disk with the same DATABASE_NAME, // but the DATABASE_VERSION is different than the version of the database that exists on disk. @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion != newVersion) { // Simplest implementation is to drop all old tables and recreate them db.execSQL("DROP TABLE IF EXISTS " + TABLE_PAYMENT); db.execSQL("DROP TABLE IF EXISTS " + TABLE_QA); db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTIF); onCreate(db); } } // Insert a paymnet into the database public void addPayment(WithdrawModel payment) { // Create and/or open the database for writing SQLiteDatabase db = getWritableDatabase(); // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures // consistency of the database. db.beginTransaction(); try { // The user might already exist in the database (i.e. the same user created multiple posts). ContentValues values = new ContentValues(); values.put(KEY_PAYMENT_VIA, payment.getVia()); values.put(KEY_PAYMENT_AMOUNT, payment.getAmount()); values.put(KEY_PAYMENT_STATUS, payment.getStatus()); values.put(KEY_PAYMENT_TIME, payment.getTime()); // Notice how we haven't specified the primary key. SQLite auto increments the primary key column. db.insertOrThrow(TABLE_PAYMENT, null, values); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to add post to database"); } finally { db.endTransaction(); } } public void addHistory(HistoryModel history) { // Create and/or open the database for writing SQLiteDatabase db = getWritableDatabase(); // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures // consistency of the database. db.beginTransaction(); try { // The user might already exist in the database (i.e. the same user created multiple posts). ContentValues values = new ContentValues(); values.put(KEY_HISTORY_TITLE, history.getTitle()); values.put(KEY_HISTORY_TIME, history.getTime()); values.put(KEY_HISTORY_COIN, history.getCoin()); // Notice how we haven't specified the primary key. SQLite auto increments the primary key column. db.insertOrThrow(TABLE_HISTORY, null, values); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to add post to database"); } finally { db.endTransaction(); } } // Insert a qa into the database public void addQA(QAModel qaModel) { deleteAllQA(); // Create and/or open the database for writing SQLiteDatabase db = getWritableDatabase(); // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures // consistency of the database. db.beginTransaction(); try { // The user might already exist in the database (i.e. the same user created multiple posts). ContentValues values = new ContentValues(); values.put(KEY_QA_QUESTION, qaModel.getQuestion()); values.put(KEY_QA_ANSWER, qaModel.getAnswer()); // Notice how we haven't specified the primary key. SQLite auto increments the primary key column. db.insertOrThrow(TABLE_QA, null, values); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to add post to database"); } finally { db.endTransaction(); } } // Insert a qa into the database public void addNotif(NotifModel notifModel) { deleteAllQA(); // Create and/or open the database for writing SQLiteDatabase db = getWritableDatabase(); // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures // consistency of the database. db.beginTransaction(); try { // The user might already exist in the database (i.e. the same user created multiple posts). ContentValues values = new ContentValues(); values.put(KEY_NOTIF_TITLE, notifModel.getTitle()); values.put(KEY_NOTIF_DESCRIPTION, notifModel.getDes()); values.put(KEY_NOTIF_TIME, notifModel.getTime()); // Notice how we haven't specified the primary key. SQLite auto increments the primary key column. db.insertOrThrow(TABLE_NOTIF, null, values); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to add notif to database"); } finally { db.endTransaction(); } } // Get all payment in the database public List<WithdrawModel> getAllPayment() { List<WithdrawModel> payment = new ArrayList<>(); // SELECT * FROM POSTS // LEFT OUTER JOIN USERS // ON POSTS.KEY_POST_USER_ID_FK = USERS.KEY_USER_ID String PAYMENT_SELECT_QUERY = "SELECT * FROM "+TABLE_PAYMENT + " ORDER BY "+KEY_PAYMENT_ID+" DESC"; // "getReadableDatabase()" and "getWriteableDatabase()" return the same object (except under low // disk space scenarios) SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(PAYMENT_SELECT_QUERY, null); try { if (cursor.moveToFirst()) { do { WithdrawModel withdrawModel= new WithdrawModel(); withdrawModel.setId(cursor.getInt(cursor.getColumnIndex(KEY_PAYMENT_ID))); withdrawModel.setVia(cursor.getString(cursor.getColumnIndex(KEY_PAYMENT_VIA))); withdrawModel.setAmount(cursor.getString(cursor.getColumnIndex(KEY_PAYMENT_AMOUNT))); withdrawModel.setStatus(cursor.getString(cursor.getColumnIndex(KEY_PAYMENT_STATUS))); withdrawModel.setTime(cursor.getString(cursor.getColumnIndex(KEY_PAYMENT_TIME))); payment.add(withdrawModel); } while(cursor.moveToNext()); } } catch (Exception e) { Log.d(TAG, "Error while trying to get posts from database"); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return payment; } // Get all history in the database public List<HistoryModel> getAllHistory() { List<HistoryModel> history = new ArrayList<>(); // SELECT * FROM POSTS // LEFT OUTER JOIN USERS // ON POSTS.KEY_POST_USER_ID_FK = USERS.KEY_USER_ID String HISTORY_SELECT_QUERY = "SELECT * FROM "+TABLE_HISTORY + " ORDER BY "+KEY_HISTORY_ID+" DESC"; // "getReadableDatabase()" and "getWriteableDatabase()" return the same object (except under low // disk space scenarios) SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(HISTORY_SELECT_QUERY, null); try { if (cursor.moveToFirst()) { do { HistoryModel historyModel = new HistoryModel(); historyModel.setId(cursor.getInt(cursor.getColumnIndex(KEY_HISTORY_ID))); historyModel.setTitle(cursor.getString(cursor.getColumnIndex(KEY_HISTORY_TITLE))); historyModel.setTime(cursor.getString(cursor.getColumnIndex(KEY_HISTORY_TIME))); historyModel.setCoin(cursor.getString(cursor.getColumnIndex(KEY_HISTORY_COIN))); history.add(historyModel); } while(cursor.moveToNext()); } } catch (Exception e) { Log.d(TAG, "Error while trying to get posts from database"); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return history; } // Get all qa in the database public List<QAModel> getAllQA() { List<QAModel> qa = new ArrayList<>(); // SELECT * FROM POSTS // LEFT OUTER JOIN USERS // ON POSTS.KEY_POST_USER_ID_FK = USERS.KEY_USER_ID String QA_SELECT_QUERY = "SELECT * FROM "+TABLE_QA + " ORDER BY "+KEY_QA_ID+" DESC"; // "getReadableDatabase()" and "getWriteableDatabase()" return the same object (except under low // disk space scenarios) SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(QA_SELECT_QUERY, null); try { if (cursor.moveToFirst()) { do { QAModel qaModel = new QAModel(); qaModel.setId(cursor.getInt(cursor.getColumnIndex(KEY_QA_ID))); qaModel.setQuestion(cursor.getString(cursor.getColumnIndex(KEY_QA_QUESTION))); qaModel.setAnswer(cursor.getString(cursor.getColumnIndex(KEY_QA_ANSWER))); qa.add(qaModel); } while(cursor.moveToNext()); } } catch (Exception e) { Log.d(TAG, "Error while trying to get posts from database"); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return qa; } // Get all qa in the database public List<NotifModel> getAllNotif() { List<NotifModel> notif = new ArrayList<>(); // SELECT * FROM POSTS // LEFT OUTER JOIN USERS // ON POSTS.KEY_POST_USER_ID_FK = USERS.KEY_USER_ID String NOTIF_SELECT_QUERY = "SELECT * FROM "+TABLE_NOTIF + " ORDER BY "+KEY_NOTIF_ID+" DESC"; // "getReadableDatabase()" and "getWriteableDatabase()" return the same object (except under low // disk space scenarios) SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(NOTIF_SELECT_QUERY, null); try { if (cursor.moveToFirst()) { do { NotifModel notifModel = new NotifModel(); notifModel.setId(cursor.getInt(cursor.getColumnIndex(KEY_NOTIF_ID))); notifModel.setTitle(cursor.getString(cursor.getColumnIndex(KEY_NOTIF_TITLE))); notifModel.setDes(cursor.getString(cursor.getColumnIndex(KEY_NOTIF_DESCRIPTION))); notifModel.setTime(cursor.getString(cursor.getColumnIndex(KEY_NOTIF_TIME))); notif.add(notifModel); } while(cursor.moveToNext()); } } catch (Exception e) { Log.d(TAG, "Error while trying to get notif from database"); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return notif; } // Delete all payment in the database public void deleteAllPayments() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { // Order of deletions is important when foreign key relationships exist. db.delete(TABLE_PAYMENT, null, null); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to delete all payment"); } finally { db.endTransaction(); } } public void deleteAllQA() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { // Order of deletions is important when foreign key relationships exist. db.delete(TABLE_QA, null, null); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to delete all qa"); } finally { db.endTransaction(); } } public void deleteAllNotif() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { // Order of deletions is important when foreign key relationships exist. db.delete(TABLE_NOTIF, null, null); db.setTransactionSuccessful(); } catch (Exception e) { Log.d(TAG, "Error while trying to delete all notifF"); } finally { db.endTransaction(); } } }
true
6e983f5d64e82dbdfea605dfc5ffd68e0fa14b1a
Java
sibi2016/OOPS-Concepts
/src/com/main/ShapeConstants.java
UTF-8
203
2.234375
2
[]
no_license
package com.main; public interface ShapeConstants { // Interface variable and method static double pi = 3.14; void circle(double radius); void circleArea(); void circlePerimeter(); }
true
6333df63e88db784adbb1b3c6ea5d4daaca520f3
Java
artisjaap/snooker-scoreboard
/src/main/java/be/qnh/gertronic/snooker/security/SecurityUtils.java
UTF-8
662
2.1875
2
[]
no_license
package be.qnh.gertronic.snooker.security; import org.springframework.security.core.context.SecurityContextHolder; import java.util.Optional; /** * Created by stijn on 20/01/18. */ public class SecurityUtils { public static Optional<MatchDetails> findSessionData() { if (SecurityContextHolder.getContext().getAuthentication() == null) { return null; } Object details = SecurityContextHolder.getContext().getAuthentication().getDetails(); if (MatchDetails.class.isAssignableFrom(details.getClass())) { return Optional.of((MatchDetails) details); } return Optional.empty(); } }
true
8b56ef604e5cb81e8a9e61920d348e6d250c96ba
Java
anty-filidor/photo-gallery
/app/src/main/java/com/example/gallery/ImageItem.java
UTF-8
4,906
2.390625
2
[]
no_license
package com.example.gallery; import android.graphics.BitmapFactory; import android.media.ExifInterface; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import java.io.File; import java.io.IOException; import java.sql.Date; import java.util.ArrayList; import java.util.Iterator; public class ImageItem implements Parcelable { private String path; private String title; public ImageItem(String path, String title) { super(); this.path = path; this.title = title; } public ImageItem(Parcel in) { super(); readFromParcel(in); } public static final Parcelable.Creator<ImageItem> CREATOR = new Parcelable.Creator<ImageItem>() { public ImageItem createFromParcel(Parcel in) { return new ImageItem(in); } public ImageItem[] newArray(int size) { return new ImageItem[size]; } }; public void readFromParcel(Parcel in) { path = in.readString(); title = in.readString(); } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(path); dest.writeString(title); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public ArrayList<ArrayList<String>> getMetaData() { ArrayList<String> metaDataValues = new ArrayList<String>(); ArrayList<String> metaDataTitles = new ArrayList<String>(); BitmapFactory.Options opts=new BitmapFactory.Options(); opts.inJustDecodeBounds=true; BitmapFactory.decodeFile(path, opts); metaDataTitles.add("Type:"); metaDataValues.add(opts.outMimeType); metaDataTitles.add("Width (px):"); metaDataValues.add("" + opts.outWidth); metaDataTitles.add("Height (px):"); metaDataValues.add("" + opts.outHeight); File file = new File(path); Date lastModified = new Date(file.lastModified()); metaDataTitles.add("Last modified:"); metaDataValues.add(lastModified.toString()); metaDataTitles.add("Size (kB):"); metaDataValues.add(file.length()/1024 + ""); metaDataTitles.add("Is hidden:"); metaDataValues.add(file.isHidden() ? "Yes" : "No"); try{ ExifInterface exif = new ExifInterface(path); metaDataTitles.add("Image description:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_IMAGE_DESCRIPTION)); metaDataTitles.add("Artist:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_ARTIST)); metaDataTitles.add("Model:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_MODEL)); metaDataTitles.add("Flash:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_FLASH)); metaDataTitles.add("Aspect frame:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_ORF_ASPECT_FRAME)); metaDataTitles.add("Saturation:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_SATURATION)); metaDataTitles.add("White balance:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_WHITE_BALANCE)); metaDataTitles.add("Color space:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_COLOR_SPACE)); metaDataTitles.add("Aperture (1/m):"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_APERTURE_VALUE)); metaDataTitles.add("Shuttler speed (s):"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_SHUTTER_SPEED_VALUE)); metaDataTitles.add("Orientation:"); metaDataValues.add(addMetaData(exif, ExifInterface.TAG_ORIENTATION)); /* Iterator itr1 = metaDataValues.listIterator(); Iterator itr2 = metaDataTitles.listIterator(); while(itr1.hasNext()) { Log.e("metadata Title", (String) itr2.next()); Log.e("metadata Value", (String) itr1.next()); } */ } catch(IOException e){ Log.e("ImageItem", "Unrecognised path!" + e.getMessage()); } ArrayList<ArrayList<String>> finalList = new ArrayList<ArrayList<String>>(); finalList.add(metaDataTitles); finalList.add(metaDataValues); return finalList; } private String addMetaData(ExifInterface exif, String TAG){ if(exif.getAttribute(TAG)==null){ return "No data"; } else return exif.getAttribute(TAG); } }
true
f7b32b18f6d0ede695b5154b2e8d245c5400c1f1
Java
elangeloscuro1/JavaKids
/JavaKidsSRC/Java001.java
UTF-8
1,909
3.953125
4
[]
no_license
import java.util.Scanner; public class Java001 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter your full name"); System.out.print("(for example: Speedy Gonzalez): "); String fullName = scan.nextLine(); System.out.println("You entered \"" + fullName + "\"\n"); System.out.print("Enter your age: "); int age = scan.nextInt();//scans on the same line and stays there waiting for a next call scan.nextLine();//finishes the previews call and get ready to get new input System.out.println("You entered \"" + age + "\"\n"); System.out.print("Enter the title of your a book: "); String bookTitle = scan.nextLine(); System.out.println("You entered \"" + bookTitle + "\"\n"); System.out.print("Enter a decimal number: "); System.out.print("(for example: 1.5): "); double aDecimal = scan.nextDouble();//scans on the same line and stays there waiting for a next call scan.nextLine();//finishes the previews call and get ready to get new input System.out.println("You entered \"" + aDecimal + "\"\n"); System.out.println("Enter four words (separated with spaces): "); String word1 = scan.next();//scans on the same line and stays there waiting for a next call String word2 = scan.next();//scans on the same line and stays there waiting for a next call String word3 = scan.next();//scans on the same line and stays there waiting for a next call String word4 = scan.next();//scans on the same line and stays there waiting for a next call scan.nextLine();//finishes the previews call and get ready to get new input System.out.println("You entered: "); System.out.println("\"" + word1 + "\""); System.out.println("\"" + word2 + "\""); System.out.println("\"" + word3 + "\""); System.out.println("\"" + word4 + "\""); System.out.println("\nEnd of the program!"); scan.close(); } }
true
89ef9274b04e50d5d3679d47e64c030e61b967ad
Java
fnk0/FormulaCalculator
/main/src/main/java/com/gabilheri/formulacalculator/main/logic/EvaluateExpression.java
UTF-8
14,453
2.828125
3
[]
no_license
package com.gabilheri.formulacalculator.main.logic; import android.app.Fragment; import android.util.Log; import com.gabilheri.formulacalculator.main.R; import com.gabilheri.formulacalculator.main.utils.Utils; import java.text.DecimalFormat; import de.congrace.exp4j.Calculable; import de.congrace.exp4j.CustomFunction; import de.congrace.exp4j.CustomOperator; import de.congrace.exp4j.ExpressionBuilder; import de.congrace.exp4j.InvalidCustomFunctionException; /** * Created by marcus on 5/15/14. * @author Marcus Gabilheri * @version 1.0 * @since May 2014 */ public class EvaluateExpression { private String expression, previousResult; private int angleType; public static int DEGREE = 0; public static int RADIANS = 1; private Fragment fragment; private DecimalFormat df; public static String LOG_TAG = "EVALUATE EXPRESSION"; private int precision; /** * Default constructor. */ public EvaluateExpression() { } /** * Constructor for the Evaluate Expression method. * @param expression * The expression to be evaluated * @param fragment * The fragment in which this expression is being callen */ public EvaluateExpression(String expression, Fragment fragment, int angleType) { this.expression = expression; this.fragment = fragment; this.angleType = angleType; precision = Utils.getPrecisionValue(fragment.getActivity()); df = Utils.getDecimalFormatForPrecision(precision); } /** * Returns the current expression of this method. * @return */ public String getExpression() { return expression; } /** * * @param expression */ public void setExpression(String expression) { this.expression = expression; } /** * Main evaluate method. Evaluates the expression and returns the result string. * @return */ public String evaluate() { String toReturn; Log.i("FULL EXPRESSION", expression); if(expression.equals("")) { return null; } CustomFunction arcSinFunc = null; CustomFunction arcCosFunc = null; CustomFunction arcTanFunc = null; CustomFunction cosdFunc = null; CustomFunction tandFunc = null; CustomFunction sindFunc = null; CustomFunction funX = null; CustomFunction taxFunc = null; CustomFunction log10 = null; CustomFunction ln = null; CustomFunction sqrt = null; CustomFunction cbrt = null; CustomFunction fact = null; CustomOperator percent = null; double varPi = Math.PI; double varE = Math.E; /** * The library has built in functions to handle all the trig functions * Overrading is necessary to handle degrees and radians */ try { cosdFunc = new CustomFunction("cos") { public double applyFunction(double[] values) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.cosDegrees(values[0]))); } else if(angleType == RADIANS) { return Double.parseDouble(df.format(Math.cos(values[0]))); } else { return 0; } } }; tandFunc = new CustomFunction("tan") { public double applyFunction(double[] values) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.tanDegrees(values[0]))); } else { return Double.parseDouble(df.format(Math.tan(values[0]))); } } }; sindFunc = new CustomFunction("sin") { public double applyFunction(double[] values) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.sinDegrees(values[0]))); } else { return Double.parseDouble(df.format(Math.sin(values[0]))); } } }; log10 = new CustomFunction("log") { public double applyFunction(double[] values) { return Math.log10(values[0]); } }; ln = new CustomFunction("ln") { public double applyFunction(double[] values) { return Math.log(values[0]); } }; sqrt = new CustomFunction("sqrt") { @Override public double applyFunction(double... doubles) { return Math.sqrt(doubles[0]); } }; fact = new CustomFunction("fact") { @Override public double applyFunction(double... doubles) { return factorial(doubles[0]); } }; cbrt = new CustomFunction("cbrt") { @Override public double applyFunction(double... doubles) { return Math.cbrt(doubles[0]); } }; arcSinFunc = new CustomFunction("arcSin") { @Override public double applyFunction(double... doubles) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.arcSinDegrees(doubles[0]))); } else { return Double.parseDouble(df.format(Math.asin(doubles[0]))); } } }; arcCosFunc = new CustomFunction("arcCos") { @Override public double applyFunction(double... doubles) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.arcCosDegrees(doubles[0]))); } else { return Double.parseDouble(df.format(Math.acos(doubles[0]))); } } }; arcTanFunc = new CustomFunction("arcTan") { @Override public double applyFunction(double... doubles) { if(angleType == DEGREE) { return Double.parseDouble(df.format(MathUtils.arcTanDegrees(doubles[0]))); } else { return Double.parseDouble(df.format(Math.atan(doubles[0]))); } } }; taxFunc = new CustomFunction("tax") { @Override public double applyFunction(double... doubles) { return doubles[0] * Utils.getTaxVaue(fragment.getActivity()); } }; /** * Override the normal modulus operand to handle the percentage. * */ // TODO implement settings to let the user choose between percent vs modulus percent = new CustomOperator("%", true, 4 ) { @Override protected double applyOperation(double[] doubles) { if (doubles[1] == 0d){ throw new ArithmeticException("Division by zero!"); } return ((doubles[0] / 100) * doubles[1]); } }; } catch (InvalidCustomFunctionException e1) { e1.printStackTrace(); } expression = Utils.stripHTML(expression); expression = expression.replaceAll(fragment.getActivity().getString(R.string.divide), "/"); expression = expression.replaceAll(fragment.getActivity().getString(R.string.multiply), "*"); expression = expression.replaceAll(fragment.getActivity().getString(R.string.cube_root), "cbrt"); expression = expression.replaceAll(fragment.getActivity().getString(R.string.sqrt), "sqrt"); if(!checkFactorial(expression)) { return "Factorial error! Should be whole number!"; } expression = expression.replaceAll(fragment.getString(R.string.factorial), "fact"); try { for (int i = 0; i < expression.length(); i++) { if (expression.charAt(i) == '(' && i > 0 && !Utils.isOperator(expression.charAt(i - 1), fragment.getActivity())) { if(expression.charAt(i) == '(' && expression.charAt(i -1) == '(') { continue; } expression = expression.substring(0, i) + "*" + expression.substring(i, expression.length()); } if (expression.charAt(i) == ')' && !Utils.isOperator(expression.charAt(i + 1), fragment.getActivity())) { if(expression.charAt(i) == ')' && expression.charAt(i + 1) == ')') { continue; } expression = expression.substring(0, i + 1) + "*" + expression.substring(i + 1, expression.length()); } if(expression.charAt(i) == 'e' || expression.charAt(i) == fragment.getActivity().getString(R.string.pi).charAt(0)) { if(Character.isDigit(expression.charAt(i - 1))) { expression = expression.substring(0, i) + "*" + expression.substring(i, expression.length()); } if(Character.isDigit(expression.charAt(i + 1))) { expression = expression.substring(0, i+1) + "*" + expression.substring(i+1, expression.length()); } } try { if (expression.charAt(i) == '.' && isNumber(expression.charAt(i - 1))) { Log.i("EVALUATE EXPRESSION!", "FOUND DOT"); expression = expression.substring(0, i) + "0" + expression.substring(i, expression.length()); i++; } } catch (Exception e) { expression = expression.substring(0, i) + "0" + expression.substring(i, expression.length()); i++; } } } catch (Exception ex) { } Log.i("EXPRESSION: ", expression); if(previousResult == null || previousResult.equals(fragment.getString(R.string.input_error))) { previousResult = "0.0"; } try { Calculable calc = new ExpressionBuilder(expression) .withOperation(percent) .withCustomFunction(cosdFunc) .withCustomFunction(sindFunc) .withCustomFunction(tandFunc) .withCustomFunction(log10) .withCustomFunction(ln) .withCustomFunction(sqrt) .withCustomFunction(cbrt) .withCustomFunction(arcSinFunc) .withCustomFunction(arcCosFunc) .withCustomFunction(arcTanFunc) .withCustomFunction(fact) .withCustomFunction(taxFunc) .withVariable(fragment.getString(R.string.pi), varPi) .withVariable(fragment.getString(R.string.var_e), varE) .withVariable(fragment.getString(R.string.ans), Double.parseDouble(previousResult)) .build(); double result = calc.calculate(); if(precision != 0) { result = Double.parseDouble(df.format(result)); } if(result % 1 == 0) { Log.i("RESULT: ", "IS INTEGER!"); long mLong = (long) result; toReturn = "" + mLong; } else { toReturn = "" + result; } } catch (Exception ex) { toReturn = fragment.getResources().getString(R.string.input_error); ex.printStackTrace(); } return toReturn; } /** * Small factorial function. * Needs to be improved for a more sofiscated version :D * @param num * The number to get the factorial for * @return * num! */ public double factorial(double num) { if(num == 0) { return 1; } return num * factorial(num -1); } public boolean isNumber(char c) { if (!Character.isDigit(c)) { return true; } return false; } /** * Helper function to check if all the factorial functions have valid input. * @param exp * the expression for this evaluate * @return * true if this expression can be evaluated. */ public boolean checkFactorial(String exp) { double toCheck; int start = 0; int end = 0; boolean check = false; for(int i = 0; i < exp.length(); i++) { if(exp.charAt(i) == '!') { Log.i("INSIDE CHECK FACTORIAL!", "FOUND FACTORIAL!"); check = true; start = i + 2; for(int j = i; j < exp.length(); j++) { if(exp.charAt(j) == ')') { end = j; break; } } } if(check) { //Log.i("INSIDE CHECK FACTORIAL", "Start: " + start + " End: " + end); toCheck = Double.parseDouble(exp.substring(start, end)); if(toCheck % 1 != 0) { return false; } } } //Log.i("INSIDE CHECK FACTORIAL!", "NO FACTORIAL!"); return true; } /** * * @return * The current Previous Answer that is being used by this expression */ public String getPreviousResult() { return previousResult; } /** * Setter to the Previous Answer * * @param previousResult * The previous Answer to be used by this Expression * @return * This Object for a Easy Chain build */ public EvaluateExpression setPreviousResult(String previousResult) { this.previousResult = previousResult; return this; } }
true
c71fbe70a6f38315e9de63640a85a03b3f15ca1c
Java
iarani5/Ejericicios-Java-parte-1
/Dvds/src/Catalogo.java
UTF-8
8,372
2.640625
3
[]
no_license
import javax.swing.JOptionPane; import java.util.*; public class Catalogo { private ArrayList<DVD> listado_dvds = new ArrayList<DVD>(); private ArrayList<CD> listado_cds = new ArrayList<CD>(); private String sub_indice; public Catalogo(){ } public String getSub_indice() { return sub_indice; } public void setSub_indice(String sub_indice) { this.sub_indice = sub_indice; } public ArrayList<DVD> getListado_dvds() { return listado_dvds; } public void setListado_dvds(ArrayList<DVD> listado_dvds) { this.listado_dvds = listado_dvds; } public ArrayList<CD> getListado_cds() { return listado_cds; } public void setListado_cds(ArrayList<CD> listado_cds) { this.listado_cds = listado_cds; } public void generar_listado_cds(){ CD cd = new CD(); cd.setTitulo("ZZ Album 1"); cd.setTiempo(2200); cd.setDisponible(true); cd.setInformacion("Aca un comentario del album 1"); cd.setGenero("Cumbia Villera"); cd.setInterprete("Iara"); cd.setCantidad_temas(12); this.listado_cds.add(cd); CD cd2 = new CD(); cd2.setTitulo("FF Album 2"); cd2.setTiempo(1000); cd2.setDisponible(false); cd2.setInformacion("Aca un comentario del album 2"); cd2.setGenero("Funk"); cd2.setInterprete("Marta"); cd2.setCantidad_temas(9); this.listado_cds.add(cd2); int choice = 0; choice = JOptionPane.showConfirmDialog(null, "Cargar CD?", "titulo", JOptionPane.YES_NO_OPTION); if(choice == JOptionPane.YES_OPTION) { do{ listado_cds.add(new CD()); listado_cds.get(listado_cds.size()-1).setTitulo(JOptionPane.showInputDialog("CD Titulo:")); listado_cds.get(listado_cds.size()-1).setTiempo(Integer.parseInt(JOptionPane.showInputDialog("CD Tiempo:"))); listado_cds.get(listado_cds.size()-1).setDisponible(Boolean.parseBoolean(JOptionPane.showInputDialog("CD Disponible (true/false):"))); listado_cds.get(listado_cds.size()-1).setInformacion(JOptionPane.showInputDialog("CD Informacion:")); listado_cds.get(listado_cds.size()-1).setGenero(JOptionPane.showInputDialog("CD Genero:")); listado_cds.get(listado_cds.size()-1).setInterprete(JOptionPane.showInputDialog("CD Interprete:")); listado_cds.get(listado_cds.size()-1).setCantidad_temas(Integer.parseInt(JOptionPane.showInputDialog("CD Cantidad de temas:"))); choice = JOptionPane.showConfirmDialog(null, "Cargar otro CD?", "titulo", JOptionPane.YES_NO_OPTION); } while(choice == JOptionPane.YES_OPTION); } } public void generar_listado_dvds(){ DVD dvd = new DVD(); dvd.setTitulo("SS peli 1"); dvd.setTiempo(2200); dvd.setDisponible(true); dvd.setInformacion("No asusta"); dvd.setGenero("Terror"); dvd.setDirector("Merluza"); this.listado_dvds.add(dvd); DVD dvd2 = new DVD(); dvd2.setTitulo("CC peli 2"); dvd2.setTiempo(1000); dvd2.setDisponible(true); dvd2.setInformacion("Medio pedorra"); dvd2.setGenero("Thriller"); dvd2.setDirector("Hakuna"); this.listado_dvds.add(dvd2); int choice = 0; choice = JOptionPane.showConfirmDialog(null, "Cargar DVD?", "titulo", JOptionPane.YES_NO_OPTION); if(choice == JOptionPane.YES_OPTION) { do{ listado_dvds.add(new DVD()); listado_dvds.get(listado_dvds.size()-1).setTitulo(JOptionPane.showInputDialog("DVD Titulo:")); listado_dvds.get(listado_dvds.size()-1).setTiempo(Integer.parseInt(JOptionPane.showInputDialog("DVD Tiempo:"))); listado_dvds.get(listado_dvds.size()-1).setDisponible(Boolean.parseBoolean(JOptionPane.showInputDialog("DVD Disponible (true/false):"))); listado_dvds.get(listado_dvds.size()-1).setInformacion(JOptionPane.showInputDialog("DVD Informacion:")); listado_dvds.get(listado_dvds.size()-1).setGenero(JOptionPane.showInputDialog("DVD Genero:")); listado_dvds.get(listado_dvds.size()-1).setDirector(JOptionPane.showInputDialog("DVD Director:")); choice = JOptionPane.showConfirmDialog(null, "Cargar otro DVD?", "titulo", JOptionPane.YES_NO_OPTION); } while(choice == JOptionPane.YES_OPTION); } } public void listadoCompleto(){ System.out.print("\n\n-------------------- Listado Completo: --------------------"); System.out.print("\n\n-------- CDS\n"); for(int i=0;i<listado_cds.size();i++){ System.out.print("\nTitulo: "+this.listado_cds.get(i).getTitulo()); System.out.print("\nTiempo:"+this.listado_cds.get(i).getTiempo()); System.out.print("\nDisponible: "+this.listado_cds.get(i).isDisponible()); System.out.print("\nInformacion: "+this.listado_cds.get(i).getInformacion()); System.out.print("\nGenero: "+this.listado_cds.get(i).getGenero()); System.out.print("\nInterprete: "+this.listado_cds.get(i).getInterprete()); System.out.print("\nCantidad de temas: "+this.listado_cds.get(i).getCantidad_temas()); System.out.print("\n"); } System.out.print("\n\n-------- DVDS\n"); for(int i=0;i<listado_dvds.size();i++){ System.out.print("\nTitulo: "+this.listado_dvds.get(i).getTitulo()); System.out.print("\nTiempo:"+this.listado_dvds.get(i).getTiempo()); System.out.print("\nDisponible: "+this.listado_dvds.get(i).isDisponible()); System.out.print("\nInformacion: "+this.listado_dvds.get(i).getInformacion()); System.out.print("\nGenero: "+this.listado_dvds.get(i).getGenero()); System.out.print("\nDirector: "+this.listado_dvds.get(i).getDirector()); System.out.print("\n"); } System.out.print("\n\n------------------------------------------------------------"); } public void cantidadDiscos(){ String a_buscar= JOptionPane.showInputDialog("\nCantidad de (CDS/DVDS):").toString(); System.out.print("\nListado Total de "+a_buscar+":"); if(a_buscar.equals("CDS")){ this.sub_indice = a_buscar; System.out.print("\n"+this.listado_cds.size()); } else if(a_buscar.equals("DVDS")){ this.sub_indice = a_buscar; System.out.print("\n"+this.listado_dvds.size()); } else{ System.out.print("\n"+"Opcion no disponible"); } } public void listadoDisponibles(){ System.out.print("\n\nListado de "+this.sub_indice+" Disponibles:"); if(sub_indice.equals("CDS")){ for(int i=0;i<listado_cds.size();i++){ if(this.listado_cds.get(i).isDisponible()){ System.out.print("\n"+this.listado_cds.get(i).getTitulo()); } } } else if(sub_indice.equals("DVDS")){ for(int i=0;i<listado_dvds.size();i++){ if(this.listado_dvds.get(i).isDisponible()){ System.out.print("\n"+this.listado_dvds.get(i).getTitulo()); } } String a_buscar_director= JOptionPane.showInputDialog("\nDirector:").toString(); System.out.print("\n\nListado de DVD dirigidos por "+a_buscar_director+":"); for(int i=0;i<listado_dvds.size();i++){ if(this.listado_dvds.get(i).getDirector().equals(a_buscar_director)){ System.out.print("\n"+this.listado_dvds.get(i).getTitulo()); } } } } public void listadoFiltrarPorTiempo(){ int cantidad_tiempo= Integer.parseInt(JOptionPane.showInputDialog("\nFiltrar por duracion de "+sub_indice+"(min):")); System.out.print("\n\nListado de "+this.sub_indice+" Que duran menos de "+cantidad_tiempo+" mins:"); if(sub_indice.equals("CDS")){ for(int i=0;i<listado_cds.size();i++){ if(this.listado_cds.get(i).getTiempo()<=cantidad_tiempo){ System.out.print("\n"+this.listado_cds.get(i).getTitulo()); } } } else if(sub_indice.equals("DVDS")){ for(int i=0;i<listado_dvds.size();i++){ if(this.listado_dvds.get(i).getTiempo()<=cantidad_tiempo){ System.out.print("\n"+this.listado_dvds.get(i).getTitulo()); } } } } public void listadoOrdenado(){ System.out.print("\n\nListado ordenado:\n"); ArrayList<String> listado_ordenado = new ArrayList<String>(); if(sub_indice.equals("CDS")){ for(int i=0;i<listado_cds.size();i++){ listado_ordenado.add(listado_cds.get(i).getTitulo()); } } else if(sub_indice.equals("DVDS")){ for(int i=0;i<listado_dvds.size();i++){ listado_ordenado.add(listado_dvds.get(i).getTitulo()); } } Collections.sort(listado_ordenado); for(String titulo : listado_ordenado){ System.out.println(titulo); } } }
true
0c8eeda1a2ff25a5f7aabf7b13a2f79d5588c4e9
Java
erdemce/usersystem
/Usersystem/src/main/java/com/spring/erdem/shared/dto/UserDto.java
UTF-8
682
1.742188
2
[]
no_license
package com.spring.erdem.shared.dto; import java.io.Serializable; import lombok.Getter; import lombok.Setter; public class UserDto implements Serializable { private static final long serialVersionUID = 8119784395508598970L; @Getter @Setter private long id; @Getter @Setter private String userId; @Getter @Setter private String firstName; @Getter @Setter private String lastName; @Getter @Setter private String email; @Getter @Setter private String password; @Getter @Setter private String encryptedPassword; @Getter @Setter private String emailVerificationToken; @Getter @Setter private Boolean emailVerificationStatus=false; }
true
5790de0c36cd04146010b7c3fb43b378ec8b29a7
Java
Qvodman/sixshop
/sixshop/src/Entity/CartInfo.java
UTF-8
684
2.296875
2
[]
no_license
package Entity; /** * 购物车信息类 * @author Qvodman * */ public class CartInfo { private String ID; private String UserID; private String GoodsID; private int number; public String getCartID() { return ID; } public void setCartID(String ID) { this.ID = ID; } public String getUserID() { return UserID; } public void setUserID(String UserID) { this.UserID = UserID; } public String getGoodsID() { return GoodsID; } public void setGoodsID(String GoodsID) { this.GoodsID = GoodsID; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } }
true
74b7999e5b5ad42b6bd4ba1a446fa40db31fbd7b
Java
Knight-Wu/exercise-book
/exerciseBook/src/main/java/algorithm/array/FindLostEle.java
UTF-8
1,001
3.765625
4
[]
no_license
package algorithm.array; import java.util.Arrays; import java.util.Collections; import java.util.List; // 最简便方法: 0到n+1求和减去当前数组的和即可,时间复杂度O(n) public class FindLostEle { public static void main(String[] args) { Integer[] a = {5, 6, 0, 1, 2, 3}; System.out.println(find(a)); } private static int find(Integer[] array) { int n = array.length; if (n <= 1) { throw new IllegalArgumentException("length must >1"); } List<Integer> list = Arrays.asList(array); Collections.sort(list); int i = 0; while (i <= n) { if (list.get(i + 1) - list.get(i) > 0 && list.get(i + 1) - list.get(i) > 1) { return (list.get(i + 1) - 1); } else if (list.get(i + 1) - list.get(i) < 0 && list.get(i) - list.get(i + 1) > 1) { return list.get(i) - 1; } i++; } return -1; } }
true
71a71579ae24d82ef49a4aefadc7cba4023187cd
Java
hhernaar/telephone-service
/src/main/java/com/hhernaar/telephone/TelephoneServiceApplication.java
UTF-8
566
1.820313
2
[ "MIT" ]
permissive
package com.hhernaar.telephone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @ComponentScan("com.hhernaar.telephone**") @PropertySource(value = {"classpath:rabbit-queue.properties"}) public class TelephoneServiceApplication { public static void main(String[] args) { SpringApplication.run(TelephoneServiceApplication.class, args); } }
true
65041b261731318313e8e7d72fab042b6d9ae118
Java
RomanKutseiko/citibikes
/src/main/java/com/kutseiko/bicycle/controller/UserController.java
UTF-8
1,861
2.171875
2
[]
no_license
package com.kutseiko.bicycle.controller; import com.kutseiko.bicycle.DTO.UserDto; import com.kutseiko.bicycle.entity.User; import com.kutseiko.bicycle.service.UserService; import java.util.List; import java.util.Optional; import javax.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") @RequiredArgsConstructor public class UserController { private final UserService userService; @GetMapping("/{id}") public Optional<User> getUserByID(@PathVariable(name = "id")Long id) { return userService.getUserById(id); } @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Optional<User> createUser(@RequestBody @Valid UserDto UserDto) { return userService.createUser(UserDto); } @PutMapping("/{id}") public Optional<User> updateUser(@RequestBody @Valid UserDto UserDto, @PathVariable(name = "id")Long id) { return userService.updateUser(id, UserDto); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public boolean updateUser(@PathVariable(name = "id")Long id) { return userService.deleteUserById(id); } }
true
0bcfb6ffe5e24487aced791ad6467f6b674df253
Java
Deyvisson1993/JavaMaster-Fuctura
/JavaMaster/src/main/java/br/com/JavaMaster/entidade/VotacaoUsuario.java
UTF-8
2,515
2.40625
2
[]
no_license
package br.com.JavaMaster.entidade; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class VotacaoUsuario { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long codigo; @ManyToOne private Votacao votacao; @ManyToOne private Usuario usuario; @Column(name = "data_cricao", nullable = false) private Date dataCriacao; public Long getCodigo() { return codigo; } public void setCodigo(Long codigo) { this.codigo = codigo; } public Votacao getVotacao() { return votacao; } public void setVotacao(Votacao votacao) { this.votacao = votacao; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Date getDataCriacao() { return dataCriacao; } public void setDataCriacao(Date dataCriacao) { this.dataCriacao = dataCriacao; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); result = prime * result + ((dataCriacao == null) ? 0 : dataCriacao.hashCode()); result = prime * result + ((usuario == null) ? 0 : usuario.hashCode()); result = prime * result + ((votacao == null) ? 0 : votacao.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VotacaoUsuario other = (VotacaoUsuario) obj; if (codigo == null) { if (other.codigo != null) return false; } else if (!codigo.equals(other.codigo)) return false; if (dataCriacao == null) { if (other.dataCriacao != null) return false; } else if (!dataCriacao.equals(other.dataCriacao)) return false; if (usuario == null) { if (other.usuario != null) return false; } else if (!usuario.equals(other.usuario)) return false; if (votacao == null) { if (other.votacao != null) return false; } else if (!votacao.equals(other.votacao)) return false; return true; } public VotacaoUsuario() { super(); } public VotacaoUsuario(Long codigo, Votacao votacao, Usuario usuario, Date dataCriacao) { super(); this.codigo = codigo; this.votacao = votacao; this.usuario = usuario; this.dataCriacao = dataCriacao; } }
true
91de11395d3f79d18a8acb1c036857efcbde3b63
Java
SamratChakrabortyy/samratCUtils
/src/main/java/in/samratc/main/strings/StrongTansformation.java
UTF-8
1,262
3.59375
4
[]
no_license
package in.samratc.main.strings; import java.util.Arrays; public class StrongTansformation { /** * Rick and Morty are best friends. Rick and Morty will change their name to strings A and B respectively. * * They want to know if it is possible to transform A into B by doing zero or more conversions. * * In one conversion you can convert all occurrences of one character in A to any other lowercase English character. */ public int solve(String a, String b) { if(isEmpty(a) && isEmpty(b)) return 1; if((isEmpty(a) || isEmpty(b)) || a.length() != b.length()) return 0; if(a.equals(b)) return 1; int[] mapsTo = new int[26]; Arrays.fill(mapsTo, -1); for(int i = 0; i < a.length(); i++){ if(mapsTo[a.charAt(i) - 'a'] != -1 && mapsTo[a.charAt(i) - 'a'] != b.charAt(i) - 'a') return 0; mapsTo[a.charAt(i) - 'a'] = b.charAt(i) - 'a'; } for(int mapped : mapsTo){ if(mapped == -1) return 1; } return 0; } public static boolean isEmpty(String s){ return s == null || s.length() == 0; } }
true
559d41575f51d9fca2c7847153380b00de6bef61
Java
LahiruDraco/opensms
/app/src/main/java/org/opensms/app/db/entity/GrnOrder.java
UTF-8
4,643
1.742188
2
[]
no_license
/* * 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 org.opensms.app.db.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonIgnore; /** * * @author dewmal */ @Entity @Table(name = "grn_order") @XmlRootElement @NamedQueries({ @NamedQuery(name = "GrnOrder.findAll", query = "SELECT g FROM GrnOrder g"), @NamedQuery(name = "GrnOrder.findByGrnOrderId", query = "SELECT g FROM GrnOrder g WHERE g.grnOrderId = :grnOrderId"), @NamedQuery(name = "GrnOrder.findByReceiveDate", query = "SELECT g FROM GrnOrder g WHERE g.receiveDate = :receiveDate")}) public class GrnOrder implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "grn_order_id") private Long grnOrderId; @Basic(optional = false) @NotNull @Column(name = "receive_date") @Temporal(TemporalType.TIMESTAMP) private Date receiveDate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "grnOrder", fetch = FetchType.LAZY) private List<GrnPayment> grnPaymentList; @JoinColumn(name = "vendor", referencedColumnName = "user_id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Vendor vendor; @JoinColumn(name = "data_entry_employee", referencedColumnName = "user_id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Employee dataEntryEmployee; @OneToMany(cascade = CascadeType.ALL, mappedBy = "grnOrder", fetch = FetchType.LAZY) private List<Batch> batchList; public GrnOrder() { } public GrnOrder(Long grnOrderId) { this.grnOrderId = grnOrderId; } public GrnOrder(Long grnOrderId, Date receiveDate) { this.grnOrderId = grnOrderId; this.receiveDate = receiveDate; } public Long getGrnOrderId() { return grnOrderId; } public void setGrnOrderId(Long grnOrderId) { this.grnOrderId = grnOrderId; } public Date getReceiveDate() { return receiveDate; } public void setReceiveDate(Date receiveDate) { this.receiveDate = receiveDate; } @XmlTransient @JsonIgnore public List<GrnPayment> getGrnPaymentList() { return grnPaymentList; } public void setGrnPaymentList(List<GrnPayment> grnPaymentList) { this.grnPaymentList = grnPaymentList; } public Vendor getVendor() { return vendor; } public void setVendor(Vendor vendor) { this.vendor = vendor; } public Employee getDataEntryEmployee() { return dataEntryEmployee; } public void setDataEntryEmployee(Employee dataEntryEmployee) { this.dataEntryEmployee = dataEntryEmployee; } @XmlTransient @JsonIgnore public List<Batch> getBatchList() { return batchList; } public void setBatchList(List<Batch> batchList) { this.batchList = batchList; } @Override public int hashCode() { int hash = 0; hash += (grnOrderId != null ? grnOrderId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof GrnOrder)) { return false; } GrnOrder other = (GrnOrder) object; if ((this.grnOrderId == null && other.grnOrderId != null) || (this.grnOrderId != null && !this.grnOrderId.equals(other.grnOrderId))) { return false; } return true; } @Override public String toString() { return "org.opensms.app.db.entity.GrnOrder[ grnOrderId=" + grnOrderId + " ]"; } }
true
70b0faff25dcc477e7958a9e92c666e64df11edc
Java
breezerong/zisecm
/zisecm-portal/src/main/java/com/ecm/portal/controller/admin/UserSessionManager.java
UTF-8
3,241
1.703125
2
[]
no_license
package com.ecm.portal.controller.admin; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ecm.core.ActionContext; import com.ecm.core.cache.manager.CacheManagerOper; import com.ecm.core.cache.manager.impl.CacheManagerCfgActivity; import com.ecm.core.cache.manager.impl.CacheManagerEcmAction; import com.ecm.core.cache.manager.impl.CacheManagerEcmCardSearch; import com.ecm.core.cache.manager.impl.CacheManagerEcmComponent; import com.ecm.core.cache.manager.impl.CacheManagerEcmDefType; import com.ecm.core.cache.manager.impl.CacheManagerEcmDocType; import com.ecm.core.cache.manager.impl.CacheManagerEcmForm; import com.ecm.core.cache.manager.impl.CacheManagerEcmGridView; import com.ecm.core.cache.manager.impl.CacheManagerEcmMenu; import com.ecm.core.cache.manager.impl.CacheManagerEcmParam; import com.ecm.core.cache.manager.impl.CacheManagerEcmStore; import com.ecm.core.cache.manager.impl.CacheManagerEcmSuggestion; import com.ecm.core.cache.manager.impl.CacheManagerLangInfo; import com.ecm.core.cache.manager.impl.CacheManagerLanguage; import com.ecm.core.exception.AccessDeniedException; import com.ecm.core.exception.NoPermissionException; import com.ecm.core.search.ESClient; import com.ecm.core.search.SearchClient; import com.ecm.core.service.SessionService; import com.ecm.portal.controller.ControllerAbstract; @Controller public class UserSessionManager extends ControllerAbstract{ @Autowired SessionService sessionService; @ResponseBody @RequestMapping("/admin/getAllSession") public Map<String, Object> initAllCache() { Map<String, Object> mp = new HashMap<String, Object> (); try { mp.put("data", sessionService.getAllObject(getToken())); mp.put("code", ActionContext.SUCESS); } catch (AccessDeniedException | NoPermissionException e) { // TODO Auto-generated catch block e.printStackTrace(); mp.put("code", ActionContext.FAILURE); mp.put("msg", e.getMessage()); } return mp; } @ResponseBody @RequestMapping(value = "/admin/removeSession", method = RequestMethod.POST) public Map<String, Object> removeSession(HttpServletRequest request, HttpServletResponse response, @RequestBody String id) { Map<String, Object> mp = new HashMap<String, Object> (); try { if(sessionService.deleteObjectById(getToken(), id)) { mp.put("code", ActionContext.SUCESS); }else { mp.put("code", ActionContext.FAILURE); } } catch (NoPermissionException e) { // TODO Auto-generated catch block e.printStackTrace(); mp.put("code", ActionContext.FAILURE); mp.put("msg", e.getMessage()); } catch (AccessDeniedException e) { // TODO Auto-generated catch block e.printStackTrace(); mp.put("code", ActionContext.FAILURE); mp.put("msg", e.getMessage()); } return mp; } }
true
cde97653cd22e87e04260276b510bb945361a654
Java
KingC100/FXErycton
/FXErycton.java
UTF-8
1,181
2.265625
2
[]
no_license
package fxerycton; import fxerycton.Bean.RoofBean; import fxerycton.Import.ReadContents; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * * @author kiichi */ public class FXErycton extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXErycton.fxml")); // 背景色設定 root.setStyle("-fx-background-color: #E9967A;"); Scene scene = new Scene(root); // アイコンセット ReadContents rc = new ReadContents(); stage.getIcons().add(new Image((getClass().getResource("FXErycton.ico").toString()))); // タイトルセット stage.setTitle("FXErcycton v0.0.1"); // ウィンドウサイズ固定 stage.setResizable(false); stage.setScene(scene); stage.show(); // 標準でシングルバトル仕様 RoofBean.setBattleType("single"); } public static void main(String[] args) { launch(args); } }
true
0c9bd3b6ac38b36476eae788156cae2dcec35c35
Java
bloc97/DiscordLoLModules
/src/lolbot/commands/SummonerExtendedInfo.java
UTF-8
6,889
2.125
2
[]
no_license
package lolbot.commands; /* * 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. */ import container.UserCommand; import helpers.MapSort; import helpers.TextFormatter; import static helpers.TextFormatter.formatCapitalUnderscore; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import lolbot.LoLCommand; import net.bloc97.riot.cache.CachedRiotApi; import net.rithms.riot.api.endpoints.match.dto.MatchList; import net.rithms.riot.api.endpoints.match.dto.MatchReference; import net.rithms.riot.api.endpoints.summoner.dto.Summoner; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.api.internal.json.objects.EmbedObject.EmbedFieldObject; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; /** * * @author bowen */ public class SummonerExtendedInfo extends LoLCommand { public SummonerExtendedInfo() { super(LoLCommandType.SEARCHSUMMONERNAME, "summonerextendedinfo", "sei"); } @Override public boolean trigger(IDiscordClient client, MessageReceivedEvent e, UserCommand c, CachedRiotApi api) { String nameSearch = c.getTokensString(); Summoner summoner = api.Summoner.getSummonerByName(nameSearch); c.next(); EmbedObject embed = new EmbedObject(); embed.color = 6732543; String profileUrl = "http://matchhistory.na.leagueoflegends.com/en/#match-history/NA1/" + summoner.getAccountId(); String profilePicUrl = "http://ddragon.leagueoflegends.com/cdn/" + api.StaticData.getDataLatestVersion() + "/img/profileicon/" + summoner.getProfileIconId() + ".png"; embed.author = new EmbedObject.AuthorObject(summoner.getName(), profileUrl, "", ""); embed.thumbnail = new EmbedObject.ThumbnailObject(profilePicUrl, "", 48, 48); embed.description = "Level " + summoner.getSummonerLevel(); embed.footer = TextFormatter.getSummonerEmbedFooter(summoner.getId(), summoner.getAccountId(), summoner.getRevisionDate()); LinkedList<EmbedFieldObject> fieldList = new LinkedList<>(); MatchList rml = api.Match.getRecentMatchListByAccountId(summoner.getAccountId()); MatchList ml = api.Match.getRankedMatchListByAccountId(summoner.getAccountId()); List<MatchReference> rmr = rml.getMatches(); List<MatchReference> mr = ml.getMatches(); fieldList.add(new EmbedFieldObject("Recent Champions: ", getMostUsedChampions(api, rmr, 4), true)); fieldList.add(new EmbedFieldObject("(Ranked): ", getMostUsedChampions(api, mr, 4), true)); fieldList.add(new EmbedFieldObject("Recent Roles: ", getPreferredRole(rmr, 2), true)); fieldList.add(new EmbedFieldObject("(Ranked): ", getPreferredRole(mr, 2), true)); fieldList.add(new EmbedFieldObject("Recent Lanes: ", getPreferredLane(rmr, 2), true)); fieldList.add(new EmbedFieldObject("(Ranked): ", getPreferredLane(mr, 2), true)); embed.fields = fieldList.toArray(new EmbedFieldObject[0]); e.getMessage().getChannel().sendMessage(embed); return true; } public String getMostUsedChampions(CachedRiotApi api, List<MatchReference> mr, int n) { double mrLength = mr.size(); Map<Long, Integer> championCount = new HashMap<>(); for (MatchReference m : mr) { long champion = m.getChampion(); if (championCount.containsKey(champion)) { championCount.put(champion, championCount.get(champion)+1); } else { championCount.put(champion, 1); } } championCount = MapSort.sortByValueDescending(championCount); Map.Entry<Long, Integer>[] championCountArray = championCount.entrySet().toArray(new Map.Entry[0]); String mostUsedChampions = ""; int range = Math.min(championCount.size(), n); for (int i=0; i<range; i++) { int value = championCountArray[i].getValue(); if (value < 2) { continue; } mostUsedChampions = mostUsedChampions + "(" + (int)(value*100/mrLength) + "%) " + api.StaticData.getDataChampion((championCountArray[i].getKey()).intValue()).getName() + "\n"; } if (mostUsedChampions.length() < 1) { return "None"; } return mostUsedChampions; } public String getPreferredLane(List<MatchReference> mr, int n) { double mrLength = mr.size(); Map<String, Integer> laneCount = new HashMap<>(); for (MatchReference m : mr) { String lane = m.getLane(); if (laneCount.containsKey(lane)) { laneCount.put(lane, laneCount.get(lane)+1); } else { laneCount.put(lane, 1); } } laneCount = MapSort.sortByValueDescending(laneCount); Map.Entry<String, Integer>[] laneCountArray = laneCount.entrySet().toArray(new Map.Entry[0]); String mostPlayedLanes = ""; int range = Math.min(laneCount.size(), n); for (int i=0; i<range; i++) { int value = laneCountArray[i].getValue(); if (value < 2) { continue; } mostPlayedLanes = mostPlayedLanes + "("+ (int)(value*100/mrLength) + "%) " + formatCapitalUnderscore(laneCountArray[i].getKey()) + "\n"; } if (mostPlayedLanes.length() < 1) { return "None"; } return mostPlayedLanes; } public String getPreferredRole(List<MatchReference> mr, int n) { double mrLength = mr.size(); Map<String, Integer> roleCount = new HashMap<>(); for (MatchReference m : mr) { String role = m.getRole(); if (roleCount.containsKey(role)) { roleCount.put(role, roleCount.get(role)+1); } else { roleCount.put(role, 1); } } roleCount = MapSort.sortByValueDescending(roleCount); Map.Entry<String, Integer>[] roleCountArray = roleCount.entrySet().toArray(new Map.Entry[0]); String mostPlayedRoles = ""; int range = Math.min(roleCount.size(), n); for (int i=0; i<range; i++) { int value = roleCountArray[i].getValue(); if (value < 2) { continue; } mostPlayedRoles = mostPlayedRoles + "(" + (int)(value*100/mrLength) + "%) " + formatCapitalUnderscore(roleCountArray[i].getKey()) + "\n"; } if (mostPlayedRoles.length() < 1) { return "None"; } return mostPlayedRoles; } }
true
0581c977579e9cca01db9c993b70c2b92d2c1bd7
Java
rechardtang/leetcode
/src/main/java/com/cn/leetcode/A0012_intToRoman.java
UTF-8
1,840
3.859375
4
[]
no_license
package com.cn.leetcode; /** * 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 * * 字符 数值 * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 * * 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: * * I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 * X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 * C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 * 给你一个整数,将其转为罗马数字。 * * * * 示例 1: * * 输入: num = 3 * 输出: "III" * 示例 2: * * 输入: num = 4 * 输出: "IV" * 示例 3: * * 输入: num = 9 * 输出: "IX" * 示例 4: * * 输入: num = 58 * 输出: "LVIII" * 解释: L = 50, V = 5, III = 3. * 示例 5: * * 输入: num = 1994 * 输出: "MCMXCIV" * 解释: M = 1000, CM = 900, XC = 90, IV = 4. * * * 提示: * * 1 <= num <= 3999 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/integer-to-roman * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class A0012_intToRoman { public int maxArea(int[] height) { return 0; } }
true
ea1bd3e2efa61ed2980a4ac0edc88b506d561448
Java
pkou428/client
/src/tweendeck/StatusTimeLine.java
SHIFT_JIS
24,898
2.296875
2
[]
no_license
package tweendeck; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import javax.swing.AbstractAction; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListCellRenderer; import javax.swing.ScrollPaneConstants; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; import twitter4j.PagableResponseList; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.User; import twitter4j.UserList; class StatusTimeLine{ /* * ^CCJǗNX * RXgN^I[o[[hĎ擾TLIׂ悤ɂׂiAll FriendsXgƂj * */ class TimeLineColumn{ JPanel columnPanel; JList statusJList; long latestStatusId; int updateInterval; JLabel titleLabel; JPopupMenu popup; JPanel menuPanel; ListEntry selectedItem; DefaultListModel listModel;//J̃cC[gǗIuWFNg /* * RXgN^ * */ public TimeLineColumn(String title){ columnPanel = new JPanel(); columnPanel.setMaximumSize(new Dimension(300,columnPanel.getMaximumSize().height)); columnPanel.setMinimumSize(new Dimension(300,columnPanel.getMinimumSize().height)); columnPanel.setPreferredSize(new Dimension(300,210)); listModel = new DefaultListModel(); titleLabel = new JLabel(title); titleLabel.setPreferredSize(new Dimension(300,40)); statusJList = new JList(listModel); statusJList.setCellRenderer(new TimeLineCellRenderer(iconList)); menuPanel = new JPanel(); menuPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); popup = new JPopupMenu(); popup.add(new ActionRetweet("Retweet")); popup.add(new ActionReply("Reply")); //}EXXi֓o^ MouseListener mouseListener = new MouseAdapter() { @Override public void mouseReleased(MouseEvent me) { if(SwingUtilities.isRightMouseButton(me)){ int index = statusJList.locationToIndex(me.getPoint()); if(index >= 0){ statusJList.setSelectedIndex(index); selectedItem = (ListEntry)listModel.get(statusJList.getSelectedIndex()); tweetDetail.setDetail(selectedItem); // JOptionPane.showMessageDialog(statusJList, "right clicked"); // tweetForm.addString("@" + selectedItem.getUser().getScreenName()); showPopup(me, statusJList); } }else if(SwingUtilities.isLeftMouseButton(me)){ selectedItem = (ListEntry)listModel.get(statusJList.getSelectedIndex()); tweetDetail.setDetail(selectedItem); // JOptionPane.showMessageDialog(statusJList, "left clicked"); } } }; statusJList.addMouseListener(mouseListener); JScrollPane scrollPane = new JScrollPane(statusJList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, // o[ ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); SpringLayout layout = new SpringLayout(); columnPanel.setLayout(layout); layout.putConstraint(SpringLayout.NORTH, titleLabel, 5, SpringLayout.NORTH, columnPanel); layout.putConstraint(SpringLayout.WEST, titleLabel, 5, SpringLayout.WEST, columnPanel); layout.putConstraint(SpringLayout.EAST, titleLabel, -200, SpringLayout.EAST, columnPanel); layout.putConstraint(SpringLayout.NORTH, menuPanel, 5, SpringLayout.NORTH, columnPanel); layout.putConstraint(SpringLayout.WEST, menuPanel, 5, SpringLayout.WEST, titleLabel); layout.putConstraint(SpringLayout.EAST, menuPanel, -5, SpringLayout.EAST, columnPanel); layout.putConstraint(SpringLayout.NORTH, scrollPane, 40, SpringLayout.NORTH, columnPanel); layout.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, columnPanel); layout.putConstraint(SpringLayout.EAST, scrollPane, 0, SpringLayout.EAST, columnPanel); layout.putConstraint(SpringLayout.SOUTH, scrollPane,0, SpringLayout.SOUTH, columnPanel); columnPanel.add(scrollPane); columnPanel.add(titleLabel); columnPanel.add(menuPanel); } private void showPopup(MouseEvent me, JList list){ if(me.isPopupTrigger()){ popup.show(list, me.getX(), me.getY()); } } /* * 擾pXbh * 莞ԂƂupdateTimeLine\bhĂяo * */ class TimerThread extends Thread{ boolean running; public TimerThread(){ running = true; } @Override public void run(){ while(running){ try{ Thread.sleep(60000L); } catch (Exception ex){ ex.printStackTrace(); } SwingUtilities.invokeLater(new Runnable(){ public void run(){ updateTimeLine(); } }); System.out.println("calling updateTimeLine" + this.hashCode()); } } public void stopRunning(){ running = false; } } /* * JpplԂ * */ public JPanel getColumnPanel(){ return columnPanel; } public final void startUpdate(){ TimerThread timer = new TimerThread(); reloadTimeLine(); timer.start(); } public void setTitle(String title){ titleLabel.setText(title); } public String getTitle(){ return titleLabel.getText(); } /* * ^CCJ̍ĕ\ * */ private void reloadTimeLine(){ JButton add = new JButton("add List"); add.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ AddList(); } }); menuPanel.add(add); try{ ResponseList<Status> statusList = twitter.getFriendsTimeline(new Paging(1, 100)); for(int i = 0; i < statusList.size(); i++){ UserData tmp; String tmpName = statusList.get(i).getUser().getName(); if(userList.containsKey(tmpName) == false){ tmp = new UserData(statusList.get(i), iconList.getImageIcon(statusList.get(i).getUser())); userList.put(tmpName, tmp); }else{ System.out.println(tmpName + "'s Data already exists"); tmp = userList.get(tmpName); } long tmpId = statusList.get(i).getId(); tmp.addTweet(tmpId, statusList.get(i).getText()); listModel.addElement(new ListEntry(tmp, tmpId)); } latestStatusId = statusList.get(0).getId(); } catch (Exception ex){ ex.printStackTrace(); } } /* * ^CC̍XV * XVpXbhƊÔQ‚ANZX”\A * */ /* * API ̎s񐔐ɂ‚(}jÃRsy * Twitter API ́A60Ԃ150܂ŎsłB * ̎s񐔐𒴂ԂłɃNGXg𑗂ꍇAHTTPXe[^XR[h 400 ԂB * F؂̕KvȂ́AsvȂ̗̂s񐔐̑ΏۂƂȂ(ȑO͎s񐔐̑ΏۊOł * public_timeline ̎擾A݂͑ΏۂƂȂĂ)B * F؂̕KvȂ̂̓[UID(AJEg)PʂŁAF؂̕svȂ̂IPAhXPʂŁAs񐔂̃JEgsȂB * [҂ɂ钍L] * Twitter ̉^p󋵂ɂĂ API 茵ݒ肳邱Ƃ(60Ԃ20܂ŁAȂ)B * ȂAPOSTnAPI(̓eA_CNgbZ[W̑MAw胆[ŨtH[ACɓ̓o^AȂ)́A * ̎s񐔐ɂ͊֌WȂAłsłB * APOSTnAPIłĂA莞ԓ̎gp񐔂܂ɂꍇ́Agp邱ƂB * ̎s񐔐KpƓsꍇ́AR𖾎̏ATwitter J҂ɃR^Ng邱ƁB * [ł闝R΁AY[UAs񐔐KpÕXN[̃XgɓB * (A̎s񐔐KpÕXgɓo^ĂA1Ԃɍő2̃NGXg󂯕tȂ) * rate_limit_status ƂuAJEg֘AAPIvgƂŁAۂ API ̎{󋵂𒲂ׂ邱ƂłB * *u̓e(statuses/update)vAufollowing(friendships/create)vA1Ɏs”\ȏ񐔂ʓr߂Ă̂ * (ڍׂ http://help.twitter.com/forums/10711/entries/15364 Q) * - ̓e: 1ő1000܂ * - _CNgbZ[W̑M: 1ő1000܂ * - following: ̓IȐ͖ĂȂ(1ő2000܂ŁA炵) * API s񐔐̊ɘa * (2010N1) OAuth oRŐV API Gh|Cg(http://api.twitter.com/ Ŏn܂ URL) ɃANZXꍇɌāA * API 60Ԃ350܂Ŏs邱Ƃł * (Ғ: ɘa[u60Ԃ450܂Ŏs”\A2010N112̃nC`nk̃T[o[׏󋵂lʁA * 2010N124ȍ~A60Ԃ350܂Ŏs”\Ƃ邱Ƃɂ͗lBIɂ́A60Ԃ1500܂Ŏs”\ɂ邱Ƃ\Ă)B * ȂÁuɘa[uvLȏԂł rate_limit_status ́AˑRƂ hourly-limit ̒lƂ 150 ԂB * uɘa[uvLɂȂĂ邱ƂmFɂ́AAPI sv(httpNGXg)ɑ΂鉞httpX|Xwb_΂悢B * httpX|Xwb_ * X-RateLimit-Limit: * A60(1)Ɏs”\ȉ񐔂A * X-RateLimit-Remaining: * AƉs”\Ȃ̂Ă * */ synchronized public void updateTimeLine(){ try{ ResponseList<Status> statusList = twitter.getFriendsTimeline(new Paging(1, 100, latestStatusId)); if(statusList.size()>0){ System.out.println("1"); for(int i = statusList.size()-1; i >= 0; i--){ UserData tmp; String tmpName = statusList.get(i).getUser().getName(); if(userList.containsKey(tmpName) == false){ tmp = new UserData(statusList.get(i), iconList.getImageIcon(statusList.get(i).getUser())); userList.put(tmpName, tmp); }else{ System.out.println(tmpName + "'s Data already exists"); tmp = userList.get(tmpName); } long tmpId = statusList.get(i).getId(); tmp.addTweet(tmpId, statusList.get(i).getText()); listModel.add(0,new ListEntry(tmp, tmpId)); } System.out.println("1.5"); latestStatusId = statusList.get(0).getId(); UpdateTimeLineThread thread = new UpdateTimeLineThread(statusList); thread.start(); } } catch(Exception ex){ System.out.println(ex.getMessage()); } } class UpdateTimeLineThread extends Thread{ Status status; ResponseList<Status> statusList; public UpdateTimeLineThread(ResponseList<Status> statusList){ this.statusList = statusList; } @Override public void run(){ int index = statusJList.getSelectedIndex(); for(int i = 0; i < listList.size(); i++){ try{ listList.get(i).updateTimeLine(statusList); } catch (Exception ex){ JOptionPane.showMessageDialog(null, "updateStatus Failed"); } } statusJList.setSelectedIndex(statusList.size() + index); } } class ActionRetweet extends AbstractAction{ public ActionRetweet(String title){ super(title); } public void actionPerformed(ActionEvent e) { tweetForm.addString("RT @" + selectedItem.getUserData().getScreenName() + ": " + selectedItem.getUserData().getTweetText(selectedItem.getTweetId())); } } class ActionReply extends AbstractAction{ public ActionReply(String title){ super(title); } public void actionPerformed(ActionEvent e) { tweetForm.addString("@" + selectedItem.getUserData().getScreenName() + " "); } } } /* * XgpJ * XgǗ҂ScreenNamelistIDnĂč쐬 * AllFriendsJŐVTL󂯎ĊǗ郊XgɏĂ郁o[̃cC[ĝ݂J֒ljĂ * */ class ListColumn extends TimeLineColumn{ PagableResponseList<User> list; String listOwnerName; HashMap<String, Integer> listMap; int listId; public ListColumn(String listOwnerName, int listId, String title){ super(title); try{ long cursor = -1; listMap = new HashMap<String, Integer>(); this.listOwnerName = listOwnerName; this.listId = listId; do{ list = twitter.getUserListMembers(listOwnerName, listId, cursor); for(int i = 0; i < list.size(); i++){ listMap.put(list.get(i).getName(), new Integer(list.get(i).getId())); } cursor = list.getNextCursor(); }while(cursor != 0); JButton remove = new JButton("remove List"); remove.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ deleteThisColumn(); } }); menuPanel.add(remove); /* this.columnPanel = new JPanel(); columnPanel.setMaximumSize(new Dimension(300,columnPanel.getMaximumSize().height)); columnPanel.setMinimumSize(new Dimension(300,columnPanel.getMinimumSize().height)); columnPanel.setPreferredSize(new Dimension(280,210)); listModel = new DefaultListModel(); statusJList = new JList(listModel); statusJList.setCellRenderer(new TimeLineCellRenderer()); //}EXXi֓o^ MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent me) { Status selectedItem = (Status)listModel.get(statusJList.getSelectedIndex()); if(SwingUtilities.isRightMouseButton(me)){ //IĂ郊Xg̃IuWFNgȂ擾 //eLXge擾ł邩eXg JOptionPane.showMessageDialog(null, "right clicked"); tweetForm.addString("@" + selectedItem.getUser().getScreenName()); }else if(SwingUtilities.isLeftMouseButton(me)){ tweetDetail.setText(selectedItem.getText()); } } }; statusJList.addMouseListener(mouseListener); JScrollPane scrollPane = new JScrollPane(statusJList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // o[ JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); SpringLayout layout = new SpringLayout(); columnPanel.setLayout(layout); layout.putConstraint(SpringLayout.NORTH, scrollPane, 0, SpringLayout.NORTH, columnPanel); layout.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, columnPanel); layout.putConstraint(SpringLayout.EAST, scrollPane, 0, SpringLayout.EAST, columnPanel); layout.putConstraint(SpringLayout.SOUTH, scrollPane,0, SpringLayout.SOUTH, columnPanel); columnPanel.add(scrollPane); */ reloadTimeLine(); } catch(Exception ex){ ex.printStackTrace(); } } public void updateTimeLine(ResponseList<Status> timeLineList){ int index = statusJList.getSelectedIndex(); int counter = 0; ArrayList<ListEntry> listEntry = new ArrayList<ListEntry>(); for(int i = timeLineList.size()-1; i >=0; i--){ if(listMap.containsKey(timeLineList.get(i).getUser().getName())){ UserData tmp; String tmpName = timeLineList.get(i).getUser().getName(); if(userList.containsKey(tmpName) == false){ tmp = new UserData(timeLineList.get(i), iconList.getImageIcon(timeLineList.get(i).getUser())); userList.put(tmpName, tmp); }else{ // System.out.println(tmpName + "'s Data already exists"); tmp = userList.get(tmpName); } long tmpId = timeLineList.get(i).getId(); tmp.addTweet(tmpId, timeLineList.get(i).getText()); listEntry.add(new ListEntry(tmp, tmpId)); counter++; } } if(index >= 0) statusJList.setSelectedIndex(counter + index); SwingUtilities.invokeLater(new AddStatusThread(listEntry)); } class AddStatusThread implements Runnable{ ArrayList<ListEntry> listEntry; public AddStatusThread(ArrayList<ListEntry> listEntry){ this.listEntry = listEntry; } public void run(){ System.out.println("thread start"); for(int i = 0;i < listEntry.size(); i++){ listModel.add(0,listEntry.get(i)); System.out.println("added list"); } } } public void reloadTimeLine(){ try{ ResponseList<Status> statusList = twitter.getUserListStatuses(this.listOwnerName, this.listId,new Paging(1, 100)); for(int i = 0; i < statusList.size(); i++){ UserData tmp; String tmpName = statusList.get(i).getUser().getName(); if(userList.containsKey(tmpName) == false){ tmp = new UserData(statusList.get(i), iconList.getImageIcon(statusList.get(i).getUser())); userList.put(tmpName, tmp); }else{ tmp = userList.get(tmpName); } long tmpId = statusList.get(i).getId(); tmp.addTweet(tmpId, statusList.get(i).getText()); listModel.addElement(new ListEntry(tmp, tmpId)); } } catch (Exception ex){ ex.printStackTrace(); } } private void deleteThisColumn(){ deleteColumn(this); } } /* * Z`̐ݒ * OƃcC[gŐFς * JTextArea1‚ŐFς͖̂plPLabelljH * */ class TimeLineCellRenderer implements ListCellRenderer{ JTextArea tmp; IconList iconList; Color evenColor = new Color(230,255,230); public TimeLineCellRenderer(IconList iconList){ tmp = null; this.iconList = iconList; } public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){ /* JPanel tmpPanel = new JPanel(); tmpPanel.setPreferredSize(new Dimension(290,50)); ListEntry tmpEntry = (ListEntry)value; JLabel tmpIcon = new JLabel(); UserData tmpUserData = tmpEntry.getUserData(); tmpIcon.setIcon(tmpUserData.getIcon()); // tmpIcon.setMaximumSize(new Dimension(50,50)); // tmpIcon.setMinimumSize(new Dimension(50,50)); // tmpIcon.setSize(new Dimension(50,50)); tmp = new JTextArea(tmpUserData.getUserName() + " >\n" + tmpUserData.getTweetText(tmpEntry.getTweetId())); // tmp.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); tmp.setLineWrap(true); // tmp.setPreferredSize(new Dimension(200,50)); tmp.setRows(3); */ // System.out.print("Rendering List \"" + list.hashCode() + "\" "); ListEntry tmpEntry = (ListEntry)value; JPanel tmp = tmpEntry.getUserData().getTweetPanel(tmpEntry.getTweetId()); if(isSelected){ tmp.getComponent(0).setBackground(list.getSelectionBackground()); }else{ tmp.getComponent(0).setBackground(index%2==0 ? evenColor : list.getBackground()); tmp.getComponent(0).setForeground(list.getForeground()); } /* tmpPanel.setLayout(new FlowLayout()); tmp.setPreferredSize(new Dimension(220,40)); tmpPanel.add(tmp); tmpPanel.add(tmpIcon); */ /* SpringLayout layout = new SpringLayout(); tmpPanel.setLayout(layout); layout.putConstraint(SpringLayout.NORTH, tmpIcon, 5, SpringLayout.NORTH, tmpPanel); layout.putConstraint(SpringLayout.WEST, tmpIcon, 5, SpringLayout.WEST, tmpPanel); layout.putConstraint(SpringLayout.EAST, tmpIcon, -5, SpringLayout.EAST, tmpPanel); layout.putConstraint(SpringLayout.SOUTH, tmpIcon,-5, SpringLayout.SOUTH, tmpPanel); layout.putConstraint(SpringLayout.NORTH, tmpIcon, 5, SpringLayout.NORTH, tmpPanel); layout.putConstraint(SpringLayout.WEST, tmpIcon, 5, SpringLayout.WEST, tmpPanel); layout.putConstraint(SpringLayout.EAST, tmpIcon, -5, SpringLayout.WEST, tmp); layout.putConstraint(SpringLayout.SOUTH, tmpIcon,-5, SpringLayout.SOUTH, tmpPanel); tmpPanel.add(tmp); tmpPanel.add(tmpIcon); */ return tmp; } } JScrollPane timeLineScrollPane; ArrayList<TimeLineColumn> columnList; JPanel timeLinePanel;//TL\p //JPanel iconPanel;//ACR\p Twitter twitter; TweetForm tweetForm; TimeLineColumn allFriends; TweetDetail tweetDetail; ArrayList<ListColumn> listList; IconList iconList; FlowLayout layout; HashMap<String, UserData> userList; /* * RXgN^ * */ public StatusTimeLine(Twitter twitter, TweetForm tweetForm, TweetDetail tweetDetail, IconList iconList, HashMap<String, UserData> userList){ this.tweetForm = tweetForm; this.tweetDetail = tweetDetail; this.iconList = iconList; this.userList = userList; timeLinePanel = new JPanel(); columnList = new ArrayList<TimeLineColumn>(); this.twitter = twitter; allFriends = new TimeLineColumn("All Friends"); allFriends.startUpdate(); columnList.add(allFriends); listList = new ArrayList<ListColumn>(); for(int i = 0; i < listList.size(); i++){ columnList.add(listList.get(i)); } BoxLayout timeLineLayout = new BoxLayout(timeLinePanel, BoxLayout.X_AXIS); timeLinePanel.setLayout(timeLineLayout); /* layout = new FlowLayout(); timeLinePanel.setLayout(layout); */ Iterator<TimeLineColumn> ite = columnList.iterator(); while(ite.hasNext()){ TimeLineColumn tmp = ite.next(); timeLinePanel.add(tmp.getColumnPanel()); } timeLineScrollPane = new JScrollPane(timeLinePanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); } public void updateAllFriends(){ allFriends.updateTimeLine(); } /* * ^CCS̗p̃plԂ * */ public JScrollPane getTimeLinePanel(){ //parentPanelԂ return timeLineScrollPane; } private void deleteColumn(ListColumn target){ //ListremoveYꂸ System.out.println("before size : " + listList.size()); listList.remove(target); System.out.println("after size : " + listList.size()); target.getColumnPanel().removeAll(); timeLinePanel.remove(target.getColumnPanel()); timeLinePanel.revalidate(); } public void AddList(){ ArrayList<UserList> list = new ArrayList<UserList>(); PagableResponseList<UserList> tmp; long cursor = -1; do{ try{ tmp = twitter.getUserLists(twitter.getScreenName(), cursor); }catch(Exception ex){ JOptionPane.showMessageDialog(null, "getUserList failed"); break; } list.addAll(tmp); cursor = tmp.getNextCursor(); }while(cursor != 0); System.out.println("list.size : " + list.size()); Object[] arry = list.toArray(); System.out.println("arry.length : " + arry.length); String[] name = new String[arry.length]; for(int i = 0; i < arry.length; i++){ name[i] = new String(((UserList)arry[i]).getFullName()); } for(int i = 0; i < arry.length; i++){ System.out.println(name[i]); } Object selectedItem = JOptionPane.showInputDialog( allFriends.getColumnPanel() , "lj郊XgIĂ" , "adding ListColumn..." , JOptionPane.INFORMATION_MESSAGE , null , name , name[0]); for(int i = 0; i < name.length; i++){ ListColumn tmpColumn = null; if(name[i].equals(selectedItem)){ try{ tmpColumn = new ListColumn(twitter.getScreenName(),((UserList)arry[i]).getId(),((UserList)arry[i]).getFullName()); }catch(Exception ex){ ex.printStackTrace(); } if(tmpColumn != null){ timeLinePanel.add(tmpColumn.getColumnPanel()); listList.add(tmpColumn); tmpColumn.getColumnPanel().revalidate(); File iniFile = new File("./tweendeck.ini"); Properties prop = null; try{ if(!iniFile.exists()){ iniFile.createNewFile(); } prop = new Properties(); prop.load(new FileInputStream(iniFile)); }catch(Exception ex){ ex.printStackTrace(); } if(prop != null){ prop.setProperty("list", prop.getProperty("list")+ ((UserList)arry[i]).getId() + "," + ((UserList)arry[i]).getFullName() + ";"); } } break; } } } }
true
ff65c0c9beea48101c8c3d84d73095d9e733f385
Java
Taewii/softuni-algorithms
/05. Combinatorial Algoritms/src/p03_variations_without_repetitions.java
UTF-8
1,096
3.203125
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class p03_variations_without_repetitions { private static String[] elements; private static String[] variations; private static boolean[] used; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); elements = reader.readLine().split("\\s+"); int k = Integer.parseInt(reader.readLine()); used = new boolean[elements.length]; variations = new String[k]; generateVariations(k, 0); } private static void generateVariations(int k, int index) { if (index >= k) { System.out.println(String.join(" ", variations)); return; } for (int i = 0; i < elements.length; i++) { if (!used[i]) { used[i] = true; variations[index] = elements[i]; generateVariations(k, index + 1); used[i] = false; } } } }
true
fd0327b4f3bd0e54b5e0800e057838f297339cb5
Java
Rkingr/Easterlyn
/src/main/java/co/sblock/commands/cheat/CenterMapCommand.java
UTF-8
2,289
2.609375
3
[]
no_license
package co.sblock.commands.cheat; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.map.MapView; import org.bukkit.map.MapView.Scale; import com.google.common.collect.ImmutableList; import co.sblock.Sblock; import co.sblock.chat.Language; import co.sblock.commands.SblockCommand; /** * Yeah, screw the new mechanics. * * @author Jikoo */ public class CenterMapCommand extends SblockCommand { public CenterMapCommand(Sblock plugin) { super(plugin, "centermap"); setPermissionLevel("helper"); setUsage("/centermap [x] [z] [world]"); } @SuppressWarnings("deprecation") @Override protected boolean onCommand(CommandSender sender, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(getLang().getValue("command.general.noConsole")); return true; } Player player = (Player) sender; ItemStack mapItem = player.getInventory().getItemInMainHand(); if (mapItem.getType() != Material.EMPTY_MAP) { sender.sendMessage(Language.getColor("bad") + "You must be holding a blank map in your main hand."); return true; } MapView view = Bukkit.createMap(player.getWorld()); view.setScale(Scale.FARTHEST); int x, z; if (args.length > 1) { try { x = Integer.valueOf(args[0]); z = Integer.valueOf(args[1]); } catch (NumberFormatException e) { sender.sendMessage(Language.getColor("bad") + "Invalid coordinates! Ex. /centermap 0 0"); return true; } if (args.length > 2) { World world = Bukkit.getWorld(args[2]); if (world == null) { sender.sendMessage(Language.getColor("bad") + "Invalid world! Ex. /centermap 0 0 Earth_the_end"); return true; } view.setWorld(world); } } else { x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); } view.setCenterX(x); view.setCenterZ(z); player.getInventory().setItemInMainHand(new ItemStack(Material.MAP, 1, view.getId())); return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { return ImmutableList.of(); } }
true
d522950e859cc8c289ddb18a2861b069d7f3ecc7
Java
AdamMowery/lab9
/src/UsedCar.java
UTF-8
434
2.953125
3
[]
no_license
/** * Created by adamm on 2/9/2017. */ public class UsedCar extends Car { private int mileage; public UsedCar(String make, String model, int year, double price) { super(make, model, year, price); } UsedCar(String make, String model, int year, double price, int mileage) { super(make, model, year, price); this.mileage = mileage; } int getMileage() { return mileage; } }
true
be091139493849c9da75c314c21841e76b35fd26
Java
giagulei/dwmaxerr
/src/main/java/gr/ntua/ece/cslab/multdimwavelets/nonstandard/zpartitioning/ZOrderPartitioner.java
UTF-8
754
2.40625
2
[]
no_license
package gr.ntua.ece.cslab.multdimwavelets.nonstandard.zpartitioning; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Partitioner; /** * @author giagulei * */ public class ZOrderPartitioner extends Partitioner<IntWritable, IntWritable> implements Configurable{ private int blockSize; private Configuration conf; @Override public int getPartition(IntWritable key, IntWritable arg1, int numOfReducers) { return (key.get()/blockSize) % numOfReducers; } public Configuration getConf() { return conf; } public void setConf(Configuration conf) { this.conf = conf; blockSize = Integer.parseInt(conf.get("PSIZE")); } }
true
ed9ca512346929933b4be9f6baf907683ea8cb9c
Java
Kamran017/Java-Language-Trials
/Practice b/AyniIDliUrunIstisna.java
UTF-8
182
1.90625
2
[]
no_license
package lab4b; import java.io.IOException; public class AyniIDliUrunIstisna extends IOException{ public AyniIDliUrunIstisna(String mesaj){ super(mesaj); } }
true
1d1334d66af739fb032591e1c3e244be26ad9a92
Java
Morshed22/AlgoInJava
/src/FenwickTree/App.java
UTF-8
345
2.75
3
[]
no_license
package FenwickTree; // for learning below here is the link //https://www.youtube.com/watch?v=aAALKHLeexw public class App { public static void main(String[] args) { int [] numbs = {3,2,-1,6,5,4,-1,3,7,2,3}; FenwickTree fenwickTree = new FenwickTree(numbs); System.out.println(fenwickTree.rangeSum(8,10)); } }
true
5505c31ccf639f0e6afd08d084c40d612a52785a
Java
alex-grigoras/tool.swagger.docgen
/src/main/java/net/wasdev/maven/plugins/swaggerdocgen/JAXRSAnnotationsUtil.java
UTF-8
3,653
2.234375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 SmartBear Software * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 net.wasdev.maven.plugins.swaggerdocgen; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import io.swagger.util.PathUtils; import io.swagger.util.ReflectionUtils; // Portions of this class were borrowed from io.swagger.jaxrs.Reader. public class JAXRSAnnotationsUtil { public static Set<String> getOperationPaths(final Class<?> cls) { final Set<String> operationPaths = new HashSet<String>(); final javax.ws.rs.Path apiPath = cls.getAnnotation(javax.ws.rs.Path.class); final Method methods[] = cls.getMethods(); for (Method method : methods) { if (ReflectionUtils.isOverriddenMethod(method, cls)) { continue; } final javax.ws.rs.Path methodPath = getAnnotation(method, javax.ws.rs.Path.class); String operationPath = getPath(apiPath, methodPath); final Map<String, String> regexMap = new HashMap<String, String>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { operationPaths.add(operationPath); } } return Collections.unmodifiableSet(operationPaths); } private static <A extends Annotation> A getAnnotation(final Method method, final Class<A> annotationClass) { A annotation = method.getAnnotation(annotationClass); if (annotation == null) { Method superclassMethod = ReflectionUtils.getOverriddenMethod(method); if (superclassMethod != null) { annotation = getAnnotation(superclassMethod, annotationClass); } } return annotation; } private static String getPath(final javax.ws.rs.Path classLevelPath, final javax.ws.rs.Path methodLevelPath) { if (classLevelPath == null && methodLevelPath == null) { return null; } final StringBuilder b = new StringBuilder(); if (classLevelPath != null) { b.append(classLevelPath.value()); } if (methodLevelPath != null && !"/".equals(methodLevelPath.value())) { String methodPath = methodLevelPath.value(); if (!methodPath.startsWith("/") && !b.toString().endsWith("/")) { b.append("/"); } if (methodPath.endsWith("/")) { methodPath = methodPath.substring(0, methodPath.length() - 1); } b.append(methodPath); } String output = b.toString(); if (!output.startsWith("/")) { output = "/" + output; } if (output.endsWith("/") && output.length() > 1) { return output.substring(0, output.length() - 1); } else { return output; } } }
true
84ce79b41458b732fc5e4cf5985d78b018e29eba
Java
VishalAnand07/Java-Codes
/src/com/company/Lecture3/Main.java
UTF-8
341
2.671875
3
[]
no_license
package com.company.Lecture3; public class Main { public static void main(String[] args) { int n=5; int r=0; while (r<n){ int c=0; while(c<n){ System.out.print("* "); c++; } System.out.println(); r++; } } }
true
7cde100ddab3bee86d324e4c2c81049b94fcc278
Java
Samekichi/BeyondVanilla
/src/main/java/net/renarld/beyondvanilla/block/CustomFenceGateBlock.java
UTF-8
7,871
2.078125
2
[ "CC0-1.0" ]
permissive
package net.renarld.beyondvanilla.block; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.HorizontalFacingBlock; import net.minecraft.block.ShapeContext; import net.minecraft.entity.ai.pathing.NavigationType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemPlacementContext; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.Properties; import net.minecraft.tag.BlockTags; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.shape.VoxelShape; import net.minecraft.util.shape.VoxelShapes; import net.minecraft.world.BlockView; import net.minecraft.world.World; import net.minecraft.world.WorldAccess; public class CustomFenceGateBlock extends HorizontalFacingBlock { public static final BooleanProperty OPEN; public static final BooleanProperty POWERED; public static final BooleanProperty IN_WALL; protected static final VoxelShape Z_AXIS_SHAPE; protected static final VoxelShape X_AXIS_SHAPE; protected static final VoxelShape IN_WALL_Z_AXIS_SHAPE; protected static final VoxelShape IN_WALL_X_AXIS_SHAPE; protected static final VoxelShape Z_AXIS_COLLISION_SHAPE; protected static final VoxelShape X_AXIS_COLLISION_SHAPE; protected static final VoxelShape Z_AXIS_CULL_SHAPE; protected static final VoxelShape X_AXIS_CULL_SHAPE; protected static final VoxelShape IN_WALL_Z_AXIS_CULL_SHAPE; protected static final VoxelShape IN_WALL_X_AXIS_CULL_SHAPE; public CustomFenceGateBlock(Settings settings) { super(settings); this.setDefaultState(((( this.stateManager.getDefaultState()).with(OPEN, false)).with(POWERED, false)).with(IN_WALL, false)); } @Override public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { if (state.get(IN_WALL)) { return (state.get(FACING)).getAxis() == Direction.Axis.X ? IN_WALL_X_AXIS_SHAPE : IN_WALL_Z_AXIS_SHAPE; } else { return (state.get(FACING)).getAxis() == Direction.Axis.X ? X_AXIS_SHAPE : Z_AXIS_SHAPE; } } @Override public BlockState getStateForNeighborUpdate(BlockState state, Direction direction, BlockState newState, WorldAccess world, BlockPos pos, BlockPos posFrom) { Direction.Axis axis = direction.getAxis(); if ((state.get(FACING)).rotateYClockwise().getAxis() != axis) { return super.getStateForNeighborUpdate(state, direction, newState, world, pos, posFrom); } else { boolean bl = this.isWall(newState) || this.isWall(world.getBlockState(pos.offset(direction.getOpposite()))); return state.with(IN_WALL, bl); } } @Override public VoxelShape getCollisionShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { if (state.get(OPEN)) { return VoxelShapes.empty(); } else { return (state.get(FACING)).getAxis() == Direction.Axis.Z ? Z_AXIS_COLLISION_SHAPE : X_AXIS_COLLISION_SHAPE; } } @Override public VoxelShape getCullingShape(BlockState state, BlockView world, BlockPos pos) { if (state.get(IN_WALL)) { return (state.get(FACING)).getAxis() == Direction.Axis.X ? IN_WALL_X_AXIS_CULL_SHAPE : IN_WALL_Z_AXIS_CULL_SHAPE; } else { return (state.get(FACING)).getAxis() == Direction.Axis.X ? X_AXIS_CULL_SHAPE : Z_AXIS_CULL_SHAPE; } } @Override public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) { switch (type) { case LAND: case AIR: return state.get(OPEN); default: return false; } } @Override public BlockState getPlacementState(ItemPlacementContext ctx) { World world = ctx.getWorld(); BlockPos blockPos = ctx.getBlockPos(); boolean bl = world.isReceivingRedstonePower(blockPos); Direction direction = ctx.getPlayerFacing(); Direction.Axis axis = direction.getAxis(); boolean bl2 = axis == Direction.Axis.Z && (this.isWall(world.getBlockState(blockPos.west())) || this.isWall(world.getBlockState(blockPos.east()))) || axis == Direction.Axis.X && (this.isWall(world.getBlockState(blockPos.north())) || this.isWall(world.getBlockState(blockPos.south()))); return (((this.getDefaultState().with(FACING, direction)).with(OPEN, bl)).with(POWERED, bl)).with(IN_WALL, bl2); } private boolean isWall(BlockState state) { return state.getBlock().isIn(BlockTags.WALLS); } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (state.get(OPEN)) { state = state.with(OPEN, false); world.setBlockState(pos, state, 10); } else { Direction direction = player.getHorizontalFacing(); if (state.get(FACING) == direction.getOpposite()) { state = state.with(FACING, direction); } state = state.with(OPEN, true); world.setBlockState(pos, state, 10); } world.syncWorldEvent(player, state.get(OPEN) ? 1008 : 1014, pos, 0); return ActionResult.success(world.isClient); } @Override public void neighborUpdate(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) { if (!world.isClient) { boolean bl = world.isReceivingRedstonePower(pos); if (state.get(POWERED) != bl) { world.setBlockState(pos,(state.with(POWERED, bl)).with(OPEN, bl), 2); if (state.get(OPEN) != bl) { world.syncWorldEvent(null, bl ? 1008 : 1014, pos, 0); } } } } @Override protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(FACING, OPEN, POWERED, IN_WALL); } public static boolean canWallConnect(BlockState state, Direction side) { return (state.get(FACING)).getAxis() == side.rotateYClockwise().getAxis(); } static { OPEN = Properties.OPEN; POWERED = Properties.POWERED; IN_WALL = Properties.IN_WALL; Z_AXIS_SHAPE = Block.createCuboidShape(0.0D, 0.0D, 6.0D, 16.0D, 16.0D, 10.0D); X_AXIS_SHAPE = Block.createCuboidShape(6.0D, 0.0D, 0.0D, 10.0D, 16.0D, 16.0D); IN_WALL_Z_AXIS_SHAPE = Block.createCuboidShape(0.0D, 0.0D, 6.0D, 16.0D, 13.0D, 10.0D); IN_WALL_X_AXIS_SHAPE = Block.createCuboidShape(6.0D, 0.0D, 0.0D, 10.0D, 13.0D, 16.0D); Z_AXIS_COLLISION_SHAPE = Block.createCuboidShape(0.0D, 0.0D, 6.0D, 16.0D, 24.0D, 10.0D); X_AXIS_COLLISION_SHAPE = Block.createCuboidShape(6.0D, 0.0D, 0.0D, 10.0D, 24.0D, 16.0D); Z_AXIS_CULL_SHAPE = VoxelShapes.union(Block.createCuboidShape(0.0D, 5.0D, 7.0D, 2.0D, 16.0D, 9.0D), Block.createCuboidShape(14.0D, 5.0D, 7.0D, 16.0D, 16.0D, 9.0D)); X_AXIS_CULL_SHAPE = VoxelShapes.union(Block.createCuboidShape(7.0D, 5.0D, 0.0D, 9.0D, 16.0D, 2.0D), Block.createCuboidShape(7.0D, 5.0D, 14.0D, 9.0D, 16.0D, 16.0D)); IN_WALL_Z_AXIS_CULL_SHAPE = VoxelShapes.union(Block.createCuboidShape(0.0D, 2.0D, 7.0D, 2.0D, 13.0D, 9.0D), Block.createCuboidShape(14.0D, 2.0D, 7.0D, 16.0D, 13.0D, 9.0D)); IN_WALL_X_AXIS_CULL_SHAPE = VoxelShapes.union(Block.createCuboidShape(7.0D, 2.0D, 0.0D, 9.0D, 13.0D, 2.0D), Block.createCuboidShape(7.0D, 2.0D, 14.0D, 9.0D, 13.0D, 16.0D)); } }
true
c7f89b8f1a5827c96889d6ad96ccfa9ec2e0146d
Java
Kirti1402/SeleniumAutomation
/Locaters.java
UTF-8
679
2.0625
2
[]
no_license
package demo; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Locaters { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver= new ChromeDriver(); driver.get("https://www.facebook.com"); WebElement username= driver.findElement(By.id("email")); username.sendKeys("kirti2714@gmail.com"); WebElement password=driver.findElement(By.id("pass")); password.sendKeys("mankrit21409"); } }
true
6d266071b7a3c1a2a3d509edbee332be8b3b0f6d
Java
chinchu141/EmployeeService
/src/main/java/com/scg/employee/controller/EmployeeController.java
UTF-8
1,047
2.015625
2
[]
no_license
package com.scg.employee.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.scg.employee.service.EmployeeService; import com.scg.employee.vo.EmployeeVO; @RestController @RequestMapping("/employee") public class EmployeeController { @Autowired private EmployeeService employeeService; @PostMapping public EmployeeVO addEmployee(@RequestBody final EmployeeVO employeeVO) { return employeeService.addEmployee(employeeVO); } @GetMapping("/list") public List<EmployeeVO> getEmployee() { return employeeService.getEmployees(); } @GetMapping("/lists") public String listDepartments() { return employeeService.getAllDepartments(); } }
true
74e96d0953ea8a5bdf833a911c88b802e9056052
Java
nimish309/nimcccref
/app/src/main/java/com/coruscate/centrecourt/Adapter/ItemReviewAdapter.java
UTF-8
3,436
2.203125
2
[]
no_license
package com.coruscate.centrecourt.Adapter; import android.graphics.Color; import android.graphics.drawable.LayerDrawable; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RatingBar; import com.coruscate.centrecourt.CustomControls.TypefacedTextView; import com.coruscate.centrecourt.R; import com.coruscate.centrecourt.UserInterface.Activity.ItemReviewActivity; import com.coruscate.centrecourt.Util.AppConstant; import com.coruscate.centrecourt.Util.JSONData; import org.json.JSONObject; import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by cis on 8/19/2015. */ public class ItemReviewAdapter extends RecyclerView.Adapter<ItemReviewAdapter.RecyclerViewHolder> { private ArrayList<String> reviewList; private ItemReviewActivity itemReviewActivity; public ItemReviewAdapter(ArrayList<String> reviewList, ItemReviewActivity itemReviewActivity) { this.reviewList = reviewList; this.itemReviewActivity = itemReviewActivity; } @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); View itemView = inflater.inflate(R.layout.item_review_row, viewGroup, false); return new RecyclerViewHolder(itemView); } @Override public void onBindViewHolder(RecyclerViewHolder vh, int position) { DrawableCompat.setTint(DrawableCompat.wrap(((LayerDrawable) vh.rattingBar.getProgressDrawable()).getDrawable(2)), Color.YELLOW); JSONObject item = getItem(position); if (item != null) { if (position == 0) { itemReviewActivity.product_id = JSONData.getString(item, "product_id"); } JSONObject user = JSONData.getJSONObjectDefNull(item, "user"); if (user != null) { vh.txtName.setText((JSONData.getString(user, "first_name") + " " + JSONData.getString(user, "last_name")).trim()); } else { vh.txtName.setText(""); } vh.rattingBar.setRating(Float.parseFloat(JSONData.getInt(item, "rating") + "")); vh.txtDays.setText(AppConstant.getTimeDiff(JSONData.getString(item, "created_at"))); vh.txtDescription.setText(JSONData.getString(item, "review")); } } @Override public int getItemCount() { return reviewList.size(); } public JSONObject getItem(int position) { try { return new JSONObject(reviewList.get(position)); } catch (Exception e) { e.printStackTrace(); return null; } } class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @InjectView(R.id.txtName) TypefacedTextView txtName; @InjectView(R.id.rattingBar) RatingBar rattingBar; @InjectView(R.id.txtDays) TypefacedTextView txtDays; @InjectView(R.id.txtDescription) TypefacedTextView txtDescription; public RecyclerViewHolder(View v) { super(v); ButterKnife.inject(this, v); } @Override public void onClick(View view) { } } }
true
4a8e02242b85a0f14daf833739590bff50f082a7
Java
donglu1000tu/oop2018
/src/week7/task1/ExpressionTest.java
UTF-8
674
3.65625
4
[]
no_license
package week7.task1; public class ExpressionTest { public static void main(String[] args) { Square a = new Square(new Numeral(10)); Subtraction b = new Subtraction(a, new Numeral(1)); Multiplication c = new Multiplication(new Numeral(2), new Numeral(3)); Addition d = new Addition(b, c); Square res = new Square(d); System.out.println(res.toString() + " = " + res.evaluate()); Division division = new Division(new Numeral(10), new Numeral(0)); try{ System.out.println(division.evaluate()); } catch (ArithmeticException e){ System.out.println(e.toString()); } } }
true
95f7d8f410977f31c2d642fcaa0a85a680bfc36a
Java
suyashsudhir/pizzastore
/pizzaBackend/src/main/java/com/example/pizzabackend/pizzabackend/models/JWTRequest.java
UTF-8
273
1.65625
2
[]
no_license
package com.example.pizzabackend.pizzabackend.models; import lombok.Data; import java.io.Serializable; @Data public class JWTRequest implements Serializable { private final String username; private final String password; private final Boolean rememberMe; }
true
f261bbe119a3ed0930eaa04dd3873c45a8389ff9
Java
cs-fullstack-fall-2018/java-assignment-basic-input-cmadisonne
/src/Main.java
UTF-8
921
3.703125
4
[]
no_license
import java.io.InputStream; import java.util.Scanner; public class Main { public static void main(String[] args) { // EXERCISE 1 // System.out.println("It's a great day today!"); System.out.println("What is your name?"); Scanner scanIn = new Scanner(System.in); String name = scanIn.nextLine(); System.out.println("Hello" + name); // EXERCISE 2 // System.out.println("Enter a number."); int firstNum = scanIn.nextInt(); System.out.println("Enter another number."); int anotherNum = scanIn.nextInt(); System.out.println(firstNum + anotherNum); System.out.println(firstNum - anotherNum); // EXERCISE 3 // System.out.println("What is your balance?"); int balance = scanIn.nextInt(); System.out.println("I've granted you $2 more! Your new balance is: " + (balance+2)); } }
true
07572abd4734c5806d8531acb855742c2a305773
Java
rrabit42/Malware_Project_EWHA
/src/androidx/work/impl/constraints/controllers/BatteryChargingController.java
UTF-8
663
2
2
[]
no_license
package androidx.work.impl.constraints.controllers; import android.content.Context; import android.support.annotation.NonNull; import androidx.work.impl.constraints.trackers.Trackers; import androidx.work.impl.model.WorkSpec; public class BatteryChargingController extends ConstraintController<Boolean> { public BatteryChargingController(Context paramContext) { super(Trackers.getInstance(paramContext).getBatteryChargingTracker()); } boolean hasConstraint(@NonNull WorkSpec paramWorkSpec) { return paramWorkSpec.constraints.requiresCharging(); } boolean isConstrained(@NonNull Boolean paramBoolean) { return paramBoolean.booleanValue() ^ true; } }
true
b273308c6b34ec7147e85911697a314e8e57dd12
Java
jurfed/game-example
/core/src/main/java/com/octavianonline/games/wheelenium/screen/WheeleniumInfoScreen.java
UTF-8
3,793
1.835938
2
[]
no_license
package com.octavianonline.games.wheelenium.screen; import com.atsisa.gox.framework.animation.IAnimationFactory; import com.atsisa.gox.framework.animation.TweenViewAnimationData; import com.atsisa.gox.framework.eventbus.IEventBus; import com.atsisa.gox.framework.eventbus.NextObserver; import com.atsisa.gox.framework.eventbus.annotation.Subscribe; import com.atsisa.gox.framework.infrastructure.IViewManager; import com.atsisa.gox.framework.rendering.IRenderer; import com.atsisa.gox.framework.screen.model.ScreenModel; import com.atsisa.gox.framework.utility.IFinishCallback; import com.atsisa.gox.framework.utility.localization.ITranslator; import com.atsisa.gox.reels.event.PayTableModelChangedEvent; import com.atsisa.gox.reels.screen.InfoScreen; import com.atsisa.gox.reels.screen.model.PayTableScreenModel; import com.atsisa.gox.reels.screen.transition.InfoScreenTransition; import com.atsisa.gox.framework.utility.logger.ILogger; import com.gwtent.reflection.client.annotations.Reflect_Full; import com.octavianonline.framework.reels.screens.OctavianInfoScreen; import javax.inject.Inject; import javax.inject.Named; /** * Represents the info screen. */ @Reflect_Full public class WheeleniumInfoScreen extends OctavianInfoScreen { /** * Initializes a new instance of the {@link InfoScreen} class. * * @param layoutId layout identifier * @param model {@link ScreenModel} * @param renderer {@link IRenderer} * @param viewManager {@link IViewManager} * @param animationFactory {@link IAnimationFactory} * @param logger {@link ILogger} * @param eventBus {@link IEventBus} * @param infoScreenTransition {@link InfoScreenTransition} * @param translator */ @Inject public WheeleniumInfoScreen(@Named(LAYOUT_ID_PROPERTY)String layoutId, IRenderer renderer, IViewManager viewManager, IAnimationFactory animationFactory, ILogger logger, IEventBus eventBus, WheeleniumScreenTransition infoScreenTransition, ITranslator translator, WheeleniumPayTableScreenModel model) { super(layoutId, model, renderer, viewManager, animationFactory, logger, eventBus, infoScreenTransition, translator); } /** * Registers events. */ protected void registerEvents() { super.registerEvents(); getEventBus().register(new PayTableModelChangedEventObserver(), PayTableModelChangedEvent.class); } @Override public void show(String viewId, TweenViewAnimationData viewAnimationData, IFinishCallback finishCallback) { viewAnimationData.setTimeSpan(0); super.show(viewAnimationData, finishCallback); } @Override protected void show(TweenViewAnimationData viewAnimationData, IFinishCallback finishCallback, Object triggeredEvent) { if (isActive()) { viewAnimationData.setTimeSpan(0); showNext(finishCallback, triggeredEvent); } else { super.show(viewAnimationData, finishCallback, triggeredEvent); } } @Subscribe public void handlePayTableModelChangedEvent(PayTableModelChangedEvent event) { ((WheeleniumPayTableScreenModel) getModel()).updatePayTableValues(event.getValues()); } private class PayTableModelChangedEventObserver extends NextObserver<PayTableModelChangedEvent> { @Override public void onNext(final PayTableModelChangedEvent payTableModelChangedEvent) { handlePayTableModelChangedEvent(payTableModelChangedEvent); } } @Override public void hide(TweenViewAnimationData viewAnimationData, final IFinishCallback callback) { viewAnimationData.setTimeSpan(0); super.hide(viewAnimationData, callback); } }
true
9a0a6618f6a443675d7e5ebfbb5619d72dcf99be
Java
Jakubzawadzillo/jakub_zawadzillo-kodilla_tester
/kodilla-intro/src/main/java/TestUser.java
UTF-8
1,155
3.15625
3
[]
no_license
public class TestUser { public static void main(String[] args) { User kuba= new User("kubus",28); User asia= new User("asia", 25); User jola= new User("jola", 32); User bartek= new User("bartek", 22); User maciek= new User("maciek", 31); User lechu= new User("leszek", 21); User cyryl= new User("Cyryl", 9); User[] users={kuba, asia, jola, bartek, maciek, lechu, cyryl}; System.out.println(averageAge(users)); System.out.println(displayBelowAverage(averageAge(users), users)); } public static float averageAge(User[] users) { int count=0; int sum=0; float average=0.0f; for (int i=0; i<7; i++) { sum= sum+ users[i].getAge(); count=i; } average= sum/count; return average; } public static int displayBelowAverage(float average, User[] users) { for (int i=0; i<7; i++) { if (users[i].getAge() < average) { System.out.println(users[i].getName()); } } return 0; } }
true
ca9980f1eb9d99857d8db7a442ad5aeeeeaa6bff
Java
ifjso/microservice-coding-workshop
/chapter09/zuulsvr/src/main/java/com/thoughtmechanix/zuulsvr/filters/ResponseFilter.java
UTF-8
945
1.953125
2
[]
no_license
package com.thoughtmechanix.zuulsvr.filters; import brave.Tracer; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component @RequiredArgsConstructor public class ResponseFilter extends ZuulFilter { private static final int FILTER_ORDER = 1; private static final boolean SHOULD_FILTER = true; private final Tracer tracer; @Override public String filterType() { return "post"; } @Override public int filterOrder() { return FILTER_ORDER; } @Override public boolean shouldFilter() { return SHOULD_FILTER; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.getResponse().addHeader("tmx-correlation-id", tracer.currentSpan().context().traceIdString()); return null; } }
true
1986fe8ec0b84080ec1a7596ee06dc06264bf0de
Java
IShostak/SpringPractice
/spring-demo-one/src/com/ishostak/springdemo/TrackCoach.java
UTF-8
584
2.828125
3
[]
no_license
package com.ishostak.springdemo; public class TrackCoach implements Coach { private FortuneService service; public TrackCoach(FortuneService service) { this.service = service; } //init method public void myInitMethod() { System.out.println("TrackCoach: inside init method"); } //destroy method public void myDestroyMethod() { System.out.println("TrackCoach: inside destroy method"); } @Override public String getDailyWorkout() { return "Run a hard 5k"; } @Override public String getDailyFortune() { return "Just do it: " + service.getFortune(); } }
true
426cc94cbc107c8bb32a8f660c9d7a7899d795e7
Java
RorschachAqr/Java_Se
/src/InterfaceCase2/TabletennisT.java
UTF-8
518
3.234375
3
[]
no_license
package InterfaceCase2; public class TabletennisT extends Trainer implements English{ public TabletennisT() { } public TabletennisT(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("乒乓球教练吃饭"); } @Override public void teach() { System.out.println("乒乓球教练教乒乓球"); } @Override public void learnEnglish() { System.out.println("乒乓球教练学英语"); } }
true
286549a5a6703392fc11bf42c87f9219178d3d70
Java
thofis/twrsprsec
/src/main/java/com/example/thofis/twrsprsec/UserPopulator.java
UTF-8
1,651
2.296875
2
[]
no_license
package com.example.thofis.twrsprsec; import java.util.Set; import com.example.thofis.twrsprsec.repository.UserRepository; import com.example.thofis.twrsprsec.security.Permission; import com.example.thofis.twrsprsec.security.Role; import com.example.thofis.twrsprsec.security.User; import lombok.RequiredArgsConstructor; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import static com.example.thofis.twrsprsec.security.Permission.PROCESS_HELLO; import static com.example.thofis.twrsprsec.security.Permission.READ_ARTICLE; import static com.example.thofis.twrsprsec.security.Role.ADMIN; import static com.example.thofis.twrsprsec.security.Role.USER; @Component @RequiredArgsConstructor public class UserPopulator implements ApplicationRunner { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; @Override public void run(ApplicationArguments args) throws Exception { userRepository.save(newUser("Thomas", passwordEncoder.encode("Passw0rt"), Set.of(USER, ADMIN) ,Set.of(PROCESS_HELLO))); userRepository.save(newUser("John", passwordEncoder.encode("Passw0rt"), Set.of(USER), Set.of(READ_ARTICLE))); } private User newUser(String username, String password, Set<Role> roles, Set<Permission> permissions) { return User.builder() .username(username) .password(password) .roles(roles) .permissions(permissions) .build(); } }
true
e43d4b7608593710e9d4a4c400d4af6cb12a1578
Java
kimdh-hyw/chap15_thread
/src/sec05_threadstates/EX01_NewRunnableTerminated/NewRunnableTerminated.java
UTF-8
826
3.875
4
[]
no_license
package sec05_threadstates.EX01_NewRunnableTerminated; public class NewRunnableTerminated { public static void main(String[] args) { //#쓰레드 상태 저장 클래스 Thread.State state; //#1. 객체 생성 (NEW) Thread myThread = new Thread() { @Override public void run() { for(long i=0; i<1000000000L ; i++) {} //시간지연 } }; state = myThread.getState(); System.out.println("myThread state = "+ state); //NEW //#2. myThread 시작 myThread.start(); state = myThread.getState(); System.out.println("myThread state = "+ state); //Runnable //#3. myThread 종료 try { myThread.join(); } catch (InterruptedException e) { } state = myThread.getState(); System.out.println("myThread state = "+ state); //TERMINATED } }
true
704a8217bc9e05a43317d04d00164d35be14ab1c
Java
chuchip/anjelica
/src/main/java/gnu/chu/anjelica/ventas/CLPedidVen.java
UTF-8
39,356
1.695313
2
[]
no_license
package gnu.chu.anjelica.ventas; /* *<p>Titulo: CLVenRep </p> * <p>Descripción: Consulta Listado Ventas a Representantes</p> * Este programa saca los margenes sobre el precio de tarifa entre unas fechas * y para una zona/Representante dada. * Tambien permite sacar una relacion de los albaranes, que no tienen precio de tarifa * puestos, dandoz< la opción de actualizarlos. * <P>Parametros</p> * <p> * repCodi = representante * verPrecio = Ver Precio de Pedidos * sbeCodi = subEmpresa * admin= administrador * </p> * Created on 03-dic-2009, 22:41:09 * * <p>Copyright: Copyright (c) 2005-2018 * Este programa es software libre. Puede redistribuirlo y/o modificarlo bajo * los terminos de la Licencia Pública General de GNU según es publicada por * la Free Software Foundation, bien de la versión 2 de dicha Licencia * o bien (según su elección) de cualquier versión posterior. * Este programa se distribuye con la esperanza de que sea útil, * pero SIN NINGUNA GARANTIA, incluso sin la garantía MERCANTIL implícita * o sin garantizar la CONVENIENCIA PARA UN PROPOSITO PARTICULAR. * Véase la Licencia Pública General de GNU para más detalles. * Debería haber recibido una copia de la Licencia Pública General junto con este programa. * Si no ha sido así, escriba a la Free Software Foundation, Inc., * en 675 Mass Ave, Cambridge, MA 02139, EEUU. * </p> */ import gnu.chu.Menu.Principal; import gnu.chu.anjelica.listados.Listados; import gnu.chu.anjelica.pad.MantRepres; import gnu.chu.anjelica.pad.pdconfig; import gnu.chu.camposdb.proPanel; import gnu.chu.camposdb.prvPanel; import gnu.chu.controles.StatusBar; import gnu.chu.interfaces.ejecutable; import gnu.chu.utilidades.EntornoUsuario; import gnu.chu.utilidades.Formatear; import gnu.chu.utilidades.Iconos; import gnu.chu.utilidades.ventana; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.print.PrinterException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.text.ParseException; import java.util.ArrayList; import java.util.Hashtable; import javax.swing.JCheckBoxMenuItem; import javax.swing.JPopupMenu; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRField; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; public class CLPedidVen extends ventana implements JRDataSource { String pvc_comen; ArrayList<String> htCam=new ArrayList(); ArrayList<String> htCamAll=new ArrayList(); ArrayList<String> htCamDef=new ArrayList(); ArrayList<JCheckBoxMenuItem> alMenuItems=new ArrayList(); JPopupMenu JpopupMenu = new JPopupMenu("Camaras"); JCheckBoxMenuItem mCamTodas=new JCheckBoxMenuItem("*TODAS*"); boolean swCliente=false; int nLineaReport,nLineaSalto; int nLineaDet; boolean swImpreso=true; proPanel pro_codiE= new proPanel(); prvPanel prv_codiE = new prvPanel(); int empCodiS,ejeNumeS,pvcNumeS,cliCodiS; ventana padre=null; String s; boolean ARG_VERPRECIO=false; String ARG_REPCODI = ""; String ARG_SBECODI = ""; private final int JTCAB_EJEPED=0; private final int JTCAB_NUMPED=1; private final int JTCAB_CLICOD=2; private final int JTCAB_CLINOMB=3; private final int JTCAB_CLIPOBL=4; private final int JTCAB_FECENT=5; private final int JTCAB_HORENT=6; private final int JTCAB_CODREP=7; private final int JTCAB_RUTA=10; private final int JTCAB_SERALB=12; private final int JTCAB_NUMALB= 13; private final int JTCAB_EJEALB=11; // private final int JTLIN_CANTI=6; // private final int JTLIN_PROCOD=1; // private final int JTLIN_PRONOMB=2; // private final int JTLIN_TIPLIN=0; // private final int JTLIN_COMENT=9; // private final int JTLIN_PRV=3; // private final int JTLIN_FECCAD=5; // private final int JTCAB_POBCLI=5; public CLPedidVen(EntornoUsuario eu, Principal p) { this(eu, p, null); } public CLPedidVen(EntornoUsuario eu, Principal p, Hashtable<String,String> ht) { EU = eu; vl = p.panel1; jf = p; eje = true; try { ponParametros(ht); setTitulo("Cons/List. Pedidos Ventas"); setAcronimo("clpeve"); if (jf.gestor.apuntar(this)) { jbInit(); } else { setErrorInit(true); } } catch (Exception e) { ErrorInit(e); } } public CLPedidVen(gnu.chu.anjelica.menu p, EntornoUsuario eu, Hashtable <String,String> ht) { EU = eu; vl = p.getLayeredPane(); eje = false; try { ponParametros(ht); setTitulo("Cons/List. Pedidos de Ventas"); setAcronimo("clpeve"); jbInit(); } catch (Exception e) { ErrorInit(e); } } void ponParametros(Hashtable<String,String> ht) { if (ht != null) { if (ht.get("repCodi") != null) ARG_REPCODI = ht.get("repCodi"); if (ht.get("verPrecio") != null) ARG_VERPRECIO = Boolean.parseBoolean(ht.get("verPrecio")); if (ht.get("sbeCodi") != null) ARG_SBECODI = ht.get("sbeCodi"); if (ht.get("admin") != null) setArgumentoAdmin(Boolean.parseBoolean(ht.get("admin"))); } } public CLPedidVen(ventana papa) throws Exception { padre=papa; dtStat=padre.dtStat; dtCon1=padre.dtCon1; vl=padre.vl; jf=padre.jf; EU=padre.EU; setTitulo("Cons/List. Pedidos de Ventas"); jbInit(); } private void jbInit() throws Exception { statusBar = new StatusBar(this); iniciarFrame(); this.setVersion("2018-05-08"); initComponents(); this.setSize(new Dimension(730, 535)); this.getContentPane().add(statusBar, BorderLayout.SOUTH); conecta(); } public void setVerPrecio(boolean verPrecio) { linPed.setVerPrecio(verPrecio); } @Override public void iniciarVentana() throws Exception { tit_usunomE.setEnabled(isArgumentoAdmin()); tit_usunomE.setText(EU.usuario); Pcabe.setDefButton(Baceptar.getBotonAccion()); pvc_feciniE.setAceptaNulo(false); pvc_fecfinE.setAceptaNulo(false); cli_codiE.setCeroIsNull(true); linPed.iniciar(this); linPed.setVerPrecio(ARG_VERPRECIO); MantRepres.llenaLinkBox(rep_codiE, dtCon1); pdconfig.llenaDiscr(dtStat, zon_codiE, pdconfig.D_ZONA,EU.em_cod); pdconfig.llenaDiscr(dtStat, rut_codiE, pdconfig.D_RUTAS, EU.em_cod); rut_codiE.setCeroIsNull(true); cli_codiE.iniciar(dtStat, this, vl, EU); cli_codiE.setVerCampoReparto(true); s="select * from programasparam where prf_host='"+Formatear.getHostName()+"'"+ " and prf_id ='clpedven.camaras'"; if (dtStat.select(s)) { do { htCamDef.add(dtStat.getString("prf_valor")); } while (dtStat.next()); } s="select cam_codi,cam_nomb from v_camaras order by cam_codi"; if (dtStat.select(s)) { mCamTodas.setSelected(htCamDef.isEmpty()); JpopupMenu.add(mCamTodas); do { JCheckBoxMenuItem mCam=new JCheckBoxMenuItem(dtStat.getString("cam_nomb")); alMenuItems.add(mCam); JpopupMenu.add(mCam); final String camCodi=dtStat.getString("cam_codi"); if (htCamDef.indexOf(camCodi)>=0) { mCam.setSelected(true); htCam.add(camCodi); } htCamAll.add(camCodi); mCam.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (mCamTodas.isSelected()) mCamTodas.setSelected(false); if (htCam.indexOf(camCodi)>=0) htCam.remove(camCodi); else htCam.add(camCodi); JpopupMenu.show(BFiltroCam,0,24); } }); } while (dtStat.next()); } sbe_codiE.iniciar(dtStat, this, vl, EU); sbe_codiE.setAceptaNulo(true); sbe_codiE.setValorInt(0); pvc_feciniE.setText(Formatear.sumaDias(Formatear.getDateAct(), -7)); pvc_fecfinE.setText(Formatear.getFechaAct("dd-MM-yyyy")); activarEventos(); } @Override public void matar(boolean cerrarConexion) { try { if (muerto || ct.isClosed()) { super.matar(cerrarConexion); return; } guardaParam(); super.matar(cerrarConexion); //To change body of generated methods, choose Tools | Templates. } catch (SQLException ex) { muerto=true; Error("Error al guardar parametros programa",ex); } } void guardaParam() throws SQLException { s="delete from programasparam where prf_host='"+Formatear.getHostName()+"'"+ " and prf_id ='clpedven.camaras'"; dtAdd.executeUpdate(s); if (!mCamTodas.isSelected()) { for (String cam:htCam) { dtAdd.addNew("programasparam"); dtAdd.setDato("prf_host",Formatear.getHostName()); dtAdd.setDato("prf_id","clpedven.camaras"); dtAdd.setDato("prf_valor",cam); dtAdd.update(); } } dtAdd.commit(); } void activarEventos() { BFiltroCam.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JpopupMenu.show(BFiltroCam,0,24); } }); mCamTodas.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { htCam.clear(); for (JCheckBoxMenuItem menuItem:alMenuItems) { menuItem.setSelected(mCamTodas.isSelected()); } if (mCamTodas.isSelected()) { for (String cam:htCamAll) { htCam.add(cam); } } JpopupMenu.show(BFiltroCam,0,24); } }); Baceptar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Baceptar_actionPerformed(Baceptar.getValor(e.getActionCommand()) ); } }); jtCabPed.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() || ! jtCabPed.isEnabled() || jtCabPed.isVacio() ) // && e.getFirstIndex() == e.getLastIndex()) return; verDatPed(EU.em_cod,jtCabPed.getValorInt(JTCAB_EJEPED),jtCabPed.getValorInt(JTCAB_NUMPED), jtCabPed.getValorInt(JTCAB_EJEALB),jtCabPed.getValString(JTCAB_SERALB),jtCabPed.getValorInt(JTCAB_NUMALB)); // System.out.println(" Row "+getValString(0,5)+ " - "+getValString(1,5)); } }); jtCabPed.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() < 2) return; if (jtCabPed.isVacio()) return; if (padre!=null) { empCodiS=EU.em_cod; ejeNumeS=jtCabPed.getValorInt(JTCAB_EJEPED); pvcNumeS=jtCabPed.getValorInt(JTCAB_NUMPED); cliCodiS=jtCabPed.getValorInt(JTCAB_CLICOD); matar(); } else { if (jtCabPed.getValorInt(JTCAB_EJEALB)==0) { irPedido(); return; } if (jtCabPed.getSelectedColumn()<=JTCAB_NUMPED) irPedido(); else irAlbaran(); } } }); } void irAlbaran() { ejecutable prog; if ((prog=jf.gestor.getProceso(pdalbara.getNombreClase()))==null) return; pdalbara cm=(pdalbara) prog; if (cm.inTransation()) { msgBox("Mantenimiento Albaranes de Ventas ocupado. No se puede realizar la busqueda"); return; } cm.PADQuery(); cm.setSerieAlbaran(jtCabPed.getValString(JTCAB_SERALB)); cm.setNumeroAlbaran(jtCabPed.getValString(JTCAB_NUMALB)); cm.setEjercAlbaran(jtCabPed.getValorInt(JTCAB_EJEALB)); cm.ej_query(); jf.gestor.ir(cm); } void irPedido() { pdpeve.irMantPedido(jf,jtCabPed.getValorInt(JTCAB_EJEPED),jtCabPed.getValorInt(JTCAB_NUMPED)); } public String getCliNomb() { return jtCabPed.getValString(JTCAB_CLINOMB); } /** * Devuelve la ruta que tiene asignado un pedido. * @return * @throws SQLException */ public String getRuta() throws SQLException { return pdpeve.getRuta(dtCon1, empCodiS, ejeNumeS, pvcNumeS); } public String getComentarioRuta() { return linPed.getComentarioRuta(); } public String getSerieAlbaran() { return jtCabPed.getValString(JTCAB_SERALB); } public int getEjercicioAlbaran() { return jtCabPed.getValorInt(JTCAB_EJEALB); } public int getNumeroAlbaran() { return jtCabPed.getValorInt(JTCAB_NUMALB); } void verDatPed(int empCodi,int ejeNume,int pvcNume,int ejeAlb,String serAlb,int numAlb) { try { linPed.setNumeroPedidos(jtCabPed.getRowCount()); linPed.verDatPed(empCodi, ejeNume, pvcNume, ejeAlb, serAlb, numAlb); } catch (SQLException k) { Error("Error al ver Datos pedidos",k); } } void Bimpri_actionPerformed(String accion) { if (jtCabPed.isVacio()) { msgBox("No hay pedidos para listar"); return; } if (accion.equals("L")) { imprImpreso(); return; } try { /** * Listado relacion de pedidos. */ swImpreso=false; java.util.HashMap mp = Listados.getHashMapDefault(); mp.put("fecini",pvc_feciniE.getDate()); mp.put("fecfin",pvc_fecfinE.getDate()); // mp.put("cli_zonrep",cli_zonrepE.getText()); // mp.put("cli_zoncre",cli_zoncreE.getText()); JasperReport jr; jr = Listados.getJasperReport(EU, "relpedven"); ResultSet rs; nLineaReport=0; nLineaSalto=0; nLineaDet=9999; // rs=dtCon1.getStatement().executeQuery(dtCon1.getStrSelect()); JasperPrint jp = JasperFillManager.fillReport(jr, mp,this); gnu.chu.print.util.printJasper(jp, EU); mensajeErr("Relacion Pedido Ventas ... IMPRESO "); } catch (ParseException | JRException | PrinterException k) { Error("Error al imprimir Pedido Venta", k); } } @Override public boolean next() throws JRException { try { if (!swImpreso) { if (nLineaReport>=jtCabPed.getRowCount()) return false; s = "SELECT c.*,ti.usu_nomco,tit_tiempo, cl.cli_nomb,cl.cli_poble" + " FROM pedvenc as c left join v_tiempospedido as ti on ti.tid_id=c.pvc_id " + " where ,v_cliente as cl " + " WHERE c.emp_codi = " + EU.em_cod + " and C.cli_codi = cl.cli_codi " + " AND C.eje_nume = " + jtCabPed.getValorInt(nLineaReport, JTCAB_EJEPED) + " and C.pvc_nume = " + jtCabPed.getValorInt(nLineaReport, JTCAB_NUMPED); if (!dtCon1.select(s)) { throw new JRException("Error al localizar pedido para listar. Linea: " + nLineaReport + " Pedido: " + jtCabPed.getValorInt(nLineaReport, JTCAB_NUMPED)); } nLineaReport++; } else { if (nLineaReport<0 || nLineaDet+1>=linPed.getLineasGrid()) { nLineaReport++; if (nLineaReport>=jtCabPed.getRowCount()) return false; nLineaDet=0; nLineaSalto++; verDatPed(EU.em_cod, jtCabPed.getValorInt(nLineaReport, JTCAB_EJEPED), jtCabPed.getValorInt(nLineaReport, JTCAB_NUMPED), jtCabPed.getValorInt(nLineaReport,JTCAB_EJEALB), jtCabPed.getValString(nLineaReport,JTCAB_SERALB),jtCabPed.getValorInt(nLineaReport,JTCAB_NUMALB) ); } else nLineaDet++; } return true; } catch (SQLException ex) { throw new JRException("Error al buscar pedido a listar",ex); } } void imprImpreso() { try { swImpreso=true; java.util.HashMap mp =Listados.getHashMapDefault(); JasperReport jr; jr = Listados.getJasperReport(EU, "pedventas"); nLineaReport=-1; nLineaDet=9999; nLineaSalto=0; JasperPrint jp = JasperFillManager.fillReport(jr, mp,this); gnu.chu.print.util.printJasper(jp, EU); mensajeErr("Relacion Pedido Ventas ... IMPRESO "); // dtCon1.select(s); // do // { // s = "update PEDVENC SET pvc_impres = 'S' WHERE emp_codi = " + dtCon1.getInt("emp_codi")+ // " and eje_nume = " + dtCon1.getInt("eje_nume")+ // " and pvc_nume = " +dtCon1.getInt("pvc_nume"); // stUp.executeUpdate(s); // } while (dtCon1.next()); // ctUp.commit(); mensajeErr("Pedido Ventas ... IMPRESO "); } catch (JRException | PrinterException k) { Error("Error al imprimir Pedido Venta", k); } } private boolean iniciarCons(boolean ejecSelect) throws SQLException, ParseException { if (pvc_feciniE.getError()) { mensajeErr("Fecha INICIAL no es valida"); pvc_feciniE.requestFocus(); return false; } if (pvc_fecfinE.getError()) { mensajeErr("Fecha FINAL no es valida"); pvc_feciniE.requestFocus(); return false; } if (! ejecSelect) return true; swCliente=false; String camCodi=""; if (!mCamTodas.isSelected()) { for (String cam:htCam) { camCodi+="'"+cam+"',"; } if (!camCodi.equals("")) camCodi=camCodi.substring(0,camCodi.length()-1); } if (!cli_codiE.isNull()) swCliente=true; s = "SELECT c.*,av.avc_id,av.avc_impres,av.cli_ruta, cl.cli_nomb,cl.cli_codrut, cl.cli_poble," + " c.rut_codi, al.rut_nomb,prc_fecsal FROM pedvenc as c" + " left join v_albavec as av on c.avc_ano = av.avc_ano " + " and c.avc_serie= av.avc_serie and c.avc_nume = av.avc_nume and av.emp_codi = c.emp_codi " + " left join tiempostarea as tt on tit_tipdoc='P' and tit_id=c.pvc_id and tt.usu_nomb='"+tit_usunomE.getText()+"'" + " left join v_pedruta as pr on c.pvc_id=pr.pvc_id " + ",clientes as cl,v_rutas as al " + " WHERE c.pvc_fecpre between to_date('" + pvc_feciniE.getText() + "','dd-MM-yyyy')" + " and to_date('" + pvc_fecfinE.getText() + "','dd-MM-yyyy')" + " and c.emp_codi = "+EU.em_cod+ " and cl.cli_codi = c.cli_codi " + " and c.rut_codi = al.rut_codi "+ " and pvc_confir = 'S'"+ (opPedAsigUsu.isSelected()?" and tt.usu_nomb='"+tit_usunomE.getText()+"'":"")+ (camCodi.equals("")?"": " and exists (select a.pro_codi from v_pedven as l,v_articulo as a where" + " a.pro_codi=l.pro_codi and l.pvc_id=c.pvc_id and a.cam_codi in ("+camCodi+"))" )+ (sbe_codiE.getValorInt()==0?"":" and cl.sbe_codi = "+sbe_codiE.getValorInt())+ (zon_codiE.isNull() || swCliente?"":" and cl.zon_codi = '"+zon_codiE.getText()+"'")+ (rep_codiE.isNull() || swCliente?"":" and cl.rep_codi = '"+rep_codiE.getText()+"'"); if (verPedidosE.getValor().equals("P")) s += " AND (c.avc_ano = 0 or pvc_cerra=0)"; if (verPedidosE.getValor().equals("L")) s += " AND c.avc_ano != 0"; if (swCliente) s += " AND c.cli_codi = " + cli_codiE.getValorInt(); s += " order by prc_fecsal,c.pvc_fecent,c.rut_codi,c.cli_codi "; jtCabPed.setEnabled(false); jtCabPed.removeAllDatos(); // debug("s: "+s); if (!dtCon1.select(s)) { mensajeErr("NO hay PEDIDOS que cumplan estas condiciones"); verPedidosE.requestFocus(); return false; } return true; } private void confJTCab() { ArrayList v=new ArrayList(); v.add("Eje."); // 0 v.add("Num.");// 1 v.add("Cliente"); // 2 v.add("Nombre Cliente"); // 3 v.add("Población"); // 4 v.add("Fec.Entrega"); // 5 v.add("Hora.Entrega"); // 6 v.add("C.Rep"); // 7 v.add("Cerr");// 8 v.add("Dep?"); // 9 v.add("Ruta");// 10 v.add("Ej.Alb");//11 v.add("S.Alb"); //12 v.add("Num.Alb"); //13 jtCabPed.setCabecera(v); jtCabPed.setMaximumSize(new Dimension(548, 158)); jtCabPed.setMinimumSize(new Dimension(548, 158)); jtCabPed.setPreferredSize(new Dimension(548, 158)); jtCabPed.setAnchoColumna(new int[]{40,49,55,150,100,76,40,40,40,40,100,40,40,60}); jtCabPed.setAlinearColumna(new int[]{2,2,2,0,0,1,0,1,1,1,0,2,1,2}); jtCabPed.setFormatoColumna(8,"BSN"); } public void setCliCodiText(String cliCodi) { cli_codiE.setText(cliCodi); } public void Baceptar_doClick() { Baceptar.getBotonAccion().doClick(); } void Baceptar_actionPerformed(String accion) { try { if (! iniciarCons(true)) return; boolean swServ=verPedidosE.getValor().equals("S") || verPedidosE.getValor().equals("M") ; // A servir (tienen albaran y no esta listado) do { if (!servRutaC.getValor().equals("*")) { boolean servRuta=false; if (dtCon1.getInt("avc_id",true)!=0) { s="select alr_nume from albrutalin where avc_id="+dtCon1.getInt("avc_id"); servRuta=dtStat.select(s); } if (servRuta && servRutaC.getValor().equals("N")) continue; if (! servRuta && servRutaC.getValor().equals("S")) continue; } if (swServ) { // Mostrar solo los disponibles para servir (tienen albaran y no estan listados) if (dtCon1.getInt("pvc_cerra")==0) continue; if (dtCon1.getObject("avc_impres")==null) continue; if ((dtCon1.getInt("avc_impres") & 1) != 0 ) { // Esta impreso if ( verPedidosE.getValor().equals("S")) continue; if (dtCon1.getInt("avc_impres") == 1 && verPedidosE.getValor().equals("M")) continue; } } boolean swImpres=false; if (!albListadoC.getValor().equals("*")) { if (dtCon1.getObject("avc_impres")!=null) swImpres= (dtCon1.getInt("avc_impres") & 1) == 1; if (swImpres && albListadoC.getValor().equals("N")) continue; if (! swImpres && albListadoC.getValor().equals("S")) continue; } if (!rut_codiE.isNull() && !swCliente) { if (dtCon1.getObject("cli_ruta")!=null) { if (! rut_codiE.getText().equals(dtCon1.getString("cli_ruta"))) continue; } else if (! rut_codiE.getText().equals(dtCon1.getString("rut_codi"))) continue; } ArrayList v=new ArrayList(); v.add(dtCon1.getString("eje_nume")); // 1 v.add(dtCon1.getString("pvc_nume")); // 2 v.add(dtCon1.getString("cli_codi")); // 3 v.add(dtCon1.getObject("pvc_clinom")==null?dtCon1.getString("cli_nomb"):dtCon1.getString("pvc_clinom")); // 4 v.add(dtCon1.getObject("cli_poble")); // 5 if (dtCon1.getObject("prc_fecsal")==null) { v.add(dtCon1.getFecha("pvc_fecent","dd-MM-yyyy")); // 5 v.add(""); } else { v.add(dtCon1.getFecha("prc_fecsal","dd-MM-yyyy")); // 5 v.add(dtCon1.getFecha("prc_fecsal","HH:mm")); } v.add(dtCon1.getString("cli_codrut")); // 6 v.add(dtCon1.getInt("pvc_cerra")!=0); // 7 v.add(dtCon1.getString("pvc_depos")); // 8 v.add(dtCon1.getString("rut_nomb")); // 9 v.add(dtCon1.getString("avc_ano")); //10 v.add(dtCon1.getString("avc_serie")); // 11 v.add(dtCon1.getString("avc_nume")); //12 jtCabPed.addLinea(v); } while (dtCon1.next()); if (jtCabPed.isVacio()) { mensajeErr("No encontrados pedidos con estos criterios"); return; } jtCabPed.requestFocusInicio(); jtCabPed.setEnabled(true); verDatPed(EU.em_cod,jtCabPed.getValorInt(JTCAB_EJEPED),jtCabPed.getValorInt(JTCAB_NUMPED), jtCabPed.getValorInt(JTCAB_EJEALB),jtCabPed.getValString(JTCAB_SERALB),jtCabPed.getValorInt(JTCAB_NUMALB)); if (accion.equals("C")) return; Bimpri_actionPerformed(accion); } catch (SQLException | ParseException k) { Error("Error al buscar pedidos", k); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; PPrinc = new gnu.chu.controles.CPanel(); Pcabe = new gnu.chu.controles.CPanel(); cLabel1 = new gnu.chu.controles.CLabel(); cli_codiE = new gnu.chu.camposdb.cliPanel(); cLabel5 = new gnu.chu.controles.CLabel(); sbe_codiE = new gnu.chu.camposdb.sbePanel(); cLabel6 = new gnu.chu.controles.CLabel(); pvc_feciniE = new gnu.chu.controles.CTextField(Types.DATE,"dd-MM-yyyy"); cLabel7 = new gnu.chu.controles.CLabel(); pvc_fecfinE = new gnu.chu.controles.CTextField(Types.DATE,"dd-MM-yyyy"); rep_codiE = new gnu.chu.controles.CLinkBox(); zon_codiE = new gnu.chu.controles.CLinkBox(); cLabel18 = new gnu.chu.controles.CLabel(); cLabel10 = new gnu.chu.controles.CLabel(); verPedidosE = new gnu.chu.controles.CComboBox(); cLabel21 = new gnu.chu.controles.CLabel(); cLabel2 = new gnu.chu.controles.CLabel(); servRutaC = new gnu.chu.controles.CComboBox(); cLabel3 = new gnu.chu.controles.CLabel(); albListadoC = new gnu.chu.controles.CComboBox(); cLabel22 = new gnu.chu.controles.CLabel(); rut_codiE = new gnu.chu.controles.CLinkBox(); BFiltroCam = new gnu.chu.controles.CButton(Iconos.getImageIcon("filter")); cLabel8 = new gnu.chu.controles.CLabel(); tit_usunomE = new gnu.chu.controles.CTextField(Types.CHAR,"X",15); opPedAsigUsu = new gnu.chu.controles.CCheckBox(); Baceptar = new gnu.chu.controles.CButtonMenu(Iconos.getImageIcon("check")); jtCabPed = new gnu.chu.controles.Cgrid(14); linPed = new gnu.chu.anjelica.ventas.PCabPedVentas(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); PPrinc.setLayout(new java.awt.GridBagLayout()); Pcabe.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED)); Pcabe.setMaximumSize(new java.awt.Dimension(725, 85)); Pcabe.setMinimumSize(new java.awt.Dimension(725, 85)); Pcabe.setName(""); // NOI18N Pcabe.setPreferredSize(new java.awt.Dimension(725, 85)); Pcabe.setLayout(null); cLabel1.setText("Ver Pedidos"); Pcabe.add(cLabel1); cLabel1.setBounds(2, 2, 70, 18); Pcabe.add(cli_codiE); cli_codiE.setBounds(80, 22, 340, 18); cLabel5.setText("Delegación"); Pcabe.add(cLabel5); cLabel5.setBounds(590, 22, 70, 18); Pcabe.add(sbe_codiE); sbe_codiE.setBounds(660, 22, 37, 18); cLabel6.setText("Usuario"); Pcabe.add(cLabel6); cLabel6.setBounds(250, 2, 49, 17); Pcabe.add(pvc_feciniE); pvc_feciniE.setBounds(500, 2, 76, 18); cLabel7.setText("A Fecha"); Pcabe.add(cLabel7); cLabel7.setBounds(580, 2, 43, 18); Pcabe.add(pvc_fecfinE); pvc_fecfinE.setBounds(630, 2, 75, 18); rep_codiE.setAncTexto(30); rep_codiE.setMayusculas(true); rep_codiE.setPreferredSize(new java.awt.Dimension(152, 18)); Pcabe.add(rep_codiE); rep_codiE.setBounds(60, 42, 190, 18); zon_codiE.setAncTexto(30); zon_codiE.setMayusculas(true); zon_codiE.setPreferredSize(new java.awt.Dimension(152, 18)); Pcabe.add(zon_codiE); zon_codiE.setBounds(310, 42, 280, 18); cLabel18.setText("Zona"); cLabel18.setPreferredSize(new java.awt.Dimension(60, 18)); Pcabe.add(cLabel18); cLabel18.setBounds(270, 42, 40, 18); cLabel10.setText("De Cliente"); Pcabe.add(cLabel10); cLabel10.setBounds(5, 22, 70, 18); verPedidosE.addItem("Pendientes","P"); verPedidosE.addItem("A servir","S"); verPedidosE.addItem("A servir + Modif.","M"); verPedidosE.addItem("Preparados","L"); verPedidosE.addItem("Todos","T"); Pcabe.add(verPedidosE); verPedidosE.setBounds(80, 2, 160, 18); cLabel21.setText("Repres."); cLabel21.setPreferredSize(new java.awt.Dimension(60, 18)); Pcabe.add(cLabel21); cLabel21.setBounds(5, 42, 50, 18); cLabel2.setText("Servidos en Ruta "); Pcabe.add(cLabel2); cLabel2.setBounds(10, 65, 100, 17); servRutaC.addItem("**","*"); servRutaC.addItem("Si","S"); servRutaC.addItem("No","N"); Pcabe.add(servRutaC); servRutaC.setBounds(110, 65, 50, 17); cLabel3.setText("Listados Albaran "); Pcabe.add(cLabel3); cLabel3.setBounds(190, 65, 100, 17); albListadoC.addItem("**","*"); albListadoC.addItem("Si","S"); albListadoC.addItem("No","N"); Pcabe.add(albListadoC); albListadoC.setBounds(290, 65, 50, 17); cLabel22.setText("Ruta"); cLabel22.setPreferredSize(new java.awt.Dimension(60, 18)); Pcabe.add(cLabel22); cLabel22.setBounds(350, 65, 40, 18); rut_codiE.setFormato(Types.CHAR,"X",2); rut_codiE.setAncTexto(30); rut_codiE.setMayusculas(true); rut_codiE.setPreferredSize(new java.awt.Dimension(152, 18)); Pcabe.add(rut_codiE); rut_codiE.setBounds(390, 65, 200, 18); BFiltroCam.setText("Camaras"); Pcabe.add(BFiltroCam); BFiltroCam.setBounds(490, 20, 90, 19); cLabel8.setText("De Fecha"); Pcabe.add(cLabel8); cLabel8.setBounds(440, 2, 49, 18); Pcabe.add(tit_usunomE); tit_usunomE.setBounds(300, 2, 76, 17); opPedAsigUsu.setText("Asig."); opPedAsigUsu.setToolTipText("Ver solo pedidos asignados a este usuario"); Pcabe.add(opPedAsigUsu); opPedAsigUsu.setBounds(380, 2, 60, 17); Baceptar.addMenu("Consultar","C"); Baceptar.addMenu("Listar Pedido","L"); Baceptar.addMenu("Listar Rel.Ped.","R"); Baceptar.setText("Aceptar"); Pcabe.add(Baceptar); Baceptar.setBounds(600, 60, 110, 26); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; PPrinc.add(Pcabe, gridBagConstraints); try {confJTCab();} catch (Exception k){Error("Error al configurar grid cabecera",k);} jtCabPed.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jtCabPed.setMaximumSize(new java.awt.Dimension(681, 110)); jtCabPed.setMinimumSize(new java.awt.Dimension(681, 110)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; PPrinc.add(jtCabPed, gridBagConstraints); linPed.setMaximumSize(new java.awt.Dimension(683, 164)); linPed.setMinimumSize(new java.awt.Dimension(683, 164)); linPed.setPreferredSize(new java.awt.Dimension(683, 164)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; PPrinc.add(linPed, gridBagConstraints); getContentPane().add(PPrinc, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private gnu.chu.controles.CButton BFiltroCam; private gnu.chu.controles.CButtonMenu Baceptar; private gnu.chu.controles.CPanel PPrinc; private gnu.chu.controles.CPanel Pcabe; private gnu.chu.controles.CComboBox albListadoC; private gnu.chu.controles.CLabel cLabel1; private gnu.chu.controles.CLabel cLabel10; private gnu.chu.controles.CLabel cLabel18; private gnu.chu.controles.CLabel cLabel2; private gnu.chu.controles.CLabel cLabel21; private gnu.chu.controles.CLabel cLabel22; private gnu.chu.controles.CLabel cLabel3; private gnu.chu.controles.CLabel cLabel5; private gnu.chu.controles.CLabel cLabel6; private gnu.chu.controles.CLabel cLabel7; private gnu.chu.controles.CLabel cLabel8; private gnu.chu.camposdb.cliPanel cli_codiE; private gnu.chu.controles.Cgrid jtCabPed; private gnu.chu.anjelica.ventas.PCabPedVentas linPed; private gnu.chu.controles.CCheckBox opPedAsigUsu; private gnu.chu.controles.CTextField pvc_fecfinE; private gnu.chu.controles.CTextField pvc_feciniE; private gnu.chu.controles.CLinkBox rep_codiE; private gnu.chu.controles.CLinkBox rut_codiE; private gnu.chu.camposdb.sbePanel sbe_codiE; private gnu.chu.controles.CComboBox servRutaC; private gnu.chu.controles.CTextField tit_usunomE; private gnu.chu.controles.CComboBox verPedidosE; private gnu.chu.controles.CLinkBox zon_codiE; // End of variables declaration//GEN-END:variables @Override public Object getFieldValue(JRField jrf) throws JRException { try { String campo = jrf.getName().toLowerCase(); if (!swImpreso) { if (campo.equals("orden")) return nLineaReport; return dtCon1.getObject(campo); } switch (campo) { case "salto": return (int) ( (nLineaSalto-1)/4); case "nlineasalto": return nLineaSalto; case "usu_nomco": return linPed.getUsuarioPedido(); case "tit_tiempo": return linPed.getTiempoPedido(); case "emp_codi": return EU.em_cod; case "eje_nume": return jtCabPed.getValorInt(nLineaReport,JTCAB_EJEPED); case "pvc_nume": return jtCabPed.getValorInt(nLineaReport,JTCAB_NUMPED); case "pvl_numlin": return nLineaDet; case "pvl_canti": return linPed.getGrid().getValString(nLineaDet,linPed.JT_CANPED); case "pro_codi": return linPed.getGrid().getValorInt(nLineaDet,linPed.JT_PROCOD); case "pro_nomb": return linPed.getGrid().getValString(nLineaDet,linPed.JT_PRONOMB); case "pvl_comen": return linPed.getGrid().getValString(nLineaDet,linPed.JT_COMENT); case "pvc_comen": return linPed.getComentarioPedido(); case "pvl_tipo": return linPed.getGrid().getValString(nLineaDet,linPed.JT_TIPLIN); case "cli_codi": return jtCabPed.getValorInt(nLineaReport,JTCAB_CLICOD); case "pvc_clinom": return jtCabPed.getValString(nLineaReport,JTCAB_CLINOMB); case "cli_pobl": return jtCabPed.getValString(nLineaReport,JTCAB_CLIPOBL); case "cli_codrut": return jtCabPed.getValString(nLineaReport,JTCAB_CODREP); case "rut_nomb": return jtCabPed.getValString(nLineaReport,JTCAB_RUTA); case "pvc_fecent": return jtCabPed.getValString(nLineaReport,JTCAB_FECENT); } throw new JRException("Campo NO VALIDO: "+campo); } catch (SQLException ex) { throw new JRException("Error al leer campo de base datos",ex); } } }
true
899225828f46a90983ef15942ba98f3ea2ea0fbb
Java
liulinpeng608/demo
/web/src/com/yzit/plateform/entity/GenScheme.java
UTF-8
2,676
1.984375
2
[]
no_license
package com.yzit.plateform.entity; import com.yzit.core.base.BaseEntity; /** * <b>功能:</b>数据库实体类<br> * <b>作者:</b>Administrator<br> * <b>日期:</b>Tue Jan 02 10:21:30 CST 2018 <br> * <b>版权所有:云优众<br> */ public class GenScheme extends BaseEntity { private static final long serialVersionUID = 1L; private Integer id;//编号 private String name;//名称 private String category;//分类 private String packageName;//生成包路径 private String moduleName;//生成模块名 private String subModuleName;//生成子模块名 private String functionName;//生成功能名 private String functionNameSimple;//生成功能名(简写) private String functionAuthor;//生成功能作者 private String genTableId;//生成表编号 private String remarks;//备注信息 private String delFlag;//删除标记(0:正常;1:删除) public Integer getId() { return this.id; } public void setId(Integer id) { this.id=id; } public String getName() { return this.name; } public void setName(String name) { this.name=name; } public String getCategory() { return this.category; } public void setCategory(String category) { this.category=category; } public String getPackageName() { return this.packageName; } public void setPackageName(String packageName) { this.packageName=packageName; } public String getModuleName() { return this.moduleName; } public void setModuleName(String moduleName) { this.moduleName=moduleName; } public String getSubModuleName() { return this.subModuleName; } public void setSubModuleName(String subModuleName) { this.subModuleName=subModuleName; } public String getFunctionName() { return this.functionName; } public void setFunctionName(String functionName) { this.functionName=functionName; } public String getFunctionNameSimple() { return this.functionNameSimple; } public void setFunctionNameSimple(String functionNameSimple) { this.functionNameSimple=functionNameSimple; } public String getFunctionAuthor() { return this.functionAuthor; } public void setFunctionAuthor(String functionAuthor) { this.functionAuthor=functionAuthor; } public String getGenTableId() { return this.genTableId; } public void setGenTableId(String genTableId) { this.genTableId=genTableId; } public String getRemarks() { return this.remarks; } public void setRemarks(String remarks) { this.remarks=remarks; } public String getDelFlag() { return this.delFlag; } public void setDelFlag(String delFlag) { this.delFlag=delFlag; } }
true
aa4a82c36fd5a90480bf8ef0803cb89c25773da0
Java
thefactoria/mybizdev
/src/main/java/fr/adservio/mybizdev/service/impl/PlacementServiceImpl.java
UTF-8
3,990
2.296875
2
[]
no_license
package fr.adservio.mybizdev.service.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fr.adservio.mybizdev.domain.Consultant; import fr.adservio.mybizdev.domain.Placement; import fr.adservio.mybizdev.domain.enumeration.Statut; import fr.adservio.mybizdev.repository.PlacementRepository; import fr.adservio.mybizdev.service.ConsultantService; import fr.adservio.mybizdev.service.PlacementService; /** * Service Implementation for managing Placement. */ @Service @Transactional public class PlacementServiceImpl implements PlacementService { private final Logger log = LoggerFactory.getLogger(PlacementServiceImpl.class); private final PlacementRepository placementRepository; @Autowired private ConsultantService consultantService; public PlacementServiceImpl(PlacementRepository placementRepository) { this.placementRepository = placementRepository; } /** * Save a placement. * * @param placement * the entity to save * @return the persisted entity */ @Override public Placement save(Placement placement) { log.debug("Request to save Placement : {}", placement); return placementRepository.save(placement); } /** * Save a list of placements. * * @param placements * the array of placement entities to save * @return the array of persisted entities */ @Override public List<Placement> save(List<Placement> placements) { log.debug("Request to save array of Placements : {}", placements); return placementRepository.save(placements); } /** * Get all the placements. * * @param pageable * the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<Placement> findAll(Pageable pageable) { log.debug("Request to get all Placements"); return placementRepository.findAll(pageable); } /** * Get one placement by id. * * @param id * the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Placement findOne(Long id) { log.debug("Request to get Placement : {}", id); return placementRepository.findOne(id); } /** * Delete the placement by id. * * @param id * the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete Placement : {}", id); placementRepository.delete(id); } /** * Archive the "id" placement. * * @param id * the id of the entity */ @Override public boolean archive(Long id) { log.debug("Request to archive Placement : {}", id); final Placement placement = findOne(id); if (placement != null) { placement.setArchived(true); return true; } return false; } @Override @Transactional(rollbackFor = { Exception.class }) public Placement goInMission(Long id, Integer tjmFinal) { final Placement placement = findOne(id); if (placement != null) { placement.setEtat(Statut.GO); placement.setTjmFinal(tjmFinal); if (placement.getConsultant() != null && placement.getConsultant().getId() != null) { final Consultant consultant = consultantService.findOne(placement.getConsultant().getId()); if (consultant != null) { consultant.setInMission(true); consultant.setDateDebutInterco(null); archiveOtherPlacements(placement.getId(), consultant.getId()); } } } return placement; } @Override public List<Placement> findAllPlacementsForConsultant(Long consultantId) { return placementRepository.findByConsultant_Id(consultantId); } private void archiveOtherPlacements(Long placementId, Long consultantId) { placementRepository.archiveOtherPlacements(placementId, consultantId); } }
true
a80b9564fdfbb23100f4f19561ae23039b701722
Java
Sarugithub/JavaProgramming
/JavaApplication2/src/PracticeExam/PracticeArrayList.java
UTF-8
636
2.828125
3
[]
no_license
/* * 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 PracticeExam; /** * * @author SACHIN AGRAWAL */ import java.util.*; public class PracticeArrayList { public static void main (String args[]) { ArrayList <String> list = new ArrayList <String>(); // Creating arraylist list.add("Ravi"); list.add("Saru"); list.add("Reha"); Iterator itr = list.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } }
true
bcb0b2c3ec4aaab37f84692b2da41af1d3a8631d
Java
merx3/DiplomaThesys
/tu.mmarinov.agileassist/src/tu/mmarinov/agileassist/internal/AgileTemplate.java
UTF-8
6,534
2.8125
3
[]
no_license
package tu.mmarinov.agileassist.internal; import java.util.ArrayList; import java.util.Arrays; import tu.mmarinov.agileassist.templatehandler.TemplateLoader; public class AgileTemplate{ private String name; private String description; private String[] defaultValues; private String proposalName; private String proposalDescription; public AgileTemplate(String name, String description, String[] defaultValues, String proposalName, String proposalDescription){ this.setName(name); this.setDescription(description); this.setDefaultValues(defaultValues); this.setProposalName(proposalName); this.setProposalDescription(proposalDescription); } @Override public boolean equals(Object t) { // TODO Auto-generated method stub if (t instanceof AgileTemplate) { AgileTemplate compareTo = (AgileTemplate)t; return compareTo.getName().equals(this.name); } return super.equals(t); } public AgileTemplate applyInput(String input){ int iterations = Integer.parseInt(input.substring(this.getName().length(), input.length())); AgileTemplate iteratedTemplate = replaceInsertSegments(iterations); AgileTemplate finalTemplate = iteratedTemplate.removeSegments(); finalTemplate.setName(input); return finalTemplate; } public AgileTemplate replaceInsertSegments(int iterations) { StringBuilder desc = new StringBuilder(this.getDescription()); ArrayList<String> defaults = new ArrayList<String>(Arrays.asList(this.getDefaultValues())); for (int i = 1; i < iterations; i++) { int startReplace = desc.indexOf("$[#"); while (startReplace >= 0) { int endReplace = desc.indexOf("]", startReplace); String whitespacesBeforeSegment = getWhitespacesBeforeSegment(desc, startReplace); String replaceTemplateName = desc.substring(startReplace + 3, endReplace); AgileTemplate replaceTemplate = TemplateLoader.getTemplate(replaceTemplateName); // add whitespaces after each new line String replacementDescription = replaceTemplate.getDescription().replaceAll("\n", "\n" + whitespacesBeforeSegment); desc = desc.replace(startReplace, endReplace + 1, replacementDescription); // add the defaults of the inserted template int segmentsBeforeCount = getDefaultSegmentsCount(desc, startReplace); String[] defaultsToInsert = replaceTemplate.getDefaultValues(); defaults.remove(segmentsBeforeCount); for (int j = 0; j < defaultsToInsert.length; j++) { defaults.add(segmentsBeforeCount + j, defaultsToInsert[j]); } startReplace = desc.indexOf("$[#", startReplace + replacementDescription.length()); } } //after replacement, all left named insertion segments are replaced with anonymous int startReplace = desc.indexOf("$[#"); while (startReplace >= 0) { int endReplace = desc.indexOf("]", startReplace); desc = desc.replace(startReplace, endReplace + 1, "$[]"); startReplace = desc.indexOf("$[#"); } return new AgileTemplate(this.getName(), desc.toString(), defaults.toArray(new String[defaults.size()]), this.getProposalName(), this.getProposalDescription()); } private int getDefaultSegmentsCount(StringBuilder sb, int endPos){ int startSearch = 0; int count = 0; while(startSearch >= 0){ int segIndex = sb.indexOf("$[", startSearch); if (segIndex >= endPos || segIndex < 0) { return count; } char nextChar = sb.charAt(segIndex + 2); if (nextChar == ']' || nextChar == '#') { count++; } startSearch = segIndex + 1; } return count; } public AgileTemplate removeSegments() { /* Segments (strings) to replace with default values * $[] * $[some-text] */ StringBuilder desc = new StringBuilder(this.getDescription()); String[] defaults = this.getDefaultValues(); int defaultValueIndex = 0; int segmentStart = desc.indexOf("$["); while (segmentStart >= 0) { int segmentEnd = desc.indexOf("]", segmentStart); if (segmentEnd - segmentStart == 2) { desc.delete(segmentStart, segmentEnd+1); desc.insert(segmentStart, defaults[defaultValueIndex]); defaultValueIndex++; } else{ desc.delete(segmentStart, segmentStart + 2); desc.insert(segmentStart, "${"); desc.delete(segmentEnd, segmentEnd + 1); desc.insert(segmentEnd, "}"); } segmentStart = desc.indexOf("$["); } return new AgileTemplate(this.getName(), desc.toString(), new String[0], this.getProposalName(), this.getProposalDescription()); } private String getWhitespacesBeforeSegment(StringBuilder desc, int segmentPos) { int whitespacesCount = 0; int currentPos = segmentPos - 1; while (currentPos >= 0 && desc.charAt(currentPos) == ' ') { whitespacesCount++; currentPos--; } char[] chars = new char[whitespacesCount]; Arrays.fill(chars, ' '); String result = new String(chars); return result; } // getters and setters public String getName() { return name; } public void setName(String name) { String nameWithoutSpaces = name.replace(" ", ""); boolean isNameValid = name.length() > 0 && nameWithoutSpaces.length() == name.length(); if (isNameValid) { this.name = name; } else{ throw new IllegalArgumentException("Template name must be without spaces and not empty."); } } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String[] getDefaultValues() { return defaultValues; } public void setDefaultValues(String[] defaultValues) { StringBuilder templateDescription = new StringBuilder(this.description); if (getDefaultSegmentsCount(templateDescription, this.description.length()) != defaultValues.length) { throw new IllegalArgumentException("Template default values must be the same number as the default segments in the template's description. Only segments with $[] and $[#some_name] count as default."); } this.defaultValues = defaultValues; } public String getProposalName() { return proposalName; } public void setProposalName(String proposalName) { String nameWithoutSpaces = proposalName.replace(" ", ""); if (proposalName.length() > 0 && nameWithoutSpaces.length() == proposalName.length()) { this.proposalName = proposalName; } else{ throw new IllegalArgumentException("Proposal name must be without spaces and not empty."); } } public String getProposalDescription() { return proposalDescription; } public void setProposalDescription(String proposalDescription) { this.proposalDescription = proposalDescription; } }
true
70cdc78301837554d4aac88d23ccade21af6befa
Java
fuyuanhehe/knowledgebase
/knowledgebase/knowledgebase/src/main/java/com/hg/knowledgebase/module/sys/mapper/IUserMapper.java
UTF-8
7,244
2.140625
2
[]
no_license
package com.hg.knowledgebase.module.sys.mapper; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.hg.knowledgebase.module.sys.entity.User; import com.hg.knowledgebase.module.sys.entity.VO.UserVO; /** * * @Description: 用户数据层 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:38:26 * @Version: 1.0.0 */ public interface IUserMapper { /** * * @Description: 插入用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:23:09 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:23:09 * @UpdateRemark: 修改内容 * @param user * @return * @throws SQLException SQL错误时候出现的异常 * boolean * @Version: 1.0.0 */ int insertUser(User user) throws SQLException; /** * * @Description: 插入批量用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午5:41:15 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午5:41:15 * @UpdateRemark: 修改内容 * @param users * @return * @throws SQLException SQL错误时候出现的异常 * int * @Version: 1.0.0 */ int insertBatchUser(@Param("users") List<UserVO> users) throws SQLException; /** * * @Description: 根据id删除用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:24:56 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:24:56 * @UpdateRemark: 修改内容 * @param uuid * @return * @throws SQLException SQL错误时候出现的异常 * boolean * @Version: 1.0.0 */ int deleteUserById(@Param("id") String id) throws SQLException; /** * * @Description: 删除批量用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午5:41:51 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午5:41:51 * @UpdateRemark: 修改内容 * @param uuid * @return * @throws SQLException SQL错误时候出现的异常 * int * @Version: 1.0.0 */ int deleteBatchUserById(@Param("ids") List<String> ids) throws SQLException; /** * * @Description: 修改用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:26:15 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:26:15 * @UpdateRemark: 修改内容 * @param user * @return * @throws SQLException SQL错误时候出现的异常 * boolean * @Version: 1.0.0 */ int updateUser(User user) throws SQLException; /** * * @Description: 根据id查询用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:28:37 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:28:37 * @UpdateRemark: 修改内容 * @param uuid * @return * @throws SQLException SQL错误时候出现的异常 * User * @Version: 1.0.0 */ UserVO selectUserById(@Param("id") String id) throws SQLException; /** * * @Description: 根据登录名查询用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:28:37 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:28:37 * @UpdateRemark: 修改内容 * @param uuid * @return * @throws SQLException SQL错误时候出现的异常 * User * @Version: 1.0.0 */ UserVO selectUserByName(@Param("name") String name) throws SQLException; /** * * @Description: 修改用户密码 * @Author: 况克冬 * @CreateDate: 2020年3月6日下午9:12:31 * @UpdateUser: 况克冬 * @UpdateDate: 2020年3月6日下午9:12:31 * @UpdateRemark: 修改内容 * @param ids * @param password * @return * @throws SQLException SQL错误时候出现的异常 * int * @Version: 1.0.0 */ int updateUserPwd(@Param("ids") List<String> ids, @Param("password") String password) throws SQLException; /** * * @Description: 根据手机或者邮件修改密码 * @Author: 况克冬 * @CreateDate: 2020年4月24日下午4:15:35 * @UpdateUser: 况克冬 * @UpdateDate: 2020年4月24日下午4:15:35 * @UpdateRemark: 修改内容 * @param phone * @param mail * @param password * @return int * @Version: 1.0.0 */ int updateUserPasswordByPhoneOrMail(@Param("phone") String phone, @Param("mail") String mail, @Param("password") String password); /** * * @Description: 根据用户名和密码查询用户 请使用selectUserByName代替 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:42:33 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:42:33 * @UpdateRemark: 修改内容 * @param name * @param pwd * @return * @throws SQLException SQL错误时候出现的异常 * User * @Version: 1.0.0 */ @Deprecated UserVO selectUserByNameAndPwd(@Param("name") String name, @Param("password") String pwd) throws SQLException; /** * * @Description: 查询所有用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:32:07 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:32:07 * @UpdateRemark: 修改内容 * @param user * @return * @throws SQLException SQL错误时候出现的异常 * List<User> * @Version: 1.0.0 */ List<UserVO> selectUserList(User user) throws SQLException; /** * * @Description: 查询所有基础用户 * @Author: 况克冬 * @CreateDate: 2020年2月26日下午4:32:07 * @UpdateUser: 况克冬 * @UpdateDate: 2020年2月26日下午4:32:07 * @UpdateRemark: 修改内容 * @param user * @return * @throws SQLException SQL错误时候出现的异常 * List<User> * @Version: 1.0.0 */ List<User> selectBaseUserList(UserVO userVO) throws SQLException; /** * * @Description: 查询用户总数 * @Author: 况克冬 * @CreateDate: 2020年3月3日下午1:56:24 * @UpdateUser: 况克冬 * @UpdateDate: 2020年3月3日下午1:56:24 * @UpdateRemark: 修改内容 * @param user * @return * @throws SQLException SQL错误时候出现的异常 * int * @Version: 1.0.0 */ int selectUserCount(User user) throws SQLException; /** * * @Description: 获取性别分组 * @Author: 况克冬 * @CreateDate: 2020年3月3日下午2:38:59 * @UpdateUser: 况克冬 * @UpdateDate: 2020年3月3日下午2:38:59 * @UpdateRemark: 修改内容 * @param user * @return * @throws Exception * Map<String,Integer> key:性别名称 value:人数 * @Version: 1.0.0 */ Map<String, Integer> selectSexGroup(User user) throws SQLException; }
true
02ce69588ab1c5643fc91cad510c8108e2c82842
Java
pritesh25/ScreenShot
/app/src/main/java/com/example/user/screenshot/MainActivity.java
UTF-8
2,316
2.328125
2
[]
no_license
package com.example.user.screenshot; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class MainActivity extends AppCompatActivity { private LinearLayout main,main1; private ImageView imageView; private Bitmap b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main = findViewById(R.id.main); main1 = findViewById(R.id.main1); imageView = findViewById(R.id.imageView); Button btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { b = Screenshot.takescreenshot(main); imageView.setImageBitmap(b); main1.setBackgroundColor(Color.parseColor("#999999")); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { storeScreenshot(b,"zSample.jpg"); } }); } public void storeScreenshot(Bitmap bitmap, String filename) { String path = Environment.getExternalStorageDirectory().toString() + "/" + filename; OutputStream out = null; File imageFile = new File(path); try { out = new FileOutputStream(imageFile); // choose JPEG format bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); } catch (FileNotFoundException e) { // manage exception ... } catch (IOException e) { // manage exception ... } finally { try { if (out != null) { out.close(); } } catch (Exception exc) { } } } }
true
5178d34df64df8c4dee13d5f57741a9214ef0e0e
Java
philemmons/Codewars2020
/Bundesliga 1. Spieltag - First Match Day/BundesligaTests.java
UTF-8
5,463
2.5
2
[]
no_license
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class BundesligaTests { @Test public void fridayEveningTest() { String[] results = new String[] { "6:0 FC Bayern Muenchen - Werder Bremen", "-:- Eintracht Frankfurt - Schalke 04", "-:- FC Augsburg - VfL Wolfsburg", "-:- Hamburger SV - FC Ingolstadt", "-:- 1. FC Koeln - SV Darmstadt", "-:- Borussia Dortmund - FSV Mainz 05", "-:- Borussia Moenchengladbach - Bayer Leverkusen", "-:- Hertha BSC Berlin - SC Freiburg", "-:- TSG 1899 Hoffenheim - RasenBall Leipzig" }; String expectedTable = " 1. FC Bayern Muenchen 1 1 0 0 6:0 3\n" + " 2. 1. FC Koeln 0 0 0 0 0:0 0\n" + " 2. Bayer Leverkusen 0 0 0 0 0:0 0\n" + " 2. Borussia Dortmund 0 0 0 0 0:0 0\n" + " 2. Borussia Moenchengladbach 0 0 0 0 0:0 0\n" + " 2. Eintracht Frankfurt 0 0 0 0 0:0 0\n" + " 2. FC Augsburg 0 0 0 0 0:0 0\n" + " 2. FC Ingolstadt 0 0 0 0 0:0 0\n" + " 2. FSV Mainz 05 0 0 0 0 0:0 0\n" + " 2. Hamburger SV 0 0 0 0 0:0 0\n" + " 2. Hertha BSC Berlin 0 0 0 0 0:0 0\n" + " 2. RasenBall Leipzig 0 0 0 0 0:0 0\n" + " 2. SC Freiburg 0 0 0 0 0:0 0\n" + " 2. Schalke 04 0 0 0 0 0:0 0\n" + " 2. SV Darmstadt 0 0 0 0 0:0 0\n" + " 2. TSG 1899 Hoffenheim 0 0 0 0 0:0 0\n" + " 2. VfL Wolfsburg 0 0 0 0 0:0 0\n" + "18. Werder Bremen 1 0 0 1 0:6 0"; String actualTable = Bundesliga.table(results); assertEquals(expectedTable, actualTable); } @Test public void saturdayEveningTest() { String[] results = new String[] { "6:0 FC Bayern Muenchen - Werder Bremen", "1:0 Eintracht Frankfurt - Schalke 04", "0:2 FC Augsburg - VfL Wolfsburg", "1:1 Hamburger SV - FC Ingolstadt", "2:0 1. FC Koeln - SV Darmstadt", "2:1 Borussia Dortmund - FSV Mainz 05", "2:1 Borussia Moenchengladbach - Bayer Leverkusen", "-:- Hertha BSC Berlin - SC Freiburg", "-:- TSG 1899 Hoffenheim - RasenBall Leipzig" }; String expectedTable = " 1. FC Bayern Muenchen 1 1 0 0 6:0 3\n" + " 2. 1. FC Koeln 1 1 0 0 2:0 3\n" + " 2. VfL Wolfsburg 1 1 0 0 2:0 3\n" + " 4. Borussia Dortmund 1 1 0 0 2:1 3\n" + " 4. Borussia Moenchengladbach 1 1 0 0 2:1 3\n" + " 6. Eintracht Frankfurt 1 1 0 0 1:0 3\n" + " 7. FC Ingolstadt 1 0 1 0 1:1 1\n" + " 7. Hamburger SV 1 0 1 0 1:1 1\n" + " 9. Hertha BSC Berlin 0 0 0 0 0:0 0\n" + " 9. RasenBall Leipzig 0 0 0 0 0:0 0\n" + " 9. SC Freiburg 0 0 0 0 0:0 0\n" + " 9. TSG 1899 Hoffenheim 0 0 0 0 0:0 0\n" + "13. Bayer Leverkusen 1 0 0 1 1:2 0\n" + "13. FSV Mainz 05 1 0 0 1 1:2 0\n" + "15. Schalke 04 1 0 0 1 0:1 0\n" + "16. FC Augsburg 1 0 0 1 0:2 0\n" + "16. SV Darmstadt 1 0 0 1 0:2 0\n" + "18. Werder Bremen 1 0 0 1 0:6 0"; String actualTable = Bundesliga.table(results); assertEquals(expectedTable, actualTable); } @Test public void sundayEveningTest() { String[] results = new String[] { "6:0 FC Bayern Muenchen - Werder Bremen", "1:0 Eintracht Frankfurt - Schalke 04", "0:2 FC Augsburg - VfL Wolfsburg", "1:1 Hamburger SV - FC Ingolstadt", "2:0 1. FC Koeln - SV Darmstadt", "2:1 Borussia Dortmund - FSV Mainz 05", "2:1 Borussia Moenchengladbach - Bayer Leverkusen", "2:1 Hertha BSC Berlin - SC Freiburg", "2:2 TSG 1899 Hoffenheim - RasenBall Leipzig" }; String expectedTable = " 1. FC Bayern Muenchen 1 1 0 0 6:0 3\n" + " 2. 1. FC Koeln 1 1 0 0 2:0 3\n" + " 2. VfL Wolfsburg 1 1 0 0 2:0 3\n" + " 4. Borussia Dortmund 1 1 0 0 2:1 3\n" + " 4. Borussia Moenchengladbach 1 1 0 0 2:1 3\n" + " 4. Hertha BSC Berlin 1 1 0 0 2:1 3\n" + " 7. Eintracht Frankfurt 1 1 0 0 1:0 3\n" + " 8. RasenBall Leipzig 1 0 1 0 2:2 1\n" + " 8. TSG 1899 Hoffenheim 1 0 1 0 2:2 1\n" + "10. FC Ingolstadt 1 0 1 0 1:1 1\n" + "10. Hamburger SV 1 0 1 0 1:1 1\n" + "12. Bayer Leverkusen 1 0 0 1 1:2 0\n" + "12. FSV Mainz 05 1 0 0 1 1:2 0\n" + "12. SC Freiburg 1 0 0 1 1:2 0\n" + "15. Schalke 04 1 0 0 1 0:1 0\n" + "16. FC Augsburg 1 0 0 1 0:2 0\n" + "16. SV Darmstadt 1 0 0 1 0:2 0\n" + "18. Werder Bremen 1 0 0 1 0:6 0"; String actualTable = Bundesliga.table(results); assertEquals(expectedTable, actualTable); } }
true
cc9173bc7405e6924af6c3523b9505976e92365a
Java
SEBHN/spring-reactive-mediamanagement
/src/main/java/de/hhn/mvs/model/FolderElements.java
UTF-8
1,448
2.640625
3
[ "MIT" ]
permissive
package de.hhn.mvs.model; import java.util.List; import java.util.Objects; public class FolderElements { private List<Subfolder> subfolders; private List<Media> media; public FolderElements() { // for jackson } public FolderElements(List<Subfolder> subfolders, List<Media> media) { this.subfolders = subfolders; this.media = media; } public List<Subfolder> getSubfolders() { return subfolders; } public void setSubfolders(List<Subfolder> subfolders) { this.subfolders = subfolders; } public List<Media> getMedia() { return media; } public void setMedia(List<Media> media) { this.media = media; } @Override public String toString() { return "Subfolders: " + subfolders.toString() + "\n" + "Media: " + media.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FolderElements externalFolderElements = (FolderElements) o; List<Subfolder> subFolders = externalFolderElements.getSubfolders(); List<Media> media = externalFolderElements.getMedia(); return Objects.equals(this.media, media) && Objects.equals(this.subfolders, subFolders); } @Override public int hashCode() { return Objects.hash(media, subfolders); } }
true
eee245e23170d8edb9b43675be61d43670cf16a9
Java
MarsITE/itAcademy-advertisement
/src/main/java/academy/softserve/configuration/ConnectionConfig.java
UTF-8
1,354
2.609375
3
[]
no_license
package academy.softserve.configuration; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.postgresql.Driver; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionConfig { private final Logger logger = LogManager.getLogger(ConnectionConfig.class); private String path; public ConnectionConfig(String path) { this.path = path; } Properties properties; private void loadProperties(){ properties = new Properties(); ClassLoader classLoader = getClass().getClassLoader(); try (InputStream input = classLoader.getResourceAsStream(path)) { if (input != null) { properties.load(input); } } catch (IOException e) { logger.error(e.getMessage()); } } public Connection getConnection() throws SQLException { DriverManager.registerDriver(new Driver()); loadProperties(); String url = properties.getProperty("JDBC_URL"); String userName = properties.getProperty("JDBC_USER"); String password = properties.getProperty("JDBC_PASSWORD"); return DriverManager.getConnection(url, userName, password); } }
true
522b45d357be6742cad7ac1805c7428b82912210
Java
jjurm/twbot
/src/main/java/com/jjurm/twbot/control/SocketListener.java
UTF-8
3,708
2.953125
3
[]
no_license
package com.jjurm.twbot.control; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.jjurm.twbot.system.config.Config; /** * Class for accepting connections and communicating through sockets. * * @author JJurM */ public class SocketListener implements Runnable { private static final Logger LOG = LogManager.getLogger(); private boolean running; /** * <tt>Commander</tt> to pass input to. */ Commander commander; ServerSocket serverSocket; Thread serverSocketThread; List<OutputStream> outputs = new ArrayList<OutputStream>(); /** * Basic constructor * * @param commander commander to pass input to */ public SocketListener(Commander commander) { this.commander = commander; serverSocketThread = new Thread(this); } /** * Starts the thread. */ public synchronized void start() { if (running) return; running = true; serverSocketThread.start(); } public synchronized void stop() { if (!running) return; running = false; try { if (serverSocket != null) serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } public void writeToAll(byte[] data) throws IOException { for (OutputStream output : outputs) { output.write(data); output.flush(); } } @Override public void run() { Thread.currentThread().setName("ServerSocketThread"); try { serverSocket = new ServerSocket(Config.socketPort, 3, null); } catch (BindException e) { LOG.error("Port " + Config.socketPort + "is already in use, terminating SocketListener"); return; } catch (IOException e) { e.printStackTrace(); } try { while (running) { @SuppressWarnings("resource") Socket socket = serverSocket.accept(); SocketThread thread = new SocketThread(commander, this, socket); thread.start(); } } catch (IOException e) { // socket closed } } /** * Each socket will be processed in separate thread. * * @author JJurM */ static class SocketThread extends Thread { /** * Index for naming threads */ static AtomicInteger atomicInteger = new AtomicInteger(1); Commander commander; SocketListener socketListener; Socket socket; /** * Index of current socket */ int socketIndex; /** * Basic constructor * * @param socket */ public SocketThread(Commander commander, SocketListener socketListener, Socket socket) { this.commander = commander; this.socketListener = socketListener; this.socket = socket; socketIndex = atomicInteger.getAndIncrement(); } @Override public void run() { setName("SocketThread-" + socketIndex); try (BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os, true)) { socketListener.outputs.add(os); LOG.info("Accepted socket #" + socketIndex); loop: while (true) { try { commander.process(br, pw); } catch (StreamCloseRequest scr) { LOG.info("Closed socket #" + socketIndex); socketListener.outputs.remove(os); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } break loop; } } } catch (IOException e) { e.printStackTrace(); } } } }
true
2d29d241d9f7a0022016e8bb694fcbf093a7e224
Java
qiqiwill/springboot
/src/main/java/com/test/crawler/dao/OverseasHotelMapper.java
UTF-8
4,257
2.03125
2
[]
no_license
package com.test.crawler.dao; import com.test.crawler.entity.*; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @Author: LIUQI * @Date: 2019/4/29 16:38 * @Description: todo */ @Repository @Mapper public interface OverseasHotelMapper { @Insert("<script> " + " insert into hotel(hotel_id, cn_name,en_name,diamond,label,lng,lat,cn_state,cn_country,cn_city,cn_district,cn_address," + " en_state,en_country,en_city,en_district,en_address,description,facilities,childpolicy,ordernum) values " + " <foreach collection='result' item='item' separator=','> " + " (#{item.hotelId}, #{item.cnName}, #{item.enName}, #{item.diamond},#{item.label}, #{item.lng}, #{item.lat}, #{item.cnState}, #{item.cnCountry}, #{item.cnCity}, #{item.cnDistrict}, #{item.cnAddress}," + " #{item.enState}, #{item.enCountry}, #{item.enCity}, #{item.enDistrict}, #{item.enAddress},#{item.description}, #{item.facilities}, #{item.childPolicy}, #{item.orderNum})" + " </foreach> " + "</script>") @Transactional void insert(@Param(value = "result") List<Hotel> result); @Transactional @Insert("<script> " + "insert into hotel_image(hotel_id, image_path) values " + "<foreach collection='result' item='item' separator=','> " + " (#{item.hotelId}, #{item.imagePath})" + "</foreach>" + "</script>") void insertImages(@Param(value = "result") List<HotelImage> result); @Transactional @Insert("<script> " + " insert into hotel_basic_room(basic_room_id, hotel_id, cn_name,en_name, room_area, addBed, facilities) values " + " <foreach collection='result' item='item' separator=','> " + " (#{item.basicRoomId}, #{item.hotelId}, #{item.cnName}, #{item.enName}, #{item.roomArea}, #{item.addBed}, #{item.facilities})" + " </foreach> " + "</script>") void insertBasicRoom(@Param(value = "result") List<HotelBasicRoom> result); @Transactional @Insert("<script> " + " insert into hotel_sub_room(room_id, hotel_id, basic_room_id, cn_name, en_name, bed_type, max_person) values " + " <foreach collection='result' item='item' separator=','> " + " (#{item.roomId}, #{item.hotelId}, #{item.basicRoomId}, #{item.cnName}, #{item.enName}, #{item.bedType}, #{item.maxPerson})" + " </foreach> " + "</script>") void insertSubRoom(@Param(value = "result") List<HotelSubRoom> result); @Transactional @Insert("<script> " + "insert into hotel_basic_room_image(hotel_basic_room_id, image_path, hotel_id) values " + "<foreach collection='result' item='item' separator=','> " + " (#{item.basicRoomId}, #{item.imagePath}, #{item.hotelId})" + "</foreach>" + "</script>") void insertRoomImages(@Param(value = "result") List<HotelRoomImage> result); //根据酒店id删除 酒店 @Delete("delete from hotel where hotel_id = #{id}") void deleteHotel(String id); @Delete("delete from hotel_image where hotel_id = #{id}") void deleteHotelImage(String id); @Delete("delete from hotel_basic_room where hotel_id = #{id}") void deleteBasicRoom(String id); @Delete("delete from hotel_sub_room where hotel_id = #{id}") void deleteSubRoom(String id); @Delete("delete from hotel_basic_room_image where hotel_id = #{id}") void deleteBasicRoomImage(String id); //根据酒店id删除 酒店 //;truncate table hotel_image;truncate table hotel_basic_room;truncate table hotel_sub_room;truncate table hotel_basic_room_image; @Update("truncate table hotel") void truncateHotel(); @Update("truncate table hotel_image") void truncateHotelImage(); @Update("truncate table hotel_basic_room") void truncateBasicRoom(); @Update("truncate table hotel_sub_room") void truncateSubRoom(); @Update("truncate table hotel_basic_room_image") void truncateBasicRoomImage(); }
true
5fb7b875f3c978abeabc126791fe296574c2e4c6
Java
P79N6A/speedx
/reverse_engineered/sources/com/alibaba/fastjson/serializer/AtomicIntegerSerializer.java
UTF-8
502
2.28125
2
[]
no_license
package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.Type; import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerSerializer implements ObjectSerializer { public static final AtomicIntegerSerializer instance = new AtomicIntegerSerializer(); public void write(JSONSerializer jSONSerializer, Object obj, Object obj2, Type type) throws IOException { jSONSerializer.getWriter().writeInt(((AtomicInteger) obj).get()); } }
true
8fe1da19ca0fa8c316875441d0ce12a6cfa795e7
Java
rakesh13/Assignments
/JavaAssignment1_B_3_2/src/main/java/com/stackroute/datamunger/query/QueryParser.java
UTF-8
2,152
2.671875
3
[]
no_license
package com.stackroute.datamunger.query; import java.util.ArrayList; import java.util.List; import com.stackroute.datamunger.restrictions.Restriction; public class QueryParser { private List<Restriction> restrictionList=new ArrayList<>(); private String whereCondition; List<String> logicalOperators= new ArrayList<>(); public List<Restriction> getRestrictionList() { return restrictionList; } public void setRestrictionList(List<Restriction> restrictionList) { this.restrictionList = restrictionList; } public List<String> getLogicalOperators() { return logicalOperators; } public void setLogicalOperators(List<String> logicalOperators) { this.logicalOperators = logicalOperators; } public QueryParser parseQuery(String query) { whereCondition=query.split("where")[1]; getRelationalAndLogicalOperators(whereCondition); return this; } private void getRelationalAndLogicalOperators(String whereCondition) { String relationalOperators[]=whereCondition.split("and|or"); for(String relationCondition:relationalOperators) { Restriction restriction = new Restriction(); relationCondition=relationCondition.trim(); String columnAndValue[] = relationCondition.split("([!|=|>|<])+"); String columnName=columnAndValue[0].trim(); String columnValue =columnAndValue[1].trim(); int startIndex = relationCondition.indexOf(columnName) + columnName.length(); int endIndex = relationCondition.indexOf(columnValue); String operator = relationCondition.substring(startIndex, endIndex).trim(); restriction.setPropertyName(columnName); restriction.setPropertyValue(columnValue); restriction.setConditionalOperator(operator); restrictionList.add(restriction); } if(relationalOperators.length>1) logicalOperatorList(whereCondition); } private void logicalOperatorList(String whereCondition) { String checkForLogicalOperators[]=whereCondition.split("\\s+"); for(String logicalOperator : checkForLogicalOperators) { if(logicalOperator.trim().equals("and") || logicalOperator.trim().equals("or")) { logicalOperators.add(logicalOperator); } } } }
true
4c43872a38ff62536408b0507f0b2eee22d1910d
Java
kengou233/task
/src/projectDemo/Product.java
GB18030
910
2.984375
3
[]
no_license
package projectDemo; /** * @author kengou * ÷װ 򵥹 */ public class Product { private String name; private double price; // ۸ private String description; // private String services[]; // public Product() {} public Product(String name,String desString) { setName(name); setDescription(desString); } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String[] getServices() { return services; } public void setServices(String[] services) { this.services = services; } }
true
77758877f20b210d4f8e2b003a44b5368490a6ee
Java
stuckless/sagetv-bmtweb
/src/org/jdna/bmt/web/client/media/GWTPersistenceOptions.java
UTF-8
663
1.859375
2
[]
no_license
package org.jdna.bmt.web.client.media; import java.io.Serializable; public class GWTPersistenceOptions implements Serializable { private static final long serialVersionUID = 1L; private boolean importAsTV = false; private boolean useTitleMasks = true; public GWTPersistenceOptions() { } public boolean isImportAsTV() { return importAsTV; } public void setImportAsTV(boolean importAsTV) { this.importAsTV = importAsTV; } public boolean isUseTitleMasks() { return useTitleMasks; } public void setUseTitleMasks(boolean useTitleMasks) { this.useTitleMasks = useTitleMasks; } }
true
2d53264c89ce248048d9e8b9dfc088534a38f696
Java
treytamaki/drexel_cs645
/project4/pp2/mitm/MITMAdminServer.java
UTF-8
3,029
3
3
[]
no_license
/** * CSE 490K Project 2 */ package mitm; import java.net.*; import java.io.*; import java.util.*; import java.util.regex.*; import javax.naming.AuthenticationException; import java.security.GeneralSecurityException; // You need to add code to do the following // 1) use SSL sockets instead of the plain sockets provided // 2) check user authentication // 3) perform the given administration command class MITMAdminServer implements Runnable { private ServerSocket m_serverSocket; private Socket m_socket = null; private HTTPSProxyEngine m_engine; private PrintWriter m_out; public MITMAdminServer( String localHost, int adminPort, HTTPSProxyEngine engine ) throws IOException, GeneralSecurityException { MITMSocketFactory socketFactory = new MITMSSLSocketFactory(); m_serverSocket = socketFactory.createServerSocket( localHost, adminPort, 0 ); m_engine = engine; } public void run() { System.out.println("Admin server initialized, listening on port " + m_serverSocket.getLocalPort()); while( true ) { try { m_socket = m_serverSocket.accept(); m_out = new PrintWriter(m_socket.getOutputStream(),true); byte[] buffer = new byte[40960]; Pattern userPwdPattern = Pattern.compile("username:(\\S+)\\s+password:(\\S+)\\s+command:(\\S+)\\sCN:(\\S*)\\s"); BufferedInputStream in = new BufferedInputStream(m_socket.getInputStream(), buffer.length); // Read a buffer full. int bytesRead = in.read(buffer); String line = bytesRead > 0 ? new String(buffer, 0, bytesRead) : ""; Matcher userPwdMatcher = userPwdPattern.matcher(line); // parse username and pwd if (userPwdMatcher.find()) { String userName = userPwdMatcher.group(1); String password = userPwdMatcher.group(2); System.out.println("Try to authenticate as: "+userName+" with password: "+password); IPasswordManager passwordManager = new EncryptedFileBasedPasswordManager(); // authenticate // if authenticated, do the command boolean authenticated = passwordManager.authenticate(userName,password); if( authenticated ) { String command = userPwdMatcher.group(3); String commonName = userPwdMatcher.group(4); doCommand( command, m_out ); } else { throw new AuthenticationException("Couldn't authenticate user: "+userName); } } } catch( InterruptedIOException e ) { } catch( Exception e ) { e.printStackTrace(); } } } // TODO implement the commands private void doCommand( String cmd, PrintWriter out ) throws IOException { if (cmd.contains("shutdown")){ m_out.println("Shutdown command received"); m_engine.shutdown(); } else if (cmd.contains("stats")){ String statInfo = "Statistics query on number of proxied SSL connections returns: "+m_engine.getSSLConnectionCount(); out.println(statInfo); } m_out.close(); m_socket.close(); } }
true
e385f0624e6770bb54d2fc2ef382fa2e8fb86a24
Java
ADSProgramacaoADS/POOA
/BankList.java
UTF-8
3,675
3.328125
3
[]
no_license
package flist; import java.util.function.Function; class Operations { public final int balance; public final int value; public Operations (int balance, int value) { this.balance = balance; this.value = value; } public String toString(){ return "(" + balance + "," + value + ")"; } } class Account{ public final String name; public final int id; public final FList<Operations> history; private Account(String name, int id) { this.name = name; this.id = id; history = FList.<Operations>empty(); } private Account(String name, int id, FList<Operations> history) { this.name = name; this.id = id; this.history = history; } public Account movement(int value) { int bal = history.isEmpty() ? 0 : history.head().balance; Operations op = new Operations(bal + value,value); FList<Operations> list = FList.<Operations>cons(op, history); return new Account(name, id, list); } public String toString() { return "( "+ name + ", " + id +")"+ history +"\n"; } private FList<Integer> valDeps(FList<Operations> deps){ if(deps.isEmpty()) return FList.<Integer>empty(); FList<Integer> rest = valDeps(deps.tail()); Integer val = deps.head().value; return FList.<Integer>cons(val, rest); } public FList<Integer> valDeps(){ return deposits().map(op -> op.value); } public FList<Operations> deposits(){ return history.filter((Operations op)-> op.value > 0); } public FList<Operations> withdraws(){ return history.filter((Operations op)-> op.value < 0); } public FList<Operations> higherDeps(int val){ return history.filter((Operations op)-> op.value > val); } private int totalDep(FList<Operations> xs) { if(xs.isEmpty()) { return 0; } int sumRest = totalDep(xs.tail()); if(xs.head().value > 0) { return xs.head().value + sumRest; } return sumRest; } public int totalDep() { return valDeps().foldRight(0, (x, y) -> x + y); } public int maxDep(){ Flist<Interger> deps = valDeps(); if(deps.isEmpty()) throw new NoSuchAttributeException(); return deps.foldLeft(deps.head(), (x,y) -> x>=y ? x:y); } public static Account newAccount(String name) { return new Account(name); } } public class Bank{ public final FList<Account> accounts; private Bank(){accounts = FList.<Account>empty();} private Bank(FList<Account> accounts){ this.accounts = accounts}; public Bank newAccount (String name){ Account acc = Account.newAccount(name, accounts.size +1); return new Bank(FList.<Account>cons(acc, accounts)); } public Account getAccount(int id){ FList<Account> list = accounts.find(acc -> acc.id== id); if(list.isEmpty()) throw new NoSuchElementException(); return list.head(); } publlic Account getAccount(String name){ FList<Account> list = accounts.find(acc -> name.equals(acc.name)); if(list.isEmpty()) throw new NoSuchElementException(); return list.head(); } public static Bank newBank() {return new Bank();} public static void main(String[] args) { Bank b = newBank().newAccount ("Jose") .newAccount ("Maria") .newAccount ("Adriana") .newAccount ("Joao"); /*Account acc = Account.newAccount("Franklin") .movement(80) .movement(90) .movement(10) .movement(50) .movement(-4) .movement(70) .movement(-20); System.out.println(acc); System.out.println(acc.deposits()); System.out.println(acc.valDeps().sort((x,y) -> x.compareTo(y))); System.out.println(acc.totalDep()); System.out.println(acc.maxDep());*/ } }
true
dfed91fd3b6c5d5061350da710b7c79529a78c51
Java
madsilver/smartpoll-web
/src/main/java/br/com/smartpoll/controllers/RegisterUserController.java
UTF-8
1,073
2.296875
2
[]
no_license
package br.com.smartpoll.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import br.com.smartpoll.daos.AccountDAO; import br.com.smartpoll.models.Account; @Controller @RequestMapping("register-user") public class RegisterUserController { @Autowired private AccountDAO accountDAO; @RequestMapping("/") public String index(){ return "site/register-user"; } @RequestMapping(value = "/save-account") @ResponseBody public String saveNewAccount(Account account){ try{ accountDAO.save(account); } catch(Exception e){ return "fail"; } return "ok"; } @RequestMapping(value = "/email-exist") @ResponseBody public String emailExist(String email){ try{ Account account = accountDAO.searchByEmail(email); if(account != null){ return "true"; } else { return "false"; } } catch(Exception e){ return "error"; } } }
true
089555ab097db6b3f88a0a7de7da82f39d0ac59f
Java
ryantberg/6005-final
/src/abc/parser/AbcTuneListener.java
UTF-8
20,031
2.359375
2
[]
no_license
package abc.parser; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import abc.player.Fraction; import abc.player.Playable; import abc.player.Tune; import abc.player.playable.Concat; import abc.player.playable.MultiNote; import abc.player.playable.Note; import abc.player.playable.Rest; import abc.sound.Pitch; public class AbcTuneListener extends AbcParserBaseListener { /** * The default composer if none is given. */ private static final String COMPOSER_DEFAULT = ""; /** * The default meter if none is given. */ private static final Fraction METER_DEFAULT = new Fraction(4, 4); /** * The time for the meter "C". */ private static final Fraction COMMON_TIME = new Fraction(4, 4); /** * The time for the meter "C|". */ private static final Fraction CUT_COMMON_TIME = new Fraction(2, 2); /** * The numerator of note lengths without numerators. */ private static final int DEFAULT_LENGTH_NUMERATOR = 1; /** * The numerator of note lengths without denominators. */ private static final int DEFAULT_LENGTH_DENOMINATOR = 1; /** * The default tempo if none is given. */ private static final int TEMPO_DEFAULT = 100; /** * The threshold for resolving the default beat length. * If meter is below, default length is 1/16. * If meter is above, default length is 1/8. */ private static final Double EIGHTH_SIXTEENTH_THRESHOLD = .75; /** * The default name for the default voice. */ private static final String DEFAULT_DEFAULT_VOICE_NAME = "default"; /** * The result of the parse. * Set when the parse is finished. */ private Tune result; // Header fields. /** * The number of the track. * Must be set during header parsing. * An integer to distinguish between "unset" and 0. */ private Integer trackNumber; /** * The title of the track. * Must be set during header parsing. */ private String title; /** * The key of the track. * Must be set during header parsing. */ private String key; /** * The composer of the track. * Must be set during header parsing. */ private String composer; /** * The meter of the track. * May be set during header parsing. * Otherwise, will be set at the end of header parsing. */ private Fraction meter; /** * The tempo of the track. * Computed at the end of header parsing. */ private Integer tempo; /** * The default beat length of the track. * May be set during header parsing. * If not set, computed using resolveDefaultLength. */ private Fraction defaultLength; // Used during parsing /** * A stack of recently parsed numbers. */ private Deque<Integer> lastParsedNumberStack; /** * The names of the voices of the piece. * Used when we don't have anything to put in the voices * map. */ private final Set<String> voiceNames; // Used during header parsing /** * The most recently parsed fraction. * Could be a stack, but there's only ever * one at a time. * Should be set to null after it's used. */ private Fraction lastParsedFraction; /** * The tempo beat. */ private Fraction tempoBeat; /** * The number of tempo beats per minute. */ private int tempoBeatsPerMinute; // Used during music parsing /** * The actual voices of the music. * Added to during music parsing as they are used. */ private final Map<String, Playable> voices; /** * The voice currently being used. * Starts out being the default voice. */ private String currentVoice; /** * Recently parsed notes; used when parsing chords * and notes. */ private Deque<Note> noteQueue; /** * The current key note-mapping. * Modified when we encounter an accidental, * reset when we hit a barline. */ private KeyMap keyMap; /** * The sequence of playables for the current major section. */ private List<Playable> currentMajorSection; /** * If we are in a repeat section, this */ private List<Playable> startOfRepeatSection; /** * Construct an AbcTuneListener. */ public AbcTuneListener() { this.voiceNames = new HashSet<>(); this.voices = new HashMap<>(); this.lastParsedNumberStack = new ArrayDeque<>(); this.noteQueue = new ArrayDeque<>(); } /** * @return the parsed tune * @throws IllegalStateException if this listener has not yet listened * to an AbcParser */ public Tune getParsedTune() throws IllegalStateException { if (result == null) { throw new IllegalStateException("Haven't parsed a tune"); } return result; } // Header parsing. /** * {@inheritDoc} * * Sets the number field. */ @Override public void exitFieldNumber(final AbcParser.FieldNumberContext ctx) { assert !this.lastParsedNumberStack.isEmpty(); this.trackNumber = this.lastParsedNumberStack.pop(); } /** * {@inheritDoc} * * Sets the title field. */ @Override public void exitFieldTitle(final AbcParser.FieldTitleContext ctx) { this.title = ctx.TEXT().getText(); } /** * {@inheritDoc} * * Sets the composer field. */ @Override public void exitFieldComposer(final AbcParser.FieldComposerContext ctx) { this.composer = ctx.TEXT().getText(); } /** * {@inheritDoc} * * Sets the default length field. */ @Override public void exitFieldDefaultLength(final AbcParser.FieldDefaultLengthContext ctx) { this.defaultLength = this.popFraction(); } /** * {@inheritDoc} * * Sets the meter field. */ @Override public void exitFieldMeter(final AbcParser.FieldMeterContext ctx) { if (ctx.METER_SHORTHAND() != null) { switch (ctx.METER_SHORTHAND().getText()) { case "C": this.meter = COMMON_TIME; break; case "C|": this.meter = CUT_COMMON_TIME; break; default: throw new RuntimeException("Impossible meter shorthand: "+ctx.METER_SHORTHAND().getText()); } } else { this.meter = this.popFraction(); } } /** * {@inheritDoc} * * Sets the fields that will be used to compute the tempo at the end of header * parsing. */ @Override public void exitFieldTempo(final AbcParser.FieldTempoContext ctx) { assert !this.lastParsedNumberStack.isEmpty(); this.tempoBeat = this.popFraction(); this.tempoBeatsPerMinute = this.lastParsedNumberStack.pop(); } /** * {@inheritDoc} * * Parse a header beat into the lastParsedFraction. */ @Override public void exitHeaderBeat(final AbcParser.HeaderBeatContext ctx) { assert this.lastParsedFraction == null; final Integer denominator = this.lastParsedNumberStack.pop(); final Integer numerator = this.lastParsedNumberStack.pop(); this.lastParsedFraction = new Fraction(numerator, denominator); } /** * {@inheritDoc} * * Adds a voice to the set of voice names. */ @Override public void exitFieldVoice(AbcParser.FieldVoiceContext ctx) { this.voiceNames.add(ctx.TEXT().getText()); } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFieldKey(AbcParser.FieldKeyContext ctx) { this.key = ctx.KEY().getText(); } /** * {@inheritDoc} * * Ensures that all fields have been set and prepares parser to parse music. */ @Override public void exitAbcHeader(AbcParser.AbcHeaderContext ctx) { assert this.trackNumber != null; assert this.title != null; assert this.key != null; if (this.composer == null) { this.composer = COMPOSER_DEFAULT; } if (this.meter == null) { this.meter = METER_DEFAULT; } if (this.defaultLength == null) { this.defaultLength = resolveDefaultLength(this.meter); } if (this.tempoBeat == null) { this.tempo = TEMPO_DEFAULT; } else { this.tempo = resolveTempo(this.defaultLength, this.tempoBeat, this.tempoBeatsPerMinute); } } // Music parsing. @Override public void enterAbcMusic(AbcParser.AbcMusicContext ctx) { // Note: this should happen immediately after exitAbcHeader. // Start parsing the music! // Add default voice final String defaultVoice = resolveDefaultVoice(this.voiceNames); this.voiceNames.add(defaultVoice); // Set current voice to default voice this.currentVoice = defaultVoice; // Set up the key resetKey(); // Start a major section startMajorSection(); } @Override public void exitAbcMusic(AbcParser.AbcMusicContext ctx) { endMajorSection(); // We're done parsing! this.result = new Tune( this.trackNumber, this.title, this.composer, this.key, this.defaultLength, this.meter, this.tempo, this.voices ); } // A note: we deal with repeats in a slightly hacky way. // If we encounter a :| with no [1s or [2s since the end of the previous // major section, we just double the current major section. // So: A A || A A A :| is parsed into sections as: // A A) (A A A :| // And then expanded to: // A A) (A A A A A A) ( // // If we encounter a [1, we move the current major section into the variable // this.startOfRepeatSection, and start parsing a new major section. // When we encounter :|, we flatten the sections into a single list: // startOfRepeatSection currentMajorSection startOfRepeatSection // Which we move into currentMajorSection and continue onwards. // Now, when we encounter a [2, we can just add it at the end of // currentMajorSection and continue onwards; we've already added the repeated // part. @Override public void exitNthRepeat(AbcParser.NthRepeatContext ctx) { if (ctx.getText() == "[1") { assert this.startOfRepeatSection == null; this.startOfRepeatSection = this.currentMajorSection; this.currentMajorSection = new ArrayList<>(); } } @Override public void exitBarline(AbcParser.BarlineContext ctx) { // Always reset the key. resetKey(); switch (ctx.getText()) { case "||": case "[|": case "|]": case "|:": // Note that we don't handle repeat-starts specially. endMajorSection(); startMajorSection(); break; case ":|": List<Playable> flatSection = new ArrayList<>(); if (this.startOfRepeatSection != null) { // Complex repeat; flatten. flatSection.addAll(this.startOfRepeatSection); flatSection.addAll(this.currentMajorSection); flatSection.addAll(this.startOfRepeatSection); this.startOfRepeatSection = null; } else { // Simple repeat; duplicate current major section. flatSection.addAll(this.currentMajorSection); flatSection.addAll(this.currentMajorSection); } this.currentMajorSection = flatSection; endMajorSection(); startMajorSection(); break; case "|": break; default: throw new RuntimeException("Impossible barline: "+ctx.getText()); } } @Override public void exitVoiceChange(AbcParser.VoiceChangeContext ctx) { endMajorSection(); final String newVoice = ctx.TEXT().getText(); this.currentVoice = newVoice; resetKey(); startMajorSection(); } @Override public void exitNoteElement(AbcParser.NoteElementContext ctx) { // Is this a note or a chord? if (ctx.note() != null) { // It's a note! // Well, it could also be a rest, in which case we'll already have // added it and the note queue will be empty: if (!this.noteQueue.isEmpty()) { this.currentMajorSection.add(this.noteQueue.removeFirst()); } } else { // It's a chord! // The first note read should be the first note in the MultiNote; // i.e. we should preserve the order of the note queue. MultiNote chord = new MultiNote(new ArrayList<>(this.noteQueue)); // Remove all of the elements from the note queue. this.noteQueue.clear(); // Add this chord. this.currentMajorSection.add(chord); } } @Override public void exitNote(AbcParser.NoteContext ctx) { final Fraction length; if (ctx.noteLength() != null) { AbcParser.NoteLengthContext nl = ctx.noteLength(); if (nl.slash() != null) { final int numerator; if (nl.number(0) != null) { numerator = Integer.parseInt(nl.number(0).getText()); } else { numerator = DEFAULT_LENGTH_NUMERATOR; } final int denominator; if (nl.number(1) != null) { denominator = Integer.parseInt(nl.number(1).getText()); } else { denominator = DEFAULT_LENGTH_DENOMINATOR; } length = new Fraction(numerator, denominator); } else { length = new Fraction( Integer.parseInt(nl.number(0).getText()), DEFAULT_LENGTH_DENOMINATOR ); } } else { length = new Fraction(DEFAULT_LENGTH_NUMERATOR, DEFAULT_LENGTH_DENOMINATOR); } AbcParser.NoteOrRestContext nr = ctx.noteOrRest(); if (nr.REST() != null) { // If this is a rest, we can't be in a chord, so just put it // directly in the current section this.currentMajorSection.add(new Rest(length)); return; } // It's a note! AbcParser.PitchContext p = nr.pitch(); final char letterNote = p.LETTER_NOTE().getText().charAt(0); final Pitch basePitch = new Pitch(Character.toUpperCase(letterNote)); // We modify our key map for the rest of the bar. if (p.ACCIDENTAL() != null) { switch (p.ACCIDENTAL().getText()) { case "__": this.keyMap.setOffset(basePitch, KeyMap.DOUBLE_FLAT_OFFSET); break; case "_": this.keyMap.setOffset(basePitch, KeyMap.FLAT_OFFSET); break; case "=": this.keyMap.setOffset(basePitch, KeyMap.NEUTRAL_OFFSET); break; case "^": this.keyMap.setOffset(basePitch, KeyMap.SHARP_OFFSET); break; case "^^": this.keyMap.setOffset(basePitch, KeyMap.DOUBLE_SHARP_OFFSET); break; default: throw new RuntimeException("Impossible accidental: " + p.ACCIDENTAL().getText()); } } final Pitch keyPitch = this.keyMap.forPitch(basePitch); int octavesUp = 0; if (Character.isLowerCase(letterNote)) { octavesUp++; } if (p.OCTAVE() != null) { for (final char c : p.OCTAVE().getText().toCharArray()) { if (c == '\'') { octavesUp++; } else { octavesUp--; } } } final Pitch resultPitch = keyPitch.transpose(Pitch.OCTAVE * octavesUp); this.noteQueue.push(new Note(resultPitch, length)); } // Both header and music @Override public void exitNumber(AbcParser.NumberContext ctx) { this.lastParsedNumberStack.push(Integer.parseInt(ctx.getText())); } // Helper methods. /** * Reset the current key we're using. */ private void resetKey() { this.keyMap = KeyMap.forKeyName(this.key); } /** * Called whenever we start a major section in the music * (at the start of the music, after a voice change, after a fancy bar) */ private void startMajorSection() { this.currentMajorSection = new ArrayList<>(); } /** * Called when we finish a major section in the music. */ private void endMajorSection() { if (currentMajorSection.isEmpty()) { return; } Playable thisSection = new Concat(currentMajorSection); if (this.voices.containsKey(this.currentVoice)) { // We've had a section with this voice before; // append this line to the current playable for this voice this.voices.put( this.currentVoice, new Concat(Arrays.asList( this.voices.get(this.currentVoice), thisSection )) ); } else { // This is the first time we've had a line in this voice this.voices.put(this.currentVoice, thisSection); } } /** * Get and unset the last parsed fraction. * * @return the last parsed fraction */ private Fraction popFraction() { assert this.lastParsedFraction != null; final Fraction result = this.lastParsedFraction; this.lastParsedFraction = null; return result; } /** * Compute the default defaultLength of a beat for a given meter. * * @param meter the meter to resolve the defaultLength for. * @return the resolved defaultLength for the meter. */ protected static Fraction resolveDefaultLength(Fraction meter) { if (meter.valueOf() < EIGHTH_SIXTEENTH_THRESHOLD) { return new Fraction(1, 16); } else { // >= return new Fraction(1, 8); } } /** * Ensure that the default name is hygenic; that is to say, that it * doesn't overlap with a user-defined voice. * * @param definedVoices voice names we have to avoid * @return a name for the default voice */ protected static String resolveDefaultVoice(Set<String> definedVoices) { // TODO: this doesn't take into account the fact that new voices // can be declared inline. If one of those pops up named "default", // we'll have a problem. // if they haven't defined a name "default" (which they probably haven't), // use the name "default" for the default voice if (!definedVoices.contains(DEFAULT_DEFAULT_VOICE_NAME)) { return DEFAULT_DEFAULT_VOICE_NAME; } // try "default1", "default2", etc. until we find one they haven't used. // If they have defined INT_MAX/2 voices named "default1", "default2"... // then they're pathological. for (int i = 0; i > 0; i++) { String nextAttempt = DEFAULT_DEFAULT_VOICE_NAME + i; if (!definedVoices.contains(nextAttempt)) { return nextAttempt; } } throw new RuntimeException("Can't create a default voice name"); } protected static int resolveTempo(Fraction defaultLength, Fraction tempoBeat, int tempoBPM) { Fraction ratio = tempoBeat.divide(defaultLength); if (ratio.denominator() != 1) { throw new RuntimeException("Can't compute integer bpm: " + tempoBeat + " / " + defaultLength + " is not a whole number"); } return ratio.numerator() * tempoBPM; } }
true
a6e3c74c0f4a2c7ac3ec0a0948984dad683d01d3
Java
JohnFantasy/SpringCloudLearning
/DeeoIntoJava/src/main/java/deepintojava/MultiThread/ABADemoCAS.java
UTF-8
1,550
3.234375
3
[]
no_license
package deepintojava.MultiThread; import java.util.concurrent.atomic.AtomicInteger; /** * @author fanyuzhuo * @createAt 2021-01-21 12:20 * @description */ public class ABADemoCAS { public static AtomicInteger a = new AtomicInteger(1); public static void main(String[] args) { Thread main = new Thread(() -> { System.out.println("operating thread:" + Thread.currentThread().getName() + ",initial value is :" + a.get()); try { int expectNo = a.get(); int newNum = expectNo + 1; Thread.sleep(1000); boolean isCasSuccess = a.compareAndSet(expectNo, newNum); System.out.println("operating thread " + Thread.currentThread().getName() + ",CAS 操作 :" + isCasSuccess); } catch (InterruptedException e) { e.printStackTrace(); } }, "main thread"); Thread botherThread = new Thread(() -> { try { Thread.sleep(20); a.incrementAndGet(); System.out.println("operating thread " + Thread.currentThread().getName() + "【increment】 操作 :" + a.get()); a.decrementAndGet(); System.out.println("operating thread " + Thread.currentThread().getName() + "【de crement】 操作 :" + a.get()); } catch (InterruptedException e) { e.printStackTrace(); } }, "bothering thread"); main.start(); botherThread.start(); } }
true
da2d86956b58dc804493f895ad36a3e1c27883b8
Java
perrywang/LiteWorkflow
/src/main/java/toolbox/common/workflow/core/SimpleExecutionContext.java
UTF-8
1,877
2.390625
2
[ "MIT" ]
permissive
package toolbox.common.workflow.core; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.script.ScriptEngine; import javax.script.ScriptException; import lombok.Data; import lombok.NoArgsConstructor; import toolbox.common.workflow.engine.scripting.ActiveRecord; import toolbox.common.workflow.engine.scripting.ScriptEngineFactory; import toolbox.common.workflow.entity.Execution; @Data @NoArgsConstructor public class SimpleExecutionContext implements ExecutionContext { private Execution execution; private ExecutionContext parentContext; private ScriptEngine scriptEngine; private ActiveRecord record; private Map<String, Object> properties = new HashMap<>(); public SimpleExecutionContext(ExecutionContext parent, Execution execution, ActiveRecord record) { this.parentContext = parent; this.execution = execution; this.record = record; this.scriptEngine = ScriptEngineFactory.createEngine(); } public SimpleExecutionContext(ExecutionContext parent, Execution execution) { this(parent,execution,new ActiveRecord()); } @Override public ActiveRecord getActiveRecord() { return record; } @Override public void setProperty(String key, Object value) { properties.put(key, value); } @Override public Object getProperty(String key) { return properties.get(key); } @Override public Set<String> getPropertyNames() { return properties.keySet(); } @Override public boolean evaluateCondition(String condition) { // TODO Auto-generated method stub try { return (boolean)scriptEngine.eval(condition); } catch (ScriptException e) { e.printStackTrace(); return false; } } }
true
93679bf053e2446eb524986e5f57d03c8d8c8a51
Java
Athlaeos/ProgressiveDifficulty
/src/main/java/me/athlaeos/progressivelydifficultmobs/commands/ManageCooldownsCommand.java
UTF-8
6,066
2.375
2
[]
no_license
package me.athlaeos.progressivelydifficultmobs.commands; import me.athlaeos.progressivelydifficultmobs.main.Main; import me.athlaeos.progressivelydifficultmobs.managers.CooldownManager; import me.athlaeos.progressivelydifficultmobs.managers.PlayerMenuUtilManager; import me.athlaeos.progressivelydifficultmobs.managers.PlayerPerksManager; import me.athlaeos.progressivelydifficultmobs.managers.PluginConfigurationManager; import me.athlaeos.progressivelydifficultmobs.menus.LevelPerkModificationMenu; import me.athlaeos.progressivelydifficultmobs.perks.Perk; import me.athlaeos.progressivelydifficultmobs.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ManageCooldownsCommand implements Command{ private final PluginConfigurationManager config; private final CooldownManager cooldownManager; public ManageCooldownsCommand(){ this.config = PluginConfigurationManager.getInstance(); this.cooldownManager = CooldownManager.getInstance(); } @Override public boolean execute(CommandSender sender, String[] args) { if (args.length > 3){ Player p; if (Main.getInstance().getServer().getPlayer(args[1]) != null) { p = Main.getInstance().getServer().getPlayer(args[1]); if (sender instanceof Player){ Player sendr = (Player) sender; if (!p.getName().equals(sendr.getName())){ if (!sendr.hasPermission("pdm.managecooldowns")){ sender.sendMessage(Utils.chat(config.getErrorNoPermission())); return true; } } } } else { sender.sendMessage(Utils.chat(config.getPlayerNotFoundError())); return true; } if (p == null){ sender.sendMessage(Utils.chat(config.getPlayerNotFoundError())); return true; } if (args[2].equalsIgnoreCase("set")){ if (args.length > 4){ if (sender.hasPermission("pdm.managecooldowns")) { if (cooldownManager.getAllCooldowns().keySet().contains(args[3])){ int newCooldown; try { newCooldown = Integer.parseInt(args[4]); } catch (IllegalArgumentException e){ sender.sendMessage(Utils.chat(config.getInvalidNumberError())); return true; } cooldownManager.setCooldown(p, newCooldown, args[3]); sender.sendMessage(Utils.chat(config.getGetCooldownMessage() .replace("{player}", p.getName()) .replace("{key}", args[3]) .replace("{cooldown}", Utils.msToTimestamp(cooldownManager.getCooldown(p, args[3]))))); } else { sender.sendMessage(Utils.chat(config.getInvalidCooldownKeyError())); } return true; } else { sender.sendMessage(Utils.chat(config.getErrorNoPermission())); return true; } } } else if (args[2].equalsIgnoreCase("get")){ if (sender.hasPermission("pdm.managecooldowns") || sender.hasPermission("pdm.getowncooldowns")){ if (cooldownManager.getAllCooldowns().keySet().contains(args[3])){ sender.sendMessage(Utils.chat(config.getGetCooldownMessage() .replace("{player}", p.getName()) .replace("{key}", args[3]) .replace("{cooldown}", Utils.msToTimestamp(cooldownManager.getCooldown(p, args[3]))))); } else { sender.sendMessage(Utils.chat(config.getInvalidCooldownKeyError())); } return true; } } } return true; } @Override public String[] getRequiredPermission() { return new String[]{"pdm.managecooldowns", "pdm.getowncooldowns"}; } @Override public String getFailureMessage() { return Utils.chat("&c/pdm cooldowns <player> <get/set> <key> <cooldown (ms)>"); } @Override public String[] getHelpEntry() { return new String[]{ Utils.chat("&8&m "), Utils.chat("&e/pdm cooldowns <player> <get/set> <key> <cooldown (ms)>"), Utils.chat("&7" + config.getCooldownCommandDescription()), Utils.chat("&7>" + config.getTranslationPermissions() + " &epdm.managecooldowns | pdm.getowncooldowns") }; } @Override public List<String> getSubcommandArgs(CommandSender sender, String[] args) { List<String> options = new ArrayList<>(); if (args.length == 2){ if (sender.hasPermission("pdm.managecooldowns")){ return null; } else { if (sender instanceof Player){ Player sendr = (Player) sender; return Collections.singletonList(sendr.getName()); } } } if (args.length == 3){ options.add("set"); options.add("get"); } if (args.length == 4){ return new ArrayList<>(cooldownManager.getAllCooldowns().keySet()); } if (args.length == 5){ return Collections.singletonList("millis"); } return options; } }
true
f71a1a281af236b58743c7d612175c07c0d51ff1
Java
regestaexe/OD
/src/com/openDams/index/configuration/IndexInfo.java
UTF-8
3,539
2.171875
2
[ "MIT" ]
permissive
package com.openDams.index.configuration; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.LockObtainFailedException; import com.regesta.framework.io.FileSizeConverter; public class IndexInfo { private String index_name; private long index_version; private boolean optimized; private int numDocs; private int numDocsArchive; private int numDocsBasket; private String lastModifyDate; private HashMap<String,String> files; private String xmlIndex; private String xmlTitle; public IndexInfo(String indexName,Directory directory,Analyzer analyzer) throws CorruptIndexException, IOException{ IndexWriter iwriter = null; IndexReader indexReader = null; try { iwriter = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED); indexReader = iwriter.getReader(); this.index_name = indexName; this.index_version = indexReader.getVersion(); this.optimized = indexReader.isOptimized(); this.numDocs = indexReader.numDocs(); Date date = new Date(IndexReader.lastModified(directory)); DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss a"); this.lastModifyDate = formatter.format(date); this.files = new HashMap<String, String>(); String[] files = directory.listAll(); for (int i = 0; i < files.length; i++) { if(files[i].startsWith("_")) this.files.put(files[i], Long.toString(Math.round(FileSizeConverter.convertSize(directory.fileLength(files[i]), FileSizeConverter.KB)))+" KB" ); } indexReader.close(); iwriter.close(); iwriter = null; directory.clearLock(directory.getLockID()); } catch (CorruptIndexException e) { if (iwriter != null) { iwriter.close(); iwriter = null; } if (indexReader != null) { indexReader.close(); indexReader = null; } throw e; } catch (LockObtainFailedException e) { if (iwriter != null) { iwriter.close(); iwriter = null; } if (indexReader != null) { indexReader.close(); indexReader = null; } throw e; } catch (IOException e) { if (iwriter != null) { iwriter.close(); iwriter = null; } if (indexReader != null) { indexReader.close(); indexReader = null; } throw e; } } public String getIndex_name() { return index_name; } public long getIndex_version() { return index_version; } public boolean isOptimized() { return optimized; } public int getNumDocs() { return numDocs; } public String getLastModifyDate() { return lastModifyDate; } public HashMap<String, String> getFiles() { return files; } public String getXmlIndex() { return xmlIndex; } public String getXmlTitle() { return xmlTitle; } public void setXmlIndex(String xmlIndex) { this.xmlIndex = xmlIndex; } public void setXmlTitle(String xmlTitle) { this.xmlTitle = xmlTitle; } public int getNumDocsArchive() { return numDocsArchive; } public void setNumDocsArchive(int numDocsArchive) { this.numDocsArchive = numDocsArchive; } public int getNumDocsBasket() { return numDocsBasket; } public void setNumDocsBasket(int numDocsBasket) { this.numDocsBasket = numDocsBasket; } }
true
42d10d4e21edb4474a8cd38073416903cba94ebc
Java
Ablu/upb.crypto.math
/src/main/java/de/upb/crypto/math/pairings/bn/BarretoNaehrigSourceGroupElement.java
UTF-8
1,532
2.796875
3
[ "Apache-2.0" ]
permissive
package de.upb.crypto.math.pairings.bn; import de.upb.crypto.math.interfaces.structures.FieldElement; import de.upb.crypto.math.pairings.generic.PairingSourceGroupElement; import java.math.BigInteger; public abstract class BarretoNaehrigSourceGroupElement extends PairingSourceGroupElement { public BarretoNaehrigSourceGroupElement(BarretoNaehrigSourceGroup curve, FieldElement x, FieldElement y) { super(curve, x, y); } public BarretoNaehrigSourceGroupElement(BarretoNaehrigSourceGroup curve) { super(curve); } @Override public BarretoNaehrigSourceGroupElement pow(BigInteger e) { return (BarretoNaehrigSourceGroupElement) super.pow(e); } /** * Point compression. * <p> * Compress point (x,y) by mapping x to an integer i in {0,1,2} such that this.getStructure().mapToPoint(y,this.compress(x,y)).equals(this). Hence (y,i) is a compression of (x,y) of approximately half size. * * @return compression of x */ public int compressX() { /* * search for correct x-coordiante wrt. to this.getStructure().getFieldOfDefinition().getCubeRoot() */ // TODO, more efficient way to injective mapping of primitive cube root into the integers for (int i = 0; i < 3; i++) { if (((BarretoNaehrigSourceGroup) this.getStructure()).mapToPoint(this.getY(), i).equals(this)) { return i; } } throw new RuntimeException("Not able to compress point"); } }
true