blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
e2a0c1f2422caacff7db67084544d47d70d69149
22,651,657,585,002
6cfee06d6e0e725c5a1677928e8b1dcf882dfb05
/src/LinearSearch.java
8594e6a5d78dd0e022351f9d974c4c7ff073cce8
[]
no_license
MinatotheFourth/ArrayPractice
https://github.com/MinatotheFourth/ArrayPractice
27aa5690cc4b18d1bb8d11ca12443a0aac3a32b3
5a46bb13c7143082e8ca5cbcdf76ab90bd7ec3a7
refs/heads/master
2020-03-23T11:41:21.975000
2018-07-19T02:49:19
2018-07-19T02:49:19
141,516,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class LinearSearch { public static void main(String[] args) { //Variable declarations and array creations String[] firstNames = new String [4]; String[] lastNames = new String[4]; String key; Scanner input = new Scanner(System.in); //This area asks the user to enter a string into the database System.out.println("Add up to four shinobi to the list"); for(int i = 0; i < firstNames.length; i++) { System.out.print("First Name: "); firstNames[i] = input.nextLine(); System.out.print("Last Name: "); lastNames[i] = input.nextLine(); System.out.print("\n"); } System.out.println("All done.\n" + "Now, enter the first name in the squad with no space at the end: "); key = input.nextLine(); Search_task(firstNames, key); //If the string is in the list if(Search_task(firstNames, key) != -1 && Search_task(firstNames, key) < 3) System.out.println("Shinobi is in the squad. Here's the list \n"); //If the user is silly else if(key.equals(null)) System.out.println("Impossible!"); //This is for if the int isn't in the index else System.out.println("Nah, fam. Nothing. Here's the list \n"); for(int x = 0; x < firstNames.length; x++) { System.out.println((x+1) + ". " + firstNames[x] + " " + lastNames[x]); } } //The Linear Search Method. It can be reused. That's the cool part. public static int Search_task(String[] name, String key ) { for(int i = 0; i < name.length; i++) { if(key.contentEquals(name[i])) return i; } return -1; } }
UTF-8
Java
1,672
java
LinearSearch.java
Java
[]
null
[]
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class LinearSearch { public static void main(String[] args) { //Variable declarations and array creations String[] firstNames = new String [4]; String[] lastNames = new String[4]; String key; Scanner input = new Scanner(System.in); //This area asks the user to enter a string into the database System.out.println("Add up to four shinobi to the list"); for(int i = 0; i < firstNames.length; i++) { System.out.print("First Name: "); firstNames[i] = input.nextLine(); System.out.print("Last Name: "); lastNames[i] = input.nextLine(); System.out.print("\n"); } System.out.println("All done.\n" + "Now, enter the first name in the squad with no space at the end: "); key = input.nextLine(); Search_task(firstNames, key); //If the string is in the list if(Search_task(firstNames, key) != -1 && Search_task(firstNames, key) < 3) System.out.println("Shinobi is in the squad. Here's the list \n"); //If the user is silly else if(key.equals(null)) System.out.println("Impossible!"); //This is for if the int isn't in the index else System.out.println("Nah, fam. Nothing. Here's the list \n"); for(int x = 0; x < firstNames.length; x++) { System.out.println((x+1) + ". " + firstNames[x] + " " + lastNames[x]); } } //The Linear Search Method. It can be reused. That's the cool part. public static int Search_task(String[] name, String key ) { for(int i = 0; i < name.length; i++) { if(key.contentEquals(name[i])) return i; } return -1; } }
1,672
0.632177
0.626794
66
24.333334
22.880674
76
false
false
0
0
0
0
0
0
2.590909
false
false
15
56959a0589dfa2dbc884a9036ee61176415b6d41
13,159,779,852,901
f24ebbed74c6b3dd8f78b3423c54e9fe1bb59d2b
/EngappsadosApp/app/src/main/java/com/engappsados/engappsadosapp/Ustats.java
f52c20e6fb0f4ae6a4fecefba02518c501fe1d46
[]
no_license
DCplayer/EngAppsados
https://github.com/DCplayer/EngAppsados
1179b4b7086f25808170d741dc0d3558822dbb8c
941676a44138b45ced45409c3cb95b920b5836ec
refs/heads/master
2021-01-20T08:29:39.477000
2017-11-20T20:21:59
2017-11-20T20:21:59
90,152,153
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.engappsados.engappsadosapp; import android.app.usage.UsageEvents; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; /** * Created by sebas on 9/26/2017. */ public class Ustats { public FirebaseUser usuario = FirebaseAuth.getInstance().getCurrentUser(); public DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference(); public String uID = usuario.getUid(); public int puntos; public boolean booleano = true; public Ustats() { mDatabaseRef.child("usuarios").child(uID).child("Puntos").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { puntos = Integer.parseInt(dataSnapshot.getValue().toString()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void getTimeUstats(Context mContext, ArrayList<String> array, ArrayList<Integer> arrayt, ArrayList<Integer> arrayp){ // UsageStats usageStats; String PackageName = "Nothing" ; long TimeInforground = 500 ; int minutes=500,seconds=500,hours=500 ; UsageStatsManager mUsageStatsManager = (UsageStatsManager)mContext.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time); if(stats != null) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : stats) { if(array.contains(usageStats.getPackageName())){ TimeInforground = usageStats.getTotalTimeInForeground(); PackageName = usageStats.getPackageName(); minutes = (int) ((TimeInforground / (1000 * 60)) % 60); seconds = (int) (TimeInforground / 1000) % 60; hours = (int) ((TimeInforground / (1000 * 60 * 60)) % 24); int indice = array.indexOf(PackageName); //si la aplicacion ya corio por mas de lo especificado en la base de datos. if(minutes >= arrayt.get(indice)){ //actualizar los puntos del usuario puntos = puntos + arrayp.get(indice); mDatabaseRef.child("usuarios").child(uID).child("Puntos").setValue(puntos); booleano = false; //toast que muestra la informacion int duracion=Toast.LENGTH_LONG; String texto = "Has obtenido " + arrayp.get(indice) + " puntos por haber estado " + arrayt.get(indice) +" o mas minutos usando: "+ array.get(indice); Toast.makeText(mContext, texto, duracion).show(); }else{ //toast que muestra la informacion int duracion=Toast.LENGTH_LONG; String texto = "No se pueden otorgar puntos aún."; Toast.makeText(mContext, texto, duracion).show(); } Log.i("BAC", "PackageName is" + PackageName + "Time is: " + hours + "h" + ":" + minutes + "m" + seconds + "s"); } } } } }
UTF-8
Java
4,229
java
Ustats.java
Java
[ { "context": "izer;\nimport java.util.TreeMap;\n\n/**\n * Created by sebas on 9/26/2017.\n */\n\npublic class Ustats {\n publ", "end": 905, "score": 0.9978983402252197, "start": 900, "tag": "USERNAME", "value": "sebas" } ]
null
[]
package com.engappsados.engappsadosapp; import android.app.usage.UsageEvents; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; /** * Created by sebas on 9/26/2017. */ public class Ustats { public FirebaseUser usuario = FirebaseAuth.getInstance().getCurrentUser(); public DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference(); public String uID = usuario.getUid(); public int puntos; public boolean booleano = true; public Ustats() { mDatabaseRef.child("usuarios").child(uID).child("Puntos").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { puntos = Integer.parseInt(dataSnapshot.getValue().toString()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void getTimeUstats(Context mContext, ArrayList<String> array, ArrayList<Integer> arrayt, ArrayList<Integer> arrayp){ // UsageStats usageStats; String PackageName = "Nothing" ; long TimeInforground = 500 ; int minutes=500,seconds=500,hours=500 ; UsageStatsManager mUsageStatsManager = (UsageStatsManager)mContext.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time); if(stats != null) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : stats) { if(array.contains(usageStats.getPackageName())){ TimeInforground = usageStats.getTotalTimeInForeground(); PackageName = usageStats.getPackageName(); minutes = (int) ((TimeInforground / (1000 * 60)) % 60); seconds = (int) (TimeInforground / 1000) % 60; hours = (int) ((TimeInforground / (1000 * 60 * 60)) % 24); int indice = array.indexOf(PackageName); //si la aplicacion ya corio por mas de lo especificado en la base de datos. if(minutes >= arrayt.get(indice)){ //actualizar los puntos del usuario puntos = puntos + arrayp.get(indice); mDatabaseRef.child("usuarios").child(uID).child("Puntos").setValue(puntos); booleano = false; //toast que muestra la informacion int duracion=Toast.LENGTH_LONG; String texto = "Has obtenido " + arrayp.get(indice) + " puntos por haber estado " + arrayt.get(indice) +" o mas minutos usando: "+ array.get(indice); Toast.makeText(mContext, texto, duracion).show(); }else{ //toast que muestra la informacion int duracion=Toast.LENGTH_LONG; String texto = "No se pueden otorgar puntos aún."; Toast.makeText(mContext, texto, duracion).show(); } Log.i("BAC", "PackageName is" + PackageName + "Time is: " + hours + "h" + ":" + minutes + "m" + seconds + "s"); } } } } }
4,229
0.627483
0.615894
99
41.696968
34.840317
173
false
false
0
0
0
0
0
0
0.686869
false
false
15
ddeff088980552f53526353b595a312ddd1dfcc7
18,743,237,345,733
96b5ab92079e1b7aa12b7eb93d1436b64e4e5f56
/app/src/main/java/com/raghunath704/covix/MyCustomAdapter.java
4223191a0c5a29e56b95dc4759d74c8b929f45ae
[]
no_license
raghunath704/Covid-Tracker
https://github.com/raghunath704/Covid-Tracker
c730d0c333e43b59c29c375e00787982dab17f8f
a19a877b88ae4b66c8a9af9fac5fc740c4b0bf84
refs/heads/master
2023-06-06T15:56:41.903000
2021-07-01T06:32:26
2021-07-01T06:32:26
381,362,927
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raghunath704.covix; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; public class MyCustomAdapter extends ArrayAdapter<CounteryModel> { private Context context; private List<CounteryModel> counteryModelList; private List<CounteryModel> counteryModelListFiltered; public MyCustomAdapter(Context context, List<CounteryModel> counteryModelList) { super(context, R.layout.list_custom_item,counteryModelList); this.context=context; this.counteryModelList=counteryModelList; this.counteryModelListFiltered=counteryModelList; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_custom_item,null,true); TextView tvCountryName=view.findViewById(R.id.tvCountryName); ImageView imageView=view.findViewById(R.id.imageFlag); tvCountryName.setText(counteryModelListFiltered.get(position).getCountry()); Glide.with(context).load(counteryModelListFiltered.get(position).getFlag()).into(imageView); return view; } @Override public int getCount() { return counteryModelListFiltered.size(); } @Nullable @Override public CounteryModel getItem(int position) { return counteryModelListFiltered.get(position); } @Override public long getItemId(int position) { return position; } @Override public Filter getFilter() { Filter filter=new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); if (constraint == null || constraint.length() == 0) { filterResults.count = counteryModelList.size(); filterResults.values = counteryModelList; } else { List<CounteryModel> resultsModel = new ArrayList<>(); String searchStr = constraint.toString().toLowerCase(); for (CounteryModel itemsModel : counteryModelList) { if (itemsModel.getCountry().toLowerCase().contains(searchStr)) { resultsModel.add(itemsModel); } filterResults.count = resultsModel.size(); filterResults.values = resultsModel; } } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { counteryModelListFiltered=(List<CounteryModel>) results.values; AffectedCountries.counteryModelList=(List<CounteryModel>) results.values; notifyDataSetChanged(); } }; return filter; } }
UTF-8
Java
3,340
java
MyCustomAdapter.java
Java
[ { "context": "package com.raghunath704.covix;\n\nimport android.content.Context;\nimport an", "end": 24, "score": 0.940566897392273, "start": 15, "tag": "USERNAME", "value": "hunath704" } ]
null
[]
package com.raghunath704.covix; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; public class MyCustomAdapter extends ArrayAdapter<CounteryModel> { private Context context; private List<CounteryModel> counteryModelList; private List<CounteryModel> counteryModelListFiltered; public MyCustomAdapter(Context context, List<CounteryModel> counteryModelList) { super(context, R.layout.list_custom_item,counteryModelList); this.context=context; this.counteryModelList=counteryModelList; this.counteryModelListFiltered=counteryModelList; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_custom_item,null,true); TextView tvCountryName=view.findViewById(R.id.tvCountryName); ImageView imageView=view.findViewById(R.id.imageFlag); tvCountryName.setText(counteryModelListFiltered.get(position).getCountry()); Glide.with(context).load(counteryModelListFiltered.get(position).getFlag()).into(imageView); return view; } @Override public int getCount() { return counteryModelListFiltered.size(); } @Nullable @Override public CounteryModel getItem(int position) { return counteryModelListFiltered.get(position); } @Override public long getItemId(int position) { return position; } @Override public Filter getFilter() { Filter filter=new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); if (constraint == null || constraint.length() == 0) { filterResults.count = counteryModelList.size(); filterResults.values = counteryModelList; } else { List<CounteryModel> resultsModel = new ArrayList<>(); String searchStr = constraint.toString().toLowerCase(); for (CounteryModel itemsModel : counteryModelList) { if (itemsModel.getCountry().toLowerCase().contains(searchStr)) { resultsModel.add(itemsModel); } filterResults.count = resultsModel.size(); filterResults.values = resultsModel; } } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { counteryModelListFiltered=(List<CounteryModel>) results.values; AffectedCountries.counteryModelList=(List<CounteryModel>) results.values; notifyDataSetChanged(); } }; return filter; } }
3,340
0.651198
0.65
99
32.737373
29.205156
105
false
false
0
0
0
0
0
0
0.545455
false
false
15
17f21ad65c1fbd4d7ee986fe180123e8bf19d17d
33,560,874,517,514
e80488e177b363a512a05dc10a7d896511a0387d
/service/service-item/src/main/java/com/atguigu/gmall/item/service/impl/ItemServiceImpl.java
68e05b5b67c7a703d997bf639bd1f81e2a87c8fd
[]
no_license
kuiba123/gmall-parent
https://github.com/kuiba123/gmall-parent
e60ac7272837e6b4ffced933945fb37f7116da11
b7053355c4567de21b447419a8d19fd6e571c847
refs/heads/master
2023-04-22T16:33:42.734000
2021-05-13T14:29:38
2021-05-13T14:29:38
347,307,173
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.gmall.item.service.impl; import com.alibaba.fastjson.JSON; import com.atguigu.gmall.item.service.ItemService; import com.atguigu.gmall.list.client.ListFeignClient; import com.atguigu.gmall.model.product.BaseCategoryView; import com.atguigu.gmall.model.product.SkuInfo; import com.atguigu.gmall.model.product.SpuSaleAttr; import com.atguigu.gmall.product.client.ProductFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadPoolExecutor; @Service public class ItemServiceImpl implements ItemService { @Autowired private ProductFeignClient productFeignClient; @Autowired private ListFeignClient listFeignClient; @Autowired private ThreadPoolExecutor threadPoolExecutor; @Override public Map<String, Object> getBySkuId(Long skuId) { Map<String, Object> result = new HashMap<>(); //通过skuId查询skuInfo CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(()->{ SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId); //保存skuInfo result.put("skuInfo",skuInfo); return skuInfo; },threadPoolExecutor); //获取商品分类 CompletableFuture<Void> categoryViewCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> { BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id()); //保存商品分类数据 result.put("categoryView",categoryView); },threadPoolExecutor); //获取商品最新价格 //获取商品最新价格 CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(() -> { BigDecimal skuPrice = productFeignClient.getSkuPrice(skuId); result.put("price", skuPrice); },threadPoolExecutor); //销售属性-销售属性值回显并锁定 CompletableFuture<Void> spuSaleAttrCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> { List<SpuSaleAttr> spuSaleAttrList = productFeignClient.getSpuSaleAttrListCheckBySku(skuInfo.getId(), skuInfo.getSpuId()); //保存数据 result.put("spuSaleAttrList",spuSaleAttrList); },threadPoolExecutor); //根据spuId查询map集合属性 CompletableFuture<Void> skuValueIdsMapCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo ->{ Map skuValueIdsMap = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId()); //保存json字符串 String mapJson = JSON.toJSONString(skuValueIdsMap); System.out.println("mapJson = " + mapJson); //保存valuesSkuJson result.put("valuesSkuJson",mapJson); },threadPoolExecutor); //更新商品incrHotScore CompletableFuture<Void> incrHotScoreCompletableFuture = CompletableFuture.runAsync(() -> { listFeignClient.incrHotScore(skuId); },threadPoolExecutor); //任务组合 CompletableFuture.allOf( skuInfoCompletableFuture, spuSaleAttrCompletableFuture, skuValueIdsMapCompletableFuture, skuPriceCompletableFuture, categoryViewCompletableFuture, incrHotScoreCompletableFuture).join(); return result; } }
UTF-8
Java
3,649
java
ItemServiceImpl.java
Java
[]
null
[]
package com.atguigu.gmall.item.service.impl; import com.alibaba.fastjson.JSON; import com.atguigu.gmall.item.service.ItemService; import com.atguigu.gmall.list.client.ListFeignClient; import com.atguigu.gmall.model.product.BaseCategoryView; import com.atguigu.gmall.model.product.SkuInfo; import com.atguigu.gmall.model.product.SpuSaleAttr; import com.atguigu.gmall.product.client.ProductFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadPoolExecutor; @Service public class ItemServiceImpl implements ItemService { @Autowired private ProductFeignClient productFeignClient; @Autowired private ListFeignClient listFeignClient; @Autowired private ThreadPoolExecutor threadPoolExecutor; @Override public Map<String, Object> getBySkuId(Long skuId) { Map<String, Object> result = new HashMap<>(); //通过skuId查询skuInfo CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(()->{ SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId); //保存skuInfo result.put("skuInfo",skuInfo); return skuInfo; },threadPoolExecutor); //获取商品分类 CompletableFuture<Void> categoryViewCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> { BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id()); //保存商品分类数据 result.put("categoryView",categoryView); },threadPoolExecutor); //获取商品最新价格 //获取商品最新价格 CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(() -> { BigDecimal skuPrice = productFeignClient.getSkuPrice(skuId); result.put("price", skuPrice); },threadPoolExecutor); //销售属性-销售属性值回显并锁定 CompletableFuture<Void> spuSaleAttrCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> { List<SpuSaleAttr> spuSaleAttrList = productFeignClient.getSpuSaleAttrListCheckBySku(skuInfo.getId(), skuInfo.getSpuId()); //保存数据 result.put("spuSaleAttrList",spuSaleAttrList); },threadPoolExecutor); //根据spuId查询map集合属性 CompletableFuture<Void> skuValueIdsMapCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo ->{ Map skuValueIdsMap = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId()); //保存json字符串 String mapJson = JSON.toJSONString(skuValueIdsMap); System.out.println("mapJson = " + mapJson); //保存valuesSkuJson result.put("valuesSkuJson",mapJson); },threadPoolExecutor); //更新商品incrHotScore CompletableFuture<Void> incrHotScoreCompletableFuture = CompletableFuture.runAsync(() -> { listFeignClient.incrHotScore(skuId); },threadPoolExecutor); //任务组合 CompletableFuture.allOf( skuInfoCompletableFuture, spuSaleAttrCompletableFuture, skuValueIdsMapCompletableFuture, skuPriceCompletableFuture, categoryViewCompletableFuture, incrHotScoreCompletableFuture).join(); return result; } }
3,649
0.701574
0.701288
93
36.580647
30.790421
133
false
false
0
0
0
0
0
0
0.655914
false
false
15
8130293508f3076ff0f234efda49392fa29c9159
9,990,093,989,393
20f34fbe1b99c5d3741ac940cfb95e70a137f49a
/src/main/java/bram/pobquiz/quiz/questionHandler/RemoveAboveCorrectQuestion.java
06b1d47c81a09b5ba47f19e66900be8d7d6d48ba
[]
no_license
termeneder/pobquiz
https://github.com/termeneder/pobquiz
3571718d5734798d9e7dde3966fb44a7f86900a7
559f14fd812dc495572b74e9d988f1b005de32ae
refs/heads/master
2016-09-05T19:11:56.581000
2015-12-18T15:08:55
2015-12-18T15:08:55
25,693,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bram.pobquiz.quiz.questionHandler; import bram.pobquiz.question.QuestionStats; import bram.pobquiz.quiz.Quiz; public class RemoveAboveCorrectQuestion implements AskedQuestionHandler { private Quiz c_quiz; private int c_correctGoal; public RemoveAboveCorrectQuestion(Quiz quiz, int correctGoal) { c_quiz = quiz; c_correctGoal = correctGoal; } @Override public void handleCorrectQuestion(QuestionStats question) { if (question.getTimesCorrect() >= c_correctGoal) { c_quiz.getQuestionList().removeQuestion(question); } } @Override public void handleIncorrectQuestion(QuestionStats question) { } }
UTF-8
Java
637
java
RemoveAboveCorrectQuestion.java
Java
[]
null
[]
package bram.pobquiz.quiz.questionHandler; import bram.pobquiz.question.QuestionStats; import bram.pobquiz.quiz.Quiz; public class RemoveAboveCorrectQuestion implements AskedQuestionHandler { private Quiz c_quiz; private int c_correctGoal; public RemoveAboveCorrectQuestion(Quiz quiz, int correctGoal) { c_quiz = quiz; c_correctGoal = correctGoal; } @Override public void handleCorrectQuestion(QuestionStats question) { if (question.getTimesCorrect() >= c_correctGoal) { c_quiz.getQuestionList().removeQuestion(question); } } @Override public void handleIncorrectQuestion(QuestionStats question) { } }
637
0.77237
0.77237
30
20.233334
23.921654
73
false
false
0
0
0
0
0
0
1.133333
false
false
15
144b15a105fa2adda354ed30409da0cd4813a1db
30,932,354,532,116
14f8d6e997cc748ce4f3dbaec43087cc177d5e2a
/src/main/java/xmlns/www_fortifysoftware_com/schema/wstypes/OptionallyNumericFilterCondition.java
fe0674edb8061cda39e657a9ea0d2ed5fc053c8f
[]
no_license
dgageot/Soap
https://github.com/dgageot/Soap
5f08c8aff017612ca82051fcba5e0e8f7d23b585
5e0778e0a802d48a4b4adc776e845294ad6a64bb
refs/heads/master
2020-05-17T07:53:43.414000
2012-08-07T08:09:21
2012-08-07T08:12:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xmlns.www_fortifysoftware_com.schema.wstypes; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p>Java class for OptionallyNumericFilterCondition complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OptionallyNumericFilterCondition"> * &lt;complexContent> * &lt;extension base="{xmlns://www.fortifysoftware.com/schema/wsTypes}SinglePropertyFilterCondition"> * &lt;attribute name="numeric" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OptionallyNumericFilterCondition") @XmlSeeAlso({ BetweenSearchCondition.class, GtSearchCondition.class, LtSearchCondition.class }) public class OptionallyNumericFilterCondition extends SinglePropertyFilterCondition { @XmlAttribute protected Boolean numeric; /** * Default no-arg constructor * */ public OptionallyNumericFilterCondition() { super(); } /** * Fully-initialising value constructor * */ public OptionallyNumericFilterCondition(final String searchConstant, final String stringCondition, final Boolean booleanCondition, final XMLGregorianCalendar dateCondition, final Long numberCondition, final EnumSpec enumCondition, final Boolean numeric) { super(searchConstant, stringCondition, booleanCondition, dateCondition, numberCondition, enumCondition); this.numeric = numeric; } /** * Gets the value of the numeric property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNumeric() { return numeric; } /** * Sets the value of the numeric property. * * @param value * allowed object is * {@link Boolean } * */ public void setNumeric(Boolean value) { this.numeric = value; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } public OptionallyNumericFilterCondition withNumeric(Boolean value) { setNumeric(value); return this; } @Override public OptionallyNumericFilterCondition withStringCondition(String value) { setStringCondition(value); return this; } @Override public OptionallyNumericFilterCondition withBooleanCondition(Boolean value) { setBooleanCondition(value); return this; } @Override public OptionallyNumericFilterCondition withDateCondition(XMLGregorianCalendar value) { setDateCondition(value); return this; } @Override public OptionallyNumericFilterCondition withNumberCondition(Long value) { setNumberCondition(value); return this; } @Override public OptionallyNumericFilterCondition withEnumCondition(EnumSpec value) { setEnumCondition(value); return this; } @Override public OptionallyNumericFilterCondition withSearchConstant(String value) { setSearchConstant(value); return this; } }
UTF-8
Java
3,974
java
OptionallyNumericFilterCondition.java
Java
[]
null
[]
package xmlns.www_fortifysoftware_com.schema.wstypes; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p>Java class for OptionallyNumericFilterCondition complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OptionallyNumericFilterCondition"> * &lt;complexContent> * &lt;extension base="{xmlns://www.fortifysoftware.com/schema/wsTypes}SinglePropertyFilterCondition"> * &lt;attribute name="numeric" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OptionallyNumericFilterCondition") @XmlSeeAlso({ BetweenSearchCondition.class, GtSearchCondition.class, LtSearchCondition.class }) public class OptionallyNumericFilterCondition extends SinglePropertyFilterCondition { @XmlAttribute protected Boolean numeric; /** * Default no-arg constructor * */ public OptionallyNumericFilterCondition() { super(); } /** * Fully-initialising value constructor * */ public OptionallyNumericFilterCondition(final String searchConstant, final String stringCondition, final Boolean booleanCondition, final XMLGregorianCalendar dateCondition, final Long numberCondition, final EnumSpec enumCondition, final Boolean numeric) { super(searchConstant, stringCondition, booleanCondition, dateCondition, numberCondition, enumCondition); this.numeric = numeric; } /** * Gets the value of the numeric property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNumeric() { return numeric; } /** * Sets the value of the numeric property. * * @param value * allowed object is * {@link Boolean } * */ public void setNumeric(Boolean value) { this.numeric = value; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } public OptionallyNumericFilterCondition withNumeric(Boolean value) { setNumeric(value); return this; } @Override public OptionallyNumericFilterCondition withStringCondition(String value) { setStringCondition(value); return this; } @Override public OptionallyNumericFilterCondition withBooleanCondition(Boolean value) { setBooleanCondition(value); return this; } @Override public OptionallyNumericFilterCondition withDateCondition(XMLGregorianCalendar value) { setDateCondition(value); return this; } @Override public OptionallyNumericFilterCondition withNumberCondition(Long value) { setNumberCondition(value); return this; } @Override public OptionallyNumericFilterCondition withEnumCondition(EnumSpec value) { setEnumCondition(value); return this; } @Override public OptionallyNumericFilterCondition withSearchConstant(String value) { setSearchConstant(value); return this; } }
3,974
0.697282
0.696024
143
26.783216
32.113903
259
false
false
0
0
0
0
0
0
0.391608
false
false
15
a646c9e3c5b4c7decdfe67fcbc34259d720e8efb
12,378,095,815,629
8c68e905a5bd3bfcec3a703fa9ac4c11a8e77206
/source/CAWL_1_0/org/sspl/parser/SharedInputStream.java
60b404454b4659ba91f1fc5ec27738f9b3757793
[]
no_license
quetzal680/cawl
https://github.com/quetzal680/cawl
7a27e4fa8bc2eea1b73ae358a532dc8e4843a2b7
b6aaaa3969b09af9bdcce001ca699ee71521e181
refs/heads/master
2021-01-10T04:50:52.085000
2011-12-12T05:15:03
2011-12-12T05:15:03
48,973,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on 2005. 1. 10 */ package org.sspl.parser; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; /** * @author Delios */ public class SharedInputStream extends InputStream { private final InputStream inputStream; private int c; private int line = 1, column = 1; public SharedInputStream(InputStream inputStream) { if (!inputStream.markSupported()) { this.inputStream = new BufferedInputStream(inputStream); } else { this.inputStream = inputStream; } } // overrides methods of InputStream @Override public void mark(int readAheadLimit) { inputStream.mark(readAheadLimit); } @Override public int read() throws IOException { int c = inputStream.read(); // 한 바이트를 읽음 column++; // column 1 증가 return c; // 읽은 바이트 리턴 } @Override public void reset() throws IOException { inputStream.reset(); } @Override public int available() throws IOException { return inputStream.available(); } @Override public void close() throws IOException { inputStream.close(); } @Override public boolean markSupported() { return inputStream.markSupported(); } // public void advance() throws IOException { c = read(); } public int current() { return c; } public int getLine() { return line; } public int getColumn() { return column; } public void newline() { line++; column = 1; } }
UTF-8
Java
1,793
java
SharedInputStream.java
Java
[ { "context": "n;\r\nimport java.io.InputStream;\r\n\r\n/**\r\n * @author Delios\r\n */\r\npublic class SharedInputStream extends InputS", "end": 183, "score": 0.8503144383430481, "start": 177, "tag": "NAME", "value": "Delios" } ]
null
[]
/* * Created on 2005. 1. 10 */ package org.sspl.parser; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; /** * @author Delios */ public class SharedInputStream extends InputStream { private final InputStream inputStream; private int c; private int line = 1, column = 1; public SharedInputStream(InputStream inputStream) { if (!inputStream.markSupported()) { this.inputStream = new BufferedInputStream(inputStream); } else { this.inputStream = inputStream; } } // overrides methods of InputStream @Override public void mark(int readAheadLimit) { inputStream.mark(readAheadLimit); } @Override public int read() throws IOException { int c = inputStream.read(); // 한 바이트를 읽음 column++; // column 1 증가 return c; // 읽은 바이트 리턴 } @Override public void reset() throws IOException { inputStream.reset(); } @Override public int available() throws IOException { return inputStream.available(); } @Override public void close() throws IOException { inputStream.close(); } @Override public boolean markSupported() { return inputStream.markSupported(); } // public void advance() throws IOException { c = read(); } public int current() { return c; } public int getLine() { return line; } public int getColumn() { return column; } public void newline() { line++; column = 1; } }
1,793
0.549688
0.543441
83
19.216867
17.104954
68
false
false
0
0
0
0
0
0
0.493976
false
false
15
df041f5ee4148d472a8abf9372f164efbbb9829f
22,617,297,846,266
414ee2a0337a9fb243f55a7d3cb2e8844c017a58
/src/main/java/com/fajar/wsclient/dto/MessageMapper.java
ff802a0fa9a0dc06eb63f9ff5b6bc8ed7f04ab3b
[]
no_license
fajaralmu/java-gui-websocket-client
https://github.com/fajaralmu/java-gui-websocket-client
9a93762ef6f4816b4386d7f99fe72f182ef9ffa5
97689aee5fc3a07e44160d0e0081b4f62ba9a8ee
refs/heads/master
2022-12-11T20:43:19.546000
2020-08-26T05:39:40
2020-08-26T05:39:40
289,448,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fajar.wsclient.dto; import java.util.Date; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class MessageMapper { public final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public static Message getMessage(String json) { try { return OBJECT_MAPPER.readValue(json, Message.class); } catch (Exception e) { System.out.println("NOT A DTO MSG"); return null; } } public static String messageAsString(Message msg) { try { return OBJECT_MAPPER.writeValueAsString(msg); } catch (JsonProcessingException e) { System.out.println("messageAsString ERROR"); // e.printStackTrace(); return "{}"; } } public static String constructMessage(String id, String destination, String msg) { Message message = new Message(destination, id, msg, new Date()); return messageAsString(message); } static final String EXAMPLE_RAW_MSG = "a[\"MESSAGE\\ndestination:/wsResp/chats/184166bd-1c19-48a0-a195-4cee810c8b66\\ncontent-type:application/json;charset=UTF-8\\nsubscription:sub-0\\nmessage-id:184166bd-1c19-48a0-a195-4cee810c8b66-10\\ncontent-length:145\\n\\n{\\\"messageTo\\\":\\\"184166bd-1c19-48a0-a195-4cee810c8b66\\\",\\\"messageFrom\\\":\\\"afaf410b-7ed5-4f8e-8011-a4fead733fd0\\\",\\\"message\\\":\\\"sdsdsd\\\",\\\"date\\\":1598144649057}\\u0000\"]"; public static void main(String[] args) throws Exception { parseSockJsResponse(EXAMPLE_RAW_MSG); } //a["MESSAGE\ndestination:/wsResp/chats/184166bd-1c19-48a0-a195-4cee810c8b66\ncontent-type:application/json;charset=UTF-8\nsubscription:sub-0\nmessage-id:184166bd-1c19-48a0-a195-4cee810c8b66-10\ncontent-length:145\n\n{\"messageTo\":\"184166bd-1c19-48a0-a195-4cee810c8b66\",\"messageFrom\":\"afaf410b-7ed5-4f8e-8011-a4fead733fd0\",\"message\":\"sdsdsd\",\"date\":1598144649057}\u0000"] public static Message parseSockJsResponse(String rawMessage) { Message message = new Message(); int firstCurlyBraces = rawMessage.indexOf("{"); rawMessage = rawMessage.substring(firstCurlyBraces, rawMessage.length()); rawMessage = rawMessage.replace("\\u0000\"]", ""); rawMessage = rawMessage.replace("\\\"", "\""); try { message = OBJECT_MAPPER.readValue(rawMessage, Message.class); } catch (Exception ex) { System.out.println("Error parsing message"); ex.printStackTrace(); } return message; } }
UTF-8
Java
2,634
java
MessageMapper.java
Java
[]
null
[]
package com.fajar.wsclient.dto; import java.util.Date; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class MessageMapper { public final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public static Message getMessage(String json) { try { return OBJECT_MAPPER.readValue(json, Message.class); } catch (Exception e) { System.out.println("NOT A DTO MSG"); return null; } } public static String messageAsString(Message msg) { try { return OBJECT_MAPPER.writeValueAsString(msg); } catch (JsonProcessingException e) { System.out.println("messageAsString ERROR"); // e.printStackTrace(); return "{}"; } } public static String constructMessage(String id, String destination, String msg) { Message message = new Message(destination, id, msg, new Date()); return messageAsString(message); } static final String EXAMPLE_RAW_MSG = "a[\"MESSAGE\\ndestination:/wsResp/chats/184166bd-1c19-48a0-a195-4cee810c8b66\\ncontent-type:application/json;charset=UTF-8\\nsubscription:sub-0\\nmessage-id:184166bd-1c19-48a0-a195-4cee810c8b66-10\\ncontent-length:145\\n\\n{\\\"messageTo\\\":\\\"184166bd-1c19-48a0-a195-4cee810c8b66\\\",\\\"messageFrom\\\":\\\"afaf410b-7ed5-4f8e-8011-a4fead733fd0\\\",\\\"message\\\":\\\"sdsdsd\\\",\\\"date\\\":1598144649057}\\u0000\"]"; public static void main(String[] args) throws Exception { parseSockJsResponse(EXAMPLE_RAW_MSG); } //a["MESSAGE\ndestination:/wsResp/chats/184166bd-1c19-48a0-a195-4cee810c8b66\ncontent-type:application/json;charset=UTF-8\nsubscription:sub-0\nmessage-id:184166bd-1c19-48a0-a195-4cee810c8b66-10\ncontent-length:145\n\n{\"messageTo\":\"184166bd-1c19-48a0-a195-4cee810c8b66\",\"messageFrom\":\"afaf410b-7ed5-4f8e-8011-a4fead733fd0\",\"message\":\"sdsdsd\",\"date\":1598144649057}\u0000"] public static Message parseSockJsResponse(String rawMessage) { Message message = new Message(); int firstCurlyBraces = rawMessage.indexOf("{"); rawMessage = rawMessage.substring(firstCurlyBraces, rawMessage.length()); rawMessage = rawMessage.replace("\\u0000\"]", ""); rawMessage = rawMessage.replace("\\\"", "\""); try { message = OBJECT_MAPPER.readValue(rawMessage, Message.class); } catch (Exception ex) { System.out.println("Error parsing message"); ex.printStackTrace(); } return message; } }
2,634
0.66325
0.581245
63
40.809525
74.818481
465
false
false
0
0
0
0
0
0
0.68254
false
false
15
a526b04864867cbe72a9068c1e1c907ffa67171d
25,975,962,261,135
e9a3c4d4ae9398d94a88853cbe0c2d882cc476bc
/app/src/main/java/com/yym/demo/activity/bottomsheet/IBottomSheetMVP.java
af9442b1386d53f1365b185366d7bf1939b9c706
[]
no_license
luoyemyy/AndroidDemo
https://github.com/luoyemyy/AndroidDemo
fca3db4d5b49e5501d0c1bac4557d31a3085c823
c00f0cb10d9080446c7c6d5e2b06bc71f044fc90
refs/heads/master
2017-12-01T06:45:29.547000
2016-07-21T05:47:28
2016-07-21T05:47:28
63,406,001
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yym.demo.activity.bottomsheet; import com.yym.demo.activity.base.IBasePresenter; import com.yym.demo.activity.base.IBaseView; /** * 2016.7.11 15:36 * yym */ public interface IBottomSheetMVP { interface IPresenter extends IBasePresenter { } interface IView extends IBaseView { } }
UTF-8
Java
318
java
IBottomSheetMVP.java
Java
[]
null
[]
package com.yym.demo.activity.bottomsheet; import com.yym.demo.activity.base.IBasePresenter; import com.yym.demo.activity.base.IBaseView; /** * 2016.7.11 15:36 * yym */ public interface IBottomSheetMVP { interface IPresenter extends IBasePresenter { } interface IView extends IBaseView { } }
318
0.720126
0.685535
20
14.9
18.93119
49
false
false
0
0
0
0
0
0
0.15
false
false
15
09274518faef5bd52381e703edc4f37693561bd8
10,075,993,337,711
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/validation/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest.java
694c24313977cf8b0902da641ada9fd0f90af418
[]
no_license
STAMP-project/dspot-experiments
https://github.com/STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919000
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
false
2023-01-26T23:57:41
2016-12-06T08:27:42
2022-02-18T17:43:31
2023-01-26T23:57:40
651,434
12
14
5
null
false
false
package com.alibaba.json.bvt.parser.stream; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONReaderScanner; import junit.framework.TestCase; import org.junit.Assert; public class JSONReaderScannerTest extends TestCase { public void test_singleQuote() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\'name\':\'\u5f20\u4e09\\\'\\n\\r\\\"\'}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } public void test_doubleQuote() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"name\":\"\u5f20\u4e09\\\'\\n\\r\\\"\"}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } public void test_doubleQuote_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{name:\"\u5f20\u4e09\\\'\\n\\r\\\"\"}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } }
UTF-8
Java
1,298
java
JSONReaderScannerTest.java
Java
[]
null
[]
package com.alibaba.json.bvt.parser.stream; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONReaderScanner; import junit.framework.TestCase; import org.junit.Assert; public class JSONReaderScannerTest extends TestCase { public void test_singleQuote() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\'name\':\'\u5f20\u4e09\\\'\\n\\r\\\"\'}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } public void test_doubleQuote() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"name\":\"\u5f20\u4e09\\\'\\n\\r\\\"\"}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } public void test_doubleQuote_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{name:\"\u5f20\u4e09\\\'\\n\\r\\\"\"}")); JSONObject json = parser.parseObject(); Assert.assertEquals("\u5f20\u4e09\'\n\r\"", json.get("name")); parser.close(); } }
1,298
0.66718
0.638675
32
39.53125
35.756977
125
false
false
0
0
0
0
0
0
0.65625
false
false
15
541f143f07dda62f2ca5ca3ec4ed729c43e11dbc
9,637,906,614,517
070fdf9e6bb5d1d4cbd81e4c8e7ed6e4f1fef5e9
/src/main/java/com/megaeyes/persistence/ibatis/iface/PlatformSubscribeDAO.java
20f29bf0e475f06693474037d8f6e1be8762a538
[]
no_license
github188/interface
https://github.com/github188/interface
342e5447239eb4c733295150d44b7f213419ac75
81269dcb2c707d545f5b178727503bb638f5e446
refs/heads/master
2020-01-23T22:00:12.025000
2016-01-25T06:39:36
2016-01-25T06:39:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.megaeyes.persistence.ibatis.iface; import com.megaeyes.persistence.ibatis.model.PlatformSubscribe; import com.megaeyes.persistence.ibatis.model.PlatformSubscribeExample; import java.util.List; public interface PlatformSubscribeDAO { /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ void insert(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int updateByPrimaryKey(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int updateByPrimaryKeySelective(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ List selectByExample(PlatformSubscribeExample example); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ PlatformSubscribe selectByPrimaryKey(String id); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int deleteByExample(PlatformSubscribeExample example); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int deleteByPrimaryKey(String id); }
UTF-8
Java
2,046
java
PlatformSubscribeDAO.java
Java
[]
null
[]
package com.megaeyes.persistence.ibatis.iface; import com.megaeyes.persistence.ibatis.model.PlatformSubscribe; import com.megaeyes.persistence.ibatis.model.PlatformSubscribeExample; import java.util.List; public interface PlatformSubscribeDAO { /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ void insert(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int updateByPrimaryKey(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int updateByPrimaryKeySelective(PlatformSubscribe record); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ List selectByExample(PlatformSubscribeExample example); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ PlatformSubscribe selectByPrimaryKey(String id); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int deleteByExample(PlatformSubscribeExample example); /** * This method was generated by Abator for iBATIS. * This method corresponds to the database table PLATFORM_SUBSCRIBE * * @abatorgenerated Thu May 03 09:55:50 CST 2012 */ int deleteByPrimaryKey(String id); }
2,046
0.698925
0.657869
63
31.492064
26.869982
71
false
false
0
0
0
0
0
0
0.174603
false
false
15
39de3bf3f0888cecd05804d7a977eb055f1555ad
26,285,199,895,452
db9f4e5a65826f8f2b3485535e7505c588f65077
/app/src/main/java/com/example/voipapp/MainActivity.java
50c32e6e6fee7d34f4e78b23848c2cc3d18d5580
[]
no_license
ibrahim-iqbal/VoIP_App
https://github.com/ibrahim-iqbal/VoIP_App
c202c340004755ae1bde885950a74545c42dcd0d
6855fc78b66d7d31ae32e5ec24995a9f042ca634
refs/heads/master
2020-12-27T15:36:26.523000
2020-02-03T13:11:58
2020-02-03T13:11:58
237,954,560
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.voipapp; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView wel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wel = findViewById(R.id.wel); wel.animate().scaleX(1.2f).scaleY(1.2f).alpha(1).setDuration(2000); Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { Intent it = new Intent(MainActivity.this, LoginActivity.class); startActivity(it); finish(); } }, 4000); } }
UTF-8
Java
966
java
MainActivity.java
Java
[]
null
[]
package com.example.voipapp; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView wel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wel = findViewById(R.id.wel); wel.animate().scaleX(1.2f).scaleY(1.2f).alpha(1).setDuration(2000); Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { Intent it = new Intent(MainActivity.this, LoginActivity.class); startActivity(it); finish(); } }, 4000); } }
966
0.641822
0.628364
36
25.833334
20.5149
79
false
false
0
0
0
0
0
0
0.555556
false
false
15
d7709f891fb2bbc58603f257f25bdeccb85b35ce
23,476,291,286,334
d3581c644636e56d0b7ab9999fb261bd38fb45a1
/src/main/java/com/IRonak/MyTodo/Controller/TodoController.java
6a928d652c365c602f74679bc91805ce946a1c8f
[]
no_license
RkColmark/MyTodo
https://github.com/RkColmark/MyTodo
2648f52dfa7e74f9273aded4fe3f910f727adabb
b8bd3e5d02c904db248e0168fc2f9949f33d7c72
refs/heads/master
2023-03-16T05:28:18.938000
2021-03-05T18:19:48
2021-03-05T18:19:48
344,803,714
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.IRonak.MyTodo.Controller; import com.IRonak.MyTodo.Entity.Todo; import com.IRonak.MyTodo.Service.ITodoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class TodoController { @Autowired private ITodoService todoService; @InitBinder public void initBinder(WebDataBinder binder) { // Date - dd/MM/yyyy SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } /* @GetMapping("/hello") public String Hello() { return "welcome"; }*/ @GetMapping("/") public String showWelcomePage(ModelMap model) { model.put("name", getLoggedinUserName()); return "welcome"; } @GetMapping("/list") public String showTodos(ModelMap model) { String name = getLoggedInUserName(model); model.put("todos", todoService.getTodosByUser(name)); return "list"; } private String getLoggedinUserName() { Object principal = SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } return principal.toString(); } private String getLoggedInUserName(ModelMap model) { Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(principle instanceof UserDetails) { return ((UserDetails) principle).getUsername(); } return principle.toString(); } @GetMapping("/add") public String showAddTodoPage(ModelMap model) { Todo todo =new Todo(); model.addAttribute("todo",todo); return "todo"; } @GetMapping("/delete") public String deleteTodo(@RequestParam int id) { todoService.deleteTodo(id); return "redirect:/list"; } @GetMapping("/showupdate") public String showTodoPage(@RequestParam int id , ModelMap model) { Todo todo = todoService.getTodoById(id).get(); model.put("todo",todo); return "todo"; } @PostMapping("/update") public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUser(getLoggedInUserName(model)); todoService.updateTodo(todo); return "redirect:/list"; } @PostMapping("/save") public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUser(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list"; } }
UTF-8
Java
3,451
java
TodoController.java
Java
[]
null
[]
package com.IRonak.MyTodo.Controller; import com.IRonak.MyTodo.Entity.Todo; import com.IRonak.MyTodo.Service.ITodoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class TodoController { @Autowired private ITodoService todoService; @InitBinder public void initBinder(WebDataBinder binder) { // Date - dd/MM/yyyy SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } /* @GetMapping("/hello") public String Hello() { return "welcome"; }*/ @GetMapping("/") public String showWelcomePage(ModelMap model) { model.put("name", getLoggedinUserName()); return "welcome"; } @GetMapping("/list") public String showTodos(ModelMap model) { String name = getLoggedInUserName(model); model.put("todos", todoService.getTodosByUser(name)); return "list"; } private String getLoggedinUserName() { Object principal = SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } return principal.toString(); } private String getLoggedInUserName(ModelMap model) { Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(principle instanceof UserDetails) { return ((UserDetails) principle).getUsername(); } return principle.toString(); } @GetMapping("/add") public String showAddTodoPage(ModelMap model) { Todo todo =new Todo(); model.addAttribute("todo",todo); return "todo"; } @GetMapping("/delete") public String deleteTodo(@RequestParam int id) { todoService.deleteTodo(id); return "redirect:/list"; } @GetMapping("/showupdate") public String showTodoPage(@RequestParam int id , ModelMap model) { Todo todo = todoService.getTodoById(id).get(); model.put("todo",todo); return "todo"; } @PostMapping("/update") public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUser(getLoggedInUserName(model)); todoService.updateTodo(todo); return "redirect:/list"; } @PostMapping("/save") public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUser(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list"; } }
3,451
0.666763
0.666763
139
23.827337
23.246235
97
false
false
0
0
0
0
0
0
0.654676
false
false
15
78d1f8c04b9f05a57330e030ee6a6c142062ba66
5,738,076,357,500
044b1394176c4f0ec90b1565ea848f49c6651d91
/src/main/java/com/example/springaop/service/LoginService.java
7da218035cd7de13a05a7845ffff3d393733544c
[]
no_license
AliceHuJie/spring-aop
https://github.com/AliceHuJie/spring-aop
d7a57d8d89a0dca4f548012bed9f073d4e5b046b
9844b47d8ab885d31d2c9a6da57195762eb8fc09
refs/heads/master
2022-05-07T10:30:03.973000
2020-02-04T14:38:47
2020-02-04T14:38:47
238,217,589
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.springaop.service; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Service public class LoginService { public void login(String name, HttpServletResponse resp) throws IOException { resp.getWriter().write("hello " + name); } }
UTF-8
Java
341
java
LoginService.java
Java
[]
null
[]
package com.example.springaop.service; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Service public class LoginService { public void login(String name, HttpServletResponse resp) throws IOException { resp.getWriter().write("hello " + name); } }
341
0.762463
0.762463
14
23.357143
24.569456
81
false
false
0
0
0
0
0
0
0.428571
false
false
15
620026de3e07f1bb693fe3fd51b01d1f4af6ea2d
32,203,664,833,644
37979b4c6dfef3aa7da03f721fb1ccc2f86536e5
/src/main/java/xcc/leetcode/permutation/PermutationsII.java
e774f9c40e0a19b51df63e9663a312600a7eaf6a
[]
no_license
xiaochenchen/leetcode-onlinejudge
https://github.com/xiaochenchen/leetcode-onlinejudge
f30cec1bc45863c1309a23414e2a59611de69850
5b55ab3608af36a45588d58c3d084eabfe2b8ce1
refs/heads/master
2021-03-12T22:17:48.207000
2014-04-06T22:48:56
2014-04-06T22:48:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xcc.leetcode.permutation; import java.util.ArrayList; import java.util.Arrays; /** * Given a collection of numbers that might contain duplicates, return all possible unique permutations. * * For example, * [1,1,2] have the following unique permutations: * [1,1,2], [1,2,1], and [2,1,1]. * * Created by lightsaber on 4/1/14. */ public class PermutationsII { public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> result = new ArrayList<Integer>(); boolean[] visited = new boolean[num.length]; Arrays.sort(num); generate(num, results, result, visited); return results; } public void generate(int[] num, ArrayList<ArrayList<Integer>> results, ArrayList<Integer> result, boolean[] visited) { // found a valid result if(result.size() == num.length) { results.add(new ArrayList<Integer>(result)); return; } for(int i = 0; i < num.length; ++i) { if(i > 0 && num[i] == num[i - 1] && visited[i - 1] == false) continue; if(!visited[i]) { result.add(num[i]); visited[i] = true; generate(num, results, result, visited); result.remove(result.size() - 1); visited[i] = false; } } } }
UTF-8
Java
1,481
java
PermutationsII.java
Java
[ { "context": " * [1,1,2], [1,2,1], and [2,1,1].\n *\n * Created by lightsaber on 4/1/14.\n */\npublic class PermutationsII\n{\n ", "end": 329, "score": 0.9995948672294617, "start": 319, "tag": "USERNAME", "value": "lightsaber" } ]
null
[]
package xcc.leetcode.permutation; import java.util.ArrayList; import java.util.Arrays; /** * Given a collection of numbers that might contain duplicates, return all possible unique permutations. * * For example, * [1,1,2] have the following unique permutations: * [1,1,2], [1,2,1], and [2,1,1]. * * Created by lightsaber on 4/1/14. */ public class PermutationsII { public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> result = new ArrayList<Integer>(); boolean[] visited = new boolean[num.length]; Arrays.sort(num); generate(num, results, result, visited); return results; } public void generate(int[] num, ArrayList<ArrayList<Integer>> results, ArrayList<Integer> result, boolean[] visited) { // found a valid result if(result.size() == num.length) { results.add(new ArrayList<Integer>(result)); return; } for(int i = 0; i < num.length; ++i) { if(i > 0 && num[i] == num[i - 1] && visited[i - 1] == false) continue; if(!visited[i]) { result.add(num[i]); visited[i] = true; generate(num, results, result, visited); result.remove(result.size() - 1); visited[i] = false; } } } }
1,481
0.563808
0.549629
55
25.927273
27.8906
120
false
false
0
0
0
0
0
0
0.727273
false
false
15
fc0ef76d94c154473768b1c17e9c4e3d9fedbbdc
13,572,096,725,982
8775c52189d0adf87f6b8d1acfd0ac294bec4865
/src/java/SignUpCheckServlet.java
bf03b5fe5b54106ff65d4e4891311cce4a669643
[]
no_license
harsh7809/Childhood
https://github.com/harsh7809/Childhood
726915e1a857c665cf98ea7ba2f7cbc4038016da
2c0beeee26ce0f43aee2c26095b6c52f4c50c7cc
refs/heads/master
2020-03-26T20:22:41.208000
2018-08-19T16:08:44
2018-08-19T16:08:44
145,320,364
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.json.JSONArray; public class SignUpCheckServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html;charset=UTF-8"); Context co=new InitialContext(); String resourceName = "java:comp/env/" + "jdbc/childhood"; DataSource ds=(DataSource)co.lookup(resourceName); Connection c=ds.getConnection(); if(c==null) { System.out.println("No connection found...."); } else { ArrayList<String> arr=new ArrayList(); System.out.println("No connection found.2221.."); String phone=request.getParameter("phone"); String query="select phone from users where phone=?"; //System.out.println("...."+query); PreparedStatement ps=c.prepareStatement(query); ps.setString(1,phone); System.out.println("Data successfully got...."+query); ResultSet rs=ps.executeQuery(); if(rs.next()) { arr.add("Yes"); JSONArray ar=new JSONArray(arr); PrintWriter write=response.getWriter(); write.write(ar.toString()); System.out.println("Data successfully got...."+ar.toString()); }//end of if........ else { arr.add("No"); JSONArray ar=new JSONArray(arr); PrintWriter write=response.getWriter(); write.write(ar.toString()); System.out.println("Data successfully got...."+ar.toString()); }//end of else.... ps.close(); }//end of else.... }//end of try catch(Exception e) { }//end of catch.... }//end of service()..... }//end of class...
UTF-8
Java
2,548
java
SignUpCheckServlet.java
Java
[]
null
[]
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.json.JSONArray; public class SignUpCheckServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html;charset=UTF-8"); Context co=new InitialContext(); String resourceName = "java:comp/env/" + "jdbc/childhood"; DataSource ds=(DataSource)co.lookup(resourceName); Connection c=ds.getConnection(); if(c==null) { System.out.println("No connection found...."); } else { ArrayList<String> arr=new ArrayList(); System.out.println("No connection found.2221.."); String phone=request.getParameter("phone"); String query="select phone from users where phone=?"; //System.out.println("...."+query); PreparedStatement ps=c.prepareStatement(query); ps.setString(1,phone); System.out.println("Data successfully got...."+query); ResultSet rs=ps.executeQuery(); if(rs.next()) { arr.add("Yes"); JSONArray ar=new JSONArray(arr); PrintWriter write=response.getWriter(); write.write(ar.toString()); System.out.println("Data successfully got...."+ar.toString()); }//end of if........ else { arr.add("No"); JSONArray ar=new JSONArray(arr); PrintWriter write=response.getWriter(); write.write(ar.toString()); System.out.println("Data successfully got...."+ar.toString()); }//end of else.... ps.close(); }//end of else.... }//end of try catch(Exception e) { }//end of catch.... }//end of service()..... }//end of class...
2,548
0.5573
0.554945
75
32.986668
20.025646
80
false
false
0
0
0
0
0
0
0.586667
false
false
15
de2e655b5da84327e02f836ed48880d0f0b9380d
31,009,663,927,508
eb3c1fa6f150fa22791f6f25e44321c1d9f1c7bd
/app/src/main/java/com/gy/listener/ui/recordsList/IImageHelper.java
cf45fae7f865dc3105e68b0f8735c2b779be856b
[]
no_license
Yairgadiel/ListenerAndroid
https://github.com/Yairgadiel/ListenerAndroid
7d815cfc4a8c52f5d85e1cdf1ced53ff3abdf93c
04f8a56dff4b5307defd71435a1e140efbd4dd9d
refs/heads/master
2023-06-25T13:29:18.957000
2021-07-28T03:41:17
2021-07-28T03:41:17
382,125,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gy.listener.ui.recordsList; import com.gy.listener.model.events.IOnCompleteListener; import com.gy.listener.model.events.IOnImageLoadedListener; import com.gy.listener.model.events.IOnImageUploadedListener; public interface IImageHelper { void pickImage(IOnImageUploadedListener listener); void loadImage(String path, IOnImageLoadedListener listener); void deleteImage(String name, IOnCompleteListener listener); }
UTF-8
Java
444
java
IImageHelper.java
Java
[]
null
[]
package com.gy.listener.ui.recordsList; import com.gy.listener.model.events.IOnCompleteListener; import com.gy.listener.model.events.IOnImageLoadedListener; import com.gy.listener.model.events.IOnImageUploadedListener; public interface IImageHelper { void pickImage(IOnImageUploadedListener listener); void loadImage(String path, IOnImageLoadedListener listener); void deleteImage(String name, IOnCompleteListener listener); }
444
0.822072
0.822072
14
30.714285
27.839922
65
false
false
0
0
0
0
0
0
0.642857
false
false
15
ec99009cf9cfd993f7defeb66f3f694b3f93bd71
5,841,155,552,171
281b50d4d50d79ea5bf34dd83fc594ba73416703
/src/15 - 10/014-Longest Common Prefix.java
0bce3978a9686686d1b1ecfb97492208f4b2e7c5
[]
no_license
lcl3356897/LeetCode-AHAHA
https://github.com/lcl3356897/LeetCode-AHAHA
14f5aa8286068133a1adaf67ad2c5067eb4216dd
fa59d2107a63c20973a2270b16f27aba0ca082a4
refs/heads/master
2016-09-06T16:47:30.952000
2015-11-03T16:23:11
2015-11-03T16:23:11
39,365,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0){ return ""; } StringBuffer rst = new StringBuffer(); for(int i=0;i<strs[0].length;i++){ for(int k=1;k<strs.length;k++){ if(i >= strs[k].length() || strs[k].charAt(i) != strs[0].charAt(i)){ return rst.toString(); } } rst.add(strs[0].charAt(i)); } return rst.toString(); } }
UTF-8
Java
507
java
014-Longest Common Prefix.java
Java
[]
null
[]
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0){ return ""; } StringBuffer rst = new StringBuffer(); for(int i=0;i<strs[0].length;i++){ for(int k=1;k<strs.length;k++){ if(i >= strs[k].length() || strs[k].charAt(i) != strs[0].charAt(i)){ return rst.toString(); } } rst.add(strs[0].charAt(i)); } return rst.toString(); } }
507
0.489152
0.477318
17
28.882353
20.157854
78
false
false
0
0
0
0
0
0
1.411765
false
false
15
59c7eb4836895d26dea6887c714fc420668f9632
5,841,155,549,496
89dfa6bf6545a3b59f4ef74360a9d16e3b87efc3
/Searching/RepeatingElement/Efficient.java
08e424386cee51dcf6e71432ce348d51401cf2d9
[]
no_license
peachmakerunderscore/DSA
https://github.com/peachmakerunderscore/DSA
6d4f5811aa25ef0c57d7ab4957946c5f3cb6be32
4e456246845102fd4271c12366aef4877760df96
refs/heads/main
2023-07-31T09:58:59.093000
2021-09-17T07:01:14
2021-09-17T07:01:14
406,716,426
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution { public static int repeating(int arr[]) { boolean visited[] = new boolean[arr.length]; for (int i = 0; i < arr.length; i++) { if (visited[arr[i]]) { return arr[i]; } visited[arr[i]] = true; } return -1; } public static void main(String args[]) { int arr[] = { 0, 2, 1, 3, 2, 2 }, n = 6; System.out.println(repeating(arr)); } }
UTF-8
Java
465
java
Efficient.java
Java
[]
null
[]
class Solution { public static int repeating(int arr[]) { boolean visited[] = new boolean[arr.length]; for (int i = 0; i < arr.length; i++) { if (visited[arr[i]]) { return arr[i]; } visited[arr[i]] = true; } return -1; } public static void main(String args[]) { int arr[] = { 0, 2, 1, 3, 2, 2 }, n = 6; System.out.println(repeating(arr)); } }
465
0.455914
0.436559
23
19.26087
19.195147
52
false
false
0
0
0
0
0
0
0.608696
false
false
15
2fd5106ee9369c9dace675a477db861066d7d5b4
12,335,146,075,765
b5186ee7df6d26df93ab046cd8ba845e7888e07c
/RaspiMediaCenter/src/raspimediacenter/GUI/Components/Video/InformationPanelGraphics.java
a5c01f03de20fb542921dff7efbda6715acd7ddc
[]
no_license
Aden-Herold/Raspi-Media-Center
https://github.com/Aden-Herold/Raspi-Media-Center
fb27096af063785c23d3c9349f72b79d55089789
71be8b9cf2c918a6c65d44224cccb6e6d7e646b8
refs/heads/master
2020-12-24T18:23:20.287000
2016-05-29T06:15:53
2016-05-29T06:15:53
56,566,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package raspimediacenter.GUI.Components.Video; import raspimediacenter.GUI.GUI; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.LinearGradientPaint; import java.awt.geom.Point2D; import raspimediacenter.GUI.SceneManager; import raspimediacenter.Logic.Utilities.ColorUtils; public class InformationPanelGraphics { private static double PANEL_SCEEN_PERCENT; private static int PANEL_HEIGHT; private final Color menuColor; public InformationPanelGraphics (double panelScreenPercent, int panelHeight) { PANEL_SCEEN_PERCENT = panelScreenPercent; PANEL_HEIGHT = panelHeight; menuColor = SceneManager.getMenuColor(); } public static double getPanelScreenPercent () { return PANEL_SCEEN_PERCENT; } public static int getPanelHeight() { return PANEL_HEIGHT; } public void createInformationPanel (Graphics2D paint) { paintListBaseCover(paint); paintBackPanel(paint); //paintInformationArea(paint); paintGradientShadow(paint); paintSeparator(paint); paintTopPanel(paint); } private void paintBackPanel(Graphics2D paint) { //Paint full back panel paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.1f)); paint.setPaint(ColorUtils.darken(menuColor, 1)); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), PANEL_HEIGHT); } private void paintInformationArea (Graphics2D paint) { //Paint information background area final Color[] informationPanelGradient = {ColorUtils.darken(menuColor, 1), new Color(0, 0, 0, 0)}; final float[] infoGradFractions = {0.95f, 1f}; LinearGradientPaint infoGrad = new LinearGradientPaint( new Point2D.Double(0, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(GUI.getScreenWidth()/2, GUI.getScreenHeight()-PANEL_HEIGHT), infoGradFractions, informationPanelGradient); paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.3f)); paint.setPaint(infoGrad); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth()/2, PANEL_HEIGHT); } private void paintGradientShadow (Graphics2D paint) { //Paint gradient sheen over back panel final Color[] sheenGradient = {new Color(255, 255, 255, 128), new Color(0,0,0,0), new Color(0,0,0,0), new Color(0, 0, 0)}; final float[] sheenGradFractions = {0f, 0.1f, 0.9f, 1f}; LinearGradientPaint sheenGrad = new LinearGradientPaint( new Point2D.Double(0, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(0, GUI.getScreenHeight()), sheenGradFractions, sheenGradient); paint.setComposite(AlphaComposite.SrcOver.derive(0.2f)); paint.setPaint(sheenGrad); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), PANEL_HEIGHT); } private void paintSeparator (Graphics2D paint) { //Paint separator line paint.setComposite(AlphaComposite.SrcOver.derive(1f)); paint.setColor(ColorUtils.darken(menuColor, 3)); paint.drawLine(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT); paint.drawLine(0, GUI.getScreenHeight()-PANEL_HEIGHT+1, GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT+1); } private void paintTopPanel (Graphics2D paint) { int height = (int)Math.floor(GUI.getScreenHeight()/15.1); final Color[] backgroundGradient = {ColorUtils.darken(menuColor, 1), new Color(0, 0, 0, 0)}; final float[] gradientFractions = {0.5f, 1f}; LinearGradientPaint panelGrad = new LinearGradientPaint( new Point2D.Double(0, 0), new Point2D.Double(400, 0), gradientFractions, backgroundGradient); paint.setPaint(panelGrad); paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.2f)); paint.fillRect(0, 0, 500, height); final Color[] separatorGradient = {ColorUtils.darken(menuColor, 3), new Color(0, 0, 0, 0)}; LinearGradientPaint separatorGrad = new LinearGradientPaint( new Point2D.Double(0, 0), new Point2D.Double(400, 0), gradientFractions, separatorGradient); paint.setPaint(separatorGrad); paint.setComposite(AlphaComposite.SrcOver.derive(1f)); paint.drawLine(0, height, 500, height); paint.drawLine(0, height-1, 500, height-1); } private void paintListBaseCover (Graphics2D paint) { final float[] gradientFractions = {0f, 0.3f}; final Color[] backgroundGradient = {new Color(0, 0, 0, 0), ColorUtils.darken(menuColor, 1)}; LinearGradientPaint menuGrad = new LinearGradientPaint( new Point2D.Double(GUI.getScreenWidth()-GUI.getScreenWidth()/4, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT), gradientFractions, backgroundGradient); paint.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); paint.setPaint(menuGrad); paint.fillRect(GUI.getScreenWidth()-GUI.getScreenWidth()/4, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth()/4, PANEL_HEIGHT); } }
UTF-8
Java
6,673
java
InformationPanelGraphics.java
Java
[]
null
[]
package raspimediacenter.GUI.Components.Video; import raspimediacenter.GUI.GUI; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.LinearGradientPaint; import java.awt.geom.Point2D; import raspimediacenter.GUI.SceneManager; import raspimediacenter.Logic.Utilities.ColorUtils; public class InformationPanelGraphics { private static double PANEL_SCEEN_PERCENT; private static int PANEL_HEIGHT; private final Color menuColor; public InformationPanelGraphics (double panelScreenPercent, int panelHeight) { PANEL_SCEEN_PERCENT = panelScreenPercent; PANEL_HEIGHT = panelHeight; menuColor = SceneManager.getMenuColor(); } public static double getPanelScreenPercent () { return PANEL_SCEEN_PERCENT; } public static int getPanelHeight() { return PANEL_HEIGHT; } public void createInformationPanel (Graphics2D paint) { paintListBaseCover(paint); paintBackPanel(paint); //paintInformationArea(paint); paintGradientShadow(paint); paintSeparator(paint); paintTopPanel(paint); } private void paintBackPanel(Graphics2D paint) { //Paint full back panel paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.1f)); paint.setPaint(ColorUtils.darken(menuColor, 1)); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), PANEL_HEIGHT); } private void paintInformationArea (Graphics2D paint) { //Paint information background area final Color[] informationPanelGradient = {ColorUtils.darken(menuColor, 1), new Color(0, 0, 0, 0)}; final float[] infoGradFractions = {0.95f, 1f}; LinearGradientPaint infoGrad = new LinearGradientPaint( new Point2D.Double(0, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(GUI.getScreenWidth()/2, GUI.getScreenHeight()-PANEL_HEIGHT), infoGradFractions, informationPanelGradient); paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.3f)); paint.setPaint(infoGrad); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth()/2, PANEL_HEIGHT); } private void paintGradientShadow (Graphics2D paint) { //Paint gradient sheen over back panel final Color[] sheenGradient = {new Color(255, 255, 255, 128), new Color(0,0,0,0), new Color(0,0,0,0), new Color(0, 0, 0)}; final float[] sheenGradFractions = {0f, 0.1f, 0.9f, 1f}; LinearGradientPaint sheenGrad = new LinearGradientPaint( new Point2D.Double(0, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(0, GUI.getScreenHeight()), sheenGradFractions, sheenGradient); paint.setComposite(AlphaComposite.SrcOver.derive(0.2f)); paint.setPaint(sheenGrad); paint.fillRect(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), PANEL_HEIGHT); } private void paintSeparator (Graphics2D paint) { //Paint separator line paint.setComposite(AlphaComposite.SrcOver.derive(1f)); paint.setColor(ColorUtils.darken(menuColor, 3)); paint.drawLine(0, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT); paint.drawLine(0, GUI.getScreenHeight()-PANEL_HEIGHT+1, GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT+1); } private void paintTopPanel (Graphics2D paint) { int height = (int)Math.floor(GUI.getScreenHeight()/15.1); final Color[] backgroundGradient = {ColorUtils.darken(menuColor, 1), new Color(0, 0, 0, 0)}; final float[] gradientFractions = {0.5f, 1f}; LinearGradientPaint panelGrad = new LinearGradientPaint( new Point2D.Double(0, 0), new Point2D.Double(400, 0), gradientFractions, backgroundGradient); paint.setPaint(panelGrad); paint.setComposite(AlphaComposite.SrcOver.derive(SceneManager.getMenuTransparency()-0.2f)); paint.fillRect(0, 0, 500, height); final Color[] separatorGradient = {ColorUtils.darken(menuColor, 3), new Color(0, 0, 0, 0)}; LinearGradientPaint separatorGrad = new LinearGradientPaint( new Point2D.Double(0, 0), new Point2D.Double(400, 0), gradientFractions, separatorGradient); paint.setPaint(separatorGrad); paint.setComposite(AlphaComposite.SrcOver.derive(1f)); paint.drawLine(0, height, 500, height); paint.drawLine(0, height-1, 500, height-1); } private void paintListBaseCover (Graphics2D paint) { final float[] gradientFractions = {0f, 0.3f}; final Color[] backgroundGradient = {new Color(0, 0, 0, 0), ColorUtils.darken(menuColor, 1)}; LinearGradientPaint menuGrad = new LinearGradientPaint( new Point2D.Double(GUI.getScreenWidth()-GUI.getScreenWidth()/4, GUI.getScreenHeight()-PANEL_HEIGHT), new Point2D.Double(GUI.getScreenWidth(), GUI.getScreenHeight()-PANEL_HEIGHT), gradientFractions, backgroundGradient); paint.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); paint.setPaint(menuGrad); paint.fillRect(GUI.getScreenWidth()-GUI.getScreenWidth()/4, GUI.getScreenHeight()-PANEL_HEIGHT, GUI.getScreenWidth()/4, PANEL_HEIGHT); } }
6,673
0.564064
0.543684
142
44.992958
33.438717
152
false
false
0
0
0
0
0
0
1.105634
false
false
15
1582d5e06f98506a434e1d1cb152fdd6102dd831
20,048,907,381,799
65b9f4766cff723823e284da85019824361c695f
/Web_App/src/main/java/com/epam/oleksandr_fomenko/java/lesson9/dao/UserDBDao.java
cdc5c4e3b0b7f4fd9efaeb49b4a4209841a53c07
[]
no_license
alexfomenkoag/automation_testing
https://github.com/alexfomenkoag/automation_testing
3890f63f493622f8187fe0cff7f05c61e1847607
72be8121d6e69d3e1ecf0df9f0b64b40b3bd917b
refs/heads/master
2020-02-26T12:38:46.219000
2016-05-29T19:25:22
2016-05-29T19:25:22
59,892,426
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.oleksandr_fomenko.java.lesson9.dao; import com.epam.oleksandr_fomenko.java.lesson9.bean.UserBean; import org.apache.log4j.Logger; import java.sql.*; import java.util.ArrayList; import java.util.List; import static com.epam.oleksandr_fomenko.java.lesson9.constants.RegistrationFormFields.*; /** * @author Oleksandr Fomenko */ public class UserDBDao implements IUserDao { private final Logger LOG = Logger.getRootLogger(); private final String USERNAME = "root"; private final String PASSWORD = "root"; private final String URL_MYSQL_CONNECTION = "jdbc:mysql://localhost:3306/mysql?useSSL=false"; private final String SELECT_ALL_USER = "SELECT firstName, lastName, firstPass, secondPass, email, login, gender FROM my_schema.users_table"; private final String SELECT_USER = "SELECT firstName, lastName, firstPass, secondPass, email, login, gender FROM my_schema.users_table WHERE my_schema.users_table.login = ?"; private final String CLEAR_USER_TABLE = "TRUNCATE TABLE my_schema.users_table"; private final String INSERT_USER = "INSERT INTO my_schema.users_table (firstName, lastName, firstPass, secondPass, email, login, gender) VALUES (?, ?, ?, ?, ?, ?, ?)"; @Override public List<UserBean> getAllUsers() { UserBean user = null; List<UserBean> listOfUsers = new ArrayList<>(); try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepSelect = connection.prepareStatement(SELECT_ALL_USER); ResultSet resultSet = prepSelect.executeQuery()) { while (resultSet.next()) { String name = resultSet.getString(USER_NAME_FIELD); String surname = resultSet.getString(USER_SURNAME_FIELD); String firstPassword = resultSet.getString(USER_PASSWORD_FIELD); String secondPassword = resultSet.getString(USER_SECOND_PASSWORD_FIELD); String email = resultSet.getString(USER_EMAIL_FIELD); String login = resultSet.getString(USER_LOGIN_FIELD); String gender = resultSet.getString(USER_GENDER_FIELD); user = new UserBean(name, surname, firstPassword, secondPassword, login, email, gender); listOfUsers.add(user); } } catch (SQLException e) { LOG.info(e.getMessage()); } return listOfUsers; } @Override public void addNewUser(UserBean user) { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepInsert = connection.prepareStatement(INSERT_USER)) { prepInsert.setString(1, user.getFirstName()); prepInsert.setString(2, user.getLastName()); prepInsert.setString(3, user.getFirstPass()); prepInsert.setString(4, user.getSecondPass()); prepInsert.setString(5, user.getEmail()); prepInsert.setString(6, user.getLogin()); prepInsert.setString(7, user.getGender().toUpperCase()); prepInsert.execute(); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } @Override public UserBean getUserByLogin(String userLogin) { UserBean user = null; try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepDelete = connection.prepareStatement(SELECT_USER)) { prepDelete.setString(1, userLogin); ResultSet resultSet = prepDelete.executeQuery(); while (resultSet.next()) { String name = resultSet.getString(USER_NAME_FIELD); String surname = resultSet.getString(USER_SURNAME_FIELD); String firstPassword = resultSet.getString(USER_PASSWORD_FIELD); String secondPassword = resultSet.getString(USER_SECOND_PASSWORD_FIELD); String email = resultSet.getString(USER_EMAIL_FIELD); String login = resultSet.getString(USER_LOGIN_FIELD); String gender = resultSet.getString(USER_GENDER_FIELD); user = new UserBean(name, surname, firstPassword, secondPassword, login, email, gender); } } catch (SQLException e) { LOG.info(e.getMessage()); } return user; } public void clearUserData() { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); Statement statement = connection.createStatement()) { statement.executeUpdate(CLEAR_USER_TABLE); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } @Override public void generateUsers() { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepInsert = connection.prepareStatement(INSERT_USER)) { prepInsert.setString(1, "Alex"); prepInsert.setString(2, "Fomenko"); prepInsert.setString(3, "qwerty"); prepInsert.setString(4, "qwerty"); prepInsert.setString(5, "alexfomenko@gmail.com"); prepInsert.setString(6, "alexfomenko"); prepInsert.setString(7, "MALE"); prepInsert.addBatch(); prepInsert.setString(1, "Lena"); prepInsert.setString(2, "Batura"); prepInsert.setString(3, "12345"); prepInsert.setString(4, "12345"); prepInsert.setString(5, "lenabatura@gmail.com"); prepInsert.setString(6, "lenabatura"); prepInsert.setString(7, "FEMALE"); prepInsert.addBatch(); prepInsert.executeBatch(); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } }
UTF-8
Java
6,049
java
UserDBDao.java
Java
[ { "context": "onstants.RegistrationFormFields.*;\n\n/**\n * @author Oleksandr Fomenko\n */\n\npublic class UserDBDao implements IUserDao {\n", "end": 343, "score": 0.9728895425796509, "start": 326, "tag": "NAME", "value": "Oleksandr Fomenko" }, { "context": "ME = \"root\";\n private final String PASSWORD = \"root\";\n private final String URL_MYSQL_CONNECTION =", "end": 535, "score": 0.9985042810440063, "start": 531, "tag": "PASSWORD", "value": "root" }, { "context": "RT_USER)) {\n\n prepInsert.setString(1, \"Alex\");\n prepInsert.setString(2, \"Fomenko\")", "end": 5165, "score": 0.9998594522476196, "start": 5161, "tag": "NAME", "value": "Alex" }, { "context": "(1, \"Alex\");\n prepInsert.setString(2, \"Fomenko\");\n prepInsert.setString(3, \"qwerty\");", "end": 5213, "score": 0.9994332790374756, "start": 5206, "tag": "NAME", "value": "Fomenko" }, { "context": ", \"qwerty\");\n prepInsert.setString(5, \"alexfomenko@gmail.com\");\n prepInsert.setString(6, \"alexfomen", "end": 5369, "score": 0.9999215602874756, "start": 5348, "tag": "EMAIL", "value": "alexfomenko@gmail.com" }, { "context": "gmail.com\");\n prepInsert.setString(6, \"alexfomenko\");\n prepInsert.setString(7, \"MALE\");\n ", "end": 5421, "score": 0.9980466365814209, "start": 5410, "tag": "USERNAME", "value": "alexfomenko" }, { "context": "addBatch();\n\n prepInsert.setString(1, \"Lena\");\n prepInsert.setString(2, \"Batura\");", "end": 5547, "score": 0.9997401237487793, "start": 5543, "tag": "NAME", "value": "Lena" }, { "context": "(1, \"Lena\");\n prepInsert.setString(2, \"Batura\");\n prepInsert.setString(3, \"12345\");\n", "end": 5594, "score": 0.9994459748268127, "start": 5588, "tag": "NAME", "value": "Batura" }, { "context": "4, \"12345\");\n prepInsert.setString(5, \"lenabatura@gmail.com\");\n prepInsert.setString(6, \"lenabatur", "end": 5747, "score": 0.9999203085899353, "start": 5727, "tag": "EMAIL", "value": "lenabatura@gmail.com" }, { "context": "gmail.com\");\n prepInsert.setString(6, \"lenabatura\");\n prepInsert.setString(7, \"FEMALE\");", "end": 5798, "score": 0.9879562258720398, "start": 5788, "tag": "USERNAME", "value": "lenabatura" } ]
null
[]
package com.epam.oleksandr_fomenko.java.lesson9.dao; import com.epam.oleksandr_fomenko.java.lesson9.bean.UserBean; import org.apache.log4j.Logger; import java.sql.*; import java.util.ArrayList; import java.util.List; import static com.epam.oleksandr_fomenko.java.lesson9.constants.RegistrationFormFields.*; /** * @author <NAME> */ public class UserDBDao implements IUserDao { private final Logger LOG = Logger.getRootLogger(); private final String USERNAME = "root"; private final String PASSWORD = "<PASSWORD>"; private final String URL_MYSQL_CONNECTION = "jdbc:mysql://localhost:3306/mysql?useSSL=false"; private final String SELECT_ALL_USER = "SELECT firstName, lastName, firstPass, secondPass, email, login, gender FROM my_schema.users_table"; private final String SELECT_USER = "SELECT firstName, lastName, firstPass, secondPass, email, login, gender FROM my_schema.users_table WHERE my_schema.users_table.login = ?"; private final String CLEAR_USER_TABLE = "TRUNCATE TABLE my_schema.users_table"; private final String INSERT_USER = "INSERT INTO my_schema.users_table (firstName, lastName, firstPass, secondPass, email, login, gender) VALUES (?, ?, ?, ?, ?, ?, ?)"; @Override public List<UserBean> getAllUsers() { UserBean user = null; List<UserBean> listOfUsers = new ArrayList<>(); try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepSelect = connection.prepareStatement(SELECT_ALL_USER); ResultSet resultSet = prepSelect.executeQuery()) { while (resultSet.next()) { String name = resultSet.getString(USER_NAME_FIELD); String surname = resultSet.getString(USER_SURNAME_FIELD); String firstPassword = resultSet.getString(USER_PASSWORD_FIELD); String secondPassword = resultSet.getString(USER_SECOND_PASSWORD_FIELD); String email = resultSet.getString(USER_EMAIL_FIELD); String login = resultSet.getString(USER_LOGIN_FIELD); String gender = resultSet.getString(USER_GENDER_FIELD); user = new UserBean(name, surname, firstPassword, secondPassword, login, email, gender); listOfUsers.add(user); } } catch (SQLException e) { LOG.info(e.getMessage()); } return listOfUsers; } @Override public void addNewUser(UserBean user) { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepInsert = connection.prepareStatement(INSERT_USER)) { prepInsert.setString(1, user.getFirstName()); prepInsert.setString(2, user.getLastName()); prepInsert.setString(3, user.getFirstPass()); prepInsert.setString(4, user.getSecondPass()); prepInsert.setString(5, user.getEmail()); prepInsert.setString(6, user.getLogin()); prepInsert.setString(7, user.getGender().toUpperCase()); prepInsert.execute(); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } @Override public UserBean getUserByLogin(String userLogin) { UserBean user = null; try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepDelete = connection.prepareStatement(SELECT_USER)) { prepDelete.setString(1, userLogin); ResultSet resultSet = prepDelete.executeQuery(); while (resultSet.next()) { String name = resultSet.getString(USER_NAME_FIELD); String surname = resultSet.getString(USER_SURNAME_FIELD); String firstPassword = resultSet.getString(USER_PASSWORD_FIELD); String secondPassword = resultSet.getString(USER_SECOND_PASSWORD_FIELD); String email = resultSet.getString(USER_EMAIL_FIELD); String login = resultSet.getString(USER_LOGIN_FIELD); String gender = resultSet.getString(USER_GENDER_FIELD); user = new UserBean(name, surname, firstPassword, secondPassword, login, email, gender); } } catch (SQLException e) { LOG.info(e.getMessage()); } return user; } public void clearUserData() { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); Statement statement = connection.createStatement()) { statement.executeUpdate(CLEAR_USER_TABLE); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } @Override public void generateUsers() { try (Connection connection = DBMySQLProcessor.getConnection(URL_MYSQL_CONNECTION, USERNAME, PASSWORD); PreparedStatement prepInsert = connection.prepareStatement(INSERT_USER)) { prepInsert.setString(1, "Alex"); prepInsert.setString(2, "Fomenko"); prepInsert.setString(3, "qwerty"); prepInsert.setString(4, "qwerty"); prepInsert.setString(5, "<EMAIL>"); prepInsert.setString(6, "alexfomenko"); prepInsert.setString(7, "MALE"); prepInsert.addBatch(); prepInsert.setString(1, "Lena"); prepInsert.setString(2, "Batura"); prepInsert.setString(3, "12345"); prepInsert.setString(4, "12345"); prepInsert.setString(5, "<EMAIL>"); prepInsert.setString(6, "lenabatura"); prepInsert.setString(7, "FEMALE"); prepInsert.addBatch(); prepInsert.executeBatch(); connection.commit(); } catch (SQLException e) { LOG.info(e.getMessage()); } } }
6,017
0.639114
0.632501
132
44.825756
35.124561
178
false
false
0
0
0
0
0
0
1.113636
false
false
15
ba32e7f882b848b472afc632c81d87c2b08a8fe1
26,766,236,194,228
bd4332f144218a4b6a90221f50e683dbb6cee49b
/src/datadriven/WebTable.java
dc33a93a97759f92d0ba9f67cd15b5bd4d6723ca
[]
no_license
amirkhadari/MyProject
https://github.com/amirkhadari/MyProject
0792e82ad7dda05851f931a77201e185a1875d40
e36243827ca5ac965e5add51da11bd6782a4480b
refs/heads/master
2020-05-03T20:44:23.918000
2019-04-05T09:58:38
2019-04-05T09:58:38
178,809,596
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datadriven; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class WebTable { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/home/innoraft/Amir/chromedriver"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://demo.automationtesting.in/WebTable.html"); String Number = driver.findElement(By.xpath("//div[text()='balajikalidindi@gmail.com']//parent::div[@role='gridcell']" + "//following-sibling::div[4]//child::div")).getText(); System.out.println(Number); } }
UTF-8
Java
807
java
WebTable.java
Java
[ { "context": "mber = driver.findElement(By.xpath(\"//div[text()='balajikalidindi@gmail.com']//parent::div[@role='gridcell']\"\n\t\t\t\t+ \"//follow", "end": 671, "score": 0.9998046159744263, "start": 646, "tag": "EMAIL", "value": "balajikalidindi@gmail.com" } ]
null
[]
package datadriven; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class WebTable { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/home/innoraft/Amir/chromedriver"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://demo.automationtesting.in/WebTable.html"); String Number = driver.findElement(By.xpath("//div[text()='<EMAIL>']//parent::div[@role='gridcell']" + "//following-sibling::div[4]//child::div")).getText(); System.out.println(Number); } }
789
0.729864
0.726146
27
28.888889
30.145737
120
false
false
0
0
0
0
0
0
1.592593
false
false
15
ba7ca87f3f57cf97fb78109799e773a43dd42e4e
25,082,609,009,850
2614f8ac7e966b5ded3bb169236d54c384132fac
/src/util/str/DBUtil.java
29b03861498c93ec2916baf8f27440610e938df8
[]
no_license
Deament/PT
https://github.com/Deament/PT
3f9f3babdbfc6aba739286a2b28704928e832553
767f1698f45e76df7c4de8c3d988899b5fed5cdb
refs/heads/master
2021-01-20T22:09:50.835000
2016-07-03T01:50:50
2016-07-03T01:50:50
61,312,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package util.str; import cn.qtone.common.utils.base.StringUtil; /** * 数据库操作的实用类. * * @author 马必强 * */ public class DBUtil { public final static StringBuffer oraclePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { return oracleExePageQuery(sql, orderBy, startIndex, totals); } public final static StringBuffer oraclePageQuery(StringBuffer sql, int startIndex, int totals) { return oracleExePageQuery(sql, null, startIndex, totals); } public final static String oraclePageQuery(String sql, String orderBy, int startIndex, int totals) { StringBuffer result = oracleExePageQuery(new StringBuffer(sql), orderBy, startIndex, totals); return result == null ? null : result.toString(); } public final static String oraclePageQuery(String sql, int startIndex, int totals) { StringBuffer result = oracleExePageQuery(new StringBuffer(sql), null, startIndex, totals); return result == null ? null : result.toString(); } public final static StringBuffer mysqlPageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { return mysqlExePageQuery(sql, orderBy, startIndex, totals); } public final static StringBuffer mysqlPageQuery(StringBuffer sql, int startIndex, int totals) { return mysqlExePageQuery(sql, null, startIndex, totals); } public final static String mysqlPageQuery(String sql, String orderBy, int startIndex, int totals) { StringBuffer result = mysqlExePageQuery(new StringBuffer(sql), orderBy, startIndex, totals); return result == null ? null : result.toString(); } public final static String mysqlPageQuery(String sql, int startIndex, int totals) { StringBuffer result = mysqlExePageQuery(new StringBuffer(sql), null, startIndex, totals); return result == null ? null : result.toString(); } /** * 将oracle中的日期时间字段转换成日期时间型的字符串. * @param field * @return */ public final static String oracleDTToString(String field) { return "to_char(" + field + ",'yyyy-mm-dd hh24:Mi:ss')"; } /** * 将oracle中的日期字段转换成日期类型的字符串. * @param field * @return */ public final static String oracleDateToString(String field) { return "to_char(" + field + ",'yyyy-mm-dd')"; } /** * 将oracle中的时间字段转换成时间类型的字符串. * @param field * @return */ public final static String oracleTimeToString(String field) { return "to_char(" + field + ",'hh24:Mi:ss')"; } /** * 使用指定的格式来将oracle中的日期时间字段转换成字符串. * @param field * @param formate * @return */ public final static String oracleDTToString(String field, String formate) { return "to_char(" + field + ",'" + formate + "')"; } /** * 将指定的日期时间字符串表示成oracle中的日期时间字段类型. * @param dateStr * @return */ public final static String stringToOracleDT(String dateStr) { return "to_date('" + dateStr + "','yyyy-mm-dd hh24:Mi:ss')"; } /** * 将指定的日期字符串表示成oracle中的日期字段类型. * @param dateStr * @return */ public final static String stringToOracleDate(String dateStr) { return "to_date('" + dateStr + "','yyyy-mm-dd')"; } /** * 将指定的时间字符串表示成oracle中的时间字段类型. * @param dateStr * @return */ public final static String stringToOracleTime(String dateStr) { return "to_date('" + dateStr + "','hh24:Mi:ss')"; } /** * oracle数据库的分页查询转换. * @param sql 查询SQL语句 * @param orderBy 排序字段,类似于order by a.id,b.id * @param startIndex 查询的开始位置,从1开始 * @param totals 要查询的结果数 * @return */ private static StringBuffer oracleExePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { if (sql != null) { int fromIndex = sql.toString().toUpperCase().lastIndexOf("FROM"); String order = StringUtil.trim(orderBy).toUpperCase().intern(); if (order != "") { if (!order.startsWith("ORDER")) order = "ORDER BY " + order; sql.insert(fromIndex-1, ",row_number() OVER(" + order + ") rn"); } else { sql.insert(fromIndex-1, ",ROWNUM as rn"); } sql.insert(0, "SELECT * FROM ("); sql.append(") WHERE rn BETWEEN "); sql.append(startIndex < 0 ? 0 : startIndex); sql.append(" AND "); sql.append(startIndex + totals - 1); } return sql; } /** * mysql 数据库的分页查询转换 * @param sql 查询SQL语句 * @param orderBy 排序字段,类似于order by a.id,b.id * @param startIndex 查询的开始位置,从1开始 * @param totals 要查询的结果数 * @return */ private static StringBuffer mysqlExePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { if (sql != null) { if (orderBy != null) { String order = orderBy.toUpperCase().trim(); if (!order.startsWith("ORDER")) order = "ORDER BY " + order; sql.append(" " + order); } sql.append(" LIMIT "); sql.append(startIndex < 1 ? 0 : (startIndex - 1)); sql.append(","); sql.append(totals); } return sql; } public static String getCountByQyery(String sql){ StringBuffer sb = new StringBuffer("select count(*) "); sb.append(sql.substring(sql.indexOf("from"),sql.length())); return sb.toString(); } public static void main(String[] args) { String sql = "SELECT a.id,a.name FROM tbl_a"; StringUtil.debug(oraclePageQuery(sql, "order by a.id", 1, 30)); StringUtil.debug(oraclePageQuery(sql, "a.name", 1, 30)); StringUtil.debug(oraclePageQuery(sql, 1, 30)); StringUtil.debug(mysqlPageQuery(sql, "order by a.id", 1, 30)); StringUtil.debug(mysqlPageQuery(sql, "a.name", 1, 30)); StringUtil.debug(mysqlPageQuery(sql, 1, 30)); } }
UTF-8
Java
5,875
java
DBUtil.java
Java
[ { "context": "se.StringUtil;\n\n\n/**\n * 数据库操作的实用类.\n * \n * @author 马必强\n *\n */\npublic class DBUtil\n{\n\tpublic final static", "end": 103, "score": 0.9996325373649597, "start": 100, "tag": "NAME", "value": "马必强" } ]
null
[]
package util.str; import cn.qtone.common.utils.base.StringUtil; /** * 数据库操作的实用类. * * @author 马必强 * */ public class DBUtil { public final static StringBuffer oraclePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { return oracleExePageQuery(sql, orderBy, startIndex, totals); } public final static StringBuffer oraclePageQuery(StringBuffer sql, int startIndex, int totals) { return oracleExePageQuery(sql, null, startIndex, totals); } public final static String oraclePageQuery(String sql, String orderBy, int startIndex, int totals) { StringBuffer result = oracleExePageQuery(new StringBuffer(sql), orderBy, startIndex, totals); return result == null ? null : result.toString(); } public final static String oraclePageQuery(String sql, int startIndex, int totals) { StringBuffer result = oracleExePageQuery(new StringBuffer(sql), null, startIndex, totals); return result == null ? null : result.toString(); } public final static StringBuffer mysqlPageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { return mysqlExePageQuery(sql, orderBy, startIndex, totals); } public final static StringBuffer mysqlPageQuery(StringBuffer sql, int startIndex, int totals) { return mysqlExePageQuery(sql, null, startIndex, totals); } public final static String mysqlPageQuery(String sql, String orderBy, int startIndex, int totals) { StringBuffer result = mysqlExePageQuery(new StringBuffer(sql), orderBy, startIndex, totals); return result == null ? null : result.toString(); } public final static String mysqlPageQuery(String sql, int startIndex, int totals) { StringBuffer result = mysqlExePageQuery(new StringBuffer(sql), null, startIndex, totals); return result == null ? null : result.toString(); } /** * 将oracle中的日期时间字段转换成日期时间型的字符串. * @param field * @return */ public final static String oracleDTToString(String field) { return "to_char(" + field + ",'yyyy-mm-dd hh24:Mi:ss')"; } /** * 将oracle中的日期字段转换成日期类型的字符串. * @param field * @return */ public final static String oracleDateToString(String field) { return "to_char(" + field + ",'yyyy-mm-dd')"; } /** * 将oracle中的时间字段转换成时间类型的字符串. * @param field * @return */ public final static String oracleTimeToString(String field) { return "to_char(" + field + ",'hh24:Mi:ss')"; } /** * 使用指定的格式来将oracle中的日期时间字段转换成字符串. * @param field * @param formate * @return */ public final static String oracleDTToString(String field, String formate) { return "to_char(" + field + ",'" + formate + "')"; } /** * 将指定的日期时间字符串表示成oracle中的日期时间字段类型. * @param dateStr * @return */ public final static String stringToOracleDT(String dateStr) { return "to_date('" + dateStr + "','yyyy-mm-dd hh24:Mi:ss')"; } /** * 将指定的日期字符串表示成oracle中的日期字段类型. * @param dateStr * @return */ public final static String stringToOracleDate(String dateStr) { return "to_date('" + dateStr + "','yyyy-mm-dd')"; } /** * 将指定的时间字符串表示成oracle中的时间字段类型. * @param dateStr * @return */ public final static String stringToOracleTime(String dateStr) { return "to_date('" + dateStr + "','hh24:Mi:ss')"; } /** * oracle数据库的分页查询转换. * @param sql 查询SQL语句 * @param orderBy 排序字段,类似于order by a.id,b.id * @param startIndex 查询的开始位置,从1开始 * @param totals 要查询的结果数 * @return */ private static StringBuffer oracleExePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { if (sql != null) { int fromIndex = sql.toString().toUpperCase().lastIndexOf("FROM"); String order = StringUtil.trim(orderBy).toUpperCase().intern(); if (order != "") { if (!order.startsWith("ORDER")) order = "ORDER BY " + order; sql.insert(fromIndex-1, ",row_number() OVER(" + order + ") rn"); } else { sql.insert(fromIndex-1, ",ROWNUM as rn"); } sql.insert(0, "SELECT * FROM ("); sql.append(") WHERE rn BETWEEN "); sql.append(startIndex < 0 ? 0 : startIndex); sql.append(" AND "); sql.append(startIndex + totals - 1); } return sql; } /** * mysql 数据库的分页查询转换 * @param sql 查询SQL语句 * @param orderBy 排序字段,类似于order by a.id,b.id * @param startIndex 查询的开始位置,从1开始 * @param totals 要查询的结果数 * @return */ private static StringBuffer mysqlExePageQuery(StringBuffer sql, String orderBy, int startIndex, int totals) { if (sql != null) { if (orderBy != null) { String order = orderBy.toUpperCase().trim(); if (!order.startsWith("ORDER")) order = "ORDER BY " + order; sql.append(" " + order); } sql.append(" LIMIT "); sql.append(startIndex < 1 ? 0 : (startIndex - 1)); sql.append(","); sql.append(totals); } return sql; } public static String getCountByQyery(String sql){ StringBuffer sb = new StringBuffer("select count(*) "); sb.append(sql.substring(sql.indexOf("from"),sql.length())); return sb.toString(); } public static void main(String[] args) { String sql = "SELECT a.id,a.name FROM tbl_a"; StringUtil.debug(oraclePageQuery(sql, "order by a.id", 1, 30)); StringUtil.debug(oraclePageQuery(sql, "a.name", 1, 30)); StringUtil.debug(oraclePageQuery(sql, 1, 30)); StringUtil.debug(mysqlPageQuery(sql, "order by a.id", 1, 30)); StringUtil.debug(mysqlPageQuery(sql, "a.name", 1, 30)); StringUtil.debug(mysqlPageQuery(sql, 1, 30)); } }
5,875
0.6737
0.666852
213
24.366198
24.250399
81
false
false
0
0
0
0
0
0
2.098592
false
false
15
dbf5f3a63cb1619ada01b1f9cc65504873c892a8
30,374,008,771,004
f3d9a6aeb2c493ae4c391c92ffbf14214c28747b
/src/main/java/xyz/kyyz/utils/extention/DateExtention.java
4681874deb1e2bc763627909f12862ae40c893c7
[ "Apache-2.0" ]
permissive
kuangyy/index
https://github.com/kuangyy/index
759103dbf44e4843a45823144be5b6a94ba7c685
5d12e2dafa819e7ac8e3971e9a34db3b40997ca1
refs/heads/master
2021-01-10T08:01:48.495000
2016-02-24T10:17:36
2016-02-24T10:17:36
52,402,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xyz.kyyz.utils.extention; import java.text.SimpleDateFormat; import java.util.Date; /** * * @ClassName: DateExtention * @Description: Date扩展 * @author yinqiang * @date Jul 23, 2015 6:24:36 PM * */ public class DateExtention { final static String dataFromat="yyyy-MM-dd"; /** * * @Title: prase * @Description: 字符串转换Date 格式:yyyy-MM-dd * @param source * @return * @author yinqiang * @throws */ public static Date prase(String source){ SimpleDateFormat sdFormat=new SimpleDateFormat(dataFromat); try { Date date= sdFormat.parse(source); return date; } catch (Exception e) { return null; // TODO: handle exception } } }
UTF-8
Java
700
java
DateExtention.java
Java
[ { "context": "e: DateExtention \n* @Description: Date扩展\n* @author yinqiang\n* @date Jul 23, 2015 6:24:36 PM \n*\n */\npublic cla", "end": 172, "score": 0.9729212522506714, "start": 164, "tag": "USERNAME", "value": "yinqiang" }, { "context": "yy-MM-dd\n\t * @param source\n\t * @return\n\t * @author yinqiang\n\t * @throws\n\t */\n\tpublic static Date prase(String", "end": 410, "score": 0.9329776763916016, "start": 402, "tag": "USERNAME", "value": "yinqiang" } ]
null
[]
package xyz.kyyz.utils.extention; import java.text.SimpleDateFormat; import java.util.Date; /** * * @ClassName: DateExtention * @Description: Date扩展 * @author yinqiang * @date Jul 23, 2015 6:24:36 PM * */ public class DateExtention { final static String dataFromat="yyyy-MM-dd"; /** * * @Title: prase * @Description: 字符串转换Date 格式:yyyy-MM-dd * @param source * @return * @author yinqiang * @throws */ public static Date prase(String source){ SimpleDateFormat sdFormat=new SimpleDateFormat(dataFromat); try { Date date= sdFormat.parse(source); return date; } catch (Exception e) { return null; // TODO: handle exception } } }
700
0.667155
0.651026
36
17.944445
15.403724
61
false
false
0
0
0
0
0
0
1.388889
false
false
15
862766c33bb5c4e644108f9c5de854eb3ea4678c
20,143,396,687,058
98d0406843f1cd771c4f5ccd54d57daee0161dc1
/src/main/java/com/fomjar/blog/comm/CommonController.java
3169be1c6f80ad03c4afea0340ce8baec862b449
[]
no_license
fomjar/free-blog
https://github.com/fomjar/free-blog
e9055b16754f037e17c71f885f7131ca6161832a
5cf9dae47b4e03472ef3ff2cc738cebc3d7b231a
refs/heads/master
2021-01-22T02:40:42.980000
2018-03-07T08:26:14
2018-03-07T08:26:14
102,250,284
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fomjar.blog.comm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.fomjar.blog.article.ArticleService; @Controller @ControllerAdvice public class CommonController { @Autowired private ArticleService service; @RequestMapping(path = {"/", "/index"}) public ModelAndView index() { return new ModelAndView("index") .addObject("articles", service.list()); } @ExceptionHandler(Exception.class) public ModelAndView exception(Exception e) { return new ModelAndView("error") .addObject("code", -1) .addObject("desc", e.getMessage()); } }
UTF-8
Java
977
java
CommonController.java
Java
[]
null
[]
package com.fomjar.blog.comm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.fomjar.blog.article.ArticleService; @Controller @ControllerAdvice public class CommonController { @Autowired private ArticleService service; @RequestMapping(path = {"/", "/index"}) public ModelAndView index() { return new ModelAndView("index") .addObject("articles", service.list()); } @ExceptionHandler(Exception.class) public ModelAndView exception(Exception e) { return new ModelAndView("error") .addObject("code", -1) .addObject("desc", e.getMessage()); } }
977
0.715455
0.714432
32
29.53125
22.278049
64
false
false
0
0
0
0
0
0
0.46875
false
false
15
9261c8e72a5eefe3c669ff20aaaa5c3fd3f7a9d2
26,938,034,948,932
2dc38553a57371e55801df1a901f2deb5c545a14
/Elki/src/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/CLIQUE.java
4e6bb2b915b54dab8105982073d4d5689620ed31
[]
no_license
artsync/Overig
https://github.com/artsync/Overig
c2ad37ce70146f761e494a3c6fa006755dd72779
8e6883ff382cdfef13311362b660b1bb97f4f229
refs/heads/master
2021-01-19T05:03:34.744000
2014-10-11T15:41:22
2014-10-11T15:41:22
25,083,390
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.lmu.ifi.dbs.elki.algorithm.clustering.subspace; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.ClusteringAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.subspace.clique.CLIQUESubspace; import de.lmu.ifi.dbs.elki.algorithm.clustering.subspace.clique.CLIQUEUnit; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroup; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroupCollection; import de.lmu.ifi.dbs.elki.data.Interval; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.Subspace; import de.lmu.ifi.dbs.elki.data.cluster.Cluster; import de.lmu.ifi.dbs.elki.data.model.SubspaceModel; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.utilities.FormatUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Description; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.pairs.Pair; /** * <p/> * Implementation of the CLIQUE algorithm, a grid-based algorithm to identify * dense clusters in subspaces of maximum dimensionality. * </p> * <p/> * The implementation consists of two steps: <br> * 1. Identification of subspaces that contain clusters <br> * 2. Identification of clusters * </p> * <p/> * The third step of the original algorithm (Generation of minimal description * for the clusters) is not (yet) implemented. * </p> * <p> * Reference: <br> * R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan:: Automatic Subspace * Clustering of High Dimensional Data for Data Mining Applications. <br> * In Proc. ACM SIGMOD Int. Conf. on Management of Data, Seattle, WA, 1998. * </p> * * @author Elke Achtert * @param <V> the type of NumberVector handled by this Algorithm */ @Title("CLIQUE: Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications") @Description("Grid-based algorithm to identify dense clusters in subspaces of maximum dimensionality.") @Reference(authors = "R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan", title = "Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications", booktitle = "Proc. SIGMOD Conference, Seattle, WA, 1998", url = "http://dx.doi.org/10.1145/276304.276314") public class CLIQUE<V extends NumberVector<V, ?>> extends AbstractAlgorithm<V, Clustering<SubspaceModel<V>>> implements ClusteringAlgorithm<Clustering<SubspaceModel<V>>, V> { /** * OptionID for {@link #XSI_PARAM} */ public static final OptionID XSI_ID = OptionID.getOrCreateOptionID("clique.xsi", "The number of intervals (units) in each dimension."); /** * Parameter to specify the number of intervals (units) in each dimension, * must be an integer greater than 0. * <p> * Key: {@code -clique.xsi} * </p> */ private final IntParameter XSI_PARAM = new IntParameter(XSI_ID, new GreaterConstraint(0)); /** * Holds the value of {@link #XSI_PARAM}. */ private int xsi; /** * OptionID for {@link #TAU_PARAM} */ public static final OptionID TAU_ID = OptionID.getOrCreateOptionID("clique.tau", "The density threshold for the selectivity of a unit, where the selectivity is" + "the fraction of total feature vectors contained in this unit."); /** * Parameter to specify the density threshold for the selectivity of a unit, * where the selectivity is the fraction of total feature vectors contained in * this unit, must be a double greater than 0 and less than 1. * <p> * Key: {@code -clique.tau} * </p> */ private final DoubleParameter TAU_PARAM = new DoubleParameter(TAU_ID, new IntervalConstraint(0, IntervalConstraint.IntervalBoundary.OPEN, 1, IntervalConstraint.IntervalBoundary.OPEN)); /** * Holds the value of {@link #TAU_PARAM}. */ private double tau; /** * OptionID for {@link #PRUNE_FLAG} */ public static final OptionID PRUNE_ID = OptionID.getOrCreateOptionID("clique.prune", "Flag to indicate that only subspaces with large coverage " + "(i.e. the fraction of the database that is covered by the dense units) " + "are selected, the rest will be pruned."); /** * Flag to indicate that only subspaces with large coverage (i.e. the fraction * of the database that is covered by the dense units) are selected, the rest * will be pruned. * <p> * Key: {@code -clique.prune} * </p> */ private final Flag PRUNE_FLAG = new Flag(PRUNE_ID); /** * Holds the value of {@link #PRUNE_FLAG}. */ private boolean prune; /** * Constructor, adhering to * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable} * * @param config Parameterization */ public CLIQUE(Parameterization config) { super(config); if(config.grab(XSI_PARAM)) { xsi = XSI_PARAM.getValue(); } if(config.grab(TAU_PARAM)) { tau = TAU_PARAM.getValue(); } if(config.grab(PRUNE_FLAG)) { prune = PRUNE_FLAG.getValue(); } // logger.getWrappedLogger().setLevel(Level.FINE); } /** * Performs the CLIQUE algorithm on the given database. * */ @Override protected Clustering<SubspaceModel<V>> runInTime(Database<V> database) throws IllegalStateException { // 1. Identification of subspaces that contain clusters if(logger.isVerbose()) { logger.verbose("*** 1. Identification of subspaces that contain clusters ***"); } SortedMap<Integer, List<CLIQUESubspace<V>>> dimensionToDenseSubspaces = new TreeMap<Integer, List<CLIQUESubspace<V>>>(); List<CLIQUESubspace<V>> denseSubspaces = findOneDimensionalDenseSubspaces(database); dimensionToDenseSubspaces.put(0, denseSubspaces); if(logger.isVerbose()) { logger.verbose(" 1-dimensional dense subspaces: " + denseSubspaces.size()); } if(logger.isDebugging()) { for(CLIQUESubspace<V> s : denseSubspaces) { logger.debug(s.toString(" ")); } } for(int k = 2; k <= database.dimensionality() && !denseSubspaces.isEmpty(); k++) { denseSubspaces = findDenseSubspaces(database, denseSubspaces); dimensionToDenseSubspaces.put(k - 1, denseSubspaces); if(logger.isVerbose()) { logger.verbose(" " + k + "-dimensional dense subspaces: " + denseSubspaces.size()); } if(logger.isDebugging()) { for(CLIQUESubspace<V> s : denseSubspaces) { logger.debug(s.toString(" ")); } } } // 2. Identification of clusters if(logger.isVerbose()) { logger.verbose("*** 2. Identification of clusters ***"); } // build result int numClusters = 1; Clustering<SubspaceModel<V>> result = new Clustering<SubspaceModel<V>>(); for(Integer dim : dimensionToDenseSubspaces.keySet()) { List<CLIQUESubspace<V>> subspaces = dimensionToDenseSubspaces.get(dim); List<Pair<Subspace<V>, Set<Integer>>> modelsAndClusters = determineClusters(database, subspaces); if(logger.isVerbose()) { logger.verbose(" " + (dim + 1) + "-dimensional clusters: " + modelsAndClusters.size()); } for(Pair<Subspace<V>, Set<Integer>> modelAndCluster : modelsAndClusters) { DatabaseObjectGroup group = new DatabaseObjectGroupCollection<Set<Integer>>(modelAndCluster.second); Cluster<SubspaceModel<V>> newCluster = new Cluster<SubspaceModel<V>>(group); newCluster.setModel(new SubspaceModel<V>(modelAndCluster.first)); newCluster.setName("cluster_" + numClusters++); result.addCluster(newCluster); } } return result; } /** * Determines the clusters in the specified dense subspaces. * * @param database the database to run the algorithm on * @param denseSubspaces the dense subspaces in reverse order by their * coverage * @return the clusters in the specified dense subspaces and the corresponding * cluster models */ private List<Pair<Subspace<V>, Set<Integer>>> determineClusters(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { List<Pair<Subspace<V>, Set<Integer>>> clusters = new ArrayList<Pair<Subspace<V>, Set<Integer>>>(); for(CLIQUESubspace<V> subspace : denseSubspaces) { List<Pair<Subspace<V>, Set<Integer>>> clustersInSubspace = subspace.determineClusters(database); if(logger.isDebugging()) { logger.debugFine("Subspace " + subspace + " clusters " + clustersInSubspace.size()); } clusters.addAll(clustersInSubspace); } return clusters; } /** * Determines the one dimensional dense subspaces and performs a pruning if * this option is chosen. * * @param database the database to run the algorithm on * @return the one dimensional dense subspaces reverse ordered by their * coverage */ private List<CLIQUESubspace<V>> findOneDimensionalDenseSubspaces(Database<V> database) { List<CLIQUESubspace<V>> denseSubspaceCandidates = findOneDimensionalDenseSubspaceCandidates(database); if(prune) { return pruneDenseSubspaces(denseSubspaceCandidates); } return denseSubspaceCandidates; } /** * Determines the {@code k}-dimensional dense subspaces and performs a pruning * if this option is chosen. * * @param database the database to run the algorithm on * @param denseSubspaces the {@code (k-1)}-dimensional dense subspaces * @return a list of the {@code k}-dimensional dense subspaces sorted in * reverse order by their coverage */ private List<CLIQUESubspace<V>> findDenseSubspaces(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { List<CLIQUESubspace<V>> denseSubspaceCandidates = findDenseSubspaceCandidates(database, denseSubspaces); if(prune) { return pruneDenseSubspaces(denseSubspaceCandidates); } return denseSubspaceCandidates; } /** * Initializes and returns the one dimensional units. * * @param database the database to run the algorithm on * @return the created one dimensional units */ private Collection<CLIQUEUnit<V>> initOneDimensionalUnits(Database<V> database) { int dimensionality = database.dimensionality(); // initialize minima and maxima double[] minima = new double[dimensionality]; double[] maxima = new double[dimensionality]; for(int d = 0; d < dimensionality; d++) { maxima[d] = -Double.MAX_VALUE; minima[d] = Double.MAX_VALUE; } // update minima and maxima for(Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); updateMinMax(featureVector, minima, maxima); } for(int i = 0; i < maxima.length; i++) { maxima[i] += 0.0001; } // determine the unit length in each dimension double[] unit_lengths = new double[dimensionality]; for(int d = 0; d < dimensionality; d++) { unit_lengths[d] = (maxima[d] - minima[d]) / xsi; } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" minima: ").append(FormatUtil.format(minima, ", ", 2)); msg.append("\n maxima: ").append(FormatUtil.format(maxima, ", ", 2)); msg.append("\n unit lengths: ").append(FormatUtil.format(unit_lengths, ", ", 2)); logger.debugFiner(msg.toString()); } // determine the boundaries of the units double[][] unit_bounds = new double[xsi + 1][dimensionality]; for(int x = 0; x <= xsi; x++) { for(int d = 0; d < dimensionality; d++) { if(x < xsi) { unit_bounds[x][d] = minima[d] + x * unit_lengths[d]; } else { unit_bounds[x][d] = maxima[d]; } } } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" unit bounds ").append(new Matrix(unit_bounds).toString(" ")); logger.debugFiner(msg.toString()); } // build the 1 dimensional units List<CLIQUEUnit<V>> units = new ArrayList<CLIQUEUnit<V>>((xsi * dimensionality)); for(int x = 0; x < xsi; x++) { for(int d = 0; d < dimensionality; d++) { units.add(new CLIQUEUnit<V>(new Interval(d, unit_bounds[x][d], unit_bounds[x + 1][d]))); } } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" total number of 1-dim units: ").append(units.size()); logger.debugFiner(msg.toString()); } return units; } /** * Updates the minima and maxima array according to the specified feature * vector. * * @param featureVector the feature vector * @param minima the array of minima * @param maxima the array of maxima */ private void updateMinMax(V featureVector, double[] minima, double[] maxima) { if(minima.length != featureVector.getDimensionality()) { throw new IllegalArgumentException("FeatureVectors differ in length."); } for(int d = 1; d <= featureVector.getDimensionality(); d++) { if((featureVector.doubleValue(d)) > maxima[d - 1]) { maxima[d - 1] = (featureVector.doubleValue(d)); } if((featureVector.doubleValue(d)) < minima[d - 1]) { minima[d - 1] = (featureVector.doubleValue(d)); } } } /** * Determines the one-dimensional dense subspace candidates by making a pass * over the database. * * @param database the database to run the algorithm on * @return the one-dimensional dense subspace candidates reverse ordered by * their coverage */ private List<CLIQUESubspace<V>> findOneDimensionalDenseSubspaceCandidates(Database<V> database) { Collection<CLIQUEUnit<V>> units = initOneDimensionalUnits(database); Collection<CLIQUEUnit<V>> denseUnits = new ArrayList<CLIQUEUnit<V>>(); Map<Integer, CLIQUESubspace<V>> denseSubspaces = new HashMap<Integer, CLIQUESubspace<V>>(); // identify dense units double total = database.size(); for(Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); for(CLIQUEUnit<V> unit : units) { unit.addFeatureVector(featureVector); // unit is a dense unit if(!it.hasNext() && unit.selectivity(total) >= tau) { denseUnits.add(unit); // add the dense unit to its subspace int dim = unit.getIntervals().iterator().next().getDimension(); CLIQUESubspace<V> subspace_d = denseSubspaces.get(dim); if(subspace_d == null) { subspace_d = new CLIQUESubspace<V>(dim); denseSubspaces.put(dim, subspace_d); } subspace_d.addDenseUnit(unit); } } } if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(" number of 1-dim dense units: ").append(denseUnits.size()); msg.append("\n number of 1-dim dense subspace candidates: ").append(denseSubspaces.size()); logger.debugFine(msg.toString()); } List<CLIQUESubspace<V>> subspaceCandidates = new ArrayList<CLIQUESubspace<V>>(denseSubspaces.values()); Collections.sort(subspaceCandidates, new CLIQUESubspace.CoverageComparator()); return subspaceCandidates; } /** * Determines the {@code k}-dimensional dense subspace candidates from the * specified {@code (k-1)}-dimensional dense subspaces. * * @param database the database to run the algorithm on * @param denseSubspaces the {@code (k-1)}-dimensional dense subspaces * @return a list of the {@code k}-dimensional dense subspace candidates * reverse ordered by their coverage */ private List<CLIQUESubspace<V>> findDenseSubspaceCandidates(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { // sort (k-1)-dimensional dense subspace according to their dimensions List<CLIQUESubspace<V>> denseSubspacesByDimensions = new ArrayList<CLIQUESubspace<V>>(denseSubspaces); Collections.sort(denseSubspacesByDimensions, new Subspace.DimensionComparator()); // determine k-dimensional dense subspace candidates double all = database.size(); List<CLIQUESubspace<V>> denseSubspaceCandidates = new ArrayList<CLIQUESubspace<V>>(); while(!denseSubspacesByDimensions.isEmpty()) { CLIQUESubspace<V> s1 = denseSubspacesByDimensions.remove(0); for(CLIQUESubspace<V> s2 : denseSubspacesByDimensions) { CLIQUESubspace<V> s = s1.join(s2, all, tau); if(s != null) { denseSubspaceCandidates.add(s); } } } // sort reverse by coverage Collections.sort(denseSubspaceCandidates, new CLIQUESubspace.CoverageComparator()); return denseSubspaceCandidates; } /** * Performs a MDL-based pruning of the specified dense subspaces as described * in the CLIQUE algorithm. * * @param denseSubspaces the subspaces to be pruned sorted in reverse order by * their coverage * @return the subspaces which are not pruned reverse ordered by their * coverage */ private List<CLIQUESubspace<V>> pruneDenseSubspaces(List<CLIQUESubspace<V>> denseSubspaces) { int[][] means = computeMeans(denseSubspaces); double[][] diffs = computeDiffs(denseSubspaces, means[0], means[1]); double[] codeLength = new double[denseSubspaces.size()]; double minCL = Double.MAX_VALUE; int min_i = -1; for(int i = 0; i < denseSubspaces.size(); i++) { int mi = means[0][i]; int mp = means[1][i]; double log_mi = mi == 0 ? 0 : StrictMath.log(mi) / StrictMath.log(2); double log_mp = mp == 0 ? 0 : StrictMath.log(mp) / StrictMath.log(2); double diff_mi = diffs[0][i]; double diff_mp = diffs[1][i]; codeLength[i] = log_mi + diff_mi + log_mp + diff_mp; if(codeLength[i] <= minCL) { minCL = codeLength[i]; min_i = i; } } return denseSubspaces.subList(0, min_i + 1); } /** * The specified sorted list of dense subspaces is divided into the selected * set I and the pruned set P. For each set the mean of the cover fractions is * computed. * * @param denseSubspaces the dense subspaces in reverse order by their * coverage * @return the mean of the cover fractions, the first value is the mean of the * selected set I, the second value is the mean of the pruned set P. */ private int[][] computeMeans(List<CLIQUESubspace<V>> denseSubspaces) { int n = denseSubspaces.size() - 1; int[] mi = new int[n + 1]; int[] mp = new int[n + 1]; double resultMI = 0; double resultMP = 0; for(int i = 0; i < denseSubspaces.size(); i++) { resultMI += denseSubspaces.get(i).getCoverage(); resultMP += denseSubspaces.get(n - i).getCoverage(); mi[i] = (int) Math.ceil(resultMI / (i + 1)); if(i != n) { mp[n - 1 - i] = (int) Math.ceil(resultMP / (i + 1)); } } int[][] result = new int[2][]; result[0] = mi; result[1] = mp; return result; } /** * The specified sorted list of dense subspaces is divided into the selected * set I and the pruned set P. For each set the difference from the specified * mean values is computed. * * @param denseSubspaces denseSubspaces the dense subspaces in reverse order * by their coverage * @param mi the mean of the selected sets I * @param mp the mean of the pruned sets P * @return the difference from the specified mean values, the first value is * the difference from the mean of the selected set I, the second * value is the difference from the mean of the pruned set P. */ private double[][] computeDiffs(List<CLIQUESubspace<V>> denseSubspaces, int[] mi, int[] mp) { int n = denseSubspaces.size() - 1; double[] diff_mi = new double[n + 1]; double[] diff_mp = new double[n + 1]; double resultMI = 0; double resultMP = 0; for(int i = 0; i < denseSubspaces.size(); i++) { double diffMI = Math.abs(denseSubspaces.get(i).getCoverage() - mi[i]); resultMI += diffMI == 0.0 ? 0 : StrictMath.log(diffMI) / StrictMath.log(2); double diffMP = (i != n) ? Math.abs(denseSubspaces.get(n - i).getCoverage() - mp[n - 1 - i]) : 0; resultMP += diffMP == 0.0 ? 0 : StrictMath.log(diffMP) / StrictMath.log(2); diff_mi[i] = resultMI; if(i != n) { diff_mp[n - 1 - i] = resultMP; } } double[][] result = new double[2][]; result[0] = diff_mi; result[1] = diff_mp; return result; } }
UTF-8
Java
21,380
java
CLIQUE.java
Java
[ { "context": " implemented.\n * </p>\n * <p>\n * Reference: <br>\n * R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan:: Automatic", "end": 2417, "score": 0.9999010562896729, "start": 2407, "tag": "NAME", "value": "R. Agrawal" }, { "context": ".\n * </p>\n * <p>\n * Reference: <br>\n * R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan:: Automatic Subspace\n ", "end": 2428, "score": 0.9998898506164551, "start": 2419, "tag": "NAME", "value": "J. Gehrke" }, { "context": "* <p>\n * Reference: <br>\n * R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan:: Automatic Subspace\n * Clustering o", "end": 2442, "score": 0.9998920559883118, "start": 2430, "tag": "NAME", "value": "D. Gunopulos" }, { "context": "ence: <br>\n * R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan:: Automatic Subspace\n * Clustering of High Dimens", "end": 2455, "score": 0.9998816847801208, "start": 2444, "tag": "NAME", "value": "P. Raghavan" }, { "context": "of Data, Seattle, WA, 1998.\n * </p>\n * \n * @author Elke Achtert\n * @param <V> the type of NumberVector handled by", "end": 2662, "score": 0.9998982548713684, "start": 2650, "tag": "NAME", "value": "Elke Achtert" }, { "context": "f maximum dimensionality.\")\n@Reference(authors = \"R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan\", title = \"", "end": 2970, "score": 0.9999011158943176, "start": 2960, "tag": "NAME", "value": "R. Agrawal" }, { "context": "imensionality.\")\n@Reference(authors = \"R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan\", title = \"Automatic S", "end": 2981, "score": 0.9998862147331238, "start": 2972, "tag": "NAME", "value": "J. Gehrke" }, { "context": "ty.\")\n@Reference(authors = \"R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan\", title = \"Automatic Subspace Cluste", "end": 2995, "score": 0.9998950362205505, "start": 2983, "tag": "NAME", "value": "D. Gunopulos" }, { "context": "ce(authors = \"R. Agrawal, J. Gehrke, D. Gunopulos, P. Raghavan\", title = \"Automatic Subspace Clustering of High ", "end": 3008, "score": 0.9998922348022461, "start": 2997, "tag": "NAME", "value": "P. Raghavan" } ]
null
[]
package de.lmu.ifi.dbs.elki.algorithm.clustering.subspace; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.ClusteringAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.clustering.subspace.clique.CLIQUESubspace; import de.lmu.ifi.dbs.elki.algorithm.clustering.subspace.clique.CLIQUEUnit; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroup; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroupCollection; import de.lmu.ifi.dbs.elki.data.Interval; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.Subspace; import de.lmu.ifi.dbs.elki.data.cluster.Cluster; import de.lmu.ifi.dbs.elki.data.model.SubspaceModel; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.utilities.FormatUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Description; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.pairs.Pair; /** * <p/> * Implementation of the CLIQUE algorithm, a grid-based algorithm to identify * dense clusters in subspaces of maximum dimensionality. * </p> * <p/> * The implementation consists of two steps: <br> * 1. Identification of subspaces that contain clusters <br> * 2. Identification of clusters * </p> * <p/> * The third step of the original algorithm (Generation of minimal description * for the clusters) is not (yet) implemented. * </p> * <p> * Reference: <br> * <NAME>, <NAME>, <NAME>, <NAME>:: Automatic Subspace * Clustering of High Dimensional Data for Data Mining Applications. <br> * In Proc. ACM SIGMOD Int. Conf. on Management of Data, Seattle, WA, 1998. * </p> * * @author <NAME> * @param <V> the type of NumberVector handled by this Algorithm */ @Title("CLIQUE: Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications") @Description("Grid-based algorithm to identify dense clusters in subspaces of maximum dimensionality.") @Reference(authors = "<NAME>, <NAME>, <NAME>, <NAME>", title = "Automatic Subspace Clustering of High Dimensional Data for Data Mining Applications", booktitle = "Proc. SIGMOD Conference, Seattle, WA, 1998", url = "http://dx.doi.org/10.1145/276304.276314") public class CLIQUE<V extends NumberVector<V, ?>> extends AbstractAlgorithm<V, Clustering<SubspaceModel<V>>> implements ClusteringAlgorithm<Clustering<SubspaceModel<V>>, V> { /** * OptionID for {@link #XSI_PARAM} */ public static final OptionID XSI_ID = OptionID.getOrCreateOptionID("clique.xsi", "The number of intervals (units) in each dimension."); /** * Parameter to specify the number of intervals (units) in each dimension, * must be an integer greater than 0. * <p> * Key: {@code -clique.xsi} * </p> */ private final IntParameter XSI_PARAM = new IntParameter(XSI_ID, new GreaterConstraint(0)); /** * Holds the value of {@link #XSI_PARAM}. */ private int xsi; /** * OptionID for {@link #TAU_PARAM} */ public static final OptionID TAU_ID = OptionID.getOrCreateOptionID("clique.tau", "The density threshold for the selectivity of a unit, where the selectivity is" + "the fraction of total feature vectors contained in this unit."); /** * Parameter to specify the density threshold for the selectivity of a unit, * where the selectivity is the fraction of total feature vectors contained in * this unit, must be a double greater than 0 and less than 1. * <p> * Key: {@code -clique.tau} * </p> */ private final DoubleParameter TAU_PARAM = new DoubleParameter(TAU_ID, new IntervalConstraint(0, IntervalConstraint.IntervalBoundary.OPEN, 1, IntervalConstraint.IntervalBoundary.OPEN)); /** * Holds the value of {@link #TAU_PARAM}. */ private double tau; /** * OptionID for {@link #PRUNE_FLAG} */ public static final OptionID PRUNE_ID = OptionID.getOrCreateOptionID("clique.prune", "Flag to indicate that only subspaces with large coverage " + "(i.e. the fraction of the database that is covered by the dense units) " + "are selected, the rest will be pruned."); /** * Flag to indicate that only subspaces with large coverage (i.e. the fraction * of the database that is covered by the dense units) are selected, the rest * will be pruned. * <p> * Key: {@code -clique.prune} * </p> */ private final Flag PRUNE_FLAG = new Flag(PRUNE_ID); /** * Holds the value of {@link #PRUNE_FLAG}. */ private boolean prune; /** * Constructor, adhering to * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable} * * @param config Parameterization */ public CLIQUE(Parameterization config) { super(config); if(config.grab(XSI_PARAM)) { xsi = XSI_PARAM.getValue(); } if(config.grab(TAU_PARAM)) { tau = TAU_PARAM.getValue(); } if(config.grab(PRUNE_FLAG)) { prune = PRUNE_FLAG.getValue(); } // logger.getWrappedLogger().setLevel(Level.FINE); } /** * Performs the CLIQUE algorithm on the given database. * */ @Override protected Clustering<SubspaceModel<V>> runInTime(Database<V> database) throws IllegalStateException { // 1. Identification of subspaces that contain clusters if(logger.isVerbose()) { logger.verbose("*** 1. Identification of subspaces that contain clusters ***"); } SortedMap<Integer, List<CLIQUESubspace<V>>> dimensionToDenseSubspaces = new TreeMap<Integer, List<CLIQUESubspace<V>>>(); List<CLIQUESubspace<V>> denseSubspaces = findOneDimensionalDenseSubspaces(database); dimensionToDenseSubspaces.put(0, denseSubspaces); if(logger.isVerbose()) { logger.verbose(" 1-dimensional dense subspaces: " + denseSubspaces.size()); } if(logger.isDebugging()) { for(CLIQUESubspace<V> s : denseSubspaces) { logger.debug(s.toString(" ")); } } for(int k = 2; k <= database.dimensionality() && !denseSubspaces.isEmpty(); k++) { denseSubspaces = findDenseSubspaces(database, denseSubspaces); dimensionToDenseSubspaces.put(k - 1, denseSubspaces); if(logger.isVerbose()) { logger.verbose(" " + k + "-dimensional dense subspaces: " + denseSubspaces.size()); } if(logger.isDebugging()) { for(CLIQUESubspace<V> s : denseSubspaces) { logger.debug(s.toString(" ")); } } } // 2. Identification of clusters if(logger.isVerbose()) { logger.verbose("*** 2. Identification of clusters ***"); } // build result int numClusters = 1; Clustering<SubspaceModel<V>> result = new Clustering<SubspaceModel<V>>(); for(Integer dim : dimensionToDenseSubspaces.keySet()) { List<CLIQUESubspace<V>> subspaces = dimensionToDenseSubspaces.get(dim); List<Pair<Subspace<V>, Set<Integer>>> modelsAndClusters = determineClusters(database, subspaces); if(logger.isVerbose()) { logger.verbose(" " + (dim + 1) + "-dimensional clusters: " + modelsAndClusters.size()); } for(Pair<Subspace<V>, Set<Integer>> modelAndCluster : modelsAndClusters) { DatabaseObjectGroup group = new DatabaseObjectGroupCollection<Set<Integer>>(modelAndCluster.second); Cluster<SubspaceModel<V>> newCluster = new Cluster<SubspaceModel<V>>(group); newCluster.setModel(new SubspaceModel<V>(modelAndCluster.first)); newCluster.setName("cluster_" + numClusters++); result.addCluster(newCluster); } } return result; } /** * Determines the clusters in the specified dense subspaces. * * @param database the database to run the algorithm on * @param denseSubspaces the dense subspaces in reverse order by their * coverage * @return the clusters in the specified dense subspaces and the corresponding * cluster models */ private List<Pair<Subspace<V>, Set<Integer>>> determineClusters(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { List<Pair<Subspace<V>, Set<Integer>>> clusters = new ArrayList<Pair<Subspace<V>, Set<Integer>>>(); for(CLIQUESubspace<V> subspace : denseSubspaces) { List<Pair<Subspace<V>, Set<Integer>>> clustersInSubspace = subspace.determineClusters(database); if(logger.isDebugging()) { logger.debugFine("Subspace " + subspace + " clusters " + clustersInSubspace.size()); } clusters.addAll(clustersInSubspace); } return clusters; } /** * Determines the one dimensional dense subspaces and performs a pruning if * this option is chosen. * * @param database the database to run the algorithm on * @return the one dimensional dense subspaces reverse ordered by their * coverage */ private List<CLIQUESubspace<V>> findOneDimensionalDenseSubspaces(Database<V> database) { List<CLIQUESubspace<V>> denseSubspaceCandidates = findOneDimensionalDenseSubspaceCandidates(database); if(prune) { return pruneDenseSubspaces(denseSubspaceCandidates); } return denseSubspaceCandidates; } /** * Determines the {@code k}-dimensional dense subspaces and performs a pruning * if this option is chosen. * * @param database the database to run the algorithm on * @param denseSubspaces the {@code (k-1)}-dimensional dense subspaces * @return a list of the {@code k}-dimensional dense subspaces sorted in * reverse order by their coverage */ private List<CLIQUESubspace<V>> findDenseSubspaces(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { List<CLIQUESubspace<V>> denseSubspaceCandidates = findDenseSubspaceCandidates(database, denseSubspaces); if(prune) { return pruneDenseSubspaces(denseSubspaceCandidates); } return denseSubspaceCandidates; } /** * Initializes and returns the one dimensional units. * * @param database the database to run the algorithm on * @return the created one dimensional units */ private Collection<CLIQUEUnit<V>> initOneDimensionalUnits(Database<V> database) { int dimensionality = database.dimensionality(); // initialize minima and maxima double[] minima = new double[dimensionality]; double[] maxima = new double[dimensionality]; for(int d = 0; d < dimensionality; d++) { maxima[d] = -Double.MAX_VALUE; minima[d] = Double.MAX_VALUE; } // update minima and maxima for(Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); updateMinMax(featureVector, minima, maxima); } for(int i = 0; i < maxima.length; i++) { maxima[i] += 0.0001; } // determine the unit length in each dimension double[] unit_lengths = new double[dimensionality]; for(int d = 0; d < dimensionality; d++) { unit_lengths[d] = (maxima[d] - minima[d]) / xsi; } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" minima: ").append(FormatUtil.format(minima, ", ", 2)); msg.append("\n maxima: ").append(FormatUtil.format(maxima, ", ", 2)); msg.append("\n unit lengths: ").append(FormatUtil.format(unit_lengths, ", ", 2)); logger.debugFiner(msg.toString()); } // determine the boundaries of the units double[][] unit_bounds = new double[xsi + 1][dimensionality]; for(int x = 0; x <= xsi; x++) { for(int d = 0; d < dimensionality; d++) { if(x < xsi) { unit_bounds[x][d] = minima[d] + x * unit_lengths[d]; } else { unit_bounds[x][d] = maxima[d]; } } } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" unit bounds ").append(new Matrix(unit_bounds).toString(" ")); logger.debugFiner(msg.toString()); } // build the 1 dimensional units List<CLIQUEUnit<V>> units = new ArrayList<CLIQUEUnit<V>>((xsi * dimensionality)); for(int x = 0; x < xsi; x++) { for(int d = 0; d < dimensionality; d++) { units.add(new CLIQUEUnit<V>(new Interval(d, unit_bounds[x][d], unit_bounds[x + 1][d]))); } } if(logger.isDebuggingFiner()) { StringBuffer msg = new StringBuffer(); msg.append(" total number of 1-dim units: ").append(units.size()); logger.debugFiner(msg.toString()); } return units; } /** * Updates the minima and maxima array according to the specified feature * vector. * * @param featureVector the feature vector * @param minima the array of minima * @param maxima the array of maxima */ private void updateMinMax(V featureVector, double[] minima, double[] maxima) { if(minima.length != featureVector.getDimensionality()) { throw new IllegalArgumentException("FeatureVectors differ in length."); } for(int d = 1; d <= featureVector.getDimensionality(); d++) { if((featureVector.doubleValue(d)) > maxima[d - 1]) { maxima[d - 1] = (featureVector.doubleValue(d)); } if((featureVector.doubleValue(d)) < minima[d - 1]) { minima[d - 1] = (featureVector.doubleValue(d)); } } } /** * Determines the one-dimensional dense subspace candidates by making a pass * over the database. * * @param database the database to run the algorithm on * @return the one-dimensional dense subspace candidates reverse ordered by * their coverage */ private List<CLIQUESubspace<V>> findOneDimensionalDenseSubspaceCandidates(Database<V> database) { Collection<CLIQUEUnit<V>> units = initOneDimensionalUnits(database); Collection<CLIQUEUnit<V>> denseUnits = new ArrayList<CLIQUEUnit<V>>(); Map<Integer, CLIQUESubspace<V>> denseSubspaces = new HashMap<Integer, CLIQUESubspace<V>>(); // identify dense units double total = database.size(); for(Iterator<Integer> it = database.iterator(); it.hasNext();) { V featureVector = database.get(it.next()); for(CLIQUEUnit<V> unit : units) { unit.addFeatureVector(featureVector); // unit is a dense unit if(!it.hasNext() && unit.selectivity(total) >= tau) { denseUnits.add(unit); // add the dense unit to its subspace int dim = unit.getIntervals().iterator().next().getDimension(); CLIQUESubspace<V> subspace_d = denseSubspaces.get(dim); if(subspace_d == null) { subspace_d = new CLIQUESubspace<V>(dim); denseSubspaces.put(dim, subspace_d); } subspace_d.addDenseUnit(unit); } } } if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(" number of 1-dim dense units: ").append(denseUnits.size()); msg.append("\n number of 1-dim dense subspace candidates: ").append(denseSubspaces.size()); logger.debugFine(msg.toString()); } List<CLIQUESubspace<V>> subspaceCandidates = new ArrayList<CLIQUESubspace<V>>(denseSubspaces.values()); Collections.sort(subspaceCandidates, new CLIQUESubspace.CoverageComparator()); return subspaceCandidates; } /** * Determines the {@code k}-dimensional dense subspace candidates from the * specified {@code (k-1)}-dimensional dense subspaces. * * @param database the database to run the algorithm on * @param denseSubspaces the {@code (k-1)}-dimensional dense subspaces * @return a list of the {@code k}-dimensional dense subspace candidates * reverse ordered by their coverage */ private List<CLIQUESubspace<V>> findDenseSubspaceCandidates(Database<V> database, List<CLIQUESubspace<V>> denseSubspaces) { // sort (k-1)-dimensional dense subspace according to their dimensions List<CLIQUESubspace<V>> denseSubspacesByDimensions = new ArrayList<CLIQUESubspace<V>>(denseSubspaces); Collections.sort(denseSubspacesByDimensions, new Subspace.DimensionComparator()); // determine k-dimensional dense subspace candidates double all = database.size(); List<CLIQUESubspace<V>> denseSubspaceCandidates = new ArrayList<CLIQUESubspace<V>>(); while(!denseSubspacesByDimensions.isEmpty()) { CLIQUESubspace<V> s1 = denseSubspacesByDimensions.remove(0); for(CLIQUESubspace<V> s2 : denseSubspacesByDimensions) { CLIQUESubspace<V> s = s1.join(s2, all, tau); if(s != null) { denseSubspaceCandidates.add(s); } } } // sort reverse by coverage Collections.sort(denseSubspaceCandidates, new CLIQUESubspace.CoverageComparator()); return denseSubspaceCandidates; } /** * Performs a MDL-based pruning of the specified dense subspaces as described * in the CLIQUE algorithm. * * @param denseSubspaces the subspaces to be pruned sorted in reverse order by * their coverage * @return the subspaces which are not pruned reverse ordered by their * coverage */ private List<CLIQUESubspace<V>> pruneDenseSubspaces(List<CLIQUESubspace<V>> denseSubspaces) { int[][] means = computeMeans(denseSubspaces); double[][] diffs = computeDiffs(denseSubspaces, means[0], means[1]); double[] codeLength = new double[denseSubspaces.size()]; double minCL = Double.MAX_VALUE; int min_i = -1; for(int i = 0; i < denseSubspaces.size(); i++) { int mi = means[0][i]; int mp = means[1][i]; double log_mi = mi == 0 ? 0 : StrictMath.log(mi) / StrictMath.log(2); double log_mp = mp == 0 ? 0 : StrictMath.log(mp) / StrictMath.log(2); double diff_mi = diffs[0][i]; double diff_mp = diffs[1][i]; codeLength[i] = log_mi + diff_mi + log_mp + diff_mp; if(codeLength[i] <= minCL) { minCL = codeLength[i]; min_i = i; } } return denseSubspaces.subList(0, min_i + 1); } /** * The specified sorted list of dense subspaces is divided into the selected * set I and the pruned set P. For each set the mean of the cover fractions is * computed. * * @param denseSubspaces the dense subspaces in reverse order by their * coverage * @return the mean of the cover fractions, the first value is the mean of the * selected set I, the second value is the mean of the pruned set P. */ private int[][] computeMeans(List<CLIQUESubspace<V>> denseSubspaces) { int n = denseSubspaces.size() - 1; int[] mi = new int[n + 1]; int[] mp = new int[n + 1]; double resultMI = 0; double resultMP = 0; for(int i = 0; i < denseSubspaces.size(); i++) { resultMI += denseSubspaces.get(i).getCoverage(); resultMP += denseSubspaces.get(n - i).getCoverage(); mi[i] = (int) Math.ceil(resultMI / (i + 1)); if(i != n) { mp[n - 1 - i] = (int) Math.ceil(resultMP / (i + 1)); } } int[][] result = new int[2][]; result[0] = mi; result[1] = mp; return result; } /** * The specified sorted list of dense subspaces is divided into the selected * set I and the pruned set P. For each set the difference from the specified * mean values is computed. * * @param denseSubspaces denseSubspaces the dense subspaces in reverse order * by their coverage * @param mi the mean of the selected sets I * @param mp the mean of the pruned sets P * @return the difference from the specified mean values, the first value is * the difference from the mean of the selected set I, the second * value is the difference from the mean of the pruned set P. */ private double[][] computeDiffs(List<CLIQUESubspace<V>> denseSubspaces, int[] mi, int[] mp) { int n = denseSubspaces.size() - 1; double[] diff_mi = new double[n + 1]; double[] diff_mp = new double[n + 1]; double resultMI = 0; double resultMP = 0; for(int i = 0; i < denseSubspaces.size(); i++) { double diffMI = Math.abs(denseSubspaces.get(i).getCoverage() - mi[i]); resultMI += diffMI == 0.0 ? 0 : StrictMath.log(diffMI) / StrictMath.log(2); double diffMP = (i != n) ? Math.abs(denseSubspaces.get(n - i).getCoverage() - mp[n - 1 - i]) : 0; resultMP += diffMP == 0.0 ? 0 : StrictMath.log(diffMP) / StrictMath.log(2); diff_mi[i] = resultMI; if(i != n) { diff_mp[n - 1 - i] = resultMP; } } double[][] result = new double[2][]; result[0] = diff_mi; result[1] = diff_mp; return result; } }
21,338
0.671422
0.665482
553
37.661846
36.119747
274
false
false
0
0
0
0
0
0
0.533454
false
false
15
2b14b967197898815360481e0c20f180be990c91
21,088,289,443,108
bf08e6f8ade8e42be6a1ba4600640819630479a2
/java/native/src/io/wulei123/demo05/classes01/Simulator.java
bce0ffec46f301f5a57bcc0286af7f9288683075
[]
no_license
wulei123/demos
https://github.com/wulei123/demos
1c57ceb87c00abed14912d94e4ec5365dbfe0037
c18fa4f0b5f34a2c2f2f654326078f088ca7fdc4
refs/heads/master
2018-11-27T00:12:52.915000
2018-10-24T07:11:21
2018-10-24T07:11:21
75,624,196
0
1
null
false
2017-06-15T09:25:21
2016-12-05T12:49:18
2017-06-10T12:53:03
2017-06-14T14:06:39
2,651
0
1
0
Java
null
null
package io.wulei123.demo05.classes01; import io.wulei123.demo05.classes02.ComputerAverage; /** * Created by ray on 2017/5/5. */ public class Simulator implements ComputerAverage{ public static void playSound(Animal animal){ animal.getAnimalName(); animal.cry(); } @Override public double average(double[] scores) { return 0; } }
UTF-8
Java
396
java
Simulator.java
Java
[ { "context": "5.classes02.ComputerAverage;\r\n\r\n/**\r\n * Created by ray on 2017/5/5.\r\n */\r\npublic class Simulator impleme", "end": 119, "score": 0.9732122421264648, "start": 116, "tag": "USERNAME", "value": "ray" } ]
null
[]
package io.wulei123.demo05.classes01; import io.wulei123.demo05.classes02.ComputerAverage; /** * Created by ray on 2017/5/5. */ public class Simulator implements ComputerAverage{ public static void playSound(Animal animal){ animal.getAnimalName(); animal.cry(); } @Override public double average(double[] scores) { return 0; } }
396
0.641414
0.588384
18
20
18.917952
52
false
false
0
0
0
0
0
0
0.277778
false
false
15
bbed070da338a8d6c94303957a422d4c5f5b8e7b
31,018,253,866,685
caf17154365f7193325356fe96c88a44719802a0
/src/com/hao/shiro/realm/CustomRealm.java
21e6fb1d98b7eafc07162da5ab8a1f66baaf623e
[]
no_license
haohj/shiro
https://github.com/haohj/shiro
b6d8529cb4daf5e7e8cb20bdf924798321c0ffbc
d5e9f42eaee8d6261d4253f9340172d352e09a0f
refs/heads/master
2020-03-21T15:10:18.089000
2018-08-09T07:30:33
2018-08-09T07:30:33
138,697,777
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hao.shiro.realm; import com.hao.shiro.po.ActiveUser; import com.hao.shiro.po.SysPermission; import com.hao.shiro.po.SysUser; import com.hao.shiro.service.SysService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; public class CustomRealm extends AuthorizingRealm { @Autowired private SysService sysService; @Override public String getName() { return "customRealm"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } /** * 认证 * * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //身份信息,用户名 String username = (String) token.getPrincipal(); SysUser user = null; try { user = sysService.findSysUserByUserCode(username); } catch (Exception e) { e.printStackTrace(); } //判断账号是否存在 if (user == null) { return null; } //根据用户id获取菜单 List<SysPermission> menuList = null; try { menuList = sysService.findMenuListByUserId(user.getId()); } catch (Exception e) { e.printStackTrace(); } //获取用户密码 String password = user.getPassword(); //盐 String salt = user.getSalt(); ActiveUser activeUser = new ActiveUser(); activeUser.setUserid(user.getId()); activeUser.setUsercode(user.getUsercode()); activeUser.setUsername(user.getUsername()); activeUser.setMenus(menuList); SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser, password, ByteSource.Util.bytes(salt), this.getName()); return simpleAuthenticationInfo; } /** * 授权 * * @param principal * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) { ActiveUser activeUser = (ActiveUser) principal.getPrimaryPrincipal(); //用户id String userId = activeUser.getUserid(); //模拟从数据库中查询权限 List<SysPermission> permissions = null; try { permissions = sysService.findPermissionListByUserId(userId); } catch (Exception e) { e.printStackTrace(); } //构建shiro授权信息 SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); for (SysPermission sysPermission : permissions) { simpleAuthorizationInfo.addStringPermission(sysPermission.getPercode()); } return simpleAuthorizationInfo; } }
UTF-8
Java
3,199
java
CustomRealm.java
Java
[ { "context": "\n\n //获取用户密码\n String password = user.getPassword();\n //盐\n String salt = user.getSalt", "end": 1728, "score": 0.6115648746490479, "start": 1717, "tag": "PASSWORD", "value": "getPassword" } ]
null
[]
package com.hao.shiro.realm; import com.hao.shiro.po.ActiveUser; import com.hao.shiro.po.SysPermission; import com.hao.shiro.po.SysUser; import com.hao.shiro.service.SysService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; public class CustomRealm extends AuthorizingRealm { @Autowired private SysService sysService; @Override public String getName() { return "customRealm"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } /** * 认证 * * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //身份信息,用户名 String username = (String) token.getPrincipal(); SysUser user = null; try { user = sysService.findSysUserByUserCode(username); } catch (Exception e) { e.printStackTrace(); } //判断账号是否存在 if (user == null) { return null; } //根据用户id获取菜单 List<SysPermission> menuList = null; try { menuList = sysService.findMenuListByUserId(user.getId()); } catch (Exception e) { e.printStackTrace(); } //获取用户密码 String password = user.<PASSWORD>(); //盐 String salt = user.getSalt(); ActiveUser activeUser = new ActiveUser(); activeUser.setUserid(user.getId()); activeUser.setUsercode(user.getUsercode()); activeUser.setUsername(user.getUsername()); activeUser.setMenus(menuList); SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser, password, ByteSource.Util.bytes(salt), this.getName()); return simpleAuthenticationInfo; } /** * 授权 * * @param principal * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) { ActiveUser activeUser = (ActiveUser) principal.getPrimaryPrincipal(); //用户id String userId = activeUser.getUserid(); //模拟从数据库中查询权限 List<SysPermission> permissions = null; try { permissions = sysService.findPermissionListByUserId(userId); } catch (Exception e) { e.printStackTrace(); } //构建shiro授权信息 SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); for (SysPermission sysPermission : permissions) { simpleAuthorizationInfo.addStringPermission(sysPermission.getPercode()); } return simpleAuthorizationInfo; } }
3,198
0.658039
0.658039
109
27.357798
26.868528
156
false
false
0
0
0
0
0
0
0.40367
false
false
15
1a99be9f710331ed5169be1abe7b23ad5473a0db
9,277,129,414,814
6087ab60b44edf4c808feb8fec16f3735632eebf
/product/server/src/test/java/com/carlos/product/service/ProductCategoryServiceTest.java
8846493acd1939a5f1a52970bdf256ce1d87ceb9
[ "Apache-2.0" ]
permissive
zouxiangzhong1998/spring-cloud-finchley
https://github.com/zouxiangzhong1998/spring-cloud-finchley
6d7ef43c1172447f0195f0955513f9398d4fd74c
7946026d9ff6bd95c27007c18cc9c73549fc38f2
refs/heads/master
2022-07-15T00:04:40.810000
2020-05-12T04:59:52
2020-05-12T05:00:18
261,460,902
1
0
Apache-2.0
false
2022-06-21T03:24:59
2020-05-05T12:28:23
2020-06-04T01:49:57
2022-06-21T03:24:58
196
0
0
3
Java
false
false
package com.carlos.product.service; import com.carlos.product.ProductApplicationTests; import com.carlos.product.pojo.ProductCategory; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Arrays; import java.util.List; /** * @author Carlos * @version 1.0.0 * @date 2020/5/5 16:36 */ public class ProductCategoryServiceTest extends ProductApplicationTests { @Autowired private ProductCategoryService productCategoryService; @Test public void findByCategoryTypeIn() { List<ProductCategory> list = productCategoryService.findByCategoryTypeIn(Arrays.asList(1, 2)); Assert.assertTrue(list.size() > 0); } }
UTF-8
Java
720
java
ProductCategoryServiceTest.java
Java
[ { "context": "til.Arrays;\nimport java.util.List;\n\n/**\n * @author Carlos\n * @version 1.0.0\n * @date 2020/5/5 16:36\n */\npub", "end": 318, "score": 0.9954018592834473, "start": 312, "tag": "NAME", "value": "Carlos" } ]
null
[]
package com.carlos.product.service; import com.carlos.product.ProductApplicationTests; import com.carlos.product.pojo.ProductCategory; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Arrays; import java.util.List; /** * @author Carlos * @version 1.0.0 * @date 2020/5/5 16:36 */ public class ProductCategoryServiceTest extends ProductApplicationTests { @Autowired private ProductCategoryService productCategoryService; @Test public void findByCategoryTypeIn() { List<ProductCategory> list = productCategoryService.findByCategoryTypeIn(Arrays.asList(1, 2)); Assert.assertTrue(list.size() > 0); } }
720
0.761111
0.738889
27
25.703703
25.843998
102
false
false
0
0
0
0
0
0
0.444444
false
false
15
55440704ef3ba7fdc15d398f5c18f28cef3d52c3
32,770,600,511,858
0c378f8d9b49b3ff5ca427000d335ebd14609f5a
/src/main/java/cmn/util/spring/batch/job/BatchJobUtil.java
41088286199715521492b564dbdb456035c5b889
[]
no_license
gregorio67/common-util
https://github.com/gregorio67/common-util
cc93c74d39ef0cc0555a71a1be687e9f508b7483
6d094a87cc1829d7d34756b465f2a381c4695575
refs/heads/master
2021-04-30T06:49:01.840000
2018-06-22T01:00:04
2018-06-22T01:00:04
121,455,833
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cmn.util.spring.batch.job; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.CommandLine; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.explore.JobExplorer; import cmn.util.common.NullUtil; import cmn.util.spring.BeanUtil; import cmn.util.spring.PropertiesUtil; public class BatchJobUtil { @Resource(name = "jobExplorer") private JobExplorer jobExplorer; /** * Return shell with full path * <pre> * * </pre> * @param groupId String * @param jobName String * @return String * @throws Exception */ public String getBatchSheel(String groupId, String jobName) throws Exception { /** Get Bean in context-jobshell.xml **/ Map<String,String> interfaceMap = BeanUtil.getBean( groupId); String shelltDir = PropertiesUtil.getString( interfaceMap.get( "directory" ) ); String shellName = interfaceMap != null ? interfaceMap.get( jobName ) : null; /** Set Shell full name **/ String execShell = shelltDir + "/" + shellName; return execShell; } /** * Run Shell with shell and parameter * <pre> * * </pre> * @param execShell String * @param shellParams String * @return int * @throws Exception */ public static Map<String, Object> runBatchShell(String execShell, String[] shellParams) throws Exception { Map<String, Object> resultMap = new HashMap<String, Object>(); int result = 0; /** Initiate Executor **/ DefaultExecutor executor = new DefaultExecutor(); /** Initiate Command Line **/ CommandLine cmdLine = CommandLine.parse(execShell); /** Set parameter to command line **/ StringBuilder sb = new StringBuilder().append("["); if (!NullUtil.isNull(shellParams) ) { for (String param : shellParams) { cmdLine.addArgument(param); sb.append(param).append(" "); } } sb.append("]"); /** Execute shell **/ try { result = executor.execute(cmdLine); resultMap.put("resultCode", result); // resultMap.put("message", new String("", execShell + " successfully started with " + sb.toString())); } catch(Exception ex) { // resultMap.put("message", String.join("", execShell + " failed to start shell with " + sb.toString())); } return resultMap; } /** * Check Batch Job running (If jobName is null, return false) * <pre> * * </pre> * @param jobName String * @return boolean * @throws Exception */ public boolean isJobRunning(String jobName) throws Exception { /** jobName is null, return true **/ if (NullUtil.isNull(jobName)) { return false; } boolean isRun = false; Set<JobExecution> executions = jobExplorer.findRunningJobExecutions(jobName); for(JobExecution execution : executions ){ if (execution.getStatus() == BatchStatus.STARTED) { isRun = true; } } return isRun; } }
UTF-8
Java
3,006
java
BatchJobUtil.java
Java
[]
null
[]
package cmn.util.spring.batch.job; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.CommandLine; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.explore.JobExplorer; import cmn.util.common.NullUtil; import cmn.util.spring.BeanUtil; import cmn.util.spring.PropertiesUtil; public class BatchJobUtil { @Resource(name = "jobExplorer") private JobExplorer jobExplorer; /** * Return shell with full path * <pre> * * </pre> * @param groupId String * @param jobName String * @return String * @throws Exception */ public String getBatchSheel(String groupId, String jobName) throws Exception { /** Get Bean in context-jobshell.xml **/ Map<String,String> interfaceMap = BeanUtil.getBean( groupId); String shelltDir = PropertiesUtil.getString( interfaceMap.get( "directory" ) ); String shellName = interfaceMap != null ? interfaceMap.get( jobName ) : null; /** Set Shell full name **/ String execShell = shelltDir + "/" + shellName; return execShell; } /** * Run Shell with shell and parameter * <pre> * * </pre> * @param execShell String * @param shellParams String * @return int * @throws Exception */ public static Map<String, Object> runBatchShell(String execShell, String[] shellParams) throws Exception { Map<String, Object> resultMap = new HashMap<String, Object>(); int result = 0; /** Initiate Executor **/ DefaultExecutor executor = new DefaultExecutor(); /** Initiate Command Line **/ CommandLine cmdLine = CommandLine.parse(execShell); /** Set parameter to command line **/ StringBuilder sb = new StringBuilder().append("["); if (!NullUtil.isNull(shellParams) ) { for (String param : shellParams) { cmdLine.addArgument(param); sb.append(param).append(" "); } } sb.append("]"); /** Execute shell **/ try { result = executor.execute(cmdLine); resultMap.put("resultCode", result); // resultMap.put("message", new String("", execShell + " successfully started with " + sb.toString())); } catch(Exception ex) { // resultMap.put("message", String.join("", execShell + " failed to start shell with " + sb.toString())); } return resultMap; } /** * Check Batch Job running (If jobName is null, return false) * <pre> * * </pre> * @param jobName String * @return boolean * @throws Exception */ public boolean isJobRunning(String jobName) throws Exception { /** jobName is null, return true **/ if (NullUtil.isNull(jobName)) { return false; } boolean isRun = false; Set<JobExecution> executions = jobExplorer.findRunningJobExecutions(jobName); for(JobExecution execution : executions ){ if (execution.getStatus() == BatchStatus.STARTED) { isRun = true; } } return isRun; } }
3,006
0.685961
0.685629
117
24.683762
24.617292
107
false
false
0
0
0
0
0
0
1.863248
false
false
15
9a895ac44869958dfbf4c54fb7d47c64f5e1b754
2,508,260,962,305
a3709a21a6f8fe95f154c809cf36cade04060064
/src/main/java/org/saculo/crawler/domain/ArticleFacade.java
0b7bbfd6f489d9b7b11be9431859793eb11a2ce2
[]
no_license
saculo/crawler
https://github.com/saculo/crawler
b2379b73332ae6e174d54c3e48eda03a165dbed2
005d0fb189491ecec50a3c9f446dc1bf6b9c0070
refs/heads/master
2022-10-05T00:19:24.890000
2020-06-16T15:35:47
2020-06-16T15:35:47
242,522,432
0
1
null
false
2022-09-01T23:20:34
2020-02-23T13:31:05
2020-06-16T15:35:50
2022-09-01T23:20:33
28
0
0
4
Java
false
false
package org.saculo.crawler.domain; import io.vavr.collection.Stream; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class ArticleFacade { private final ArticleDownloader articleDownloader; private final ArticleCreator articleCreator; public Stream<Article> createArticles () { return articleDownloader.download() .map(articleCreator::create); } }
UTF-8
Java
430
java
ArticleFacade.java
Java
[]
null
[]
package org.saculo.crawler.domain; import io.vavr.collection.Stream; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class ArticleFacade { private final ArticleDownloader articleDownloader; private final ArticleCreator articleCreator; public Stream<Article> createArticles () { return articleDownloader.download() .map(articleCreator::create); } }
430
0.725581
0.725581
15
27.666666
20.815592
61
false
false
0
0
0
0
0
0
0.4
false
false
15
6cb37f62bd09009893f464042c28ddcaa9753204
4,020,089,440,378
4cea15a3b85f620984c56d9ec6a94c3e57d09a62
/src/main/java/com/core/PageOperations/HomePage.java
680030bd6bc3da495735f30dfdaa1dee874bb41c
[]
no_license
myselfamey/MakeMyTripAssignment
https://github.com/myselfamey/MakeMyTripAssignment
0b640ce36849b25112d2138e9fc39ad1dfbdf312
f6213cde4c073c5f6656ccfcf110bb69d4f7b00d
refs/heads/master
2023-04-03T10:13:57.800000
2021-03-29T06:23:28
2021-03-29T06:23:28
352,440,756
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.core.PageOperations; import com.core.Constants.MonthEnum; import com.core.PageEvents.HomePageEvents; import com.core.Utils.HelperUtils; import com.core.Utils.WebUtils; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; public class HomePage implements HomePageEvents { private final WebDriver homePageDriver; private final String cityAutosuggestionsKey = "//div[@role='listbox']/div[1]/ul/li[%]/div/div[2]"; private final String childrenLocatorKey = "//li[@data-cy='children-$']"; private final String adultsLocatorKey = "//li[@data-cy='adults-$']"; private final String infantsLocatorKey = "//li[@data-cy='infants-$']"; private final String travellersCLassLocatorKey = "//li[@data-cy='travelClass-$']"; public HomePage(WebDriver driver) { homePageDriver = driver; } public String getPageUrl() { return WebUtils.getCurrentUrl(homePageDriver); } public String getPageTitle() { return WebUtils.getPageTitle(homePageDriver); } public void closeLoginAccountPopupIfPresents() { if (WebUtils.isDisplayed(homePageDriver, loginPopup)) WebUtils.elementClick(WebUtils.getElement(homePageDriver, loginAccountButton)); } public boolean roundTripVisibility() { return WebUtils.isDisplayed(homePageDriver, roundTripOption); } public void selectTripType(String trip) { WebUtils.getElements(homePageDriver, tripTypeGeneric) .stream() .filter(tripType -> trip.equalsIgnoreCase(WebUtils.getAttributeValue(tripType, "data-cy"))) .forEach(tripType -> WebUtils.elementClick(tripType)); } public boolean roundTripSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, roundTripOption), "class").equals("selected"); } public boolean fromCitySectionVisibility() { return WebUtils.isDisplayed(homePageDriver, fromCitySection); } public boolean toCitySectionVisibility() { return WebUtils.isDisplayed(homePageDriver, toCitySection); } public String fromCitySectionTitleText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, fromCitySectionTitleText)); } public String toCitySectionTitleText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, toCitySectionTitleText)); } public void selectFromCityOption() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, fromCitySelectedName)); } public void enterKeysForSourceCity(String city) { enterKeysForCity(city, sourceCityPlaceholder); } public void enterKeysForDestinationCity(String city) { enterKeysForCity(city, destinationCityPlaceholder); } public void selectSourceCityFromAutosuggestions(String cityCode) { selectCityFromAutosuggestions(cityCode, cityAutosuggestionsKey); } public void selectDestinationCityFromAutosuggestions(String cityCode) { selectCityFromAutosuggestions(cityCode, cityAutosuggestionsKey); } public String verifySourceCitySelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, fromCitySelectedName), "value"); } public String verifySourceCityCodeSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, fromCitySelectedCode), "title"); } public String verifyDestinationCitySelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, toCitySelectedName), "value"); } public String verifyDestinationCityCodeSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, toCitySelectedCode), "title"); } public void selectDepartureDate(String date) { selectDateOnCalender(date); } public void selectReturnDate(String date) { selectDateOnCalender(date); } public String verifyDepartureDate() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, departureDateValue), "value"); } public String verifyReturnDate() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, returnDateValue), "value"); } public boolean verifyDepartureSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, departureDateSection); } public boolean verifyReturnSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, returnDateSection); } public String verifyDepartureSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, departureDateText)); } public String verifyReturnSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, returnDateText)); } public void selectTravellersSection() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, travellersAndClassSection)); } public boolean verifyTravellersSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, travellersAndClassSection); } public String verifyTravellersSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, travellersAndClassSectionText)); } public String travellersClassValueSelected() { return WebUtils.getText(WebUtils.getElement(homePageDriver, travellersClassValueSelected)); } public String verifyOverallTravellers() { return WebUtils.getText(WebUtils.getElement(homePageDriver, overallTravellers)); } public void selectChildren(int children) { String value = String.valueOf(children); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(childrenLocatorKey.replace("$", value)))); } public void selectAdults(int adults) { String value = String.valueOf(adults); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(adultsLocatorKey.replace("$", value)))); } public void selectInfants(int infants) { String value = String.valueOf(infants); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(infantsLocatorKey.replace("$", value)))); } public void selectTravellerClass(String value) { for (int i = 0; i <= 2; i++) { WebElement element = WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(travellersCLassLocatorKey.replace("$", String.valueOf(i)))); if (value.equalsIgnoreCase(element.getText())) WebUtils.elementClick(element); } } public void clickOnApplyButtonOfTravellerSection() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, TravellersAndClassButton)); } public FlightSearchPage clickOnSearchButtonOfHomePage() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, submitBookingDetails)); return new FlightSearchPage(homePageDriver); } public boolean searchButtonOfHomePageVisibility() { return WebUtils.isDisplayed(homePageDriver, submitBookingDetails); } private void enterKeysForCity(String city, By locator) { for (Character character : city.toCharArray()) { WebUtils.enterKeys(WebUtils.getElement(homePageDriver, locator), String.valueOf(character)); try { HelperUtils.doWait(Thread.currentThread(), 700); } catch (InterruptedException e) { e.printStackTrace(); } } } private void selectCityFromAutosuggestions(String cityCode, String locatorKey) { List<WebElement> autosuggestions = WebUtils.getElements(homePageDriver, WebUtils.getLocatorFromXpath(locatorKey.replace("[%]", ""))); for (int i = 0; i < autosuggestions.size(); i++) { if (cityCode.equals(WebUtils.getText(autosuggestions.get(i)))) { WebUtils.elementClick(WebUtils .getElement(homePageDriver, WebUtils .getLocatorFromXpath(locatorKey.replace("%", String.valueOf(i + 1))))); break; } } } private void selectDateOnCalender(String date) { String[] time = date.split(" "); String dateOfMonth = time[0]; String month = time[1]; String year = time[2]; selectMonthYear(month, year); selectDateAfterMonth(dateOfMonth, month); } private void selectMonthYear(String month, String year) { boolean flag = false; List<WebElement> monthYearCaptionsElements = WebUtils.getElements(homePageDriver, monthYearCaptionCalender); while (true) { for (WebElement element : monthYearCaptionsElements) { String monthYearCaption = WebUtils.getText(element); if ((MonthEnum.valueOf(month.toUpperCase()).getFullname() + year).equalsIgnoreCase(monthYearCaption)) { flag = true; break; } } if (flag == true) break; WebUtils.elementClick(WebUtils.getElement(homePageDriver, rightArrowCalender)); } } private void selectDateAfterMonth(String dayOfMonth, String month) { List<WebElement> dateElements = WebUtils.getElements(homePageDriver, availableDateCalender); for (WebElement element : dateElements) { String text = element.getAttribute("aria-label"); if (text.toLowerCase().contains(month.toLowerCase() + " " + dayOfMonth)) { WebUtils.elementClick(element); break; } } } }
UTF-8
Java
9,809
java
HomePage.java
Java
[]
null
[]
package com.core.PageOperations; import com.core.Constants.MonthEnum; import com.core.PageEvents.HomePageEvents; import com.core.Utils.HelperUtils; import com.core.Utils.WebUtils; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; public class HomePage implements HomePageEvents { private final WebDriver homePageDriver; private final String cityAutosuggestionsKey = "//div[@role='listbox']/div[1]/ul/li[%]/div/div[2]"; private final String childrenLocatorKey = "//li[@data-cy='children-$']"; private final String adultsLocatorKey = "//li[@data-cy='adults-$']"; private final String infantsLocatorKey = "//li[@data-cy='infants-$']"; private final String travellersCLassLocatorKey = "//li[@data-cy='travelClass-$']"; public HomePage(WebDriver driver) { homePageDriver = driver; } public String getPageUrl() { return WebUtils.getCurrentUrl(homePageDriver); } public String getPageTitle() { return WebUtils.getPageTitle(homePageDriver); } public void closeLoginAccountPopupIfPresents() { if (WebUtils.isDisplayed(homePageDriver, loginPopup)) WebUtils.elementClick(WebUtils.getElement(homePageDriver, loginAccountButton)); } public boolean roundTripVisibility() { return WebUtils.isDisplayed(homePageDriver, roundTripOption); } public void selectTripType(String trip) { WebUtils.getElements(homePageDriver, tripTypeGeneric) .stream() .filter(tripType -> trip.equalsIgnoreCase(WebUtils.getAttributeValue(tripType, "data-cy"))) .forEach(tripType -> WebUtils.elementClick(tripType)); } public boolean roundTripSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, roundTripOption), "class").equals("selected"); } public boolean fromCitySectionVisibility() { return WebUtils.isDisplayed(homePageDriver, fromCitySection); } public boolean toCitySectionVisibility() { return WebUtils.isDisplayed(homePageDriver, toCitySection); } public String fromCitySectionTitleText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, fromCitySectionTitleText)); } public String toCitySectionTitleText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, toCitySectionTitleText)); } public void selectFromCityOption() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, fromCitySelectedName)); } public void enterKeysForSourceCity(String city) { enterKeysForCity(city, sourceCityPlaceholder); } public void enterKeysForDestinationCity(String city) { enterKeysForCity(city, destinationCityPlaceholder); } public void selectSourceCityFromAutosuggestions(String cityCode) { selectCityFromAutosuggestions(cityCode, cityAutosuggestionsKey); } public void selectDestinationCityFromAutosuggestions(String cityCode) { selectCityFromAutosuggestions(cityCode, cityAutosuggestionsKey); } public String verifySourceCitySelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, fromCitySelectedName), "value"); } public String verifySourceCityCodeSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, fromCitySelectedCode), "title"); } public String verifyDestinationCitySelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, toCitySelectedName), "value"); } public String verifyDestinationCityCodeSelected() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, toCitySelectedCode), "title"); } public void selectDepartureDate(String date) { selectDateOnCalender(date); } public void selectReturnDate(String date) { selectDateOnCalender(date); } public String verifyDepartureDate() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, departureDateValue), "value"); } public String verifyReturnDate() { return WebUtils.getAttributeValue(WebUtils.getElement(homePageDriver, returnDateValue), "value"); } public boolean verifyDepartureSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, departureDateSection); } public boolean verifyReturnSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, returnDateSection); } public String verifyDepartureSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, departureDateText)); } public String verifyReturnSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, returnDateText)); } public void selectTravellersSection() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, travellersAndClassSection)); } public boolean verifyTravellersSectionVisibility() { return WebUtils.isDisplayed(homePageDriver, travellersAndClassSection); } public String verifyTravellersSectionText() { return WebUtils.getText(WebUtils.getElement(homePageDriver, travellersAndClassSectionText)); } public String travellersClassValueSelected() { return WebUtils.getText(WebUtils.getElement(homePageDriver, travellersClassValueSelected)); } public String verifyOverallTravellers() { return WebUtils.getText(WebUtils.getElement(homePageDriver, overallTravellers)); } public void selectChildren(int children) { String value = String.valueOf(children); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(childrenLocatorKey.replace("$", value)))); } public void selectAdults(int adults) { String value = String.valueOf(adults); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(adultsLocatorKey.replace("$", value)))); } public void selectInfants(int infants) { String value = String.valueOf(infants); WebUtils.elementClick(WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(infantsLocatorKey.replace("$", value)))); } public void selectTravellerClass(String value) { for (int i = 0; i <= 2; i++) { WebElement element = WebUtils.getElement(homePageDriver, WebUtils.getLocatorFromXpath(travellersCLassLocatorKey.replace("$", String.valueOf(i)))); if (value.equalsIgnoreCase(element.getText())) WebUtils.elementClick(element); } } public void clickOnApplyButtonOfTravellerSection() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, TravellersAndClassButton)); } public FlightSearchPage clickOnSearchButtonOfHomePage() { WebUtils.elementClick(WebUtils.getElement(homePageDriver, submitBookingDetails)); return new FlightSearchPage(homePageDriver); } public boolean searchButtonOfHomePageVisibility() { return WebUtils.isDisplayed(homePageDriver, submitBookingDetails); } private void enterKeysForCity(String city, By locator) { for (Character character : city.toCharArray()) { WebUtils.enterKeys(WebUtils.getElement(homePageDriver, locator), String.valueOf(character)); try { HelperUtils.doWait(Thread.currentThread(), 700); } catch (InterruptedException e) { e.printStackTrace(); } } } private void selectCityFromAutosuggestions(String cityCode, String locatorKey) { List<WebElement> autosuggestions = WebUtils.getElements(homePageDriver, WebUtils.getLocatorFromXpath(locatorKey.replace("[%]", ""))); for (int i = 0; i < autosuggestions.size(); i++) { if (cityCode.equals(WebUtils.getText(autosuggestions.get(i)))) { WebUtils.elementClick(WebUtils .getElement(homePageDriver, WebUtils .getLocatorFromXpath(locatorKey.replace("%", String.valueOf(i + 1))))); break; } } } private void selectDateOnCalender(String date) { String[] time = date.split(" "); String dateOfMonth = time[0]; String month = time[1]; String year = time[2]; selectMonthYear(month, year); selectDateAfterMonth(dateOfMonth, month); } private void selectMonthYear(String month, String year) { boolean flag = false; List<WebElement> monthYearCaptionsElements = WebUtils.getElements(homePageDriver, monthYearCaptionCalender); while (true) { for (WebElement element : monthYearCaptionsElements) { String monthYearCaption = WebUtils.getText(element); if ((MonthEnum.valueOf(month.toUpperCase()).getFullname() + year).equalsIgnoreCase(monthYearCaption)) { flag = true; break; } } if (flag == true) break; WebUtils.elementClick(WebUtils.getElement(homePageDriver, rightArrowCalender)); } } private void selectDateAfterMonth(String dayOfMonth, String month) { List<WebElement> dateElements = WebUtils.getElements(homePageDriver, availableDateCalender); for (WebElement element : dateElements) { String text = element.getAttribute("aria-label"); if (text.toLowerCase().contains(month.toLowerCase() + " " + dayOfMonth)) { WebUtils.elementClick(element); break; } } } }
9,809
0.691814
0.69059
263
36.285172
36.226978
158
false
false
0
0
0
0
0
0
0.574144
false
false
15
db7bce4a32692166a0e563b850b7849cf76509d4
21,801,254,036,291
2d3a54a0b5e8b034f4011e93a30f5dfd509662c1
/algorithms1/percolation/PercolationStats.java
9e198c590639266bf9892a930fbed9630a3cf38e
[]
no_license
akustik/java
https://github.com/akustik/java
618a0956a3fc7c6448a1f273b61f441f4727aab5
872c028425f16eeef2db6bfd04028825bbda6b23
refs/heads/master
2021-01-23T11:40:52.647000
2017-04-12T06:48:35
2017-04-12T06:48:35
88,019,084
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Performs statistical tests with the percolation model. */ public class PercolationStats { private double[] threshold; private int nExperiments; /** * Performs T independent computational experiments on an N-by-N grid. */ public PercolationStats(int N, int T) { nExperiments = T; if (N <= 0) throw new IllegalArgumentException("The matrix size must be positive"); if (nExperiments <= 0) throw new IllegalArgumentException( "The number of experiments must be positive"); threshold = new double[nExperiments]; for (int expIdx = 0; expIdx < nExperiments; expIdx++) { Percolation model = new Percolation(N); do { model.open(StdRandom.uniform(N) + 1, StdRandom.uniform(N) + 1); } while(!model.percolates()); int openCount = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (model.isOpen(i, j)) openCount++; } } threshold[expIdx] = ((double) openCount) / ((double) N*N); } } /** * sample mean of percolation threshold */ public double mean() { return StdStats.mean(threshold); } /** * sample standard deviation of percolation threshold */ public double stddev() { if (nExperiments > 1) return StdStats.stddev(threshold); else return Double.NaN; } /** * returns lower bound of the 95% confidence interval */ public double confidenceLo() { return mean() - 1.96 * stddev() / Math.sqrt(nExperiments); } /** * returns upper bound of the 95% confidence interval */ public double confidenceHi() { return mean() + 1.96 * stddev() / Math.sqrt(nExperiments); } public static void main(String[] args) { PercolationStats stats = new PercolationStats( Integer.parseInt(args[0]), Integer.parseInt(args[1])); System.out.println("mean = " + stats.mean()); System.out.println("stddev = " + stats.stddev()); System.out.println("95% confidence interval = " + stats.confidenceLo() + ", " + stats.confidenceHi()); } }
UTF-8
Java
2,488
java
PercolationStats.java
Java
[]
null
[]
/** * Performs statistical tests with the percolation model. */ public class PercolationStats { private double[] threshold; private int nExperiments; /** * Performs T independent computational experiments on an N-by-N grid. */ public PercolationStats(int N, int T) { nExperiments = T; if (N <= 0) throw new IllegalArgumentException("The matrix size must be positive"); if (nExperiments <= 0) throw new IllegalArgumentException( "The number of experiments must be positive"); threshold = new double[nExperiments]; for (int expIdx = 0; expIdx < nExperiments; expIdx++) { Percolation model = new Percolation(N); do { model.open(StdRandom.uniform(N) + 1, StdRandom.uniform(N) + 1); } while(!model.percolates()); int openCount = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (model.isOpen(i, j)) openCount++; } } threshold[expIdx] = ((double) openCount) / ((double) N*N); } } /** * sample mean of percolation threshold */ public double mean() { return StdStats.mean(threshold); } /** * sample standard deviation of percolation threshold */ public double stddev() { if (nExperiments > 1) return StdStats.stddev(threshold); else return Double.NaN; } /** * returns lower bound of the 95% confidence interval */ public double confidenceLo() { return mean() - 1.96 * stddev() / Math.sqrt(nExperiments); } /** * returns upper bound of the 95% confidence interval */ public double confidenceHi() { return mean() + 1.96 * stddev() / Math.sqrt(nExperiments); } public static void main(String[] args) { PercolationStats stats = new PercolationStats( Integer.parseInt(args[0]), Integer.parseInt(args[1])); System.out.println("mean = " + stats.mean()); System.out.println("stddev = " + stats.stddev()); System.out.println("95% confidence interval = " + stats.confidenceLo() + ", " + stats.confidenceHi()); } }
2,488
0.513666
0.504421
91
26.351648
23.199268
85
false
false
0
0
0
0
0
0
0.351648
false
false
15
c6665458c964eb5ae082408e128dfabe8086f11c
24,927,990,232,067
d837775035a54188110d950575b563c48a7571a4
/src/main/java/gak/library/music/proxy/implementation/ArtistProxy.java
875e7aa93878b70f14aff85a1c07e5f39b9dd110
[]
no_license
Yvangak/gakmusicstore
https://github.com/Yvangak/gakmusicstore
89584d2cefa1b46d9425da96da6ed08c34649458
fd2a82b49735d141e6af1cb67073a68a96477469
refs/heads/master
2020-05-15T18:30:33.532000
2019-04-23T15:36:20
2019-04-23T15:36:20
182,427,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gak.library.music.proxy.implementation; import gak.library.music.adapter.ArtistAdapter; import gak.library.music.domain.Artist; import gak.library.music.exception.ApiCorruptedResultException; import gak.library.music.exception.ArtistNotFoundException; import gak.library.music.proxy.IArtistProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.text.MessageFormat; @Component public class ArtistProxy extends ProxyConfiguration implements IArtistProxy { @Value("${last.fm.api.artist.info.url}") private String url; @Value("${last.fm.api.key}") private String apiKey; @Autowired private RestTemplate restTemplate; @Override public Artist getArtistInfo(String artistName) throws ArtistNotFoundException, ApiCorruptedResultException { String request = MessageFormat.format(url, apiKey, artistName); ResponseEntity<String> response = restTemplate.getForEntity(request, String.class); String result = response.getBody(); return ArtistAdapter.convertToArtist(result); } }
UTF-8
Java
1,288
java
ArtistProxy.java
Java
[]
null
[]
package gak.library.music.proxy.implementation; import gak.library.music.adapter.ArtistAdapter; import gak.library.music.domain.Artist; import gak.library.music.exception.ApiCorruptedResultException; import gak.library.music.exception.ArtistNotFoundException; import gak.library.music.proxy.IArtistProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.text.MessageFormat; @Component public class ArtistProxy extends ProxyConfiguration implements IArtistProxy { @Value("${last.fm.api.artist.info.url}") private String url; @Value("${last.fm.api.key}") private String apiKey; @Autowired private RestTemplate restTemplate; @Override public Artist getArtistInfo(String artistName) throws ArtistNotFoundException, ApiCorruptedResultException { String request = MessageFormat.format(url, apiKey, artistName); ResponseEntity<String> response = restTemplate.getForEntity(request, String.class); String result = response.getBody(); return ArtistAdapter.convertToArtist(result); } }
1,288
0.78882
0.78882
39
32.025642
29.159584
112
false
false
0
0
0
0
0
0
0.589744
false
false
15
5c47a8001be76acd7a3f3117a2731cdb2115bb3c
240,518,217,440
5eb5612a630e92877a51685afeeb9a1522df8969
/src/test/java/com/zx/RedisTest.java
6db2596cdce48a358dd7799382983fe5ea66dfc0
[]
no_license
poseidon2011/redis
https://github.com/poseidon2011/redis
cdce9ce388b172dfaf2ad560a3cfd9b6a914633b
6aca36702dc336c5a3da96563f37b79632aaef1c
refs/heads/master
2021-06-16T08:40:23.242000
2017-05-24T15:21:14
2017-05-24T15:21:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zx; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet; import java.util.Set; /** * Created by 97038 on 2017-05-10. */ public class RedisTest { public static void main(String[] args) { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("192.168.0.104",7001)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7002)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7003)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7004)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7005)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7006)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7007)); JedisPoolConfig cfg = new JedisPoolConfig(); cfg.setMaxTotal(100); JedisCluster jc =new JedisCluster(jedisClusterNode,6000,100,cfg); System.out.println(jc.set("a","111")); System.out.println(jc.set("b","222")); System.out.println(jc.set("c","333")); System.out.println(jc.set("d","444")); System.out.println(jc.set("e","555")); System.out.println(jc.get("a")); System.out.println(jc.get("b")); System.out.println(jc.get("c")); System.out.println(jc.get("d")); System.out.println(jc.get("e")); } }
UTF-8
Java
1,471
java
RedisTest.java
Java
[ { "context": "HashSet;\nimport java.util.Set;\n\n/**\n * Created by 97038 on 2017-05-10.\n */\npublic class RedisTest {\n\n ", "end": 215, "score": 0.9971895217895508, "start": 210, "tag": "USERNAME", "value": "97038" }, { "context": "();\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7001));\n jedisClusterNode.add(new HostAnd", "end": 437, "score": 0.9996694326400757, "start": 424, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7002));\n jedisClusterNode.add(new HostAnd", "end": 506, "score": 0.9996534585952759, "start": 493, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7003));\n jedisClusterNode.add(new HostAnd", "end": 575, "score": 0.9996543526649475, "start": 562, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7004));\n jedisClusterNode.add(new HostAnd", "end": 644, "score": 0.9996732473373413, "start": 631, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7005));\n jedisClusterNode.add(new HostAnd", "end": 713, "score": 0.9996439814567566, "start": 700, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7006));\n jedisClusterNode.add(new HostAnd", "end": 782, "score": 0.9996464252471924, "start": 769, "tag": "IP_ADDRESS", "value": "192.168.0.104" }, { "context": "));\n jedisClusterNode.add(new HostAndPort(\"192.168.0.104\",7007));\n\n JedisPoolConfig cfg = new Jedis", "end": 851, "score": 0.9996468424797058, "start": 838, "tag": "IP_ADDRESS", "value": "192.168.0.104" } ]
null
[]
package com.zx; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet; import java.util.Set; /** * Created by 97038 on 2017-05-10. */ public class RedisTest { public static void main(String[] args) { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("192.168.0.104",7001)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7002)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7003)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7004)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7005)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7006)); jedisClusterNode.add(new HostAndPort("192.168.0.104",7007)); JedisPoolConfig cfg = new JedisPoolConfig(); cfg.setMaxTotal(100); JedisCluster jc =new JedisCluster(jedisClusterNode,6000,100,cfg); System.out.println(jc.set("a","111")); System.out.println(jc.set("b","222")); System.out.println(jc.set("c","333")); System.out.println(jc.set("d","444")); System.out.println(jc.set("e","555")); System.out.println(jc.get("a")); System.out.println(jc.get("b")); System.out.println(jc.get("c")); System.out.println(jc.get("d")); System.out.println(jc.get("e")); } }
1,471
0.648538
0.556084
43
33.209301
25.249046
73
false
false
0
0
0
0
0
0
0.976744
false
false
15
59066a1e4c8d3ad74845c8cb0778bf98ce951549
8,839,042,748,910
a6866a8f46c97815dd66847d3a25dbfbabf670af
/supermarket/src/supermarket/run/SupermarketRun.java
9d1d23219e394bbbe860e8944433e682efaaddb2
[]
no_license
eagualco/Supermarket
https://github.com/eagualco/Supermarket
fc69cd55db3262c97753d4d571f28354884ab0d5
726c3f59b08365e58726bc0603228081ccaffbd7
refs/heads/master
2020-09-10T08:47:58.621000
2019-11-14T16:49:01
2019-11-14T16:49:01
221,700,329
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package supermarket.run; import java.util.ArrayList; import java.util.Collections; import java.util.List; import supermarket.entities.*; public class SupermarketRun { public static void main(String[] args) { List<Product> productList = new ArrayList<>(); productList.add(new Drink("Coca-Cola Zero", 1.5f, 20)); productList.add(new Drink("Coca-Cola", 1.5f, 18)); productList.add(new HairProduct("Shampoo Sedal", 500, 19)); productList.add(new Fruit("Frutillas", 64, "kilo")); for(Product product : productList) { System.out.println(product.toString()); } System.out.println("=============================\n"); Collections.sort(productList); // sort by price in ascending order System.out.println("Producto más caro: " + productList.get(productList.size()-1).getName()); System.out.println("\nProducto más barato: " + productList.get(0).getName()); } }
WINDOWS-1250
Java
905
java
SupermarketRun.java
Java
[]
null
[]
package supermarket.run; import java.util.ArrayList; import java.util.Collections; import java.util.List; import supermarket.entities.*; public class SupermarketRun { public static void main(String[] args) { List<Product> productList = new ArrayList<>(); productList.add(new Drink("Coca-Cola Zero", 1.5f, 20)); productList.add(new Drink("Coca-Cola", 1.5f, 18)); productList.add(new HairProduct("Shampoo Sedal", 500, 19)); productList.add(new Fruit("Frutillas", 64, "kilo")); for(Product product : productList) { System.out.println(product.toString()); } System.out.println("=============================\n"); Collections.sort(productList); // sort by price in ascending order System.out.println("Producto más caro: " + productList.get(productList.size()-1).getName()); System.out.println("\nProducto más barato: " + productList.get(0).getName()); } }
905
0.675526
0.6567
33
26.363636
26.941933
94
false
false
0
0
0
0
0
0
1.939394
false
false
15
ecaafc2659456e089bf489c7ed0a307e1f00d01d
1,838,246,007,168
7f9e44a5f3137f2830fb8b0c3c0dd5ea5ca39aa2
/src/main/java/std/wlj/cache/lru/CacheStats.java
9a353c0f3261c5611eb85abb4459ab9d4c7eb3d5
[]
no_license
wjohnson000/wlj-place-test
https://github.com/wjohnson000/wlj-place-test
042398f3b6f3472638e2c6d263419eb4670a5dde
d23ece28efe4f79b9f5343a75b1a85e8567d3021
refs/heads/master
2021-08-03T22:42:30.127000
2021-04-29T21:19:27
2021-04-29T21:19:27
18,767,871
0
0
null
false
2021-08-03T12:18:26
2014-04-14T16:30:20
2021-04-29T21:19:37
2021-08-03T12:18:24
2,332
0
0
13
Java
false
false
package std.wlj.cache.lru; import java.util.concurrent.atomic.LongAdder; /** * Cache statistics: * <ul> * <li><strong>GET count</strong> - the number of 'get' calls</li> * <li><strong>HIT count</strong> - the number of 'get' calls that returned a non-null value</li> * <li><strong>PUT count</strong> - the number of 'put' calls</li> * <li><strong>EVICT count</strong> - the number of entries removed to make room for newer ones</li> * <li><strong>EXPIRE count</strong> - the number of entries removed because of expiration</li> * <li><strong>REMOVE count</strong> - the number of 'remove' calls</li> * </ul> * @author wjohnson000 * */ public class CacheStats { private LongAdder getCount = new LongAdder(); private LongAdder hitCount = new LongAdder(); private LongAdder putCount = new LongAdder(); private LongAdder evictCount = new LongAdder(); private LongAdder expireCount = new LongAdder(); private LongAdder removeCount = new LongAdder(); public void incrGetCount() { getCount.increment(); } public void incrHitCount() { hitCount.increment(); } public void incrPutCount() { putCount.increment(); } public void incrEvictCount() { evictCount.increment(); } public void incrExpireCount() { expireCount.increment(); } public void incrRemoveCount() { removeCount.increment(); } public long getGetCount() { return getCount.longValue(); } public long getHitCount() { return hitCount.longValue(); } public long getPutCount() { return putCount.longValue(); } public long getEvictCount() { return evictCount.longValue(); } public long getExpireCount() { return expireCount.longValue(); } public long getRemoveCount() { return removeCount.longValue(); } }
UTF-8
Java
1,923
java
CacheStats.java
Java
[ { "context": " number of 'remove' calls</li>\n * </ul>\n * @author wjohnson000\n *\n */\npublic class CacheStats {\n\n private Lon", "end": 653, "score": 0.99937504529953, "start": 642, "tag": "USERNAME", "value": "wjohnson000" } ]
null
[]
package std.wlj.cache.lru; import java.util.concurrent.atomic.LongAdder; /** * Cache statistics: * <ul> * <li><strong>GET count</strong> - the number of 'get' calls</li> * <li><strong>HIT count</strong> - the number of 'get' calls that returned a non-null value</li> * <li><strong>PUT count</strong> - the number of 'put' calls</li> * <li><strong>EVICT count</strong> - the number of entries removed to make room for newer ones</li> * <li><strong>EXPIRE count</strong> - the number of entries removed because of expiration</li> * <li><strong>REMOVE count</strong> - the number of 'remove' calls</li> * </ul> * @author wjohnson000 * */ public class CacheStats { private LongAdder getCount = new LongAdder(); private LongAdder hitCount = new LongAdder(); private LongAdder putCount = new LongAdder(); private LongAdder evictCount = new LongAdder(); private LongAdder expireCount = new LongAdder(); private LongAdder removeCount = new LongAdder(); public void incrGetCount() { getCount.increment(); } public void incrHitCount() { hitCount.increment(); } public void incrPutCount() { putCount.increment(); } public void incrEvictCount() { evictCount.increment(); } public void incrExpireCount() { expireCount.increment(); } public void incrRemoveCount() { removeCount.increment(); } public long getGetCount() { return getCount.longValue(); } public long getHitCount() { return hitCount.longValue(); } public long getPutCount() { return putCount.longValue(); } public long getEvictCount() { return evictCount.longValue(); } public long getExpireCount() { return expireCount.longValue(); } public long getRemoveCount() { return removeCount.longValue(); } }
1,923
0.633385
0.631825
75
24.639999
24.65584
102
true
false
0
0
0
0
0
0
0.266667
false
false
15
8d761925bbfd9a09470fbabb1785e80060676e4b
1,838,246,005,403
9ab91b074703bcfe9c9407e1123e2b551784a680
/plugins/org.eclipse.osee.framework.core.model.test/src/org/eclipse/osee/framework/core/model/mocks/MockOseeTransactionDataAccessor.java
3f9ea47d1d91cd01ed48aaee5095c85c9f944dc0
[]
no_license
pkdevbox/osee
https://github.com/pkdevbox/osee
7ad9c083c3df8a7e9ef6185a419680cc08e21769
7e31f80f43d6d0b661af521fdd93b139cb694001
refs/heads/master
2021-01-22T00:30:05.686000
2015-06-08T21:19:57
2015-06-09T18:42:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2004, 2007 Boeing. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ package org.eclipse.osee.framework.core.model.mocks; import java.util.Collection; import org.eclipse.osee.framework.core.data.IOseeBranch; import org.eclipse.osee.framework.core.enums.TransactionVersion; import org.eclipse.osee.framework.core.model.Branch; import org.eclipse.osee.framework.core.model.TransactionRecord; import org.eclipse.osee.framework.core.model.cache.ITransactionDataAccessor; import org.eclipse.osee.framework.core.model.cache.TransactionCache; import org.eclipse.osee.framework.jdk.core.type.OseeCoreException; /** * @author Roberto E. Escobar */ public class MockOseeTransactionDataAccessor implements ITransactionDataAccessor { private boolean wasLoadCalled = false; private boolean wasStoreCalled = false; public void setLoadCalled(boolean wasLoadCalled) { this.wasLoadCalled = wasLoadCalled; } public void setStoreCalled(boolean wasStoreCalled) { this.wasStoreCalled = wasStoreCalled; } public boolean wasLoaded() { return wasLoadCalled; } public boolean wasStoreCalled() { return wasStoreCalled; } // @Override // public void load(AbstractOseeCache<T> cache) throws OseeCoreException { // Assert.assertNotNull(cache); // setLoadCalled(true); // } // // @Override // public void store(Collection<T> types) throws OseeCoreException { // Assert.assertNotNull(types); // setStoreCalled(true); // } @Override public void loadTransactionRecord(TransactionCache cache, Collection<Integer> transactionIds) throws OseeCoreException { wasLoadCalled = true; } @Override public TransactionRecord loadTransactionRecord(TransactionCache cache, IOseeBranch branch, TransactionVersion transactionType) throws OseeCoreException { return null; } @Override public void load(TransactionCache transactionCache) throws OseeCoreException { // Empty } @Override public TransactionRecord getOrLoadPriorTransaction(TransactionCache cache, int transactionNumber, long branchUuid) throws OseeCoreException { return null; } @Override public TransactionRecord getHeadTransaction(TransactionCache cache, Branch branch) throws OseeCoreException { return null; } }
UTF-8
Java
2,782
java
MockOseeTransactionDataAccessor.java
Java
[ { "context": "g/legal/epl-v10.html\n *\n * Contributors:\n * Boeing - initial API and implementation\n ***************", "end": 396, "score": 0.7024257183074951, "start": 392, "tag": "NAME", "value": "eing" }, { "context": "k.jdk.core.type.OseeCoreException;\n\n/**\n * @author Roberto E. Escobar\n */\npublic class MockOseeTransactionDataAccessor ", "end": 1081, "score": 0.9998833537101746, "start": 1063, "tag": "NAME", "value": "Roberto E. Escobar" } ]
null
[]
/******************************************************************************* * Copyright (c) 2004, 2007 Boeing. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ package org.eclipse.osee.framework.core.model.mocks; import java.util.Collection; import org.eclipse.osee.framework.core.data.IOseeBranch; import org.eclipse.osee.framework.core.enums.TransactionVersion; import org.eclipse.osee.framework.core.model.Branch; import org.eclipse.osee.framework.core.model.TransactionRecord; import org.eclipse.osee.framework.core.model.cache.ITransactionDataAccessor; import org.eclipse.osee.framework.core.model.cache.TransactionCache; import org.eclipse.osee.framework.jdk.core.type.OseeCoreException; /** * @author <NAME> */ public class MockOseeTransactionDataAccessor implements ITransactionDataAccessor { private boolean wasLoadCalled = false; private boolean wasStoreCalled = false; public void setLoadCalled(boolean wasLoadCalled) { this.wasLoadCalled = wasLoadCalled; } public void setStoreCalled(boolean wasStoreCalled) { this.wasStoreCalled = wasStoreCalled; } public boolean wasLoaded() { return wasLoadCalled; } public boolean wasStoreCalled() { return wasStoreCalled; } // @Override // public void load(AbstractOseeCache<T> cache) throws OseeCoreException { // Assert.assertNotNull(cache); // setLoadCalled(true); // } // // @Override // public void store(Collection<T> types) throws OseeCoreException { // Assert.assertNotNull(types); // setStoreCalled(true); // } @Override public void loadTransactionRecord(TransactionCache cache, Collection<Integer> transactionIds) throws OseeCoreException { wasLoadCalled = true; } @Override public TransactionRecord loadTransactionRecord(TransactionCache cache, IOseeBranch branch, TransactionVersion transactionType) throws OseeCoreException { return null; } @Override public void load(TransactionCache transactionCache) throws OseeCoreException { // Empty } @Override public TransactionRecord getOrLoadPriorTransaction(TransactionCache cache, int transactionNumber, long branchUuid) throws OseeCoreException { return null; } @Override public TransactionRecord getHeadTransaction(TransactionCache cache, Branch branch) throws OseeCoreException { return null; } }
2,770
0.703091
0.698778
83
32.518074
34.645664
156
false
false
0
0
0
0
0
0
0.373494
false
false
15
ae9368100bfe1916cf4e75fee3055f22806c1a8c
9,809,705,359,290
5cf8a3af06f4201a01de1e9a162b80dba20a1980
/shopping/src/main/java/com/nestor/entity/PayStatus.java
df1dc89eb5b37a1aa7ade3f6f2a4610991ae3610
[]
no_license
BrightHZz/Floriculture
https://github.com/BrightHZz/Floriculture
4cff347894e4d651e782f9d83c3cf25d5066661c
949b5fad7cff8d42161400a2042b5d7750fa90be
refs/heads/master
2020-05-07T08:59:30.417000
2019-03-31T07:05:08
2019-03-31T07:05:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nestor.entity; public enum PayStatus { PAYSUCCESS, PAYFAILED, PENDING // private PayStatus() { // // } }
UTF-8
Java
129
java
PayStatus.java
Java
[]
null
[]
package com.nestor.entity; public enum PayStatus { PAYSUCCESS, PAYFAILED, PENDING // private PayStatus() { // // } }
129
0.643411
0.643411
8
14.125
12.139167
31
false
false
0
0
0
0
0
0
1
false
false
15
4b621f31e3cd5d38e464fa4ec24942afc4c4677e
27,384,711,546,559
7b5be33ae6feb7e31479d214955f5b43041f8588
/ServerJavaProject/ServerJavaProject/src/model/ClientHandler.java
1d1d4691d85bdbe23097fea988d012f1d40f6b3e
[]
no_license
Doredel/JavaProjectMaze
https://github.com/Doredel/JavaProjectMaze
4a70cf30355a2eff647fdf0f06c0d8e4b2e6c96f
7193fda4b53e6e6714820c728452807ec0727d00
refs/heads/master
2016-08-13T00:30:45.382000
2016-01-30T22:15:41
2016-01-30T22:15:41
47,512,034
0
3
null
false
2016-01-12T16:48:26
2015-12-06T20:13:55
2015-12-06T20:16:19
2016-01-12T16:48:26
11,483
0
0
0
Java
null
null
package model; import java.io.InputStream; import java.io.OutputStream; public interface ClientHandler { /** * This method handles the client's commands. * after reading a command from the input stream, the method will analyze the command * and call to the match method. The return value of the method will be print * to the output stream. * *@param inFromClient The input stream that from him will be read the commands. *@param outToClient The output stream that will get the values(like maze,solution etc.) *and prints it. *@return nothing. */ public void handleClient(InputStream inFromClient, OutputStream outToClient); /** * Exit method, that closes the run method, all the threads neatly and saves the cache. * * @return nothing */ public void exit(); }
UTF-8
Java
834
java
ClientHandler.java
Java
[]
null
[]
package model; import java.io.InputStream; import java.io.OutputStream; public interface ClientHandler { /** * This method handles the client's commands. * after reading a command from the input stream, the method will analyze the command * and call to the match method. The return value of the method will be print * to the output stream. * *@param inFromClient The input stream that from him will be read the commands. *@param outToClient The output stream that will get the values(like maze,solution etc.) *and prints it. *@return nothing. */ public void handleClient(InputStream inFromClient, OutputStream outToClient); /** * Exit method, that closes the run method, all the threads neatly and saves the cache. * * @return nothing */ public void exit(); }
834
0.701439
0.701439
27
28.888889
31.343182
89
false
false
0
0
0
0
0
0
1.148148
false
false
15
4a109405ca91e15e2014d74792ada95b649930ff
26,190,710,636,105
8b59d89dea1faf19180c85227722157488916c82
/Applet Programmig/ExecutionOrder.java
3ae52c1b1e5f17dcc21a0f766e383c396cf8896c
[]
no_license
VinayakSingoriya/Java-Learning
https://github.com/VinayakSingoriya/Java-Learning
ebc8afbfbc6c925c51568efc99e7714e6a9512f2
7d8ed751b0928c694fb3c5c48156b83f2320b8f5
refs/heads/main
2023-07-09T06:02:33.953000
2021-08-24T08:00:45
2021-08-24T08:00:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.applet.*; import java.awt.*; public class ExecutionOrder extends Applet{ String msg; public void init(){ setBackground(Color.blue); setForeground(Color.green); msg = "Inside init() ---"; } public void start(){ msg+="Inside start()----"; } public void paint(Graphics g){ msg+="Inside paint()."; g.drawString(msg, 10, 30); } }
UTF-8
Java
355
java
ExecutionOrder.java
Java
[]
null
[]
import java.applet.*; import java.awt.*; public class ExecutionOrder extends Applet{ String msg; public void init(){ setBackground(Color.blue); setForeground(Color.green); msg = "Inside init() ---"; } public void start(){ msg+="Inside start()----"; } public void paint(Graphics g){ msg+="Inside paint()."; g.drawString(msg, 10, 30); } }
355
0.656338
0.64507
17
19.941177
11.918698
43
false
false
0
0
0
0
0
0
1.764706
false
false
15
82787282b18c2b7f1be85352df108e8a7b6ca00b
16,836,271,849,653
c7193b292d559211868f8ed7dad1a1f18930c469
/given_parser/ast/BoolType.java
b5fd79d32b795500255bb14d5d655faa56aeb00d
[]
no_license
anitasouv/431-compiler
https://github.com/anitasouv/431-compiler
092aac92450b5027241283afc98d887e5f31c101
7548e32289f9ffe3f7a2e6759c91582e878cd12c
refs/heads/master
2020-03-17T16:06:28.980000
2018-06-13T20:24:08
2018-06-13T20:24:08
133,736,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ast; public class BoolType implements Type { public boolean equals(Type left) { return (left instanceof BoolType); } public String toLLVMType() { return "i1"; } public String printType() { return "boolType"; } }
UTF-8
Java
263
java
BoolType.java
Java
[]
null
[]
package ast; public class BoolType implements Type { public boolean equals(Type left) { return (left instanceof BoolType); } public String toLLVMType() { return "i1"; } public String printType() { return "boolType"; } }
263
0.619772
0.61597
18
13.611111
13.650962
40
false
false
0
0
0
0
0
0
0.222222
false
false
15
0fac169eff6d47e29fa37ddce88cf929a505f0fe
27,367,531,671,248
f69bbc07e6e2e753d78478ca3f3c92bb92fa8bf2
/src/main/java/no/imr/nmdapi/client/loader/mapper/SaMapper.java
e407f3e0721e267e58599b23e980322710800621
[]
no_license
Institute-of-Marine-Research-NMD/Application-export-echosounder
https://github.com/Institute-of-Marine-Research-NMD/Application-export-echosounder
d31bc933aab4eef780d1ffe13c88f09dcf33c393
c6522d75138f5ba7c081cbbd77d9dfaa00a25d81
refs/heads/master
2020-05-29T20:43:07.364000
2018-03-21T11:03:30
2018-03-21T11:03:30
42,051,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package no.imr.nmdapi.client.loader.mapper; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import no.imr.nmdapi.client.loader.pojo.Sa; import org.springframework.jdbc.core.RowMapper; /** * Maps SA objects from the database to Sa objects * * @author sjurl */ public class SaMapper implements RowMapper<Sa> { @Override public Sa mapRow(ResultSet rs, int rowNum) throws SQLException { Sa sa = new Sa(); sa.setAcousticcategory(BigInteger.valueOf(rs.getInt("acousticcategory"))); sa.setCh(BigInteger.valueOf(rs.getInt("ch"))); sa.setChType(rs.getString("ch_type")); sa.setSa(BigDecimal.valueOf(rs.getDouble("sa"))); return sa; } }
UTF-8
Java
762
java
SaMapper.java
Java
[ { "context": "ects from the database to Sa objects\n *\n * @author sjurl\n */\npublic class SaMapper implements RowMapper<Sa", "end": 327, "score": 0.9988318085670471, "start": 322, "tag": "USERNAME", "value": "sjurl" } ]
null
[]
package no.imr.nmdapi.client.loader.mapper; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import no.imr.nmdapi.client.loader.pojo.Sa; import org.springframework.jdbc.core.RowMapper; /** * Maps SA objects from the database to Sa objects * * @author sjurl */ public class SaMapper implements RowMapper<Sa> { @Override public Sa mapRow(ResultSet rs, int rowNum) throws SQLException { Sa sa = new Sa(); sa.setAcousticcategory(BigInteger.valueOf(rs.getInt("acousticcategory"))); sa.setCh(BigInteger.valueOf(rs.getInt("ch"))); sa.setChType(rs.getString("ch_type")); sa.setSa(BigDecimal.valueOf(rs.getDouble("sa"))); return sa; } }
762
0.7021
0.7021
27
27.222221
23.443129
82
false
false
0
0
0
0
0
0
0.518519
false
false
15
8ed94964631e40542aba87da320da5dcb36165f1
7,421,703,519,547
35089a8b8b7597e7be201f05513a8867fb96eacb
/dip-util-struts/src/main/java/edu/ucla/mbi/util/struts/action/TableMgrSupport.java
0518305c7727232143b9fc25b831624a76c684d1
[]
no_license
IMExConsortium/dip-utils
https://github.com/IMExConsortium/dip-utils
33a54976dd1e8cd19e3a2e4b1e2fb0ea25fd5ae5
ff390f7a10ced0adffac53094f3bb40a96da79f8
refs/heads/master
2021-01-10T17:52:46.416000
2018-07-16T01:37:03
2018-07-16T01:37:03
43,386,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ucla.mbi.util.struts.action; /* ============================================================================= * $HeadURL:: $ * $Id:: $ * Version: $Rev:: $ *============================================================================== * $ * TableMgrSupport - record->table map manager $ * $ * $ ============================================================================ */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.opensymphony.xwork2.ActionSupport; import java.util.*; import java.util.regex.PatternSyntaxException; import java.io.*; import org.json.*; import edu.ucla.mbi.util.data.*; import edu.ucla.mbi.util.context.*; import edu.ucla.mbi.util.struts.interceptor.*; import org.apache.struts2.ServletActionContext; import org.apache.struts2.util.ServletContextAware; import javax.servlet.ServletContext; public abstract class TableMgrSupport extends ManagerSupport { //-------------------------------------------------------------------------- // operations //----------- public static final String TABLE_ADD = "tadd"; // add table public static final String TABLE_DRP = "tdrp"; // drop table public static final String COLUMN_SVE = "csve"; // save current column public static final String COLUMN_ADD = "cadd"; // add column public static final String COLUMN_DRP = "cdrp"; // drop column public static final String COLUMN_MOV = "cmov"; // move column //-------------------------------------------------------------------------- // return values //-------------- public static final String JSON ="json"; //-------------------------------------------------------------------------- // configuration //-------------- private TableViewContext tableContext; public void setTableContext( TableViewContext context ){ this.tableContext = context; } public TableViewContext getTableContext() { return tableContext; } //-------------------------------------------------------------------------- public Map getTables(){ return getTableContext().getTables(); } //-------------------------------------------------------------------------- // current page //------------- private String pageId; public void setPageid( String pageId ) { this.pageId = pageId; } public String getPageid() { return pageId; } //-------------------------------------------------------------------------- // initialize //----------- public void initialize(){ initialize( false ); } public void initialize( boolean force ){ Log log = LogFactory.getLog( this.getClass() ); log.info( "initializing: ActionContext=" + getContext() ); // initialize tableContext //------------------------ if( getTableContext() != null && ( getTableContext().getTables() == null || force ) ){ // process json configuration //--------------------------- if( getTableContext() instanceof TableViewJsonContext ){ TableViewJsonContext tvgc = (TableViewJsonContext) this.getTableContext(); String jsonPath = (String) tvgc.getJsonContext() .getConfig().get( "json-config" ); log.info( " JsonTableDef=" + jsonPath ); if ( jsonPath != null && jsonPath.length() > 0 ) { String cpath = jsonPath.replaceAll("^\\s+","" ); cpath = jsonPath.replaceAll("\\s+$","" ); try { ServletContext sc = getServletContext(); log.info( " ServletContext sc=" + sc ); InputStream is = getServletContext().getResourceAsStream( cpath ); log.info( " JsonTableDef stream=" + is ); tvgc.jsonInitialize( is ); tvgc.initialize(); } catch ( Exception e ){ e.printStackTrace(); log.info( "JsonConfig reading error" ); } tvgc.initialize(); } } } } //-------------------------------------------------------------------------- protected void saveTableContext(){ Log log = LogFactory.getLog( this.getClass() ); log.info( "storing: ActionContext=" + getContext() ); if( getTableContext() != null && getTableContext() instanceof TableViewJsonContext ){ JsonContext jsonContext = ((TableViewJsonContext) getTableContext()).getJsonContext(); String jsonConfigFile = (String) jsonContext.getConfig().get( "json-config" ); String srcPath = getServletContext().getRealPath( jsonConfigFile ); log.info( " srcPath=" + srcPath ); try{ File sf = new File( srcPath ); PrintWriter spw = new PrintWriter( sf ); jsonContext.writeJsonConfigDef( spw ); spw.close(); getTableContext().initialize(); // reinitialize } catch( IOException ioe ){ // NOTE: log me !!!! } } } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- public String execute() throws Exception { // force table initialization //--------------------------- initialize( true ); // decode operation //----------------- String opcode = null; if( getOp() != null ) { for( Iterator<String> ii = getOp().keySet().iterator(); ii.hasNext(); ) { String key = ii.next(); if ( key.equals( TABLE_ADD ) ) { return tableAdd(); } if ( key.equals( TABLE_DRP ) ) { return tableDrop(); } if ( key.equals( COLUMN_SVE ) ) { return columnSave(); } if ( key.equals( COLUMN_ADD ) ) { return columnAdd(); } if ( key.equals( COLUMN_DRP ) ) { return columnDrop(); } if ( key.equals( COLUMN_MOV ) ) { return columnMove(); } } return JSON; } return SUCCESS; } //-------------------------------------------------------------------------- private String tableAdd(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: table add" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String tableDrop(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: table drop" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnAdd(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column add" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnDrop(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column drop" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnSave(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column save" ); // update JsonContext //------------------- if( getTableContext() != null && getTableContext() instanceof TableViewJsonContext ){ JsonContext jsonContext = ((TableViewJsonContext) getTableContext()).getJsonContext(); // modify column definition //------------------------- Map<String,Object> tables = jsonContext.getJsonConfig(); // make changes permanent //----------------------- saveTableContext(); // reinitialize //------------- initialize( true ); } return JSON; } //-------------------------------------------------------------------------- private String columnMove(){ saveTableContext(); return JSON; } //-------------------------------------------------------------------------- // validation //----------- public void validate() { } }
UTF-8
Java
9,506
java
TableMgrSupport.java
Java
[]
null
[]
package edu.ucla.mbi.util.struts.action; /* ============================================================================= * $HeadURL:: $ * $Id:: $ * Version: $Rev:: $ *============================================================================== * $ * TableMgrSupport - record->table map manager $ * $ * $ ============================================================================ */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.opensymphony.xwork2.ActionSupport; import java.util.*; import java.util.regex.PatternSyntaxException; import java.io.*; import org.json.*; import edu.ucla.mbi.util.data.*; import edu.ucla.mbi.util.context.*; import edu.ucla.mbi.util.struts.interceptor.*; import org.apache.struts2.ServletActionContext; import org.apache.struts2.util.ServletContextAware; import javax.servlet.ServletContext; public abstract class TableMgrSupport extends ManagerSupport { //-------------------------------------------------------------------------- // operations //----------- public static final String TABLE_ADD = "tadd"; // add table public static final String TABLE_DRP = "tdrp"; // drop table public static final String COLUMN_SVE = "csve"; // save current column public static final String COLUMN_ADD = "cadd"; // add column public static final String COLUMN_DRP = "cdrp"; // drop column public static final String COLUMN_MOV = "cmov"; // move column //-------------------------------------------------------------------------- // return values //-------------- public static final String JSON ="json"; //-------------------------------------------------------------------------- // configuration //-------------- private TableViewContext tableContext; public void setTableContext( TableViewContext context ){ this.tableContext = context; } public TableViewContext getTableContext() { return tableContext; } //-------------------------------------------------------------------------- public Map getTables(){ return getTableContext().getTables(); } //-------------------------------------------------------------------------- // current page //------------- private String pageId; public void setPageid( String pageId ) { this.pageId = pageId; } public String getPageid() { return pageId; } //-------------------------------------------------------------------------- // initialize //----------- public void initialize(){ initialize( false ); } public void initialize( boolean force ){ Log log = LogFactory.getLog( this.getClass() ); log.info( "initializing: ActionContext=" + getContext() ); // initialize tableContext //------------------------ if( getTableContext() != null && ( getTableContext().getTables() == null || force ) ){ // process json configuration //--------------------------- if( getTableContext() instanceof TableViewJsonContext ){ TableViewJsonContext tvgc = (TableViewJsonContext) this.getTableContext(); String jsonPath = (String) tvgc.getJsonContext() .getConfig().get( "json-config" ); log.info( " JsonTableDef=" + jsonPath ); if ( jsonPath != null && jsonPath.length() > 0 ) { String cpath = jsonPath.replaceAll("^\\s+","" ); cpath = jsonPath.replaceAll("\\s+$","" ); try { ServletContext sc = getServletContext(); log.info( " ServletContext sc=" + sc ); InputStream is = getServletContext().getResourceAsStream( cpath ); log.info( " JsonTableDef stream=" + is ); tvgc.jsonInitialize( is ); tvgc.initialize(); } catch ( Exception e ){ e.printStackTrace(); log.info( "JsonConfig reading error" ); } tvgc.initialize(); } } } } //-------------------------------------------------------------------------- protected void saveTableContext(){ Log log = LogFactory.getLog( this.getClass() ); log.info( "storing: ActionContext=" + getContext() ); if( getTableContext() != null && getTableContext() instanceof TableViewJsonContext ){ JsonContext jsonContext = ((TableViewJsonContext) getTableContext()).getJsonContext(); String jsonConfigFile = (String) jsonContext.getConfig().get( "json-config" ); String srcPath = getServletContext().getRealPath( jsonConfigFile ); log.info( " srcPath=" + srcPath ); try{ File sf = new File( srcPath ); PrintWriter spw = new PrintWriter( sf ); jsonContext.writeJsonConfigDef( spw ); spw.close(); getTableContext().initialize(); // reinitialize } catch( IOException ioe ){ // NOTE: log me !!!! } } } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- public String execute() throws Exception { // force table initialization //--------------------------- initialize( true ); // decode operation //----------------- String opcode = null; if( getOp() != null ) { for( Iterator<String> ii = getOp().keySet().iterator(); ii.hasNext(); ) { String key = ii.next(); if ( key.equals( TABLE_ADD ) ) { return tableAdd(); } if ( key.equals( TABLE_DRP ) ) { return tableDrop(); } if ( key.equals( COLUMN_SVE ) ) { return columnSave(); } if ( key.equals( COLUMN_ADD ) ) { return columnAdd(); } if ( key.equals( COLUMN_DRP ) ) { return columnDrop(); } if ( key.equals( COLUMN_MOV ) ) { return columnMove(); } } return JSON; } return SUCCESS; } //-------------------------------------------------------------------------- private String tableAdd(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: table add" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String tableDrop(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: table drop" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnAdd(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column add" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnDrop(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column drop" ); saveTableContext(); return JSON; } //-------------------------------------------------------------------------- private String columnSave(){ Log log = LogFactory.getLog( this.getClass() ); log.info( " OP: column save" ); // update JsonContext //------------------- if( getTableContext() != null && getTableContext() instanceof TableViewJsonContext ){ JsonContext jsonContext = ((TableViewJsonContext) getTableContext()).getJsonContext(); // modify column definition //------------------------- Map<String,Object> tables = jsonContext.getJsonConfig(); // make changes permanent //----------------------- saveTableContext(); // reinitialize //------------- initialize( true ); } return JSON; } //-------------------------------------------------------------------------- private String columnMove(){ saveTableContext(); return JSON; } //-------------------------------------------------------------------------- // validation //----------- public void validate() { } }
9,506
0.396697
0.396276
330
27.806061
26.711681
80
false
false
0
0
0
0
79
0.024511
0.3
false
false
15
ce9e38bff1e7561caf1e2cb5f65907860e29d641
7,164,005,460,153
43d9f1da9b359e9c899d15a8ff13e0a3e4cc64ed
/Risk.java
d3c083ceaac26cf7dc529327fadb89e7105c9580
[]
no_license
tshibley/Risk-Model
https://github.com/tshibley/Risk-Model
c1ca802d88fb46313825cc7709476493bdce30aa
3efa0d9c6844b9869062948c54c03cc210c47a3a
refs/heads/master
2020-04-15T07:28:56.017000
2019-01-07T21:03:04
2019-01-07T21:03:04
164,495,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class Risk { public static void main(String[] args) { ArrayList<Integer> troopNumbersMaster = new ArrayList<Integer>(); System.out.println("Simulating a Risk turn with the following setup:"); System.out.println(); System.out.println("The first value is the attacking country, the rest of the"); System.out.println("values are the chain of defending countries"); /** * Edit the numbers below here for attacking a defending troop setups and the * number of trials to run */ // The attacking Troop troopNumbersMaster.add(45); // The defending Troops troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); // The number of trials int totalReps = 100000; /** * Do not edit below here */ System.out.println(troopNumbersMaster); System.out.println(); Integer[] copyDeep = new Integer[troopNumbersMaster.size()]; copyDeep = troopNumbersMaster.toArray(copyDeep); int winCount = 0; for (int i = 0; i < totalReps; i++) { ArrayList<Integer> troopNumbers = new ArrayList<Integer>(Arrays.asList(copyDeep)); // the starting index for the attackers int attackingIndex = 0; // Have the attacking index attack the next square until depleted while (attackingIndex < troopNumbers.size() - 1 && troopNumbers.get(attackingIndex) > 1) { // System.out.println("Attacking Index " + attackingIndex); // System.out.println(troopNumbers); int attacking = troopNumbers.get(attackingIndex); int defending = troopNumbers.get(attackingIndex + 1); int[] res = simulateBattle(new int[] { attacking, defending }); if (res[0] > 1) { // the attacker won, needs to leave one behind // System.out.println("attacker Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[0] - 1); attackingIndex++; } else { // the defender won // System.out.println("defender Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[1]); } } // simulation is finisished, attacker won if they made it to the last index if (attackingIndex == troopNumbers.size() - 1) { winCount++; } } double percentWon = (double) winCount / (double) totalReps; System.out.println("Result: "); System.out.printf("Win percent: %.2f %n", percentWon * 100); } public static int[] simulateBattle(int[] input) { int attacking = input[0]; int defending = input[1]; // System.out.println("Battling " + attacking + " vs " + defending); while (attacking > 1 && defending > 0) { // System.out.println("Attacking: " + attacking); // System.out.println("Defending: " + defending); int[] attackingRolls = new int[Math.min(attacking - 1, 3)]; int[] defendingRolls = new int[Math.min(defending, 2)]; for (int i = 0; i < attackingRolls.length; i++) { attackingRolls[i] = (int) (Math.random() * 6) + 1; } for (int i = 0; i < defendingRolls.length; i++) { defendingRolls[i] = (int) (Math.random() * 6) + 1; } Arrays.sort(attackingRolls); Arrays.sort(defendingRolls); attackingRolls = reverseArray(attackingRolls); defendingRolls = reverseArray(defendingRolls); // System.out.println("attacking Rolls:"); // System.out.println(Arrays.toString(attackingRolls)); // System.out.println("defending Rolls:"); // System.out.println(Arrays.toString(defendingRolls)); for (int i = 0; i < Math.min(attackingRolls.length, defendingRolls.length); i++) { if (attackingRolls[i] > defendingRolls[i]) { defending--; // System.out.println("minus one defending"); } else { attacking--; // System.out.println("minus one attacking"); } } } int[] result = new int[] { attacking, defending }; return result; } public static int[] reverseArray(int[] validData) { for (int i = 0; i < validData.length / 2; i++) { int temp = validData[i]; validData[i] = validData[validData.length - i - 1]; validData[validData.length - i - 1] = temp; } return validData; } }
UTF-8
Java
4,610
java
Risk.java
Java
[]
null
[]
import java.util.*; class Risk { public static void main(String[] args) { ArrayList<Integer> troopNumbersMaster = new ArrayList<Integer>(); System.out.println("Simulating a Risk turn with the following setup:"); System.out.println(); System.out.println("The first value is the attacking country, the rest of the"); System.out.println("values are the chain of defending countries"); /** * Edit the numbers below here for attacking a defending troop setups and the * number of trials to run */ // The attacking Troop troopNumbersMaster.add(45); // The defending Troops troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); // The number of trials int totalReps = 100000; /** * Do not edit below here */ System.out.println(troopNumbersMaster); System.out.println(); Integer[] copyDeep = new Integer[troopNumbersMaster.size()]; copyDeep = troopNumbersMaster.toArray(copyDeep); int winCount = 0; for (int i = 0; i < totalReps; i++) { ArrayList<Integer> troopNumbers = new ArrayList<Integer>(Arrays.asList(copyDeep)); // the starting index for the attackers int attackingIndex = 0; // Have the attacking index attack the next square until depleted while (attackingIndex < troopNumbers.size() - 1 && troopNumbers.get(attackingIndex) > 1) { // System.out.println("Attacking Index " + attackingIndex); // System.out.println(troopNumbers); int attacking = troopNumbers.get(attackingIndex); int defending = troopNumbers.get(attackingIndex + 1); int[] res = simulateBattle(new int[] { attacking, defending }); if (res[0] > 1) { // the attacker won, needs to leave one behind // System.out.println("attacker Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[0] - 1); attackingIndex++; } else { // the defender won // System.out.println("defender Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[1]); } } // simulation is finisished, attacker won if they made it to the last index if (attackingIndex == troopNumbers.size() - 1) { winCount++; } } double percentWon = (double) winCount / (double) totalReps; System.out.println("Result: "); System.out.printf("Win percent: %.2f %n", percentWon * 100); } public static int[] simulateBattle(int[] input) { int attacking = input[0]; int defending = input[1]; // System.out.println("Battling " + attacking + " vs " + defending); while (attacking > 1 && defending > 0) { // System.out.println("Attacking: " + attacking); // System.out.println("Defending: " + defending); int[] attackingRolls = new int[Math.min(attacking - 1, 3)]; int[] defendingRolls = new int[Math.min(defending, 2)]; for (int i = 0; i < attackingRolls.length; i++) { attackingRolls[i] = (int) (Math.random() * 6) + 1; } for (int i = 0; i < defendingRolls.length; i++) { defendingRolls[i] = (int) (Math.random() * 6) + 1; } Arrays.sort(attackingRolls); Arrays.sort(defendingRolls); attackingRolls = reverseArray(attackingRolls); defendingRolls = reverseArray(defendingRolls); // System.out.println("attacking Rolls:"); // System.out.println(Arrays.toString(attackingRolls)); // System.out.println("defending Rolls:"); // System.out.println(Arrays.toString(defendingRolls)); for (int i = 0; i < Math.min(attackingRolls.length, defendingRolls.length); i++) { if (attackingRolls[i] > defendingRolls[i]) { defending--; // System.out.println("minus one defending"); } else { attacking--; // System.out.println("minus one attacking"); } } } int[] result = new int[] { attacking, defending }; return result; } public static int[] reverseArray(int[] validData) { for (int i = 0; i < validData.length / 2; i++) { int temp = validData[i]; validData[i] = validData[validData.length - i - 1]; validData[validData.length - i - 1] = temp; } return validData; } }
4,610
0.621909
0.609544
134
33.410446
25.120964
96
false
false
0
0
0
0
0
0
0.686567
false
false
15
773512071ae7af7f530da14ccd38c3bf8d9af8af
32,564,442,068,989
ff960974a3c92978bca985478d94ea4910fc443a
/src/com/bjwg/main/util/Test.java
4c7b872f25a4c10ea167baf2d4b85267e8f4a730
[ "Apache-2.0" ]
permissive
liangjinx/BJWG
https://github.com/liangjinx/BJWG
d92551fa169eb4d16b3d1797d15a52395b7f3652
f0186f8d369af0fb682f24bb4b98b2cdb0d6a893
refs/heads/master
2021-01-10T08:38:43.381000
2016-02-28T09:06:20
2016-02-28T09:06:20
52,712,878
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*package com.bjwg.main.util; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; *//** * @author Allen * @version 创建时间:2015-9-25 下午05:31:53 * @Modified By:Administrator * Version: 1.0 * jdk : 1.6 * 类说明: *//* public class Test { public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access public static final String UPLOAD_IMAGE_URL = "";// 上传多媒体文件 public static final String UPLOAD_FODDER_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews"; public static final String GET_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/get"; // url public static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"; public static final String APP_ID = "wxa549b28c24cf341e"; public static final String SECRET = "78d8a8cd7a4fa700142d06b96bf44a37"; *//** * 发送消息 * * @param uploadurl * apiurl * @param access_token * @param data * 发送数据 * @return *//* public static String sendMsg(String url, String token, String data) { org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); String sendurl = String.format("%s?access_token=%s", url, token); PostMethod post = new PostMethod(sendurl); post .setRequestHeader( "User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0"); post.setRequestHeader("Host", "file.api.weixin.qq.com"); post.setRequestHeader("Connection", "Keep-Alive"); post.setRequestHeader("Cache-Control", "no-cache"); String result = null; try { post.setRequestBody(data); int status = client.executeMethod(post); if (status == HttpStatus.SC_OK) { String responseContent = post.getResponseBodyAsString(); System.out.println(responseContent); JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象 JsonObject json = jsonparer.parse(responseContent) .getAsJsonObject(); if (json.get("errcode") != null && json.get("errcode").getAsString().equals("0")) { result = json.get("errmsg").getAsString(); } } } catch (Exception e) { e.printStackTrace(); } finally { return result; } } public static void main(String[] args) throws Exception { String accessToken = getToken(GET_TOKEN_URL, APP_ID, SECRET);// 获取token在微信接口之一中获取 if (accessToken != null)// token成功获取 { System.out.println(accessToken); File file = new File("f:" + File.separator + "2000.JPG"); // 获取本地文件 String id = uploadImage(UPLOAD_IMAGE_URL, accessToken, "image", file);// java微信接口之三—上传多媒体文件 可获取 if (id != null) { // 构造数据 Map map = new HashMap(); map.put("thumb_media_id", id); map.put("author", "wxx"); map.put("title", "标题"); map.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs"); map.put("digest", "digest"); map.put("show_cover_pic", "0"); Map map2 = new HashMap(); map2.put("thumb_media_id", id); map2.put("author", "wxx"); map2.put("content_source_url", ""); map2.put("title", "标题"); map2.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs"); map2.put("digest", "digest"); Map map3 = new HashMap(); List<Map> list = new ArrayList<Map>(); list.add(map); list.add(map2); map3.put("articles", list); Gson gson = new Gson(); String result = gson.toJson(map3);// 转换成json数据格式 String mediaId = uploadFodder(UPLOAD_FODDER_URL, accessToken, result); if (mediaId != null) { String ids = getGroups(GET_USER_GROUP, accessToken);// 在java微信接口之二—获取用户组 if (ids != null) { String[] idarray = ids.split(",");// 用户组id数组 for (String gid : idarray) { JsonObject jObj = new JsonObject(); JsonObject filter = new JsonObject(); filter.addProperty("group_id", gid); jObj.add("filter", filter); JsonObject mpnews = new JsonObject(); mpnews.addProperty("media_id", mediaId); jObj.add("mpnews", mpnews); jObj.addProperty("msgtype", "mpnews"); System.out.println(jObj.toString()); String result2 = sendMsg(SEND_MESSAGE_URL, accessToken, jObj.toString()); System.out.println(result2); } } } } } } } */
UTF-8
Java
6,128
java
Test.java
Java
[ { "context": "ttpclient.methods.PostMethod;\r\n\r\n*//**\r\n * @author Allen\r\n * @version 创建时间:2015-9-25 下午05:31:53\r\n * @Modif", "end": 293, "score": 0.9990543723106384, "start": 288, "tag": "NAME", "value": "Allen" }, { "context": "f341e\";\r\n public static final String SECRET = \"78d8a8cd7a4fa700142d06b96bf44a37\";\r\n\r\n\r\n *//**\r\n * 发送消息\r\n * \r\n * @p", "end": 1058, "score": 0.9996483325958252, "start": 1026, "tag": "KEY", "value": "78d8a8cd7a4fa700142d06b96bf44a37" }, { "context": "ia_id\", id);\r\n map.put(\"author\", \"wxx\");\r\n map.put(\"title\", \"标题\");\r\n ", "end": 3564, "score": 0.7948249578475952, "start": 3561, "tag": "USERNAME", "value": "wxx" } ]
null
[]
/*package com.bjwg.main.util; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; *//** * @author Allen * @version 创建时间:2015-9-25 下午05:31:53 * @Modified By:Administrator * Version: 1.0 * jdk : 1.6 * 类说明: *//* public class Test { public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access public static final String UPLOAD_IMAGE_URL = "";// 上传多媒体文件 public static final String UPLOAD_FODDER_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews"; public static final String GET_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/get"; // url public static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"; public static final String APP_ID = "wxa549b28c24cf341e"; public static final String SECRET = "78d8a8cd7a4fa700142d06b96bf44a37"; *//** * 发送消息 * * @param uploadurl * apiurl * @param access_token * @param data * 发送数据 * @return *//* public static String sendMsg(String url, String token, String data) { org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); String sendurl = String.format("%s?access_token=%s", url, token); PostMethod post = new PostMethod(sendurl); post .setRequestHeader( "User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0"); post.setRequestHeader("Host", "file.api.weixin.qq.com"); post.setRequestHeader("Connection", "Keep-Alive"); post.setRequestHeader("Cache-Control", "no-cache"); String result = null; try { post.setRequestBody(data); int status = client.executeMethod(post); if (status == HttpStatus.SC_OK) { String responseContent = post.getResponseBodyAsString(); System.out.println(responseContent); JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象 JsonObject json = jsonparer.parse(responseContent) .getAsJsonObject(); if (json.get("errcode") != null && json.get("errcode").getAsString().equals("0")) { result = json.get("errmsg").getAsString(); } } } catch (Exception e) { e.printStackTrace(); } finally { return result; } } public static void main(String[] args) throws Exception { String accessToken = getToken(GET_TOKEN_URL, APP_ID, SECRET);// 获取token在微信接口之一中获取 if (accessToken != null)// token成功获取 { System.out.println(accessToken); File file = new File("f:" + File.separator + "2000.JPG"); // 获取本地文件 String id = uploadImage(UPLOAD_IMAGE_URL, accessToken, "image", file);// java微信接口之三—上传多媒体文件 可获取 if (id != null) { // 构造数据 Map map = new HashMap(); map.put("thumb_media_id", id); map.put("author", "wxx"); map.put("title", "标题"); map.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs"); map.put("digest", "digest"); map.put("show_cover_pic", "0"); Map map2 = new HashMap(); map2.put("thumb_media_id", id); map2.put("author", "wxx"); map2.put("content_source_url", ""); map2.put("title", "标题"); map2.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs"); map2.put("digest", "digest"); Map map3 = new HashMap(); List<Map> list = new ArrayList<Map>(); list.add(map); list.add(map2); map3.put("articles", list); Gson gson = new Gson(); String result = gson.toJson(map3);// 转换成json数据格式 String mediaId = uploadFodder(UPLOAD_FODDER_URL, accessToken, result); if (mediaId != null) { String ids = getGroups(GET_USER_GROUP, accessToken);// 在java微信接口之二—获取用户组 if (ids != null) { String[] idarray = ids.split(",");// 用户组id数组 for (String gid : idarray) { JsonObject jObj = new JsonObject(); JsonObject filter = new JsonObject(); filter.addProperty("group_id", gid); jObj.add("filter", filter); JsonObject mpnews = new JsonObject(); mpnews.addProperty("media_id", mediaId); jObj.add("mpnews", mpnews); jObj.addProperty("msgtype", "mpnews"); System.out.println(jObj.toString()); String result2 = sendMsg(SEND_MESSAGE_URL, accessToken, jObj.toString()); System.out.println(result2); } } } } } } } */
6,128
0.484576
0.470169
155
36.077419
27.709911
109
false
false
0
0
0
0
0
0
0.709677
false
false
15
2dc0cc4b1d3f75f48cf13873950b0d967b0459d2
11,845,519,868,498
579dcf59f56c37db0cfa75668bfb16399dd82623
/src/main/java/com/example/demo2/api/PersonController.java
4f344351d7e1f0f0a7919a2e58a746ff0d082b50
[]
no_license
divyam-agarwal/Spring-demo
https://github.com/divyam-agarwal/Spring-demo
79aec11e9bc64ac5498faf997f01d67ff952cb27
9e96601f6fb580906a88c0d5814f0fe32d71c0b2
refs/heads/main
2023-05-09T09:13:27.306000
2021-06-03T20:33:39
2021-06-03T20:33:39
373,632,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo2.api; import com.example.demo2.model.Person; import com.example.demo2.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.util.annotation.NonNull; import javax.validation.Valid; import java.util.List; import java.util.Optional; import java.util.UUID; @RequestMapping("api/v1/person") @RestController public class PersonController { private final PersonService personService; @Autowired public PersonController(PersonService personService) { this.personService = personService; } @PostMapping public void addPerson(@NonNull @Valid @RequestBody Person person){ personService.addPerson(person); } @GetMapping public List<Person> allPersons(){ return personService.allPersons(); } @GetMapping(path = "{id}") public Person selectPersonById(@PathVariable UUID id) { return personService.selectPersonById(id).orElse(null); } @DeleteMapping(path = "{id}") public void deletePersonById(@PathVariable("id") UUID id){ personService.deletePerson(id); } @PutMapping(path = "{id}") public void updatePersonById(@PathVariable("id") UUID id,@NonNull @Valid @RequestBody Person updatedPerson){ personService.updatePerson(id,updatedPerson); } }
UTF-8
Java
1,383
java
PersonController.java
Java
[]
null
[]
package com.example.demo2.api; import com.example.demo2.model.Person; import com.example.demo2.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.util.annotation.NonNull; import javax.validation.Valid; import java.util.List; import java.util.Optional; import java.util.UUID; @RequestMapping("api/v1/person") @RestController public class PersonController { private final PersonService personService; @Autowired public PersonController(PersonService personService) { this.personService = personService; } @PostMapping public void addPerson(@NonNull @Valid @RequestBody Person person){ personService.addPerson(person); } @GetMapping public List<Person> allPersons(){ return personService.allPersons(); } @GetMapping(path = "{id}") public Person selectPersonById(@PathVariable UUID id) { return personService.selectPersonById(id).orElse(null); } @DeleteMapping(path = "{id}") public void deletePersonById(@PathVariable("id") UUID id){ personService.deletePerson(id); } @PutMapping(path = "{id}") public void updatePersonById(@PathVariable("id") UUID id,@NonNull @Valid @RequestBody Person updatedPerson){ personService.updatePerson(id,updatedPerson); } }
1,383
0.727404
0.724512
47
28.425531
24.383238
112
false
false
0
0
0
0
0
0
0.404255
false
false
15
52e73e997d867fed3a059b2a99c41325313bc219
16,887,811,461,604
460b21df67a6f3e59e5de034c51a72871afa7a3c
/src/main/java/base/scanner/Demo03.java
0b9fbcb5a1d4a4fe25e8771aea481985cf221660
[]
no_license
sinoeast/JavaSE
https://github.com/sinoeast/JavaSE
c44df91d9d29f59c1bd177d7a66534aa4e20bd3c
aa9858cbaf5e75da8f8fc8537e7b323b8e48cf13
refs/heads/master
2023-03-31T05:53:30.474000
2021-04-06T11:59:49
2021-04-06T11:59:49
350,665,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package base.scanner; import java.util.Scanner; /** * @author lantian */ public class Demo03 { public static void main(String[] args) { //输入多个数字。求总和和平均数 ,没输入一个数字用回车键确认,通过输入非数字来结束输入执行结果 Scanner scanner = new Scanner(System.in); double total = 0; double num = 0; while (scanner.hasNextDouble()){ double x = scanner.nextDouble(); total += x; num += 1; } System.out.println("总和:"+total); System.out.println("平均:"+total/num); scanner.close(); } }
UTF-8
Java
669
java
Demo03.java
Java
[ { "context": "canner;\n\nimport java.util.Scanner;\n\n/**\n * @author lantian\n */\npublic class Demo03 {\n\n public static void", "end": 72, "score": 0.9974352717399597, "start": 65, "tag": "USERNAME", "value": "lantian" } ]
null
[]
package base.scanner; import java.util.Scanner; /** * @author lantian */ public class Demo03 { public static void main(String[] args) { //输入多个数字。求总和和平均数 ,没输入一个数字用回车键确认,通过输入非数字来结束输入执行结果 Scanner scanner = new Scanner(System.in); double total = 0; double num = 0; while (scanner.hasNextDouble()){ double x = scanner.nextDouble(); total += x; num += 1; } System.out.println("总和:"+total); System.out.println("平均:"+total/num); scanner.close(); } }
669
0.555556
0.546737
28
19.25
17.753521
56
false
false
0
0
0
0
0
0
0.392857
false
false
15
2b8fdd7eba3ecb4fb28bb74d2ed2af811fb86f3d
33,036,888,458,784
98391b51ca4d1c8837678b10c1feb9b7bcf6e919
/addressbook-web-tests/src/test/java/sv/pft/addressbook/appmanager/ContactsHelper.java
a90e2dc020a535fb169714bfae96ec76f0b39ce1
[ "Apache-2.0" ]
permissive
ltana/java_prog_for_test
https://github.com/ltana/java_prog_for_test
6a25a3143c900f1886909c602a386a4b2d1019d0
7c41c413c0904a37c18ddd7061997221c0da6cf3
refs/heads/master
2021-01-21T13:44:13.800000
2016-04-25T21:27:19
2016-04-25T21:27:19
52,155,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sv.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import sv.pft.addressbook.Model.ContactData; import sv.pft.addressbook.Model.Contacts; import java.util.List; public class ContactsHelper extends HelperBase { public ContactsHelper(WebDriver wd) { super(wd); } public void saveContact() { click(By.xpath("//div[@id='content']/form/input[21]")); } public void fillContactData(ContactData contactData, boolean creating) { type(By.name("firstname"), contactData.getName()); type(By.name("lastname"), contactData.getLastname()); type(By.name("address"), contactData.getAddress()); type(By.name("home"), contactData.getHomePhone()); type(By.name("mobile"), contactData.getMobilePhone()); type(By.name("work"), contactData.getWorkPhone()); type(By.name("email"), contactData.getEmail1()); type(By.name("email2"), contactData.getEmail2()); type(By.name("email3"), contactData.getEmail3()); attach(By.name("photo"), contactData.getPhoto()); if (creating) { if (contactData.getGroups().size() > 0) Assert.assertTrue(contactData.getGroups().size() == 1); new Select(wd.findElement(By.name("new_group"))) .selectByVisibleText(contactData.getGroups().iterator().next().getName()); } else { Assert.assertFalse(isElementPresent(By.name("new_group"))); } } public void initAddContact() { click(By.linkText("add new")); } public void initModificationContact(int id) { click(By.cssSelector("a[href='edit.php?id=" + id + "']")); } public void submitContactModification() { click(By.name("update")); } private void selectById(int id) { wd.findElement(By.cssSelector("input[id = '" + id + "']")).click(); } public int getContactId(String name) { int id = Integer.parseInt(wd.findElement(By.xpath(".//*[@id='maintable']/tbody/tr[td = '" + name + "']/td[1]/input")).getAttribute("id")); return id; } public void initViewContact(int id) { click(By.cssSelector("a[href='view.php?id=" + id + "']")); } public String infoFromDetailedForm() { String element = wd.findElement(By.id("content")).getText(); return element; } public ContactData infoFromEditFormForContactName(String name) { initModificationContact(getContactId(name)); String firstname = wd.findElement(By.name("firstname")).getAttribute("value"); String lasttname = wd.findElement(By.name("lastname")).getAttribute("value"); String homePhone = wd.findElement(By.name("home")).getAttribute("value"); String mobilePhone = wd.findElement(By.name("mobile")).getAttribute("value"); String workPhone = wd.findElement(By.name("work")).getAttribute("value"); String address = wd.findElement(By.name("address")).getAttribute("value"); wd.navigate().back(); return new ContactData().withId(getContactId(name)).withName(firstname).withLastname(lasttname) .withHomePhone(homePhone).withMobilePhone(mobilePhone).withWorkPhone(workPhone) .withAddress(address); } public void deleteSelectedContact() { click(By.xpath("//*[@id='content']/form[2]/div[2]/input[@type='button']")); } public void create(ContactData contact) { initAddContact(); fillContactData(contact, true); saveContact(); contactCache = null; } public void delete(ContactData contact) throws InterruptedException { selectById(contact.getId()); deleteSelectedContact(); acceptAlert(); Thread.sleep(1000); contactCache = null; } public void modify(ContactData contact) { initModificationContact(contact.getId()); fillContactData(contact, false); submitContactModification(); contactCache = null; } public boolean isThereAContact() { return isElementPresent(By.name("selected[]")); } public int count() { return wd.findElements(By.name("selected[]")).size(); } private Contacts contactCache = null; public Contacts all() { if (contactCache != null) { return new Contacts(contactCache); } contactCache = new Contacts(); List<WebElement> elements = wd.findElements(By.cssSelector("[name=entry]")); for (WebElement element : elements) { int id = Integer.parseInt(element.findElement(By.cssSelector("input")).getAttribute("id")); String name = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(3)")).getText(); String lastname = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(2)")).getText(); String allPhones = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(6)")) .getText(); String address = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(4)")).getText(); String allEmails = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(5)")) .getText(); contactCache.add(new ContactData().withId(id).withName(name).withLastname(lastname) .withAllPhones(allPhones).withAddress(address).withAllEmails(allEmails)); // System.out.println("contact1 = " + allEmails); } return new Contacts(contactCache); } public ContactData infoFromEditForm(ContactData contact) { initModificationContact(contact.getId()); String firstname = wd.findElement(By.name("firstname")).getAttribute("value"); String lasttname = wd.findElement(By.name("lastname")).getAttribute("value"); String homePhone = wd.findElement(By.name("home")).getAttribute("value"); String mobilePhone = wd.findElement(By.name("mobile")).getAttribute("value"); String workPhone = wd.findElement(By.name("work")).getAttribute("value"); String address = wd.findElement(By.name("address")).getAttribute("value"); String email1 = wd.findElement(By.name("email")).getAttribute("value"); String email2 = wd.findElement(By.name("email2")).getAttribute("value"); String email3 = wd.findElement(By.name("email3")).getAttribute("value"); wd.navigate().back(); return new ContactData().withId(contact.getId()).withName(firstname).withLastname(lasttname) .withHomePhone(homePhone).withMobilePhone(mobilePhone).withWorkPhone(workPhone).withAddress(address) .withEmail1(email1).withEmail2(email2).withEmail3(email3); } }
UTF-8
Java
6,903
java
ContactsHelper.java
Java
[]
null
[]
package sv.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import sv.pft.addressbook.Model.ContactData; import sv.pft.addressbook.Model.Contacts; import java.util.List; public class ContactsHelper extends HelperBase { public ContactsHelper(WebDriver wd) { super(wd); } public void saveContact() { click(By.xpath("//div[@id='content']/form/input[21]")); } public void fillContactData(ContactData contactData, boolean creating) { type(By.name("firstname"), contactData.getName()); type(By.name("lastname"), contactData.getLastname()); type(By.name("address"), contactData.getAddress()); type(By.name("home"), contactData.getHomePhone()); type(By.name("mobile"), contactData.getMobilePhone()); type(By.name("work"), contactData.getWorkPhone()); type(By.name("email"), contactData.getEmail1()); type(By.name("email2"), contactData.getEmail2()); type(By.name("email3"), contactData.getEmail3()); attach(By.name("photo"), contactData.getPhoto()); if (creating) { if (contactData.getGroups().size() > 0) Assert.assertTrue(contactData.getGroups().size() == 1); new Select(wd.findElement(By.name("new_group"))) .selectByVisibleText(contactData.getGroups().iterator().next().getName()); } else { Assert.assertFalse(isElementPresent(By.name("new_group"))); } } public void initAddContact() { click(By.linkText("add new")); } public void initModificationContact(int id) { click(By.cssSelector("a[href='edit.php?id=" + id + "']")); } public void submitContactModification() { click(By.name("update")); } private void selectById(int id) { wd.findElement(By.cssSelector("input[id = '" + id + "']")).click(); } public int getContactId(String name) { int id = Integer.parseInt(wd.findElement(By.xpath(".//*[@id='maintable']/tbody/tr[td = '" + name + "']/td[1]/input")).getAttribute("id")); return id; } public void initViewContact(int id) { click(By.cssSelector("a[href='view.php?id=" + id + "']")); } public String infoFromDetailedForm() { String element = wd.findElement(By.id("content")).getText(); return element; } public ContactData infoFromEditFormForContactName(String name) { initModificationContact(getContactId(name)); String firstname = wd.findElement(By.name("firstname")).getAttribute("value"); String lasttname = wd.findElement(By.name("lastname")).getAttribute("value"); String homePhone = wd.findElement(By.name("home")).getAttribute("value"); String mobilePhone = wd.findElement(By.name("mobile")).getAttribute("value"); String workPhone = wd.findElement(By.name("work")).getAttribute("value"); String address = wd.findElement(By.name("address")).getAttribute("value"); wd.navigate().back(); return new ContactData().withId(getContactId(name)).withName(firstname).withLastname(lasttname) .withHomePhone(homePhone).withMobilePhone(mobilePhone).withWorkPhone(workPhone) .withAddress(address); } public void deleteSelectedContact() { click(By.xpath("//*[@id='content']/form[2]/div[2]/input[@type='button']")); } public void create(ContactData contact) { initAddContact(); fillContactData(contact, true); saveContact(); contactCache = null; } public void delete(ContactData contact) throws InterruptedException { selectById(contact.getId()); deleteSelectedContact(); acceptAlert(); Thread.sleep(1000); contactCache = null; } public void modify(ContactData contact) { initModificationContact(contact.getId()); fillContactData(contact, false); submitContactModification(); contactCache = null; } public boolean isThereAContact() { return isElementPresent(By.name("selected[]")); } public int count() { return wd.findElements(By.name("selected[]")).size(); } private Contacts contactCache = null; public Contacts all() { if (contactCache != null) { return new Contacts(contactCache); } contactCache = new Contacts(); List<WebElement> elements = wd.findElements(By.cssSelector("[name=entry]")); for (WebElement element : elements) { int id = Integer.parseInt(element.findElement(By.cssSelector("input")).getAttribute("id")); String name = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(3)")).getText(); String lastname = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(2)")).getText(); String allPhones = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(6)")) .getText(); String address = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(4)")).getText(); String allEmails = element.findElement(By.cssSelector("[name=entry]>td:nth-of-type(5)")) .getText(); contactCache.add(new ContactData().withId(id).withName(name).withLastname(lastname) .withAllPhones(allPhones).withAddress(address).withAllEmails(allEmails)); // System.out.println("contact1 = " + allEmails); } return new Contacts(contactCache); } public ContactData infoFromEditForm(ContactData contact) { initModificationContact(contact.getId()); String firstname = wd.findElement(By.name("firstname")).getAttribute("value"); String lasttname = wd.findElement(By.name("lastname")).getAttribute("value"); String homePhone = wd.findElement(By.name("home")).getAttribute("value"); String mobilePhone = wd.findElement(By.name("mobile")).getAttribute("value"); String workPhone = wd.findElement(By.name("work")).getAttribute("value"); String address = wd.findElement(By.name("address")).getAttribute("value"); String email1 = wd.findElement(By.name("email")).getAttribute("value"); String email2 = wd.findElement(By.name("email2")).getAttribute("value"); String email3 = wd.findElement(By.name("email3")).getAttribute("value"); wd.navigate().back(); return new ContactData().withId(contact.getId()).withName(firstname).withLastname(lasttname) .withHomePhone(homePhone).withMobilePhone(mobilePhone).withWorkPhone(workPhone).withAddress(address) .withEmail1(email1).withEmail2(email2).withEmail3(email3); } }
6,903
0.640736
0.635955
171
39.36842
33.552769
147
false
false
0
0
0
0
0
0
0.561404
false
false
15
07eb1b3f85331568d88616eff200e033de2ec9ef
27,917,287,465,509
faba0b51442e57a01f27d79ce45ff2e3508faabc
/app/src/main/java/com/example/ahn/StudyBoard/BoardConfirm.java
e65ccd17a2333e78f0dbbe924c7482eac8182338
[]
no_license
myroom9/MiniProject
https://github.com/myroom9/MiniProject
e6e463e88e08a62cbcb66abebed250b90238ca51
965913918d8a9613d7be878765897265b5c19152
refs/heads/master
2021-06-11T11:15:34.373000
2017-03-11T12:54:42
2017-03-11T12:54:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ahn.StudyBoard; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.ahn.studyviewer.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Map; /** * Created by Ahn on 2017-03-08. */ public class BoardConfirm extends AppCompatActivity{ String TAG = "@@@"; private String studyTitle; DatabaseReference root, root1; String[] studyTitles; TextView TView01, TView02, TView03, TView04, TView05, TView06, TView07, TView08, TView09; FirebaseAuth.AuthStateListener auth; String currentUserEmail, currentUserUid; protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.board_confirm); TView01 = (TextView) findViewById(R.id.TView01); TView02 = (TextView) findViewById(R.id.TView02); TView03 = (TextView) findViewById(R.id.TView03); TView04 = (TextView) findViewById(R.id.TView04); TView05 = (TextView) findViewById(R.id.TView05); TView06 = (TextView) findViewById(R.id.TView06); TView07 = (TextView) findViewById(R.id.TView07); TView08 = (TextView) findViewById(R.id.TView08); TView09 = (TextView) findViewById(R.id.TView09); root = FirebaseDatabase.getInstance().getReference().child("study"); root1 = FirebaseDatabase.getInstance().getReference().child("group"); Intent intent = getIntent(); studyTitles = intent.getExtras().getString("studyTitle").split(" "); root.addValueEventListener(new ValueEventListener() { @Override /*********************************************************** * study밑의 데이터를 활용하는 곳 * ***********************************************************/ public void onDataChange(DataSnapshot dataSnapshot) { Log.d(TAG, "@@@@@@@@@@@@@" + studyTitles[2]); for (DataSnapshot studyData : dataSnapshot.getChildren()) { String data = studyData.getValue().toString(); String[] array = data.split("studyTitle="); String studyTitleData = array[1].replace("}", ""); Log.d(TAG, "studyTitles[2]" + studyTitles[2] + "array[1]=" + studyTitleData+" "); if(studyTitles[2].equals(studyTitleData)) { data = data.replaceAll(" ", ""); data = data.replaceAll(",", "="); data = data.replace("}", ""); Log.d(TAG, "@@@@@@@@@@@@@" + data); String[] completeData = data.split("="); for(int i=0; i<completeData.length; i++){ Log.d(TAG, "@@@@@@@@@@@@@" + completeData[i]); } TView01.setText(completeData[21]); TView02.setText(completeData[17]); TView03.setText(completeData[15]); TView04.setText(completeData[1]); TView05.setText(completeData[5]); TView06.setText(completeData[7]); TView07.setText(completeData[11]); TView08.setText(completeData[19]); TView09.setText(completeData[3]); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // 현재 로그인한 유저의 데이터를 가져오기 위함 if (user != null) { currentUserEmail = user.getEmail(); // 현재 로그인한 유저의 이메일 받아오는 곳 currentUserUid = user.getUid(); // 현재 로그인한 유저의 UID값 받아오는 곳 } } /*********************************************************** * 내 스터디로 등록하는 버튼 클릭시 * ***********************************************************/ public void registerMyStudyBtn(View view){ root1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(root1.child(studyTitles[2]).equals("")){ Map<String, Object> map = new HashMap<String, Object>(); //HashMap으로 값을 넣으면 Key값이 생성되지않고 바로 들어가기 때문에 HashMap으로 데이터 저장 map.put(studyTitles[2], ""); root1.updateChildren(map); } } @Override public void onCancelled(DatabaseError databaseError) { } }); /************************************************************************ *그룹에 이미 유저가 저장 되있는 경우 데이터를 또 넣지 않게 하기 위한 곳* ************************************************************************/ if(!(root1.child(studyTitles[2]).equals(currentUserUid))) { // 유저의 UID값을 비교 Map<String, Object> groupUserMap = new HashMap<String, Object>(); groupUserMap.put(currentUserUid,currentUserEmail); root1.child(studyTitles[2]).updateChildren(groupUserMap); }else{ Toast.makeText(getApplicationContext(), "이미 등록된 스터디입니다!", Toast.LENGTH_LONG).show(); } } public void backBtn(View view){ finish(); } }
UTF-8
Java
6,200
java
BoardConfirm.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by Ahn on 2017-03-08.\n */\n\npublic class BoardConfirm ext", "end": 723, "score": 0.9993921518325806, "start": 720, "tag": "USERNAME", "value": "Ahn" } ]
null
[]
package com.example.ahn.StudyBoard; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.ahn.studyviewer.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Map; /** * Created by Ahn on 2017-03-08. */ public class BoardConfirm extends AppCompatActivity{ String TAG = "@@@"; private String studyTitle; DatabaseReference root, root1; String[] studyTitles; TextView TView01, TView02, TView03, TView04, TView05, TView06, TView07, TView08, TView09; FirebaseAuth.AuthStateListener auth; String currentUserEmail, currentUserUid; protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.board_confirm); TView01 = (TextView) findViewById(R.id.TView01); TView02 = (TextView) findViewById(R.id.TView02); TView03 = (TextView) findViewById(R.id.TView03); TView04 = (TextView) findViewById(R.id.TView04); TView05 = (TextView) findViewById(R.id.TView05); TView06 = (TextView) findViewById(R.id.TView06); TView07 = (TextView) findViewById(R.id.TView07); TView08 = (TextView) findViewById(R.id.TView08); TView09 = (TextView) findViewById(R.id.TView09); root = FirebaseDatabase.getInstance().getReference().child("study"); root1 = FirebaseDatabase.getInstance().getReference().child("group"); Intent intent = getIntent(); studyTitles = intent.getExtras().getString("studyTitle").split(" "); root.addValueEventListener(new ValueEventListener() { @Override /*********************************************************** * study밑의 데이터를 활용하는 곳 * ***********************************************************/ public void onDataChange(DataSnapshot dataSnapshot) { Log.d(TAG, "@@@@@@@@@@@@@" + studyTitles[2]); for (DataSnapshot studyData : dataSnapshot.getChildren()) { String data = studyData.getValue().toString(); String[] array = data.split("studyTitle="); String studyTitleData = array[1].replace("}", ""); Log.d(TAG, "studyTitles[2]" + studyTitles[2] + "array[1]=" + studyTitleData+" "); if(studyTitles[2].equals(studyTitleData)) { data = data.replaceAll(" ", ""); data = data.replaceAll(",", "="); data = data.replace("}", ""); Log.d(TAG, "@@@@@@@@@@@@@" + data); String[] completeData = data.split("="); for(int i=0; i<completeData.length; i++){ Log.d(TAG, "@@@@@@@@@@@@@" + completeData[i]); } TView01.setText(completeData[21]); TView02.setText(completeData[17]); TView03.setText(completeData[15]); TView04.setText(completeData[1]); TView05.setText(completeData[5]); TView06.setText(completeData[7]); TView07.setText(completeData[11]); TView08.setText(completeData[19]); TView09.setText(completeData[3]); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // 현재 로그인한 유저의 데이터를 가져오기 위함 if (user != null) { currentUserEmail = user.getEmail(); // 현재 로그인한 유저의 이메일 받아오는 곳 currentUserUid = user.getUid(); // 현재 로그인한 유저의 UID값 받아오는 곳 } } /*********************************************************** * 내 스터디로 등록하는 버튼 클릭시 * ***********************************************************/ public void registerMyStudyBtn(View view){ root1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(root1.child(studyTitles[2]).equals("")){ Map<String, Object> map = new HashMap<String, Object>(); //HashMap으로 값을 넣으면 Key값이 생성되지않고 바로 들어가기 때문에 HashMap으로 데이터 저장 map.put(studyTitles[2], ""); root1.updateChildren(map); } } @Override public void onCancelled(DatabaseError databaseError) { } }); /************************************************************************ *그룹에 이미 유저가 저장 되있는 경우 데이터를 또 넣지 않게 하기 위한 곳* ************************************************************************/ if(!(root1.child(studyTitles[2]).equals(currentUserUid))) { // 유저의 UID값을 비교 Map<String, Object> groupUserMap = new HashMap<String, Object>(); groupUserMap.put(currentUserUid,currentUserEmail); root1.child(studyTitles[2]).updateChildren(groupUserMap); }else{ Toast.makeText(getApplicationContext(), "이미 등록된 스터디입니다!", Toast.LENGTH_LONG).show(); } } public void backBtn(View view){ finish(); } }
6,200
0.535132
0.515954
138
41.695652
27.007677
102
false
false
0
0
0
0
0
0
0.73913
false
false
15
d9fc07afe840dea0a0eb25851fa406664727a78d
24,644,522,396,700
b3932606fd913fd86754270b82b2ea6eaa7fe4e3
/src/main/java/com/ptv/Daemon/PtvConfig.java
21efb34b2cf5808c477c00b4f6fa09a7b19fe42e
[]
no_license
vis-lee/nreader
https://github.com/vis-lee/nreader
becf080bf28a1a1c53531b7d3c4dc9b607e68c6d
8373c89cd08ca8744d4b16d8d375b8f59f165c9c
refs/heads/master
2022-12-28T21:51:24.218000
2015-11-23T03:32:26
2015-11-23T03:32:26
256,900,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ptv.Daemon; public class PtvConfig implements PtvConstant { public int parseConfig(){ int retcode = SUCCESS; return retcode; } }
UTF-8
Java
161
java
PtvConfig.java
Java
[]
null
[]
package com.ptv.Daemon; public class PtvConfig implements PtvConstant { public int parseConfig(){ int retcode = SUCCESS; return retcode; } }
161
0.68323
0.68323
14
10.5
14.024214
47
false
false
0
0
0
0
0
0
1.142857
false
false
15
ce351788bf0fa8e4c99bd4c5824814ba9bb83bba
28,089,086,123,297
dab29f11b0e4797e9a07b3d0258f44f82e0baab3
/gtm-engine-common-api/src/main/java/br/com/globality/gtm/engine/common/domain/Transacao.java
10d53c818b9bca9eca858ad4dbbe1698a86159ed
[]
no_license
globalityrepo/gtm-engine
https://github.com/globalityrepo/gtm-engine
3f9b863d0bcb22271a6167a26a34b04220cce66b
b34bf5c08f60ffcdadf1c82d0c658730ff0e2213
refs/heads/master
2021-07-04T19:26:42.147000
2017-09-28T01:34:23
2017-09-28T01:34:23
100,310,438
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.globality.gtm.engine.common.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; /** * @author Bryan Duarte * */ @Entity @Table(name = "TRANS") @NamedQueries({ @NamedQuery(name = "Transacao.findAll", query = "select t from Transacao t") }) @SequenceGenerator(name = "seq_transacao", sequenceName = "SQ15_TRANS", initialValue = 1) public class Transacao extends AbstractDomain { /** * */ private static final long serialVersionUID = -3180924629857955885L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_transacao") @Column(name = "N_TRANS", nullable = false, unique = true) private Long id; @Column(name = "C_TRANS", nullable = true, length = 64) @NotNull private String codigo; @Column(name = "R_TRANS", nullable = true, length = 512) @NotNull private String descricao; @Column(name = "Q_DIA_EVNTO", nullable = true) @NotNull private Long qtdeDiaEvento; @Column(name = "Q_DIA_CONTD_EVNTO", nullable = true) @NotNull private Long qtdeDiaConteudoEvento; @Column(name = "C_TRANS_REST", nullable = true, length = 1) @NotNull private String restricao; @Transient private String qtdeDiaEventoFormatado; @Transient private String qtdeDiaConteudoEventoFormatado; @Transient private String restricaoFormatado; @Transient private String idTransacaoInstancia; @Transient private Long idParametro; @Transient private String valorParametro; @Transient private List<TransacaoParametro> parametros; @Transient private List<TransacaoPasso> passos; @Transient private List<TransacaoGrupo> grupos; @Transient private boolean selecionado; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Long getQtdeDiaEvento() { return qtdeDiaEvento; } public void setQtdeDiaEvento(Long qtdeDiaEvento) { this.qtdeDiaEvento = qtdeDiaEvento; } public String getQtdeDiaEventoFormatado() { if (qtdeDiaEvento!=null && qtdeDiaEvento > 0L) { if (qtdeDiaEvento > 1L) { return qtdeDiaEvento + " dias"; } else { return qtdeDiaEvento + " dia"; } } return "-"; } public void setQtdeDiaEventoFormatado(String qtdeDiaEventoFormatado) { this.qtdeDiaEventoFormatado = qtdeDiaEventoFormatado; } public Long getQtdeDiaConteudoEvento() { return qtdeDiaConteudoEvento; } public void setQtdeDiaConteudoEvento(Long qtdeDiaConteudoEvento) { this.qtdeDiaConteudoEvento = qtdeDiaConteudoEvento; } public String getQtdeDiaConteudoEventoFormatado() { if (qtdeDiaConteudoEvento!=null && qtdeDiaConteudoEvento > 0L) { if (qtdeDiaConteudoEvento > 1L) { return qtdeDiaConteudoEvento + " dias"; } else { return qtdeDiaConteudoEvento + " dia"; } } return "-"; } public void setQtdeDiaConteudoEventoFormatado(String qtdeDiaConteudoEventoFormatado) { this.qtdeDiaConteudoEventoFormatado = qtdeDiaConteudoEventoFormatado; } public String getRestricao() { return restricao; } public void setRestricao(String restricao) { this.restricao = restricao; } public String getRestricaoFormatado() { return restricao!=null && restricao.equalsIgnoreCase("Y") ? "SIM" : "NÃO"; } public void setRestricaoFormatado(String restricaoFormatado) { this.restricaoFormatado = restricaoFormatado; } public List<TransacaoParametro> getParametros() { return parametros; } public void setParametros(List<TransacaoParametro> parametros) { this.parametros = parametros; } public String getIdTransacaoInstancia() { return idTransacaoInstancia; } public void setIdTransacaoInstancia(String idTransacaoInstancia) { this.idTransacaoInstancia = idTransacaoInstancia; } public Long getIdParametro() { return idParametro; } public void setIdParametro(Long idParametro) { this.idParametro = idParametro; } public String getValorParametro() { return valorParametro; } public void setValorParametro(String valorParametro) { this.valorParametro = valorParametro; } public List<TransacaoPasso> getPassos() { return passos; } public void setPassos(List<TransacaoPasso> passos) { this.passos = passos; } public List<TransacaoGrupo> getGrupos() { return grupos; } public void setGrupos(List<TransacaoGrupo> grupos) { this.grupos = grupos; } public boolean isSelecionado() { return selecionado; } public void setSelecionado(boolean selecionado) { this.selecionado = selecionado; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Transacao other = (Transacao) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
UTF-8
Java
5,594
java
Transacao.java
Java
[ { "context": "ax.validation.constraints.NotNull;\n\n/**\n * @author Bryan Duarte\n *\n */\n@Entity\n@Table(name = \"TRANS\")\n@NamedQueri", "end": 514, "score": 0.999880850315094, "start": 502, "tag": "NAME", "value": "Bryan Duarte" } ]
null
[]
package br.com.globality.gtm.engine.common.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; /** * @author <NAME> * */ @Entity @Table(name = "TRANS") @NamedQueries({ @NamedQuery(name = "Transacao.findAll", query = "select t from Transacao t") }) @SequenceGenerator(name = "seq_transacao", sequenceName = "SQ15_TRANS", initialValue = 1) public class Transacao extends AbstractDomain { /** * */ private static final long serialVersionUID = -3180924629857955885L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_transacao") @Column(name = "N_TRANS", nullable = false, unique = true) private Long id; @Column(name = "C_TRANS", nullable = true, length = 64) @NotNull private String codigo; @Column(name = "R_TRANS", nullable = true, length = 512) @NotNull private String descricao; @Column(name = "Q_DIA_EVNTO", nullable = true) @NotNull private Long qtdeDiaEvento; @Column(name = "Q_DIA_CONTD_EVNTO", nullable = true) @NotNull private Long qtdeDiaConteudoEvento; @Column(name = "C_TRANS_REST", nullable = true, length = 1) @NotNull private String restricao; @Transient private String qtdeDiaEventoFormatado; @Transient private String qtdeDiaConteudoEventoFormatado; @Transient private String restricaoFormatado; @Transient private String idTransacaoInstancia; @Transient private Long idParametro; @Transient private String valorParametro; @Transient private List<TransacaoParametro> parametros; @Transient private List<TransacaoPasso> passos; @Transient private List<TransacaoGrupo> grupos; @Transient private boolean selecionado; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Long getQtdeDiaEvento() { return qtdeDiaEvento; } public void setQtdeDiaEvento(Long qtdeDiaEvento) { this.qtdeDiaEvento = qtdeDiaEvento; } public String getQtdeDiaEventoFormatado() { if (qtdeDiaEvento!=null && qtdeDiaEvento > 0L) { if (qtdeDiaEvento > 1L) { return qtdeDiaEvento + " dias"; } else { return qtdeDiaEvento + " dia"; } } return "-"; } public void setQtdeDiaEventoFormatado(String qtdeDiaEventoFormatado) { this.qtdeDiaEventoFormatado = qtdeDiaEventoFormatado; } public Long getQtdeDiaConteudoEvento() { return qtdeDiaConteudoEvento; } public void setQtdeDiaConteudoEvento(Long qtdeDiaConteudoEvento) { this.qtdeDiaConteudoEvento = qtdeDiaConteudoEvento; } public String getQtdeDiaConteudoEventoFormatado() { if (qtdeDiaConteudoEvento!=null && qtdeDiaConteudoEvento > 0L) { if (qtdeDiaConteudoEvento > 1L) { return qtdeDiaConteudoEvento + " dias"; } else { return qtdeDiaConteudoEvento + " dia"; } } return "-"; } public void setQtdeDiaConteudoEventoFormatado(String qtdeDiaConteudoEventoFormatado) { this.qtdeDiaConteudoEventoFormatado = qtdeDiaConteudoEventoFormatado; } public String getRestricao() { return restricao; } public void setRestricao(String restricao) { this.restricao = restricao; } public String getRestricaoFormatado() { return restricao!=null && restricao.equalsIgnoreCase("Y") ? "SIM" : "NÃO"; } public void setRestricaoFormatado(String restricaoFormatado) { this.restricaoFormatado = restricaoFormatado; } public List<TransacaoParametro> getParametros() { return parametros; } public void setParametros(List<TransacaoParametro> parametros) { this.parametros = parametros; } public String getIdTransacaoInstancia() { return idTransacaoInstancia; } public void setIdTransacaoInstancia(String idTransacaoInstancia) { this.idTransacaoInstancia = idTransacaoInstancia; } public Long getIdParametro() { return idParametro; } public void setIdParametro(Long idParametro) { this.idParametro = idParametro; } public String getValorParametro() { return valorParametro; } public void setValorParametro(String valorParametro) { this.valorParametro = valorParametro; } public List<TransacaoPasso> getPassos() { return passos; } public void setPassos(List<TransacaoPasso> passos) { this.passos = passos; } public List<TransacaoGrupo> getGrupos() { return grupos; } public void setGrupos(List<TransacaoGrupo> grupos) { this.grupos = grupos; } public boolean isSelecionado() { return selecionado; } public void setSelecionado(boolean selecionado) { this.selecionado = selecionado; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Transacao other = (Transacao) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
5,588
0.729304
0.722868
256
20.847656
21.495373
95
false
false
0
0
0
0
0
0
1.488281
false
false
15
691900af40aca4318825b6975946cea07d4ecd1e
1,700,807,079,130
7c3d483e4988a046dd25c2dc36ccce576c2c6daf
/important/src/previousinterview/MinimumJumps.java
bbe4287004f79e32e04f6186d8d5c566219218fe
[]
no_license
pavan0169/myplacementscodes
https://github.com/pavan0169/myplacementscodes
cf909de5787e15a10a5c3948fa9795190551b974
e82974090a96948e6266d0663748687cc6340d88
refs/heads/main
2023-01-22T00:28:08.358000
2020-11-25T08:39:41
2020-11-25T08:39:41
315,872,960
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package previousinterview; import java.util.*; /* Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then we cannot move through that element. Examples: Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} Output: 3 (1-> 3 -> 8 -> 9) Explanation: Jump from 1st element to 2nd element as there is only 1 step, now there are three options 5, 8 or 9. If 8 or 9 is chosen then the end node 9 can be reached. So 3 jumps are made. Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: 10 Explanation: In every step a jump is needed so the count of jumps is 10. */ public class MinimumJumps { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0; i<n; i++) { arr[i]=sc.nextInt(); } sc.close(); int ans=minimumJumps(arr); System.out.println(ans); } public static int minimumJumps(int[] arr) { int n=arr.length; if(n==0) { return 0; } if(arr[0]==0) { return 0; } int jumps=1; int maxreach=arr[0]; int steps=arr[0]; for(int i=1; i<arr.length; i++) { if(i==n-1) return jumps; maxreach=Math.max(maxreach, arr[i]+i); steps--; if(steps==0) { jumps++; if(i>=maxreach) return -1; steps=maxreach-i; } } return -1; } }
UTF-8
Java
1,583
java
MinimumJumps.java
Java
[]
null
[]
package previousinterview; import java.util.*; /* Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then we cannot move through that element. Examples: Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} Output: 3 (1-> 3 -> 8 -> 9) Explanation: Jump from 1st element to 2nd element as there is only 1 step, now there are three options 5, 8 or 9. If 8 or 9 is chosen then the end node 9 can be reached. So 3 jumps are made. Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: 10 Explanation: In every step a jump is needed so the count of jumps is 10. */ public class MinimumJumps { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0; i<n; i++) { arr[i]=sc.nextInt(); } sc.close(); int ans=minimumJumps(arr); System.out.println(ans); } public static int minimumJumps(int[] arr) { int n=arr.length; if(n==0) { return 0; } if(arr[0]==0) { return 0; } int jumps=1; int maxreach=arr[0]; int steps=arr[0]; for(int i=1; i<arr.length; i++) { if(i==n-1) return jumps; maxreach=Math.max(maxreach, arr[i]+i); steps--; if(steps==0) { jumps++; if(i>=maxreach) return -1; steps=maxreach-i; } } return -1; } }
1,583
0.600758
0.565382
71
20.295774
23.039705
126
false
false
0
0
0
0
0
0
2.12676
false
false
15
35756ceccf0b8e6916c5b986622c96e0141dbdb3
32,950,989,140,070
7fd9685830a1f32f4d35ece96f624e30321f10e5
/app/src/main/java/com/mwtraking/beinmedia/hajjhealthy/listners/PaginationAdapterCallback.java
ac8cddaa79732f0173e4385fcf6af6b4ae8e5a3e
[]
no_license
mwaked/E-70-HelathyHajj
https://github.com/mwaked/E-70-HelathyHajj
89903c70c35a3bcf231215919807a313a2e8b450
731d7b53dd533f7654dbaed99267941ed3077aaf
refs/heads/master
2020-03-25T03:17:58.947000
2018-08-02T19:01:44
2018-08-02T19:01:44
143,333,847
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mwtraking.beinmedia.hajjhealthy.listners; /** * Created by Mahmoud Waked */ public interface PaginationAdapterCallback { void retryPageLoad(); }
UTF-8
Java
165
java
PaginationAdapterCallback.java
Java
[ { "context": "beinmedia.hajjhealthy.listners;\n\n/**\n * Created by Mahmoud Waked\n */\n\npublic interface PaginationAdapterCallback {", "end": 86, "score": 0.9998664855957031, "start": 73, "tag": "NAME", "value": "Mahmoud Waked" } ]
null
[]
package com.mwtraking.beinmedia.hajjhealthy.listners; /** * Created by <NAME> */ public interface PaginationAdapterCallback { void retryPageLoad(); }
158
0.757576
0.757576
9
17.333334
19.476482
53
false
false
0
0
0
0
0
0
0.222222
false
false
15
67944a0d24d5e0dc7b34a071339d2758d64c03f5
26,362,509,297,680
d489b98d522d97c9453557761e3572e68db2720b
/src/Dijkstra.java
71a7ecdad7be0ddbb37f270071b09e4d15963a07
[]
no_license
yuvrajrr/CheapestRoadTrip
https://github.com/yuvrajrr/CheapestRoadTrip
4985b42b053f722a3ffec84e7aaa914210d61c1f
a486c4e3b5382f5962a3de7aa9c1b0cc83b52179
refs/heads/main
2022-12-29T22:13:14.777000
2020-10-14T02:22:57
2020-10-14T02:22:57
303,861,711
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import java.io.*; // This class represents a Dijkstra object public class Dijkstra { // Maps a city to its corresponding node private HashMap<String, Node> city_map = new HashMap<String, Node>(); // Maps a city to an ArrayList of adjacent Nodes private HashMap<String, ArrayList<Node>> final_map = new HashMap<String, ArrayList<Node>>(); // Keeps track of all the visited Nodes private ArrayList<Node> visited = new ArrayList<Node>(); // HashMap that stores the distance of each city from the root node private HashMap<String,Double> distance = new HashMap<String, Double>(); // HashMap that stores the shortest path of every Node private HashMap<String, String> path = new HashMap<String, String>(); private String filename; // The constructor will assign the values passed through to the state variables public Dijkstra(HashMap<String, Node> City_map, HashMap<String, ArrayList<Node>> Final_map, String File) { city_map = City_map; final_map = Final_map; filename = File; // The HashMap that represents the distance of each node is initially set to the maximum value a double can hold for(String s: city_map.keySet()) { distance.put(s, Double.MAX_VALUE); } // The distance of the auxiliary node is initially set to 0 distance.put("Aux", 0.0); } // Getter that returns the visited ArrayList of Nodes public ArrayList<Node> getVisited(){ return visited; } // Getter that returns the HashMap of the path public HashMap<String, String> getPath(){ return path; } // Getter that returns the HashMap of the distance of each node public HashMap<String, Double> getDistance(){ return distance; } // Function that returns a boolean true or false after checking if a Node has already been visited public boolean Visit(String key_string) { for(int i = 0; i<visited.size() ; i++) { if(key_string.compareTo(visited.get(i).getCity()) == 0) { return true; } } return false; } // Function that finds the node with the smallest distance public String min_node() { String min = null; double min_val = Double.MAX_VALUE; for(String key: distance.keySet()) { if( Visit(key) == false && distance.get(key)<min_val) { min_val = distance.get(key); min = key; } } return min; } // Function that runs the algorithm to find the shortest path public void search() { // The initial minimum string is set to the Auxiliary string String minimum = "Aux"; ArrayList<Node> connected_nodes = new ArrayList<Node>(); // The while loop runs until all nodes have been visited while((visited.size()*2+1) != city_map.size()) { // Adjacent nodes of the Node with the smallest distance from the root are stored in connected_nodes connected_nodes = final_map.get(minimum); // Every Node that is adjacent to the Node with the smallest distance from the root Node is traversed for(Node current:connected_nodes) { // If the price (weight) of the adjacent node + the distance is less than the current distance of the node, the distance is updated // The path of the Node that has been updated is stored with the minimum Node being set as the parent Node if(current.getPrice() + distance.get(minimum) < distance.get(current.getCity())) { distance.put(current.getCity(), current.getPrice() + distance.get(minimum)); path.put(current.getCity(), minimum); // If the adjacent node has no outgoing nodes it is set as visited if(final_map.get(current.getCity()) == null) { visited.add(current); } } } // The minimum Node is set as visited visited.add(city_map.get(minimum)); // A new minimum node is found using the min_node() function minimum = min_node(); } } // The path from the start city to the end city is found public void pathCreate(String start, String end) throws IOException { String start0 = (start+"0").toUpperCase(); String start1 = (start+"1").toUpperCase(); String end0 = (end+"0").toUpperCase(); String end1 = (end+"1").toUpperCase(); String current0 = end0; String current1 = end1; ArrayList<Node> path0 = new ArrayList<Node>(); ArrayList<Node> path1 = new ArrayList<Node>(); // Since each city is represented by 2 Nodes, Node0 and Node1, both paths are found by using the path HashMap and tracing it back to the starting Node // This while loop runs until the path of Node0 (cheapest Node of the end city) has been found while(!(current0.compareTo(start0) == 0) && !(current0.compareTo(start1) == 0)) { path0.add(city_map.get(current0)); current0 = path.get(current0); } path0.add(city_map.get(start0)); // This while loop runs until the path of Node1 (second cheapest Node of the end city) has been found while(current1.compareTo(start0) != 0 && current1.compareTo(start1) != 0) { path1.add(city_map.get(current1)); current1 = path.get(current1); } path1.add(city_map.get(start1)); double total0 = 0.0; double total1 = 0.0; // The total cost of the path for Node0 is found for(int i = 0; i<path0.size() ; i++) { total0 += path0.get(i).getPrice(); } // The total cost of the path for Node1 is found for(int i = 0; i<path1.size() ; i++) { total1 += path1.get(i).getPrice(); } ArrayList<Node> reverse = new ArrayList<Node>(); double finalPrice; // The cheaper path array is reversed since it was stored in the reverse order if(total0 < total1) { for(int j = (path0.size() - 1) ; j > -1 ; j--) { reverse.add(path0.get(j)); } finalPrice = total0; } else { for(int j = (path1.size() - 1) ; j > -1 ; j--) { reverse.add(path1.get(j)); } finalPrice = total1; } // The reversed array is passed through with the cost of that path (cheapest cost) to be written to the output file pathWrite(reverse, finalPrice); } // The cheapest cost path is written to the output file public void pathWrite(ArrayList<Node> finalPath, double finalPrice) throws IOException{ BufferedWriter w = new BufferedWriter(new FileWriter(filename, true)); w.write("\n"); w.write("\n"); // The headings are written in first w.write(String.format("%-20s | %-30s | %-20s \r\n", "City", "Meal Choice", "Cost of Meal")); w.write("------------------------------------------------------------------------"); w.write("\n"); // The first city is written in seperately since the meal will says "No Meal" w.write(String.format("%-20s | %-30s | %-20s \r\n", finalPath.get(0).getCity().substring(0, finalPath.get(0).getCity().length() - 1), "No Meal", "$0.00")); w.write("------------------------------------------------------------------------"); w.write("\n"); // The loop will run for the size of the remaining path and write the City, Meal, and Cost in a table for(int i = 1; i < finalPath.size() ; i++) { w.write(String.format("%-20s | %-30s | %-20s \r\n", finalPath.get(i).getCity().substring(0, finalPath.get(i).getCity().length() - 1), finalPath.get(i).getMeal(), "$"+finalPath.get(i).getPrice())); w.write("------------------------------------------------------------------------"); w.write("\n"); } w.write("Total Cost: $" + Double.toString(finalPrice)); w.close(); } }
UTF-8
Java
7,467
java
Dijkstra.java
Java
[]
null
[]
import java.util.*; import java.io.*; // This class represents a Dijkstra object public class Dijkstra { // Maps a city to its corresponding node private HashMap<String, Node> city_map = new HashMap<String, Node>(); // Maps a city to an ArrayList of adjacent Nodes private HashMap<String, ArrayList<Node>> final_map = new HashMap<String, ArrayList<Node>>(); // Keeps track of all the visited Nodes private ArrayList<Node> visited = new ArrayList<Node>(); // HashMap that stores the distance of each city from the root node private HashMap<String,Double> distance = new HashMap<String, Double>(); // HashMap that stores the shortest path of every Node private HashMap<String, String> path = new HashMap<String, String>(); private String filename; // The constructor will assign the values passed through to the state variables public Dijkstra(HashMap<String, Node> City_map, HashMap<String, ArrayList<Node>> Final_map, String File) { city_map = City_map; final_map = Final_map; filename = File; // The HashMap that represents the distance of each node is initially set to the maximum value a double can hold for(String s: city_map.keySet()) { distance.put(s, Double.MAX_VALUE); } // The distance of the auxiliary node is initially set to 0 distance.put("Aux", 0.0); } // Getter that returns the visited ArrayList of Nodes public ArrayList<Node> getVisited(){ return visited; } // Getter that returns the HashMap of the path public HashMap<String, String> getPath(){ return path; } // Getter that returns the HashMap of the distance of each node public HashMap<String, Double> getDistance(){ return distance; } // Function that returns a boolean true or false after checking if a Node has already been visited public boolean Visit(String key_string) { for(int i = 0; i<visited.size() ; i++) { if(key_string.compareTo(visited.get(i).getCity()) == 0) { return true; } } return false; } // Function that finds the node with the smallest distance public String min_node() { String min = null; double min_val = Double.MAX_VALUE; for(String key: distance.keySet()) { if( Visit(key) == false && distance.get(key)<min_val) { min_val = distance.get(key); min = key; } } return min; } // Function that runs the algorithm to find the shortest path public void search() { // The initial minimum string is set to the Auxiliary string String minimum = "Aux"; ArrayList<Node> connected_nodes = new ArrayList<Node>(); // The while loop runs until all nodes have been visited while((visited.size()*2+1) != city_map.size()) { // Adjacent nodes of the Node with the smallest distance from the root are stored in connected_nodes connected_nodes = final_map.get(minimum); // Every Node that is adjacent to the Node with the smallest distance from the root Node is traversed for(Node current:connected_nodes) { // If the price (weight) of the adjacent node + the distance is less than the current distance of the node, the distance is updated // The path of the Node that has been updated is stored with the minimum Node being set as the parent Node if(current.getPrice() + distance.get(minimum) < distance.get(current.getCity())) { distance.put(current.getCity(), current.getPrice() + distance.get(minimum)); path.put(current.getCity(), minimum); // If the adjacent node has no outgoing nodes it is set as visited if(final_map.get(current.getCity()) == null) { visited.add(current); } } } // The minimum Node is set as visited visited.add(city_map.get(minimum)); // A new minimum node is found using the min_node() function minimum = min_node(); } } // The path from the start city to the end city is found public void pathCreate(String start, String end) throws IOException { String start0 = (start+"0").toUpperCase(); String start1 = (start+"1").toUpperCase(); String end0 = (end+"0").toUpperCase(); String end1 = (end+"1").toUpperCase(); String current0 = end0; String current1 = end1; ArrayList<Node> path0 = new ArrayList<Node>(); ArrayList<Node> path1 = new ArrayList<Node>(); // Since each city is represented by 2 Nodes, Node0 and Node1, both paths are found by using the path HashMap and tracing it back to the starting Node // This while loop runs until the path of Node0 (cheapest Node of the end city) has been found while(!(current0.compareTo(start0) == 0) && !(current0.compareTo(start1) == 0)) { path0.add(city_map.get(current0)); current0 = path.get(current0); } path0.add(city_map.get(start0)); // This while loop runs until the path of Node1 (second cheapest Node of the end city) has been found while(current1.compareTo(start0) != 0 && current1.compareTo(start1) != 0) { path1.add(city_map.get(current1)); current1 = path.get(current1); } path1.add(city_map.get(start1)); double total0 = 0.0; double total1 = 0.0; // The total cost of the path for Node0 is found for(int i = 0; i<path0.size() ; i++) { total0 += path0.get(i).getPrice(); } // The total cost of the path for Node1 is found for(int i = 0; i<path1.size() ; i++) { total1 += path1.get(i).getPrice(); } ArrayList<Node> reverse = new ArrayList<Node>(); double finalPrice; // The cheaper path array is reversed since it was stored in the reverse order if(total0 < total1) { for(int j = (path0.size() - 1) ; j > -1 ; j--) { reverse.add(path0.get(j)); } finalPrice = total0; } else { for(int j = (path1.size() - 1) ; j > -1 ; j--) { reverse.add(path1.get(j)); } finalPrice = total1; } // The reversed array is passed through with the cost of that path (cheapest cost) to be written to the output file pathWrite(reverse, finalPrice); } // The cheapest cost path is written to the output file public void pathWrite(ArrayList<Node> finalPath, double finalPrice) throws IOException{ BufferedWriter w = new BufferedWriter(new FileWriter(filename, true)); w.write("\n"); w.write("\n"); // The headings are written in first w.write(String.format("%-20s | %-30s | %-20s \r\n", "City", "Meal Choice", "Cost of Meal")); w.write("------------------------------------------------------------------------"); w.write("\n"); // The first city is written in seperately since the meal will says "No Meal" w.write(String.format("%-20s | %-30s | %-20s \r\n", finalPath.get(0).getCity().substring(0, finalPath.get(0).getCity().length() - 1), "No Meal", "$0.00")); w.write("------------------------------------------------------------------------"); w.write("\n"); // The loop will run for the size of the remaining path and write the City, Meal, and Cost in a table for(int i = 1; i < finalPath.size() ; i++) { w.write(String.format("%-20s | %-30s | %-20s \r\n", finalPath.get(i).getCity().substring(0, finalPath.get(i).getCity().length() - 1), finalPath.get(i).getMeal(), "$"+finalPath.get(i).getPrice())); w.write("------------------------------------------------------------------------"); w.write("\n"); } w.write("Total Cost: $" + Double.toString(finalPrice)); w.close(); } }
7,467
0.63332
0.619124
201
35.149254
35.378799
199
false
false
0
0
0
0
0
0
2.656716
false
false
15
b8579b31b3d69d73d4b61a9f11671463f7368abc
7,980,049,267,550
0c569f9aee9ec281874184e9c57a2523138b9e29
/forexfeed/src/main/java/com/superstar/forex/forexfeed/service/FXFeedManagerImpl.java
77c4512fbe192c82971911458c6bfdaf456f73be
[]
no_license
ishamuruga/microservices
https://github.com/ishamuruga/microservices
9d4282f7d75b449d20255e5e78aa2d65940a3334
d058127be5fa948e050aba650da4cdd6f5eb8503
refs/heads/main
2023-07-18T08:57:52.280000
2021-08-29T21:15:24
2021-08-29T21:15:24
387,890,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.superstar.forex.forexfeed.service; import java.math.BigDecimal; import com.superstar.forex.forexfeed.exception.NoForexFeedException; import com.superstarbank.vomodel.forex.ForexFeedRequest; import com.superstarbank.vomodel.forex.ForexFeedResponse; import org.springframework.stereotype.Service; @Service public class FXFeedManagerImpl extends BaseFxSource implements FXFeedManager { @Override public ForexFeedResponse getFxRates(ForexFeedRequest fxReq) throws Exception { ForexFeedResponse fxRes = new ForexFeedResponse(); String key = fxReq.getDestCcy().concat(fxReq.getSrcCcy()); BigDecimal fxRate = new BigDecimal(0); System.out.println(key); if (getFXRatesData().containsKey(key)){ fxRate = getFXRatesData().get(key); } else { throw new NoForexFeedException("No Forex Feed available"); } fxRes.setFxReq(fxReq); fxRes.setValue(fxRate.multiply(new BigDecimal(fxReq.getAmount()))); return fxRes; } }
UTF-8
Java
1,074
java
FXFeedManagerImpl.java
Java
[]
null
[]
package com.superstar.forex.forexfeed.service; import java.math.BigDecimal; import com.superstar.forex.forexfeed.exception.NoForexFeedException; import com.superstarbank.vomodel.forex.ForexFeedRequest; import com.superstarbank.vomodel.forex.ForexFeedResponse; import org.springframework.stereotype.Service; @Service public class FXFeedManagerImpl extends BaseFxSource implements FXFeedManager { @Override public ForexFeedResponse getFxRates(ForexFeedRequest fxReq) throws Exception { ForexFeedResponse fxRes = new ForexFeedResponse(); String key = fxReq.getDestCcy().concat(fxReq.getSrcCcy()); BigDecimal fxRate = new BigDecimal(0); System.out.println(key); if (getFXRatesData().containsKey(key)){ fxRate = getFXRatesData().get(key); } else { throw new NoForexFeedException("No Forex Feed available"); } fxRes.setFxReq(fxReq); fxRes.setValue(fxRate.multiply(new BigDecimal(fxReq.getAmount()))); return fxRes; } }
1,074
0.695531
0.6946
37
28.027027
27.377726
82
false
false
0
0
0
0
0
0
0.405405
false
false
15
314938ab495dbc570e331d39840084d1d7922dcd
33,114,197,889,067
ea1be5dc1aaf73be8deb0281db9c942e0e20bda7
/app/src/main/java/com/example/runningh/plugintestdemo/ActivityHookHelper.java
b0c9bfe217539cc041ec3ef4af106a4962a41428
[]
no_license
hwldzh/pluginTestDemo
https://github.com/hwldzh/pluginTestDemo
ffff7f7a136799d9ae53d184b1506141bed91ec3
43e0c6d19ef012c79de698de40e8d0067946ad19
refs/heads/master
2021-05-01T11:21:46.322000
2018-02-11T11:56:46
2018-02-11T11:56:46
121,118,628
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.runningh.plugintestdemo; import android.os.Handler; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by RunningH on 2018/2/5. */ public class ActivityHookHelper { public static final String RAW_INTENT = "RAW_INTENT"; /** * Hook AMS * 主要完成的操作是将真正要启动的Activity替换成在Manifest里面注册的坑位Activity */ public static void hookActivityWithPit() { try { /*Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative"); Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault"); gDefaultField.setAccessible(true); Object gDefaultValue = gDefaultField.get(null);*/ Class<?> activityManagerClass = Class.forName("android.app.ActivityManager"); Field singletonField = activityManagerClass.getDeclaredField("IActivityManagerSingleton"); singletonField.setAccessible(true); Object singletonValue = singletonField.get(null); //gDefault是一个 android.util.Singleton对象;取出这个单例里面的字段 Class<?> singletonClass = Class.forName("android.util.Singleton"); //gDefault是一个Singleton类型的,我们需要从Singleton中再取出这个单例的AMS代理 Field mInstance = singletonClass.getDeclaredField("mInstance"); mInstance.setAccessible(true); //取出了AMS代理对象,这里的AMS代理对象就是gDefaultValue对象的值 Object iActivityManager = mInstance.get(singletonValue); Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager"); Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader() , new Class<?>[]{iActivityManagerInterface}, new IActivityManagerHandler(iActivityManager)); //将gDefaultValue对象的值(即上面的iActivityManager对象)设置为(AMS代理对象的)代理对象的值 mInstance.set(singletonValue, proxy); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static void hookHandler() { try { Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); //ActivityThread有一个静态方法返回了自己,这里可以获取activityThread对象 Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread"); currentActivityThread.setAccessible(true); Object activityThread = currentActivityThread.invoke(null); Field mH = activityThreadClass.getDeclaredField("mH"); mH.setAccessible(true); Handler mHValue = (Handler) mH.get(activityThread); //获取activityThread对象中mH变量的值,其中mH的类型是Handler类型 Field callback = Handler.class.getDeclaredField("mCallback"); callback.setAccessible(true); callback.set(mHValue, new ActivityCallbackHandler(mHValue)); //将一个自定义的Callback设置给Handler } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
3,486
java
ActivityHookHelper.java
Java
[ { "context": "import java.lang.reflect.Proxy;\n\n/**\n * Created by RunningH on 2018/2/5.\n */\n\npublic class ActivityHookHelpe", "end": 197, "score": 0.7978160977363586, "start": 190, "tag": "NAME", "value": "Running" }, { "context": "ava.lang.reflect.Proxy;\n\n/**\n * Created by RunningH on 2018/2/5.\n */\n\npublic class ActivityHookHelper", "end": 198, "score": 0.46562087535858154, "start": 197, "tag": "USERNAME", "value": "H" } ]
null
[]
package com.example.runningh.plugintestdemo; import android.os.Handler; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by RunningH on 2018/2/5. */ public class ActivityHookHelper { public static final String RAW_INTENT = "RAW_INTENT"; /** * Hook AMS * 主要完成的操作是将真正要启动的Activity替换成在Manifest里面注册的坑位Activity */ public static void hookActivityWithPit() { try { /*Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative"); Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault"); gDefaultField.setAccessible(true); Object gDefaultValue = gDefaultField.get(null);*/ Class<?> activityManagerClass = Class.forName("android.app.ActivityManager"); Field singletonField = activityManagerClass.getDeclaredField("IActivityManagerSingleton"); singletonField.setAccessible(true); Object singletonValue = singletonField.get(null); //gDefault是一个 android.util.Singleton对象;取出这个单例里面的字段 Class<?> singletonClass = Class.forName("android.util.Singleton"); //gDefault是一个Singleton类型的,我们需要从Singleton中再取出这个单例的AMS代理 Field mInstance = singletonClass.getDeclaredField("mInstance"); mInstance.setAccessible(true); //取出了AMS代理对象,这里的AMS代理对象就是gDefaultValue对象的值 Object iActivityManager = mInstance.get(singletonValue); Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager"); Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader() , new Class<?>[]{iActivityManagerInterface}, new IActivityManagerHandler(iActivityManager)); //将gDefaultValue对象的值(即上面的iActivityManager对象)设置为(AMS代理对象的)代理对象的值 mInstance.set(singletonValue, proxy); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static void hookHandler() { try { Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); //ActivityThread有一个静态方法返回了自己,这里可以获取activityThread对象 Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread"); currentActivityThread.setAccessible(true); Object activityThread = currentActivityThread.invoke(null); Field mH = activityThreadClass.getDeclaredField("mH"); mH.setAccessible(true); Handler mHValue = (Handler) mH.get(activityThread); //获取activityThread对象中mH变量的值,其中mH的类型是Handler类型 Field callback = Handler.class.getDeclaredField("mCallback"); callback.setAccessible(true); callback.set(mHValue, new ActivityCallbackHandler(mHValue)); //将一个自定义的Callback设置给Handler } catch (Exception e) { e.printStackTrace(); } } }
3,486
0.677011
0.675111
73
42.260273
33.345444
112
false
false
0
0
0
0
0
0
0.547945
false
false
15
39e9aaa8d32ffee3c9e9406b7004b465f0f20c28
29,472,065,600,111
c669a35eb7b81322afe858df2197eda1e3d8786b
/jhj-service/src/main/java/com/jhj/service/users/UserSmsNoticeService.java
f28d187cf376f98505a102934df4eea34b10b88a
[]
no_license
bellmit/jhj-parent
https://github.com/bellmit/jhj-parent
b6bbb963b9d4c586767f692463543e111965120b
c530885d8999668e0ec25dd3403ac8daac0a19c1
refs/heads/master
2022-01-21T17:08:57.310000
2017-07-03T05:54:13
2017-07-03T05:54:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jhj.service.users; import java.util.List; import com.github.pagehelper.PageInfo; import com.jhj.po.model.user.UserSmsNotice; import com.jhj.vo.user.UserSmsNoticeSearchVo; public interface UserSmsNoticeService { int deleteByPrimaryKey(Long id); int insert(UserSmsNotice record); int insertSelective(UserSmsNotice record); int updateByPrimaryKeySelective(UserSmsNotice record); int updateByPrimaryKey(UserSmsNotice record); UserSmsNotice initPo(); UserSmsNotice selectByPrimaryKey(Long id); PageInfo selectByListPage(UserSmsNoticeSearchVo searchVo, int pageNo, int pageSize); List<UserSmsNotice> selectBySearchVo(UserSmsNoticeSearchVo searchVo); Integer totalBySearchVo(UserSmsNoticeSearchVo searchVo); }
UTF-8
Java
792
java
UserSmsNoticeService.java
Java
[]
null
[]
package com.jhj.service.users; import java.util.List; import com.github.pagehelper.PageInfo; import com.jhj.po.model.user.UserSmsNotice; import com.jhj.vo.user.UserSmsNoticeSearchVo; public interface UserSmsNoticeService { int deleteByPrimaryKey(Long id); int insert(UserSmsNotice record); int insertSelective(UserSmsNotice record); int updateByPrimaryKeySelective(UserSmsNotice record); int updateByPrimaryKey(UserSmsNotice record); UserSmsNotice initPo(); UserSmsNotice selectByPrimaryKey(Long id); PageInfo selectByListPage(UserSmsNoticeSearchVo searchVo, int pageNo, int pageSize); List<UserSmsNotice> selectBySearchVo(UserSmsNoticeSearchVo searchVo); Integer totalBySearchVo(UserSmsNoticeSearchVo searchVo); }
792
0.768939
0.768939
30
24.4
25.127144
85
false
false
0
0
0
0
0
0
0.733333
false
false
15
f5d708578bcbcd298b13e188bd1974d92c7865fe
22,582,938,109,104
42288ecf03f491433ab3276cb81596cdab2ec51b
/cod-admin/src/main/java/com/tlkj/cod/admin/model/enums/SystemCodeSet.java
74b806b5f831af0cdd4d02f366a4e5e9fc45e250
[]
no_license
WilleamZhao/codframe
https://github.com/WilleamZhao/codframe
4fe8e0ee5454151f2e0d794acadc86a6fc1988b7
8abda53d51899c5e14c2bc7d480b51a537a25caf
refs/heads/develop
2023-02-25T15:50:47.176000
2022-02-16T02:04:55
2022-02-16T02:04:55
185,297,749
3
0
null
false
2023-02-22T06:44:01
2019-05-07T01:29:54
2022-02-17T02:24:52
2023-02-22T06:43:58
98,108
4
0
12
Java
false
false
package com.tlkj.cod.admin.model.enums; /** * Desc 系统设置Code * * @author sourcod * @version 1.0 * @className SystemCodeSet * @date 2019/3/7 6:28 PM */ public enum SystemCodeSet { attachment("attachment", "附件设置"), log("log", "日志设置"), cache("cache", "缓存设置"), allow("allow_disable", "是否启用黑白名称"), ip("allow_ip", "允许登录ip设置"), webFrontUrl("web_front_url", "网站前端地址"), webName("web_name", "前端网站名称"), webAdminUrl("web_admin_url", "网站后台地址"), webAdminName("web_admin_name", "网站后台名称"); private String code; private String name; SystemCodeSet(String code, String name){ this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UTF-8
Java
1,043
java
SystemCodeSet.java
Java
[ { "context": "n.model.enums;\n\n/**\n * Desc 系统设置Code\n *\n * @author sourcod\n * @version 1.0\n * @className SystemCodeSet\n * @d", "end": 83, "score": 0.999653160572052, "start": 76, "tag": "USERNAME", "value": "sourcod" } ]
null
[]
package com.tlkj.cod.admin.model.enums; /** * Desc 系统设置Code * * @author sourcod * @version 1.0 * @className SystemCodeSet * @date 2019/3/7 6:28 PM */ public enum SystemCodeSet { attachment("attachment", "附件设置"), log("log", "日志设置"), cache("cache", "缓存设置"), allow("allow_disable", "是否启用黑白名称"), ip("allow_ip", "允许登录ip设置"), webFrontUrl("web_front_url", "网站前端地址"), webName("web_name", "前端网站名称"), webAdminUrl("web_admin_url", "网站后台地址"), webAdminName("web_admin_name", "网站后台名称"); private String code; private String name; SystemCodeSet(String code, String name){ this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,043
0.587166
0.575401
46
19.326086
14.979775
45
false
false
0
0
0
0
0
0
0.608696
false
false
15
20b716ab8891ec28711f19d38f5b77e0e3dcd75f
28,630,252,019,776
10b651fe7518a9609aa5a0e70c1a07cefeeb1b79
/src/main/java/module-info.java
7d18ae5bc02485036677bd3f6b7659d5b8fff360
[ "MIT" ]
permissive
Aclrian/MessdienerPlanErsteller
https://github.com/Aclrian/MessdienerPlanErsteller
0dede54410c7872d5db958c9bea8cebb49ed177d
21dd68fb920c776067ced915ef1f02e7efd89534
refs/heads/main
2023-08-29T09:56:38.472000
2023-07-29T17:18:31
2023-07-29T17:18:31
117,584,378
13
0
MIT
false
2023-09-14T16:34:29
2018-01-15T19:05:23
2023-05-22T13:09:08
2023-09-14T16:34:28
161,785
3
0
12
Java
false
false
module MessdienerplanErsteller.main { requires java.desktop; requires java.sql; requires java.xml; requires javafx.controls; requires javafx.fxml; requires javafx.web; requires html2pdf;//this is the only direct dependency that is non-modular requires jodconverter.local; requires jodconverter.core; requires org.apache.commons.io; requires org.apache.logging.log4j; requires spring.web; requires com.google.gson; requires org.apache.logging.log4j.core; opens net.aclrian.fx; opens net.aclrian.mpe; opens net.aclrian.mpe.controller; opens net.aclrian.mpe.converter; opens net.aclrian.mpe.messdiener; opens net.aclrian.mpe.messe; opens net.aclrian.mpe.pfarrei; opens net.aclrian.mpe.utils; exports net.aclrian.fx; exports net.aclrian.mpe; exports net.aclrian.mpe.controller; exports net.aclrian.mpe.converter; exports net.aclrian.mpe.messdiener; exports net.aclrian.mpe.messe; exports net.aclrian.mpe.pfarrei; exports net.aclrian.mpe.utils; exports net.aclrian.mpe.controller.converter; opens net.aclrian.mpe.controller.converter; }
UTF-8
Java
1,165
java
module-info.java
Java
[]
null
[]
module MessdienerplanErsteller.main { requires java.desktop; requires java.sql; requires java.xml; requires javafx.controls; requires javafx.fxml; requires javafx.web; requires html2pdf;//this is the only direct dependency that is non-modular requires jodconverter.local; requires jodconverter.core; requires org.apache.commons.io; requires org.apache.logging.log4j; requires spring.web; requires com.google.gson; requires org.apache.logging.log4j.core; opens net.aclrian.fx; opens net.aclrian.mpe; opens net.aclrian.mpe.controller; opens net.aclrian.mpe.converter; opens net.aclrian.mpe.messdiener; opens net.aclrian.mpe.messe; opens net.aclrian.mpe.pfarrei; opens net.aclrian.mpe.utils; exports net.aclrian.fx; exports net.aclrian.mpe; exports net.aclrian.mpe.controller; exports net.aclrian.mpe.converter; exports net.aclrian.mpe.messdiener; exports net.aclrian.mpe.messe; exports net.aclrian.mpe.pfarrei; exports net.aclrian.mpe.utils; exports net.aclrian.mpe.controller.converter; opens net.aclrian.mpe.controller.converter; }
1,165
0.725322
0.722747
40
28.15
15.905267
78
false
false
0
0
0
0
0
0
0.8
false
false
15
03fcf8559821acbba6951f810a3de5e0ba2a07a4
1,984,274,927,655
859aa35e7af5c5a3b1437a6727760b76340b5d03
/src/delphos/PruebasTED.java
6f10235943e8a39d1c809d5c4ebfea091e0f00f1
[]
no_license
mjtenmat/ATHENA
https://github.com/mjtenmat/ATHENA
275d94a73d1fc0a20361746fa7b180a5bea35b2b
73f1a8071cad928b35b05e0555b787b9ec272b5f
refs/heads/master
2021-01-13T13:46:02.941000
2018-09-26T10:10:21
2018-09-26T10:10:21
76,355,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package delphos; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class PruebasTED { public static void main(String[] args) throws Exception { Response resp; Document doc; String cookie, url; Map<String,String> postParameters = new HashMap<String,String>(); // url = "http://ted.europa.eu/TED/"; // resp = Jsoup.connect(url) // .execute(); // cookie = resp.cookie("JSESSIONID"); // System.out.println("\nPedida: " + url); // System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); // System.out.println("Cookies: " + resp.cookies()); // System.out.println("Url de la respuesta: " + resp.url()); // System.out.println("Cookie JSESSIONID: " + cookie); // url = resp.url().toString(); // doc = resp.parse(); //System.out.println(doc.toString()); // url = "http://ted.europa.eu/TED/misc/chooseLanguage.do?lgId=en"; // postParameters.put("action", "cl"); // resp = Jsoup.connect(url) // .method(Method.POST) // //.cookie("JSESSIONID", cookie) // .data(postParameters) // .execute(); // cookie = resp.cookie("JSESSIONID"); // System.out.println("\nPedida: " + url); // System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); // System.out.println("Cookies: " + resp.cookies()); // System.out.println("Url de la respuesta: " + resp.url()); // System.out.println("Cookie JSESSIONID: " + cookie); // url = resp.url().toString(); // doc = resp.parse(); //System.out.println(doc.toString()); //Login url = "http://ted.europa.eu/TED/"; resp = Jsoup.connect(url) //.method(Method.POST) //.cookie("JSESSIONID", cookie) //.data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); url = "http://ted.europa.eu/TED/misc/chooseLanguage.do?lgId=en"; postParameters.put("action", "cl"); resp = Jsoup.connect(url) .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); url = "http://ted.europa.eu/TED/search/search.do"; resp = Jsoup.connect(url) //.method(Method.POST) .cookies(resp.cookies()) //.data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.out.println("Lanzamos la consulta"); url = "http://ted.europa.eu/TED/search/search.do"; postParameters.put("action", "search"); postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .referrer("http://ted.europa.eu/TED/search/search.do") .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.exit(0); url = "http://ted.europa.eu/TED/search/search.do?"; postParameters.put("action", "search"); //postParameters.put("", ""); //postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); //postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); //postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .method(Method.POST) //.cookie("JSESSIONID", cookie) .data(postParameters) .followRedirects(false) .execute(); cookie = resp.cookie("JSESSIONID"); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Cookie JSESSIONID: " + cookie); System.out.println("Redirección a:" + resp.header("location")); //url = resp.url().toString(); //doc = resp.parse(); url = resp.header("location"); resp = Jsoup.connect(url) .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(false) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.exit(0); postParameters.put("action", "search"); //postParameters.put("", ""); //postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); //postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); //postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .method(Method.POST) //.cookie("JSESSIONID", cookie) .data(postParameters) .followRedirects(false) .execute(); cookie = resp.cookie("JSESSIONID"); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Cookie JSESSIONID: " + cookie); url = resp.url().toString(); doc = resp.parse(); escribirFichero(doc.toString()); } private static void escribirFichero(String texto){ try{ File fichero = new File("/tmp/ted.html"); BufferedWriter writer = new BufferedWriter(new FileWriter(fichero)); writer.write(texto); writer.close(); } catch (Exception e){ e.printStackTrace(); } } }
UTF-8
Java
11,323
java
PruebasTED.java
Java
[]
null
[]
package delphos; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class PruebasTED { public static void main(String[] args) throws Exception { Response resp; Document doc; String cookie, url; Map<String,String> postParameters = new HashMap<String,String>(); // url = "http://ted.europa.eu/TED/"; // resp = Jsoup.connect(url) // .execute(); // cookie = resp.cookie("JSESSIONID"); // System.out.println("\nPedida: " + url); // System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); // System.out.println("Cookies: " + resp.cookies()); // System.out.println("Url de la respuesta: " + resp.url()); // System.out.println("Cookie JSESSIONID: " + cookie); // url = resp.url().toString(); // doc = resp.parse(); //System.out.println(doc.toString()); // url = "http://ted.europa.eu/TED/misc/chooseLanguage.do?lgId=en"; // postParameters.put("action", "cl"); // resp = Jsoup.connect(url) // .method(Method.POST) // //.cookie("JSESSIONID", cookie) // .data(postParameters) // .execute(); // cookie = resp.cookie("JSESSIONID"); // System.out.println("\nPedida: " + url); // System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); // System.out.println("Cookies: " + resp.cookies()); // System.out.println("Url de la respuesta: " + resp.url()); // System.out.println("Cookie JSESSIONID: " + cookie); // url = resp.url().toString(); // doc = resp.parse(); //System.out.println(doc.toString()); //Login url = "http://ted.europa.eu/TED/"; resp = Jsoup.connect(url) //.method(Method.POST) //.cookie("JSESSIONID", cookie) //.data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); url = "http://ted.europa.eu/TED/misc/chooseLanguage.do?lgId=en"; postParameters.put("action", "cl"); resp = Jsoup.connect(url) .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); url = "http://ted.europa.eu/TED/search/search.do"; resp = Jsoup.connect(url) //.method(Method.POST) .cookies(resp.cookies()) //.data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.out.println("Lanzamos la consulta"); url = "http://ted.europa.eu/TED/search/search.do"; postParameters.put("action", "search"); postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .referrer("http://ted.europa.eu/TED/search/search.do") .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(true) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.exit(0); url = "http://ted.europa.eu/TED/search/search.do?"; postParameters.put("action", "search"); //postParameters.put("", ""); //postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); //postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); //postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .method(Method.POST) //.cookie("JSESSIONID", cookie) .data(postParameters) .followRedirects(false) .execute(); cookie = resp.cookie("JSESSIONID"); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Cookie JSESSIONID: " + cookie); System.out.println("Redirección a:" + resp.header("location")); //url = resp.url().toString(); //doc = resp.parse(); url = resp.header("location"); resp = Jsoup.connect(url) .method(Method.POST) .cookies(resp.cookies()) .data(postParameters) .followRedirects(false) .execute(); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Redirección a:" + resp.header("location")); escribirFichero(resp.parse().toString()); System.exit(0); postParameters.put("action", "search"); //postParameters.put("", ""); //postParameters.put("Rs.gp.11500808.pid","home"); postParameters.put("lgId","en"); //postParameters.put("Rs.gp.11500809.pid","releaseCalendar"); postParameters.put("quickSearchCriteria",""); //postParameters.put("s.gp.11500811.pid","secured"); postParameters.put("searchCriteria.searchScopeId","4"); postParameters.put("searchCriteria.ojs",""); postParameters.put("searchCriteria.freeText","energía"); postParameters.put("searchCriteria.countryList","AT,BE"); postParameters.put("searchCriteria.contractList","'Supply+contract','Service+contract'"); postParameters.put("searchCriteria.documentTypeList","'Contract+notice','Contract+award'"); postParameters.put("searchCriteria.cpvCodeList","09100000,09200000"); postParameters.put("searchCriteria.publicationDateChoice","RANGE_PUBLICATION_DATE"); postParameters.put("searchCriteria.fromPublicationDate","01-01-2010"); postParameters.put("searchCriteria.toPublicationDate","31-12-2014"); postParameters.put("searchCriteria.publicationDate",""); postParameters.put("searchCriteria.documentationDate",""); postParameters.put("searchCriteria.place",""); postParameters.put("searchCriteria.procedureList",""); postParameters.put("searchCriteria.regulationList",""); postParameters.put("searchCriteria.nutsCodeList",""); postParameters.put("searchCriteria.documentNumber",""); postParameters.put("searchCriteria.deadline",""); postParameters.put("searchCriteria.authorityName",""); postParameters.put("searchCriteria.mainActivityList",""); postParameters.put("searchCriteria.directiveList",""); postParameters.put("searchCriteria.statisticsMode","on"); resp = Jsoup.connect(url) .method(Method.POST) //.cookie("JSESSIONID", cookie) .data(postParameters) .followRedirects(false) .execute(); cookie = resp.cookie("JSESSIONID"); System.out.println("\nPedida: " + url); System.out.println("Código: " + resp.statusCode() + " " + resp.statusMessage()); System.out.println("Cookies: " + resp.cookies()); System.out.println("Url de la respuesta: " + resp.url()); System.out.println("Cookie JSESSIONID: " + cookie); url = resp.url().toString(); doc = resp.parse(); escribirFichero(doc.toString()); } private static void escribirFichero(String texto){ try{ File fichero = new File("/tmp/ted.html"); BufferedWriter writer = new BufferedWriter(new FileWriter(fichero)); writer.write(texto); writer.close(); } catch (Exception e){ e.printStackTrace(); } } }
11,323
0.70146
0.686157
268
41.182835
22.960873
93
false
false
0
0
0
0
0
0
3.223881
false
false
15
b3f973edfd6259224555aeddd65a6bd9039cac66
33,148,557,612,079
dcaa5a5cc0c5ade24f34f9ef9ebdef77b64bcc16
/src/Models/Customer.java
c9830f9478d0df9001d620503ea369c9eb932d72
[]
no_license
cygnu5101/JavaStuff
https://github.com/cygnu5101/JavaStuff
6dae0cf219a83e7e9e3a1123816ea034a2f68857
585524b14eb188f18feff033896e3bd48dbd4bb9
refs/heads/master
2021-01-02T05:11:26.267000
2020-02-10T12:16:12
2020-02-10T12:16:12
239,502,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Models; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * * @author 30289355 */ public class Customer extends User { // instance variables======================================================= private String addressLine1; private String addressLine2; private String town; private String postcode; private boolean isRegistered; private HashMap<Integer,Order> orders; //Getters===================================================================== public HashMap getOrders() { return orders; } public String getAddressLine1() { return addressLine1; } public String getAddressLine2() { return addressLine2; } public String getTown() { return town; } public String getPostcode() { return postcode; } public boolean getIsRegistered() { return isRegistered; } //Setters=================================================================== public void setOrders(HashMap<Integer,Order>ordersIn) { orders=ordersIn; } public void setAddressLine1(String addressLine1In) { addressLine1 = addressLine1In; } public void setAddressLine2(String addressLine2In) { addressLine2 = addressLine2In; } public void setTown(String townIn) { town = townIn; } public void setPostcode(String postcodeIn) { postcode = postcodeIn; } public void setIsRegistered(boolean isRegisteredIn) { isRegistered = isRegisteredIn; } //Constructors============================================================== public Customer() // this constructor takes in 0 arguements { super(); // calls to person class addressLine1=""; addressLine2=""; town=""; postcode=""; isRegistered=true; orders = new HashMap(); } public Customer(String userNameIn, String passwordIn, String firstNameIn, String lastNameIn, String addressLine1In, String addressLine2In, String postcodeIn, String townIn, Date dobIn) // constructor takes in 4 arguements { super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); // call to base class addressLine1 = addressLine1In; addressLine2 = addressLine2In; postcode = postcodeIn; town = townIn; isRegistered = true; orders = new HashMap(); } public Customer(String userNameIn,String passwordIn,String firstNameIn,String lastNameIn,Date dobIn) { super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); isRegistered =true; orders= new HashMap(); } //methods public void AddOrder(Order o) { DBManager db = new DBManager(); int orderId = db.AddOrder(o,this.getUserName()); o.setOrderId(orderId); orders.put(orderId,o); } public Order findLatestOrder() { Order currentOrder = new Order(); if(orders.isEmpty()) { AddOrder(currentOrder); } else { currentOrder = orders.entrySet().iterator().next().getValue(); for(Map.Entry<Integer, Order> orderEntry : orders.entrySet()) { Order order = orderEntry.getValue(); if(order.getOrderDate().after(currentOrder.getOrderDate())) { currentOrder = order; } } if(currentOrder.getStatus().equals("Complete")) { currentOrder = new Order(); AddOrder(currentOrder); } } return currentOrder; } public String displayGreeting() { String output = "<html>Hello " + getFirstName() + "<br>You are logged in as a Customer</html>"; return output; } }
UTF-8
Java
4,772
java
Customer.java
Java
[ { "context": "ap;\r\nimport java.util.Map;\r\n\r\n/**\r\n *\r\n * @author 30289355\r\n */\r\npublic class Customer extends User\r\n{\r\n ", "end": 313, "score": 0.990972638130188, "start": 305, "tag": "USERNAME", "value": "30289355" }, { "context": "String userNameIn, String passwordIn, String firstNameIn,\r\n String lastNameIn, St", "end": 2459, "score": 0.859719455242157, "start": 2450, "tag": "NAME", "value": "firstName" }, { "context": " String firstNameIn,\r\n String lastNameIn, String addressLine1In,\r\n ", "end": 2499, "score": 0.9487804174423218, "start": 2491, "tag": "NAME", "value": "lastName" }, { "context": " {\r\n\r\n super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); // call to base cl", "end": 2832, "score": 0.9559223651885986, "start": 2823, "tag": "NAME", "value": "firstName" }, { "context": " super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); // call to base class\r\n\r\n ", "end": 2843, "score": 0.9203755855560303, "start": 2835, "tag": "NAME", "value": "lastName" }, { "context": "obIn)\r\n {\r\n super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn);\r\n isRegistered =true;", "end": 3314, "score": 0.8238155245780945, "start": 3305, "tag": "NAME", "value": "firstName" } ]
null
[]
/* * 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 Models; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * * @author 30289355 */ public class Customer extends User { // instance variables======================================================= private String addressLine1; private String addressLine2; private String town; private String postcode; private boolean isRegistered; private HashMap<Integer,Order> orders; //Getters===================================================================== public HashMap getOrders() { return orders; } public String getAddressLine1() { return addressLine1; } public String getAddressLine2() { return addressLine2; } public String getTown() { return town; } public String getPostcode() { return postcode; } public boolean getIsRegistered() { return isRegistered; } //Setters=================================================================== public void setOrders(HashMap<Integer,Order>ordersIn) { orders=ordersIn; } public void setAddressLine1(String addressLine1In) { addressLine1 = addressLine1In; } public void setAddressLine2(String addressLine2In) { addressLine2 = addressLine2In; } public void setTown(String townIn) { town = townIn; } public void setPostcode(String postcodeIn) { postcode = postcodeIn; } public void setIsRegistered(boolean isRegisteredIn) { isRegistered = isRegisteredIn; } //Constructors============================================================== public Customer() // this constructor takes in 0 arguements { super(); // calls to person class addressLine1=""; addressLine2=""; town=""; postcode=""; isRegistered=true; orders = new HashMap(); } public Customer(String userNameIn, String passwordIn, String firstNameIn, String lastNameIn, String addressLine1In, String addressLine2In, String postcodeIn, String townIn, Date dobIn) // constructor takes in 4 arguements { super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); // call to base class addressLine1 = addressLine1In; addressLine2 = addressLine2In; postcode = postcodeIn; town = townIn; isRegistered = true; orders = new HashMap(); } public Customer(String userNameIn,String passwordIn,String firstNameIn,String lastNameIn,Date dobIn) { super(userNameIn,passwordIn,firstNameIn,lastNameIn,dobIn); isRegistered =true; orders= new HashMap(); } //methods public void AddOrder(Order o) { DBManager db = new DBManager(); int orderId = db.AddOrder(o,this.getUserName()); o.setOrderId(orderId); orders.put(orderId,o); } public Order findLatestOrder() { Order currentOrder = new Order(); if(orders.isEmpty()) { AddOrder(currentOrder); } else { currentOrder = orders.entrySet().iterator().next().getValue(); for(Map.Entry<Integer, Order> orderEntry : orders.entrySet()) { Order order = orderEntry.getValue(); if(order.getOrderDate().after(currentOrder.getOrderDate())) { currentOrder = order; } } if(currentOrder.getStatus().equals("Complete")) { currentOrder = new Order(); AddOrder(currentOrder); } } return currentOrder; } public String displayGreeting() { String output = "<html>Hello " + getFirstName() + "<br>You are logged in as a Customer</html>"; return output; } }
4,772
0.484912
0.478206
189
23.248676
25.346416
121
false
false
0
0
0
0
78
0.061609
0.428571
false
false
15
322d2b70e4efbddad3e2324090e859087b008a44
12,386,685,713,523
32799659126c6ff4ed691c5d620f431ef15ed041
/2018.10.02 - Arrays/Lab14i_new.java
ff15c0026f4303572e1007e6472c12374f4b3e88
[]
no_license
yduncoo/APCS-1
https://github.com/yduncoo/APCS-1
02ea89287d085748b052c1a71a5232b1c654b56e
add336e158e037a848a7a06d8270405090c03d9d
refs/heads/master
2022-01-07T12:03:23.444000
2019-06-07T14:46:54
2019-06-07T14:46:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; import java.util.Scanner; public class Lab14i_new { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Input a number, either in base 10 or roman numeral: "); String input = keyboard.nextLine(); keyboard.close(); try { //If input is number int num = Integer.parseInt(input); if (num > 3999) { //max number with support in Roman Numeral System System.out.println("no. pls smaller number"); System.exit(1); } String result = intToRM(num); System.out.println(input + " is " + result); } catch (NumberFormatException e) { //If input is not a number String rn = input.toUpperCase().replaceAll("[^IVXLCDM]", ""); //Remove all non-roman numerals int result = RMtoInt(rn); System.out.println(rn + " is " + result); } } //Roman numerals and values public static char[] RM = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' }; public static Integer[] value = { 1, 5, 10, 50, 100, 500, 1000 }; public static String intToRM(int num) { String result = "", nineFour = ""; int i = 1; while(num > 0) { if (value[value.length - i] <= num) { //Deal with the roman numerals IX, IV, etc. String numStr = num + ""; if ((num + "").contains("9")) { int indexOf9FromBack = numStr.length() - 1 - numStr.indexOf("9"); //Find the magnitude of the 9, i.e. 9x100 num -= (9 * Math.pow(10, indexOf9FromBack)); nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, indexOf9FromBack))]; nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, (indexOf9FromBack + 1)))]; } else if ((num + "").contains("4")) { int indexOf4FromBack = numStr.length() - 1 - numStr.indexOf("4"); //Find the magnitude of the 9, i.e. 9x100 num -= (4 * Math.pow(10, indexOf4FromBack)); nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, indexOf4FromBack))]; nineFour += RM[Arrays.asList(value).indexOf((int) (5 * Math.pow(10, indexOf4FromBack)))]; } else { result += RM[RM.length - i]; num -= value[value.length - i]; } } else i++; } return result + nineFour; } public static int RMtoInt(String roem) { char[] romanNumerals = roem.toCharArray(); String RMStr = new String(RM); int result = 0; for (int i = 0; i < romanNumerals.length; i++) { char char1 = romanNumerals[i]; if (RMStr.contains(char1 + "")) //if the roman numerals array contains a character of the user's input { if (i < romanNumerals.length - 1) { //Check if there is any instances of IX, IV, etc. char char2 = romanNumerals[i + 1]; if (value[RMStr.indexOf(char2)] > value[RMStr.indexOf(char1)]) { result += (value[RMStr.indexOf(char2)] - value[RMStr.indexOf(char1)]); romanNumerals[i] = ' '; romanNumerals[i + 1] = ' '; } else { int ind = RMStr.indexOf(char1); //Find index of the roman numeral result += value[ind]; //add the value of the roman numeral to the result romanNumerals[i] = ' '; //remove the roman numeral from the array of roman numerals } } else { int ind = RMStr.indexOf(char1); result += value[ind]; romanNumerals[i] = ' '; } } } return result; } } //5th SPOOKtober 2018 (05 10 2018)
UTF-8
Java
4,336
java
Lab14i_new.java
Java
[]
null
[]
import java.util.Arrays; import java.util.Scanner; public class Lab14i_new { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Input a number, either in base 10 or roman numeral: "); String input = keyboard.nextLine(); keyboard.close(); try { //If input is number int num = Integer.parseInt(input); if (num > 3999) { //max number with support in Roman Numeral System System.out.println("no. pls smaller number"); System.exit(1); } String result = intToRM(num); System.out.println(input + " is " + result); } catch (NumberFormatException e) { //If input is not a number String rn = input.toUpperCase().replaceAll("[^IVXLCDM]", ""); //Remove all non-roman numerals int result = RMtoInt(rn); System.out.println(rn + " is " + result); } } //Roman numerals and values public static char[] RM = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' }; public static Integer[] value = { 1, 5, 10, 50, 100, 500, 1000 }; public static String intToRM(int num) { String result = "", nineFour = ""; int i = 1; while(num > 0) { if (value[value.length - i] <= num) { //Deal with the roman numerals IX, IV, etc. String numStr = num + ""; if ((num + "").contains("9")) { int indexOf9FromBack = numStr.length() - 1 - numStr.indexOf("9"); //Find the magnitude of the 9, i.e. 9x100 num -= (9 * Math.pow(10, indexOf9FromBack)); nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, indexOf9FromBack))]; nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, (indexOf9FromBack + 1)))]; } else if ((num + "").contains("4")) { int indexOf4FromBack = numStr.length() - 1 - numStr.indexOf("4"); //Find the magnitude of the 9, i.e. 9x100 num -= (4 * Math.pow(10, indexOf4FromBack)); nineFour += RM[Arrays.asList(value).indexOf((int) Math.pow(10, indexOf4FromBack))]; nineFour += RM[Arrays.asList(value).indexOf((int) (5 * Math.pow(10, indexOf4FromBack)))]; } else { result += RM[RM.length - i]; num -= value[value.length - i]; } } else i++; } return result + nineFour; } public static int RMtoInt(String roem) { char[] romanNumerals = roem.toCharArray(); String RMStr = new String(RM); int result = 0; for (int i = 0; i < romanNumerals.length; i++) { char char1 = romanNumerals[i]; if (RMStr.contains(char1 + "")) //if the roman numerals array contains a character of the user's input { if (i < romanNumerals.length - 1) { //Check if there is any instances of IX, IV, etc. char char2 = romanNumerals[i + 1]; if (value[RMStr.indexOf(char2)] > value[RMStr.indexOf(char1)]) { result += (value[RMStr.indexOf(char2)] - value[RMStr.indexOf(char1)]); romanNumerals[i] = ' '; romanNumerals[i + 1] = ' '; } else { int ind = RMStr.indexOf(char1); //Find index of the roman numeral result += value[ind]; //add the value of the roman numeral to the result romanNumerals[i] = ' '; //remove the roman numeral from the array of roman numerals } } else { int ind = RMStr.indexOf(char1); result += value[ind]; romanNumerals[i] = ' '; } } } return result; } } //5th SPOOKtober 2018 (05 10 2018)
4,336
0.468173
0.446494
123
34.260162
32.562096
129
false
false
0
0
0
0
0
0
0.609756
false
false
15
c05c396811ab2761782c64f26e0edf0b1958adb0
6,614,249,640,644
7160c7c4f385742b35cee8aba7201673a50715c6
/chuoyue-web/src/main/java/com/fuyunwang/chuoyue/system/controller/TbStudentController.java
a16a80461163f8a29402a68938d2574477494678
[ "Apache-2.0" ]
permissive
fuyunwang/video_surveillance
https://github.com/fuyunwang/video_surveillance
37af12ea1ab404f730ec239af2b08085bbc3462b
5c8fbc6d9a9a27e3437a6f4158e0e6169cb2f87b
refs/heads/master
2023-06-19T00:57:52.354000
2020-11-10T02:08:00
2020-11-10T02:08:00
298,540,383
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fuyunwang.chuoyue.system.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fuyunwang.chuoyue.common.base.ResponseResult; import com.fuyunwang.chuoyue.common.utils.GlobalUtil; import com.fuyunwang.chuoyue.system.entity.TbAcl; import com.fuyunwang.chuoyue.system.entity.TbAgent; import com.fuyunwang.chuoyue.system.entity.TbRole; import com.fuyunwang.chuoyue.system.mapper.TbAclMapper; import com.fuyunwang.chuoyue.system.mapper.TbRoleMapper; import com.fuyunwang.chuoyue.system.service.ITbStudentService; import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpMethod; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.Collection; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author FuyunWang * @since 2020-07-21 */ @RestController @RequestMapping("/tb-student") public class TbStudentController { @Autowired @Qualifier(value = "tbStudentServiceImpl") private ITbStudentService iTbStudentService; @Autowired private TbRoleMapper tbRoleMapper; @PreAuthorize("hasAuthority('administrator')") @RequestMapping(value = "/index/ad",method = RequestMethod.POST) public ResponseResult indexAministrator(){ return ResponseResult.createBySuccess("只有超管才能看到"); } @PreAuthorize("hasAnyAuthority('administrator','senior')") @RequestMapping(value = "/index/se",method = RequestMethod.POST) public ResponseResult indexSenior(){ return ResponseResult.createBySuccess("高管和超管才能看到"); } @PreAuthorize("hasAnyAuthority('administrator','senior','junior')") @RequestMapping(value = "/index/ju",method = RequestMethod.POST) public ResponseResult indexJunior(){ return ResponseResult.createBySuccess("中管、高管、超管才能看到"); } @RequestMapping(value = "/index/lo",method = RequestMethod.POST) public ResponseResult indexLogin(@AuthenticationPrincipal UserDetails userDetails){ String username = userDetails.getUsername(); return ResponseResult.createBySuccess("登陆就能看到", GlobalUtil.data(username)); } @RequestMapping(value = "/index/anon",method = RequestMethod.POST) public ResponseResult indexAnon(){ return ResponseResult.createBySuccess("不登陆也能看到"); } @RequestMapping(value = "/excel/export/anon",method = RequestMethod.GET) public ModelAndView exportAllStudentsInfoExcel(){ return iTbStudentService.exportAllStudentsInfoExcel(); } }
UTF-8
Java
3,214
java
TbStudentController.java
Java
[ { "context": ".List;\n\n/**\n * <p>\n * 前端控制器\n * </p>\n *\n * @author FuyunWang\n * @since 2020-07-21\n */\n@RestController\n@Request", "end": 1440, "score": 0.9998624920845032, "start": 1431, "tag": "NAME", "value": "FuyunWang" } ]
null
[]
package com.fuyunwang.chuoyue.system.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fuyunwang.chuoyue.common.base.ResponseResult; import com.fuyunwang.chuoyue.common.utils.GlobalUtil; import com.fuyunwang.chuoyue.system.entity.TbAcl; import com.fuyunwang.chuoyue.system.entity.TbAgent; import com.fuyunwang.chuoyue.system.entity.TbRole; import com.fuyunwang.chuoyue.system.mapper.TbAclMapper; import com.fuyunwang.chuoyue.system.mapper.TbRoleMapper; import com.fuyunwang.chuoyue.system.service.ITbStudentService; import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpMethod; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.Collection; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author FuyunWang * @since 2020-07-21 */ @RestController @RequestMapping("/tb-student") public class TbStudentController { @Autowired @Qualifier(value = "tbStudentServiceImpl") private ITbStudentService iTbStudentService; @Autowired private TbRoleMapper tbRoleMapper; @PreAuthorize("hasAuthority('administrator')") @RequestMapping(value = "/index/ad",method = RequestMethod.POST) public ResponseResult indexAministrator(){ return ResponseResult.createBySuccess("只有超管才能看到"); } @PreAuthorize("hasAnyAuthority('administrator','senior')") @RequestMapping(value = "/index/se",method = RequestMethod.POST) public ResponseResult indexSenior(){ return ResponseResult.createBySuccess("高管和超管才能看到"); } @PreAuthorize("hasAnyAuthority('administrator','senior','junior')") @RequestMapping(value = "/index/ju",method = RequestMethod.POST) public ResponseResult indexJunior(){ return ResponseResult.createBySuccess("中管、高管、超管才能看到"); } @RequestMapping(value = "/index/lo",method = RequestMethod.POST) public ResponseResult indexLogin(@AuthenticationPrincipal UserDetails userDetails){ String username = userDetails.getUsername(); return ResponseResult.createBySuccess("登陆就能看到", GlobalUtil.data(username)); } @RequestMapping(value = "/index/anon",method = RequestMethod.POST) public ResponseResult indexAnon(){ return ResponseResult.createBySuccess("不登陆也能看到"); } @RequestMapping(value = "/excel/export/anon",method = RequestMethod.GET) public ModelAndView exportAllStudentsInfoExcel(){ return iTbStudentService.exportAllStudentsInfoExcel(); } }
3,214
0.778205
0.775321
84
36.142857
27.208693
87
false
false
0
0
0
0
0
0
0.52381
false
false
15
3a67bf7155578b0bfc4601dfdd371a99f808d8d1
11,020,886,113,352
b5545ba4f7cad02a8af16afcfe87a8248321bd47
/firtree/ranker/arxiv/print.java
b4dd4f6554481f83b9434881e25f11430175f6f2
[]
no_license
xiaojiew1/QrySpec
https://github.com/xiaojiew1/QrySpec
374daf842c550b53100dda8f0cfbde2496026e11
ab592b6081468a9eda28c723ea97da9836e0f99f
refs/heads/master
2020-08-31T04:57:54.711000
2020-07-13T06:06:02
2020-07-13T06:06:02
218,594,776
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
String dataNodePath = opts.dir + "/Node_" + leavesModel.get(i_leaf); System.out.println("------------Processing leaf "+ leavesModel.get(i_leaf) + "------------"); long start_load = System.currentTimeMillis(); timeStamp("Scan data"); AttrInfo ainfo_leaf = AttributesReader.read(dataNodePath + "/fir.fs.fs.attr"); // read the data, save labels and values of selected features BufferedReader br_dta = new BufferedReader(new FileReader(dataNodePath + "/fir.dta")); int col_num = ainfo_leaf.attributes.size(); //col refers to the columns in the matrix, not in the data file List<List<Double>> xMat_arraylist = new ArrayList<List<Double>>(); //dynamic memory for temp data storage - features ArrayList<Double> y_double_arraylist = new ArrayList<Double>(); //dynamic memory for temp data storage - labels for(String line = br_dta.readLine(); line != null; line = br_dta.readLine()){ String[] data = line.split("\t+"); y_double_arraylist.add(Double.parseDouble(data[ainfo_core.getClsCol()])); ArrayList<Double> current_selected_attr = new ArrayList<Double>(); for(int j = 0; j < col_num; j++){ current_selected_attr.add(Double.parseDouble(data[ainfo_leaf.attributes.get(j).getColumn()])); } xMat_arraylist.add(current_selected_attr); } br_dta.close(); long end_load = System.currentTimeMillis(); int row_num = y_double_arraylist.size(); // number of data points System.out.println("Number of data points: " + row_num); //copy the data into regular arrays, as required for regression model input double[] y_double = new double[row_num]; double[][] xMat = new double[row_num][col_num]; for(int i = 0; i < row_num; i++){ y_double[i] = y_double_arraylist.get(i); for(int j = 0; j < col_num; j++){ xMat[i][j] = xMat_arraylist.get(i).get(j); } } // Train OLS with polynomial terms timeStamp("Training OLS with transformed features"); double[][] xMat_trans = new double[xMat.length][xMat[0].length * opts.poly_degree]; for(int i = 0; i < xMat.length; i++){ for(int j = 0; j < xMat[0].length; j++){ for(int i_trans = 0; i_trans < opts.poly_degree; i_trans++){ xMat_trans[i][j * opts.poly_degree + i_trans] = Math.pow(xMat[i][j], i_trans + 1); } } } // Setting the last parameter to True to use SVD decomposition as part of the regression OLS ols_trans = new OLS(xMat_trans, y_double, true); double[] ols_trans_coef = ols_trans.coefficients(); double ols_trans_intercept = ols_trans.intercept(); // get the range of each selected feature for thresholding ArrayList<ArrayList<Double>> attr_range = new ArrayList<ArrayList<Double>>(); for(int j = 0; j < col_num; j++){ ArrayList<Double> current_attr_range = new ArrayList<Double>(); double current_attr_min = Double.POSITIVE_INFINITY; double current_attr_max = Double.NEGATIVE_INFINITY; for(int i = 0; i < row_num; i++){ if(xMat[i][j] < current_attr_min){ current_attr_min = xMat[i][j]; } if(xMat[i][j] > current_attr_max){ current_attr_max = xMat[i][j]; } } current_attr_range.add(current_attr_min); current_attr_range.add(current_attr_max); attr_range.add(current_attr_range); } timeStamp("Saving the model"); BufferedWriter modelTrans_out = new BufferedWriter(new FileWriter(dataNodePath + "/model_polydegree_" + opts.poly_degree + ".txt")); modelTrans_out.write("intercept\t" + ols_trans_intercept + "\n"); for (int i_attr = 0; i_attr < col_num; i_attr++) { modelTrans_out.write(ainfo_leaf.idToName(i_attr) + "\t"); for(int i_poly = 0; i_poly < opts.poly_degree; i_poly++){ modelTrans_out.write(ols_trans_coef[i_attr * opts.poly_degree + i_poly] + "\t" ); } modelTrans_out.write(attr_range.get(i_attr).get(0) + "\t" + attr_range.get(i_attr).get(1) + "\n"); } modelTrans_out.flush(); modelTrans_out.close(); long end_train = System.currentTimeMillis(); System.out.println("Finished training OLS on this node in " + (end_train - start_load) / 1000.0 + " (s)."); System.out.println("Without loading data, the model training step takes " + (end_train - end_load) / 1000.0 + " (s).");
UTF-8
Java
4,136
java
print.java
Java
[]
null
[]
String dataNodePath = opts.dir + "/Node_" + leavesModel.get(i_leaf); System.out.println("------------Processing leaf "+ leavesModel.get(i_leaf) + "------------"); long start_load = System.currentTimeMillis(); timeStamp("Scan data"); AttrInfo ainfo_leaf = AttributesReader.read(dataNodePath + "/fir.fs.fs.attr"); // read the data, save labels and values of selected features BufferedReader br_dta = new BufferedReader(new FileReader(dataNodePath + "/fir.dta")); int col_num = ainfo_leaf.attributes.size(); //col refers to the columns in the matrix, not in the data file List<List<Double>> xMat_arraylist = new ArrayList<List<Double>>(); //dynamic memory for temp data storage - features ArrayList<Double> y_double_arraylist = new ArrayList<Double>(); //dynamic memory for temp data storage - labels for(String line = br_dta.readLine(); line != null; line = br_dta.readLine()){ String[] data = line.split("\t+"); y_double_arraylist.add(Double.parseDouble(data[ainfo_core.getClsCol()])); ArrayList<Double> current_selected_attr = new ArrayList<Double>(); for(int j = 0; j < col_num; j++){ current_selected_attr.add(Double.parseDouble(data[ainfo_leaf.attributes.get(j).getColumn()])); } xMat_arraylist.add(current_selected_attr); } br_dta.close(); long end_load = System.currentTimeMillis(); int row_num = y_double_arraylist.size(); // number of data points System.out.println("Number of data points: " + row_num); //copy the data into regular arrays, as required for regression model input double[] y_double = new double[row_num]; double[][] xMat = new double[row_num][col_num]; for(int i = 0; i < row_num; i++){ y_double[i] = y_double_arraylist.get(i); for(int j = 0; j < col_num; j++){ xMat[i][j] = xMat_arraylist.get(i).get(j); } } // Train OLS with polynomial terms timeStamp("Training OLS with transformed features"); double[][] xMat_trans = new double[xMat.length][xMat[0].length * opts.poly_degree]; for(int i = 0; i < xMat.length; i++){ for(int j = 0; j < xMat[0].length; j++){ for(int i_trans = 0; i_trans < opts.poly_degree; i_trans++){ xMat_trans[i][j * opts.poly_degree + i_trans] = Math.pow(xMat[i][j], i_trans + 1); } } } // Setting the last parameter to True to use SVD decomposition as part of the regression OLS ols_trans = new OLS(xMat_trans, y_double, true); double[] ols_trans_coef = ols_trans.coefficients(); double ols_trans_intercept = ols_trans.intercept(); // get the range of each selected feature for thresholding ArrayList<ArrayList<Double>> attr_range = new ArrayList<ArrayList<Double>>(); for(int j = 0; j < col_num; j++){ ArrayList<Double> current_attr_range = new ArrayList<Double>(); double current_attr_min = Double.POSITIVE_INFINITY; double current_attr_max = Double.NEGATIVE_INFINITY; for(int i = 0; i < row_num; i++){ if(xMat[i][j] < current_attr_min){ current_attr_min = xMat[i][j]; } if(xMat[i][j] > current_attr_max){ current_attr_max = xMat[i][j]; } } current_attr_range.add(current_attr_min); current_attr_range.add(current_attr_max); attr_range.add(current_attr_range); } timeStamp("Saving the model"); BufferedWriter modelTrans_out = new BufferedWriter(new FileWriter(dataNodePath + "/model_polydegree_" + opts.poly_degree + ".txt")); modelTrans_out.write("intercept\t" + ols_trans_intercept + "\n"); for (int i_attr = 0; i_attr < col_num; i_attr++) { modelTrans_out.write(ainfo_leaf.idToName(i_attr) + "\t"); for(int i_poly = 0; i_poly < opts.poly_degree; i_poly++){ modelTrans_out.write(ols_trans_coef[i_attr * opts.poly_degree + i_poly] + "\t" ); } modelTrans_out.write(attr_range.get(i_attr).get(0) + "\t" + attr_range.get(i_attr).get(1) + "\n"); } modelTrans_out.flush(); modelTrans_out.close(); long end_train = System.currentTimeMillis(); System.out.println("Finished training OLS on this node in " + (end_train - start_load) / 1000.0 + " (s)."); System.out.println("Without loading data, the model training step takes " + (end_train - end_load) / 1000.0 + " (s).");
4,136
0.660783
0.654739
98
41.193878
34.962856
132
false
false
0
0
0
0
0
0
0.785714
false
false
15
fa8e848cc39cfd58929f2b27ee91d0982935a8d8
22,239,340,709,001
7d4df8592f8e5fedcd7373b04a55352ba7524d4e
/src/main/java/com/gameSys/monitor/response/QueryBoxOnlineResp.java
4fc215e6e16017ec8d11c84e7a27d959803f77de
[]
no_license
wengbinbin/redisMonitor
https://github.com/wengbinbin/redisMonitor
35f4b2afd4064339deeba69975b989d4f40eb110
fb0a338a4dd13faec6ca9341ed5517e25fdd1127
refs/heads/master
2021-06-04T18:42:55.892000
2016-08-31T10:44:10
2016-08-31T10:44:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gameSys.monitor.response; import com.gameSys.monitor.pojo.OnlineMachineInfo; public class QueryBoxOnlineResp extends RespResult{ /** * */ private static final long serialVersionUID = 3359194099261474100L; private OnlineMachineInfo onlineMachineInfo; public OnlineMachineInfo getOnlineMachineInfo() { return onlineMachineInfo; } public void setOnlineMachineInfo(OnlineMachineInfo onlineMachineInfo) { this.onlineMachineInfo = onlineMachineInfo; } }
UTF-8
Java
482
java
QueryBoxOnlineResp.java
Java
[]
null
[]
package com.gameSys.monitor.response; import com.gameSys.monitor.pojo.OnlineMachineInfo; public class QueryBoxOnlineResp extends RespResult{ /** * */ private static final long serialVersionUID = 3359194099261474100L; private OnlineMachineInfo onlineMachineInfo; public OnlineMachineInfo getOnlineMachineInfo() { return onlineMachineInfo; } public void setOnlineMachineInfo(OnlineMachineInfo onlineMachineInfo) { this.onlineMachineInfo = onlineMachineInfo; } }
482
0.807054
0.767635
20
23.1
25.305927
72
false
false
0
0
0
0
0
0
1
false
false
15
8860bda7e5c882ffc07c426bea3e6897c474d59f
18,150,531,824,284
0cfcfd78888a46ebf7d996f709b33de608df25b7
/08-Heap-And-Priority-Queue/03-Add-And-Sift-Up-in-Heap/src/main/java/Main.java
b290d9a1c6c4339360b7fcdd36e1461329990881
[]
no_license
diuuu-boom/Data-Structures
https://github.com/diuuu-boom/Data-Structures
d16d5b15b7f98bf430eb1d11cd4fc265af5bba87
340db1f89500c017867acede6dd8335b45726c0e
refs/heads/master
2022-03-03T23:07:15.063000
2019-09-27T06:39:46
2019-09-27T06:39:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright © 2018, TaoDing * <p> * All Rights Reserved. */ import java.util.Random; /** * 类功能描述 * * @author Leon * @version 2018/11/5 15:36 */ public class Main { public static void main(String[] args) { int times = 100000; MaxHeap<Integer> maxHeap = new MaxHeap<>(); for (int i = 0; i < times; i++) { maxHeap.add(new Random().nextInt(Integer.MAX_VALUE)); } System.out.println("add complete!!!"); } }
UTF-8
Java
490
java
Main.java
Java
[ { "context": "/**\n * Copyright © 2018, TaoDing\n * <p>\n * All Rights Reserved.\n */\n\nimport java.u", "end": 32, "score": 0.933814287185669, "start": 25, "tag": "NAME", "value": "TaoDing" }, { "context": "port java.util.Random;\n\n/**\n * 类功能描述\n *\n * @author Leon\n * @version 2018/11/5 15:36\n */\npublic class Main", "end": 126, "score": 0.9890820980072021, "start": 122, "tag": "NAME", "value": "Leon" } ]
null
[]
/** * Copyright © 2018, TaoDing * <p> * All Rights Reserved. */ import java.util.Random; /** * 类功能描述 * * @author Leon * @version 2018/11/5 15:36 */ public class Main { public static void main(String[] args) { int times = 100000; MaxHeap<Integer> maxHeap = new MaxHeap<>(); for (int i = 0; i < times; i++) { maxHeap.add(new Random().nextInt(Integer.MAX_VALUE)); } System.out.println("add complete!!!"); } }
490
0.551148
0.505219
26
17.423077
18.445705
65
false
false
0
0
0
0
0
0
0.307692
false
false
15
fa47cb430ea123bcf4c9b5efbbc25f9a8459ee2d
5,025,111,741,590
da181f89e0b26ffb3fc5f9670a3a5f8f1ccf0884
/BackGestionTextilLevel/src/ar/com/textillevel/gui/util/controles/calendario/PanelMes.java
e275e50f34870eb2651939f36eb23c298a049e84
[]
no_license
nacho270/GTL
https://github.com/nacho270/GTL
a1b14b5c95f14ee758e6b458de28eae3890c60e1
7909ed10fb14e24b1536e433546399afb9891467
refs/heads/master
2021-01-23T15:04:13.971000
2020-09-18T00:58:24
2020-09-18T00:58:24
34,962,369
2
1
null
false
2016-08-22T22:12:57
2015-05-02T20:31:49
2016-01-19T00:16:27
2016-08-22T22:12:57
35,547
1
0
8
Java
null
null
package ar.com.textillevel.gui.util.controles.calendario; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import ar.com.fwcommon.util.DateUtil; import ar.com.textillevel.gui.util.GenericUtils; import ar.com.textillevel.gui.util.controles.calendario.renderers.DefaultEventosRenderer; import ar.com.textillevel.gui.util.controles.calendario.renderers.EventosRenderer; public class PanelMes extends JPanel { private static final long serialVersionUID = 8208864787756561580L; public static Color WEEK_DAYS_FOREGROUND = (Color) UIManager.get("List.foreground"); public static Color SELECTED_DAY_FOREGROUND = (Color) UIManager.get("List.selectionForeground"); public static Color SELECTED_DAY_BACKGROUND = (Color) UIManager.get("List.selectionBackground"); public static Color DAYS_GRID_BACKGROUND = Color.WHITE; private GregorianCalendar calendar; private List<EventoCalendario> eventos; private PanelDiaMes[][] pDias; private FocusablePanel daysGrid; private PanelDiaMes panelDiaActual; private static final String[] DAYS = new String[] { "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb" }; private List<EventoCalendario> allEventos; private final Map<Integer, List<EventoCalendario>> mapaEventosDia = new LinkedHashMap<Integer, List<EventoCalendario>>(); public PanelMes(int mes, int anio, List<EventoCalendario> eventos) { setAllEventos(eventos); setUpComponentes(mes, anio, new DefaultEventosRenderer()); } public PanelMes(int mes, int anio, List<EventoCalendario> eventos, EventosRenderer<? extends JComponent> renderer) { setAllEventos(eventos); setUpComponentes(mes, anio,renderer); } private void setUpComponentes(int mes, int anio, EventosRenderer<? extends JComponent> renderer) { calendar = DateUtil.getGregorianCalendar(); calendar.set(GregorianCalendar.DAY_OF_MONTH, 1); calendar.set(GregorianCalendar.MONTH, mes); calendar.set(GregorianCalendar.YEAR, anio); pDias = new PanelDiaMes[7][7]; for (int i = 0; i < 7; i++) { pDias[0][i] = new PanelDiaMes(DAYS[i]); } int offset = calendar.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; int lastDay = calendar.getActualMaximum(Calendar.DATE); for (int i = 1; i < 7; i++) { for (int j = 0; j < 7; j++) { pDias[i][j] = new PanelDiaMes(null,null,renderer); pDias[i][j].addMouseListener(new AdaptadorEventosMouse()); } } for(int i = 0; i < lastDay; i++) { pDias[(i + offset) / 7 + 1][(i + offset) % 7].setNroDia(i + 1); pDias[(i + offset) / 7 + 1][(i + offset) % 7].setEventosDia(mapaEventosDia.get(i+1)); pDias[(i + offset) / 7 + 1][(i + offset) % 7].update(); } daysGrid = new FocusablePanel(new GridLayout(7, 7, 5, 5)); for (int i = 0; i < 7; i++){ for (int j = 0; j < 7; j++){ daysGrid.add(pDias[i][j]); } } Dimension dimensionPantalla = GenericUtils.getDimensionPantalla(); daysGrid.setPreferredSize(new Dimension((int)dimensionPantalla.getWidth()-100,(int)dimensionPantalla.getHeight()-100)); daysGrid.setBorder(BorderFactory.createLoweredBevelBorder()); JPanel daysPanel = new JPanel(); daysPanel.add(daysGrid); add(daysPanel, BorderLayout.CENTER); } public List<EventoCalendario> getEventos() { return eventos; } public void setEventos(List<EventoCalendario> eventos) { this.eventos = eventos; } private class PanelDiaMes extends JPanel { private static final long serialVersionUID = -4757121690725695895L; private List<EventoCalendario> eventosDia; private JLabel lblDia; private JLabel lblDescripcion; private Integer nroDia; private EventosRenderer<? extends JComponent> renderer; public PanelDiaMes(List<EventoCalendario> eventosDia, Integer nroDia, EventosRenderer<? extends JComponent> renderer) { setEventosDia(eventosDia); setNroDia(nroDia); setRenderer(renderer); construirParaEventos(nroDia,eventosDia); } private void construirParaEventos(Integer nroDia, List<EventoCalendario> eventosDia2) { lblDia = crearLabelDiaEvento(nroDia); setBorder(BorderFactory.createLineBorder(SELECTED_DAY_BACKGROUND)); setLayout(new GridBagLayout()); add(lblDia,GenericUtils.createGridBagConstraints(0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 1, 0, 0)); if(getNroDia()!=null){ add(getRenderer().getComponent(eventosDia2),GenericUtils.createGridBagConstraints(0, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 1, 1, 1, 0.3)); } } private JLabel crearLabelDiaEvento(Integer dia) { JLabel lblDia2 = new JLabel( (dia==null?"":String.valueOf(dia))); lblDia2.setOpaque(true); Font font = lblDia2.getFont(); lblDia2.setFont(new Font(font.getName(), Font.BOLD, font.getSize() + 5)); lblDia2.setHorizontalAlignment(JLabel.CENTER); lblDia2.setVerticalAlignment(JLabel.CENTER); return lblDia2; } /* ******************************************************************************************************* */ public PanelDiaMes(String dia) { construirParaTituloDia(dia); } private void construirParaTituloDia(String dia) { lblDia = crearLabelDia(dia); setLayout(new GridBagLayout()); add(lblDia,GenericUtils.createGridBagConstraints(0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 1, 0, 0)); setBorder(BorderFactory.createLineBorder(SELECTED_DAY_BACKGROUND)); } private JLabel crearLabelDia(String dia) { JLabel lblDia2 = new JLabel(dia); lblDia2.setOpaque(true); lblDia2.setForeground(SELECTED_DAY_BACKGROUND); Font font = lblDia2.getFont(); lblDia2.setFont(new Font(font.getName(), Font.BOLD, font.getSize()+10)); lblDia2.setHorizontalAlignment(JLabel.CENTER); lblDia2.setVerticalAlignment(JLabel.CENTER); return lblDia2; } /* ******************************************************************************************************* */ public void update() { remove(lblDia); if(lblDescripcion!=null){ remove(lblDescripcion); } construirParaEventos(getNroDia(),getEventosDia()); } public List<EventoCalendario> getEventosDia() { return eventosDia; } public void setEventosDia(List<EventoCalendario> eventosDia) { this.eventosDia = eventosDia; } public Integer getNroDia() { return nroDia; } public void setNroDia(Integer nroDia) { this.nroDia = nroDia; } public void mouseClicked() { if(panelDiaActual != null){ panelDiaActual.setBackground(null); panelDiaActual.setOpaque(false); panelDiaActual.repaint(); panelDiaActual.lblDia.setForeground(Color.BLACK); panelDiaActual.lblDia.setBackground(null); } panelDiaActual = this; setOpaque(true); lblDia.setForeground(SELECTED_DAY_FOREGROUND); lblDia.setBackground(SELECTED_DAY_BACKGROUND); repaint(); } public EventosRenderer<? extends JComponent> getRenderer() { return renderer; } public void setRenderer(EventosRenderer<? extends JComponent> renderer) { this.renderer = renderer; } } private static class FocusablePanel extends JPanel { private static final long serialVersionUID = 1843135464196644820L; public FocusablePanel(LayoutManager layout) { super(layout); } } private class AdaptadorEventosMouse extends MouseAdapter{ @Override public void mouseClicked(MouseEvent e) { PanelDiaMes p = (PanelDiaMes)e.getSource(); p.mouseClicked(); } } public List<EventoCalendario> getAllEventos() { return allEventos; } public void setAllEventos(List<EventoCalendario> allEventos) { this.allEventos = allEventos; if(mapaEventosDia.keySet().isEmpty()){ if(allEventos!=null){ for(EventoCalendario e : allEventos){ Integer dia = DateUtil.getDia(e.getFecha()); if(mapaEventosDia.get(dia) == null){ mapaEventosDia.put(dia, new ArrayList<EventoCalendario>()); } mapaEventosDia.get(dia).add(e); } } } } }
WINDOWS-1252
Java
8,767
java
PanelMes.java
Java
[ { "context": "vate static final String[] DAYS = new String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n", "end": 1703, "score": 0.9978647232055664, "start": 1700, "tag": "NAME", "value": "Dom" }, { "context": "atic final String[] DAYS = new String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivat", "end": 1710, "score": 0.7554818391799927, "start": 1707, "tag": "NAME", "value": "Lun" }, { "context": "nal String[] DAYS = new String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivate List<", "end": 1717, "score": 0.9885965585708618, "start": 1714, "tag": "NAME", "value": "Mar" }, { "context": "ing[] DAYS = new String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivate List<EventoC", "end": 1724, "score": 0.9994368553161621, "start": 1721, "tag": "NAME", "value": "Mié" }, { "context": "AYS = new String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivate List<EventoCalendar", "end": 1731, "score": 0.9858329892158508, "start": 1728, "tag": "NAME", "value": "Jue" }, { "context": "ew String[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivate List<EventoCalendario> all", "end": 1738, "score": 0.9857248663902283, "start": 1735, "tag": "NAME", "value": "Vie" }, { "context": "ng[] { \"Dom\", \"Lun\", \"Mar\", \"Mié\", \"Jue\", \"Vie\", \"Sáb\" };\r\n\r\n\tprivate List<EventoCalendario> allEventos", "end": 1745, "score": 0.9419026970863342, "start": 1742, "tag": "NAME", "value": "Sáb" } ]
null
[]
package ar.com.textillevel.gui.util.controles.calendario; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import ar.com.fwcommon.util.DateUtil; import ar.com.textillevel.gui.util.GenericUtils; import ar.com.textillevel.gui.util.controles.calendario.renderers.DefaultEventosRenderer; import ar.com.textillevel.gui.util.controles.calendario.renderers.EventosRenderer; public class PanelMes extends JPanel { private static final long serialVersionUID = 8208864787756561580L; public static Color WEEK_DAYS_FOREGROUND = (Color) UIManager.get("List.foreground"); public static Color SELECTED_DAY_FOREGROUND = (Color) UIManager.get("List.selectionForeground"); public static Color SELECTED_DAY_BACKGROUND = (Color) UIManager.get("List.selectionBackground"); public static Color DAYS_GRID_BACKGROUND = Color.WHITE; private GregorianCalendar calendar; private List<EventoCalendario> eventos; private PanelDiaMes[][] pDias; private FocusablePanel daysGrid; private PanelDiaMes panelDiaActual; private static final String[] DAYS = new String[] { "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb" }; private List<EventoCalendario> allEventos; private final Map<Integer, List<EventoCalendario>> mapaEventosDia = new LinkedHashMap<Integer, List<EventoCalendario>>(); public PanelMes(int mes, int anio, List<EventoCalendario> eventos) { setAllEventos(eventos); setUpComponentes(mes, anio, new DefaultEventosRenderer()); } public PanelMes(int mes, int anio, List<EventoCalendario> eventos, EventosRenderer<? extends JComponent> renderer) { setAllEventos(eventos); setUpComponentes(mes, anio,renderer); } private void setUpComponentes(int mes, int anio, EventosRenderer<? extends JComponent> renderer) { calendar = DateUtil.getGregorianCalendar(); calendar.set(GregorianCalendar.DAY_OF_MONTH, 1); calendar.set(GregorianCalendar.MONTH, mes); calendar.set(GregorianCalendar.YEAR, anio); pDias = new PanelDiaMes[7][7]; for (int i = 0; i < 7; i++) { pDias[0][i] = new PanelDiaMes(DAYS[i]); } int offset = calendar.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; int lastDay = calendar.getActualMaximum(Calendar.DATE); for (int i = 1; i < 7; i++) { for (int j = 0; j < 7; j++) { pDias[i][j] = new PanelDiaMes(null,null,renderer); pDias[i][j].addMouseListener(new AdaptadorEventosMouse()); } } for(int i = 0; i < lastDay; i++) { pDias[(i + offset) / 7 + 1][(i + offset) % 7].setNroDia(i + 1); pDias[(i + offset) / 7 + 1][(i + offset) % 7].setEventosDia(mapaEventosDia.get(i+1)); pDias[(i + offset) / 7 + 1][(i + offset) % 7].update(); } daysGrid = new FocusablePanel(new GridLayout(7, 7, 5, 5)); for (int i = 0; i < 7; i++){ for (int j = 0; j < 7; j++){ daysGrid.add(pDias[i][j]); } } Dimension dimensionPantalla = GenericUtils.getDimensionPantalla(); daysGrid.setPreferredSize(new Dimension((int)dimensionPantalla.getWidth()-100,(int)dimensionPantalla.getHeight()-100)); daysGrid.setBorder(BorderFactory.createLoweredBevelBorder()); JPanel daysPanel = new JPanel(); daysPanel.add(daysGrid); add(daysPanel, BorderLayout.CENTER); } public List<EventoCalendario> getEventos() { return eventos; } public void setEventos(List<EventoCalendario> eventos) { this.eventos = eventos; } private class PanelDiaMes extends JPanel { private static final long serialVersionUID = -4757121690725695895L; private List<EventoCalendario> eventosDia; private JLabel lblDia; private JLabel lblDescripcion; private Integer nroDia; private EventosRenderer<? extends JComponent> renderer; public PanelDiaMes(List<EventoCalendario> eventosDia, Integer nroDia, EventosRenderer<? extends JComponent> renderer) { setEventosDia(eventosDia); setNroDia(nroDia); setRenderer(renderer); construirParaEventos(nroDia,eventosDia); } private void construirParaEventos(Integer nroDia, List<EventoCalendario> eventosDia2) { lblDia = crearLabelDiaEvento(nroDia); setBorder(BorderFactory.createLineBorder(SELECTED_DAY_BACKGROUND)); setLayout(new GridBagLayout()); add(lblDia,GenericUtils.createGridBagConstraints(0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 1, 0, 0)); if(getNroDia()!=null){ add(getRenderer().getComponent(eventosDia2),GenericUtils.createGridBagConstraints(0, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 1, 1, 1, 0.3)); } } private JLabel crearLabelDiaEvento(Integer dia) { JLabel lblDia2 = new JLabel( (dia==null?"":String.valueOf(dia))); lblDia2.setOpaque(true); Font font = lblDia2.getFont(); lblDia2.setFont(new Font(font.getName(), Font.BOLD, font.getSize() + 5)); lblDia2.setHorizontalAlignment(JLabel.CENTER); lblDia2.setVerticalAlignment(JLabel.CENTER); return lblDia2; } /* ******************************************************************************************************* */ public PanelDiaMes(String dia) { construirParaTituloDia(dia); } private void construirParaTituloDia(String dia) { lblDia = crearLabelDia(dia); setLayout(new GridBagLayout()); add(lblDia,GenericUtils.createGridBagConstraints(0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 1, 0, 0)); setBorder(BorderFactory.createLineBorder(SELECTED_DAY_BACKGROUND)); } private JLabel crearLabelDia(String dia) { JLabel lblDia2 = new JLabel(dia); lblDia2.setOpaque(true); lblDia2.setForeground(SELECTED_DAY_BACKGROUND); Font font = lblDia2.getFont(); lblDia2.setFont(new Font(font.getName(), Font.BOLD, font.getSize()+10)); lblDia2.setHorizontalAlignment(JLabel.CENTER); lblDia2.setVerticalAlignment(JLabel.CENTER); return lblDia2; } /* ******************************************************************************************************* */ public void update() { remove(lblDia); if(lblDescripcion!=null){ remove(lblDescripcion); } construirParaEventos(getNroDia(),getEventosDia()); } public List<EventoCalendario> getEventosDia() { return eventosDia; } public void setEventosDia(List<EventoCalendario> eventosDia) { this.eventosDia = eventosDia; } public Integer getNroDia() { return nroDia; } public void setNroDia(Integer nroDia) { this.nroDia = nroDia; } public void mouseClicked() { if(panelDiaActual != null){ panelDiaActual.setBackground(null); panelDiaActual.setOpaque(false); panelDiaActual.repaint(); panelDiaActual.lblDia.setForeground(Color.BLACK); panelDiaActual.lblDia.setBackground(null); } panelDiaActual = this; setOpaque(true); lblDia.setForeground(SELECTED_DAY_FOREGROUND); lblDia.setBackground(SELECTED_DAY_BACKGROUND); repaint(); } public EventosRenderer<? extends JComponent> getRenderer() { return renderer; } public void setRenderer(EventosRenderer<? extends JComponent> renderer) { this.renderer = renderer; } } private static class FocusablePanel extends JPanel { private static final long serialVersionUID = 1843135464196644820L; public FocusablePanel(LayoutManager layout) { super(layout); } } private class AdaptadorEventosMouse extends MouseAdapter{ @Override public void mouseClicked(MouseEvent e) { PanelDiaMes p = (PanelDiaMes)e.getSource(); p.mouseClicked(); } } public List<EventoCalendario> getAllEventos() { return allEventos; } public void setAllEventos(List<EventoCalendario> allEventos) { this.allEventos = allEventos; if(mapaEventosDia.keySet().isEmpty()){ if(allEventos!=null){ for(EventoCalendario e : allEventos){ Integer dia = DateUtil.getDia(e.getFecha()); if(mapaEventosDia.get(dia) == null){ mapaEventosDia.put(dia, new ArrayList<EventoCalendario>()); } mapaEventosDia.get(dia).add(e); } } } } }
8,767
0.6915
0.675071
264
31.200758
31.162231
183
false
false
0
0
0
0
0
0
2.590909
false
false
15
8d4bbc2e1be2e7641d644c9c658de182c6db8b56
14,078,902,822,154
b9ac9e785180a60e5668b90a6ce3c08ad90e3e0e
/src/org/hackerrank/algorithms/MinMaxSum.java
74b3c56eb29a900045846100b70154a71ba9d823
[]
no_license
rkaranam/smart-interviews
https://github.com/rkaranam/smart-interviews
b2455d20879f0c2cc80cfe3eac995dfbad0144be
b0c6c83570081b427c263dac55a97ed3c9f99d93
refs/heads/master
2020-05-30T09:49:51.414000
2019-08-19T06:04:19
2019-08-19T06:04:19
189,655,418
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.hackerrank.algorithms; import java.util.Arrays; public class MinMaxSum { public static void main(String[] args) { int[] arr = {0, 54, -12, 23, 4}; minMaxSum(arr); } private static void minMaxSum(int[] arr) { Arrays.sort(arr); // int minSum = 0, maxSum = 0; // Changed int to long as variable // as variable overflows for large values of arr elements long minSum = 0, maxSum = 0; for(int i=0; i<4; i++) { minSum += arr[i]; } for(int j=arr.length-1; j>(arr.length-1-4); j--) { maxSum += arr[j]; } System.out.println(minSum + " " + maxSum); } }
UTF-8
Java
595
java
MinMaxSum.java
Java
[]
null
[]
package org.hackerrank.algorithms; import java.util.Arrays; public class MinMaxSum { public static void main(String[] args) { int[] arr = {0, 54, -12, 23, 4}; minMaxSum(arr); } private static void minMaxSum(int[] arr) { Arrays.sort(arr); // int minSum = 0, maxSum = 0; // Changed int to long as variable // as variable overflows for large values of arr elements long minSum = 0, maxSum = 0; for(int i=0; i<4; i++) { minSum += arr[i]; } for(int j=arr.length-1; j>(arr.length-1-4); j--) { maxSum += arr[j]; } System.out.println(minSum + " " + maxSum); } }
595
0.616807
0.588235
27
21.037037
17.914368
59
false
false
0
0
0
0
0
0
2
false
false
15
19b07224213ae17197edd4ec3715f0f484af3329
35,313,221,141,679
4aed66ad4fb140f5823e748cae8fd71ac402cf67
/src/main/java/com/xiaoshabao/webframework/ui/dto/BillDto.java
b66d74adef07467472c64cfbabe3f50d3ebd9d9f
[]
no_license
manxx5521/shabao-test
https://github.com/manxx5521/shabao-test
f4236cd0da3f3a5944a28d08f58d090be64329ca
3cd8b95ed401feb20d759f31618b27bb4669ad7e
refs/heads/master
2020-04-12T03:57:41.256000
2019-01-15T06:37:46
2019-01-15T06:37:46
60,821,316
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiaoshabao.webframework.ui.dto; import com.xiaoshabao.webframework.ui.entity.BillEngineEntity; import com.xiaoshabao.webframework.ui.entity.BillEntity; public class BillDto extends BillEntity{ BillEngineEntity billEngineEntity; public BillEngineEntity getBillEngineEntity() { return billEngineEntity; } public void setBillEngineEntity(BillEngineEntity billEngineEntity) { this.billEngineEntity = billEngineEntity; } }
UTF-8
Java
464
java
BillDto.java
Java
[]
null
[]
package com.xiaoshabao.webframework.ui.dto; import com.xiaoshabao.webframework.ui.entity.BillEngineEntity; import com.xiaoshabao.webframework.ui.entity.BillEntity; public class BillDto extends BillEntity{ BillEngineEntity billEngineEntity; public BillEngineEntity getBillEngineEntity() { return billEngineEntity; } public void setBillEngineEntity(BillEngineEntity billEngineEntity) { this.billEngineEntity = billEngineEntity; } }
464
0.793103
0.793103
18
23.777779
24.807158
69
false
false
0
0
0
0
0
0
0.888889
false
false
15
303d2aa6c205016b56b5c5f916b80af9dd7a02ac
25,280,177,570,957
7400fb1649c4154741461d849abda1bb8dc45c8d
/cu-design-patterns/src/main/java/com/cu/dp/creational/abstractfactory/Circle.java
b61cba188306b78b35a2aa2797077ebdb8fbe8f7
[]
no_license
vriyaz/cu-repo
https://github.com/vriyaz/cu-repo
8bd7010c67a4935a768e2c54ed1ad3a5bbb71863
b799f3aeba8d3fd1941401ea1d52275c66f3689f
refs/heads/master
2021-01-18T09:26:03.409000
2015-04-05T01:15:47
2015-04-05T01:15:47
23,696,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cu.dp.creational.abstractfactory; import com.cu.utils.Logger; public class Circle implements Shape { public void draw() { Logger.log("Inside Circle::draw()"); } }
UTF-8
Java
182
java
Circle.java
Java
[]
null
[]
package com.cu.dp.creational.abstractfactory; import com.cu.utils.Logger; public class Circle implements Shape { public void draw() { Logger.log("Inside Circle::draw()"); } }
182
0.725275
0.725275
10
17.200001
17.690676
45
false
false
0
0
0
0
0
0
0.7
false
false
15
66c2cd4fc77f096a5ec974a3778c4520ec7efd9d
37,443,524,895,314
767eb03deb1edaf43802317da43b1145542fce51
/java/testing/junit/src/test/java/simplyianm/MathUtilsTest.java
82e5f18ecb5c0e2860f3c5b63a8aff613436c77c
[ "Apache-2.0" ]
permissive
abilashgt/study_java
https://github.com/abilashgt/study_java
ce03d237befb557226dc022dab3c003488ae4aee
c5a1ea78bcf3a23fd320cf5a669d85a416fa8073
refs/heads/master
2022-12-05T22:18:30.547000
2020-05-21T00:16:53
2020-05-21T00:16:53
79,113,088
0
0
Apache-2.0
false
2022-11-24T05:00:41
2017-01-16T11:45:12
2020-05-21T00:17:05
2022-11-24T05:00:38
92
0
0
8
Java
false
false
package simplyianm; import org.junit.Test; import simplyianm.MathUtils; import static org.junit.Assert.*; public class MathUtilsTest { @Test public void testMultiply(){ double a = 5; double b = -4.0; double expected = - 20.0; double result = MathUtils.multiply(a, b); assertEquals(expected, result, 0.00001); } }
UTF-8
Java
370
java
MathUtilsTest.java
Java
[]
null
[]
package simplyianm; import org.junit.Test; import simplyianm.MathUtils; import static org.junit.Assert.*; public class MathUtilsTest { @Test public void testMultiply(){ double a = 5; double b = -4.0; double expected = - 20.0; double result = MathUtils.multiply(a, b); assertEquals(expected, result, 0.00001); } }
370
0.62973
0.597297
19
18.473684
16.053753
49
false
false
0
0
0
0
0
0
0.631579
false
false
15
0af3cfac155311c32bd955f67c86b0b6ce117b46
38,448,547,236,293
72adee827046f465376a3443b29e14a5cf58c196
/app/src/main/java/com/example/workoutapp/WorkoutActivity.java
4c8034f38d766150c4fe8f87260a29ff1abd4c08
[]
no_license
Pratheekshap29/FITme
https://github.com/Pratheekshap29/FITme
439f46d09a047f4bad2bf5934f2d7bad4336235f
9a944414da7919deff9d2742cb86891ccbdca46b
refs/heads/main
2023-08-21T23:38:02.597000
2021-10-04T12:41:24
2021-10-04T12:41:24
376,756,795
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.workoutapp; import android.content.Intent; import android.os.Bundle; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.CountDownTimer; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; public class WorkoutActivity extends AppCompatActivity { private ArrayList<String> wNameArr=new ArrayList<String>(); private ArrayList<String> wTimeArr=new ArrayList<String>(); TextView routineName,delay; RecyclerView recview; myworkoutadapter adapter; FloatingActionButton faddw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_workout); routineName=(TextView)findViewById(R.id.RoutineNameTitle); delay=(TextView)findViewById(R.id.DelayTitle); Intent i = getIntent(); String routine_name = i.getStringExtra("routine_name"); String routine_delay = i.getStringExtra("routine_delay"); String key= i.getStringExtra("key"); routineName.setText(routine_name); delay.setText(routine_delay); recview=(RecyclerView)findViewById(R.id.recview2); recview.setLayoutManager(new LinearLayoutManager(this)); // Log.w(String.valueOf(0), key); FirebaseRecyclerOptions<workoutmodel> options = new FirebaseRecyclerOptions.Builder<workoutmodel>() .setQuery(FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child("routines").child(key).child("workouts"), workoutmodel.class).build(); FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child("routines").child(key).child("workouts").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot snapshot : dataSnapshot.getChildren()) { workoutmodel model = snapshot.getValue(workoutmodel.class); wNameArr.add(model.getName()); wTimeArr.add(model.getTime()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); adapter=new myworkoutadapter(options,key,routine_name,routine_delay,wNameArr,wTimeArr); recview.setAdapter(adapter); faddw=(FloatingActionButton)findViewById(R.id.addBtn2); faddw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(getApplicationContext(),addworkout.class); i.putExtra("key",key); startActivity(i); } }); // start.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent i=new Intent(WorkoutActivity.this,WorkoutTimerActivity.class); // i.putExtra("key",key); // i.putExtra("routine_name",routine_name); // i.putExtra("delay_delay",routine_delay); // startActivity(i); // } // }); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onStop() { super.onStop(); adapter.stopListening(); } }
UTF-8
Java
4,372
java
WorkoutActivity.java
Java
[]
null
[]
package com.example.workoutapp; import android.content.Intent; import android.os.Bundle; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.CountDownTimer; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; public class WorkoutActivity extends AppCompatActivity { private ArrayList<String> wNameArr=new ArrayList<String>(); private ArrayList<String> wTimeArr=new ArrayList<String>(); TextView routineName,delay; RecyclerView recview; myworkoutadapter adapter; FloatingActionButton faddw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_workout); routineName=(TextView)findViewById(R.id.RoutineNameTitle); delay=(TextView)findViewById(R.id.DelayTitle); Intent i = getIntent(); String routine_name = i.getStringExtra("routine_name"); String routine_delay = i.getStringExtra("routine_delay"); String key= i.getStringExtra("key"); routineName.setText(routine_name); delay.setText(routine_delay); recview=(RecyclerView)findViewById(R.id.recview2); recview.setLayoutManager(new LinearLayoutManager(this)); // Log.w(String.valueOf(0), key); FirebaseRecyclerOptions<workoutmodel> options = new FirebaseRecyclerOptions.Builder<workoutmodel>() .setQuery(FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child("routines").child(key).child("workouts"), workoutmodel.class).build(); FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child("routines").child(key).child("workouts").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot snapshot : dataSnapshot.getChildren()) { workoutmodel model = snapshot.getValue(workoutmodel.class); wNameArr.add(model.getName()); wTimeArr.add(model.getTime()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); adapter=new myworkoutadapter(options,key,routine_name,routine_delay,wNameArr,wTimeArr); recview.setAdapter(adapter); faddw=(FloatingActionButton)findViewById(R.id.addBtn2); faddw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(getApplicationContext(),addworkout.class); i.putExtra("key",key); startActivity(i); } }); // start.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent i=new Intent(WorkoutActivity.this,WorkoutTimerActivity.class); // i.putExtra("key",key); // i.putExtra("routine_name",routine_name); // i.putExtra("delay_delay",routine_delay); // startActivity(i); // } // }); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onStop() { super.onStop(); adapter.stopListening(); } }
4,372
0.666514
0.665828
125
33.984001
30.027451
154
false
false
0
0
0
0
0
0
0.624
false
false
15
8040a3b9dec0c3472052d5931b0febb5aee15ec7
37,649,683,319,650
8fe0eef60273173ed11bbd371179ef1f98f090e9
/MMetric Spark/src/main/java/spark/M_Metric2/MapCountSP.java
ab8db54570861f60d3fd3a8e668a7ebc7316a50e
[]
no_license
SaeedSarabchi/Parallel-Community-Mining
https://github.com/SaeedSarabchi/Parallel-Community-Mining
567b1b44c64a0cde642b6a130da66270b119736e
6bb99d16a8167efcc9a63aaae25cd1de10dbb15e
refs/heads/master
2023-02-11T15:37:23.542000
2021-01-07T13:57:02
2021-01-07T13:57:02
327,627,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spark.M_Metric2; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MapCountSP extends Mapper<Object, Text, Text, IntWritable> { private Text myKey = new Text(); private IntWritable one = new IntWritable(1); @Override public void map( Object key, Text value, Context context ) throws IOException, InterruptedException { String line = value.toString(); String[] strings = line.split( "\t" ); if ( strings.length == 2 ) { myKey.set( strings[0] ); context.write( myKey, one ); myKey.set( strings[1] ); context.write( myKey, one ); } } }
UTF-8
Java
695
java
MapCountSP.java
Java
[]
null
[]
package spark.M_Metric2; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MapCountSP extends Mapper<Object, Text, Text, IntWritable> { private Text myKey = new Text(); private IntWritable one = new IntWritable(1); @Override public void map( Object key, Text value, Context context ) throws IOException, InterruptedException { String line = value.toString(); String[] strings = line.split( "\t" ); if ( strings.length == 2 ) { myKey.set( strings[0] ); context.write( myKey, one ); myKey.set( strings[1] ); context.write( myKey, one ); } } }
695
0.693525
0.686331
30
22.200001
19.910467
72
false
false
0
0
0
0
0
0
1.933333
false
false
15
772efd354270a4c6549e0c04b5e921f6f3a8b09d
36,515,811,980,694
97c95aa94c4a1bf7cd79d4d05f804a26145161c3
/src/main/java/com/saramin/lab/search/module/RestSearchModule.java
b39287733a1f97c1d31be132b3320071cbef39b9
[]
no_license
antkdi/search
https://github.com/antkdi/search
9788e941152e880b9d7f7ae3fff006d1f3a81aef
8ccfce6732c35caf5ec38a6eb2fe1184711d7475
refs/heads/master
2021-01-22T21:48:58.194000
2017-03-27T10:50:13
2017-03-27T10:50:13
85,478,947
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.saramin.lab.search.module; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Repository; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.saramin.lab.search.common.CommonUtils; import com.saramin.lab.search.common.GlobalConstant; import com.saramin.lab.search.query.SearchQueryBuilder; import com.saramin.lab.search.vo.RestResultVO; import lombok.extern.slf4j.Slf4j; @Slf4j @Repository public class RestSearchModule { @Autowired Environment env; @Autowired RestTemplate restTemplate; @Autowired CommonUtils common; /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(String selectStr, String fromStr, String whereStr) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://182.162.109.118:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", selectStr); paramMap.add("from", fromStr); paramMap.add("where", whereStr); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = selectStr.split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); map.put(fields[j], String.valueOf(record.get(fields[j]))); } list.add(map); map = null; } restVO.setResult(list); } // 파싱 끝 return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(String selectStr, String fromStr, String whereStr,String limit) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://182.162.109.118:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", selectStr); paramMap.add("from", fromStr); paramMap.add("where", whereStr); paramMap.add("limit", limit); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = selectStr.split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); if(fields[j].equals("count(*)")){ map.put("cnt", String.valueOf(record.get(fields[j]))); }else if(fields[j].equals("area_bcode")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("area_bcode_nm",GlobalConstant.AREA_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); map.put("area_mcode_nm",GlobalConstant.AREA_MCODE_MAP.get(String.valueOf(record.get(fields[j])).substring(0,3)+"000")); }else if(fields[j].equals("jikjong_cd")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("jikjong_nm", GlobalConstant.JIK_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); }else{ map.put(fields[j], String.valueOf(record.get(fields[j]))); } } list.add(map); map = null; } restVO.setResult(list); } return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(SearchQueryBuilder query) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://182.162.109.118:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", query.getSelectCloumn()); paramMap.add("from", query.getFrom()); paramMap.add("where", common.null2Str(query.getWhereClause().toString(), "") +" " + common.null2Str(query.getSortingClause().toString(),"") ); paramMap.add("limit", String.valueOf(query.getPageSize())); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = query.getSelectCloumn().split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); if(fields[j].equals("count(*)")){ map.put("cnt", String.valueOf(record.get(fields[j]))); }else if(fields[j].equals("area_bcode")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("area_bcode_nm",GlobalConstant.AREA_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); map.put("area_mcode_nm",GlobalConstant.AREA_MCODE_MAP.get(String.valueOf(record.get(fields[j])).substring(0,3)+"000")); }else if(fields[j].equals("jikjong_cd")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("jikjong_nm", GlobalConstant.JIK_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); }else{ map.put(fields[j], String.valueOf(record.get(fields[j]))); } } list.add(map); map = null; } restVO.setResult(list); } return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } public BufferedReader getBufferedReader(String apiUrl) { try { URL url = new URL(apiUrl); return new BufferedReader(new InputStreamReader(url.openStream(),GlobalConstant.CHARSET_UTF8)); } catch (IOException e) { e.printStackTrace(); } return null; } public StringBuffer readerToStrBuff(BufferedReader reader) { StringBuffer sb = new StringBuffer(); String tmp; try { while ( (tmp = reader.readLine()) != null){ sb.append(tmp); sb.append(System.lineSeparator()); } } catch (IOException e) { log.error("BufferRead Error : ",e); } return sb; } }
UTF-8
Java
9,974
java
RestSearchModule.java
Java
[ { "context": " new RestResultVO();\r\n\t\t//String apiUrl = \"http://182.162.109.118:6166/search\";\r\n\t\tString apiUrl = env.getProperty(", "end": 1472, "score": 0.9997605681419373, "start": 1457, "tag": "IP_ADDRESS", "value": "182.162.109.118" }, { "context": " new RestResultVO();\r\n\t\t//String apiUrl = \"http://182.162.109.118:6166/search\";\r\n\t\tString apiUrl = env.getProperty(", "end": 3661, "score": 0.9997262358665466, "start": 3646, "tag": "IP_ADDRESS", "value": "182.162.109.118" }, { "context": " new RestResultVO();\r\n\t\t//String apiUrl = \"http://182.162.109.118:6166/search\";\r\n\t\tString apiUrl = env.getProperty(", "end": 6556, "score": 0.99970942735672, "start": 6541, "tag": "IP_ADDRESS", "value": "182.162.109.118" } ]
null
[]
package com.saramin.lab.search.module; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Repository; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.saramin.lab.search.common.CommonUtils; import com.saramin.lab.search.common.GlobalConstant; import com.saramin.lab.search.query.SearchQueryBuilder; import com.saramin.lab.search.vo.RestResultVO; import lombok.extern.slf4j.Slf4j; @Slf4j @Repository public class RestSearchModule { @Autowired Environment env; @Autowired RestTemplate restTemplate; @Autowired CommonUtils common; /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(String selectStr, String fromStr, String whereStr) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://172.16.17.32:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", selectStr); paramMap.add("from", fromStr); paramMap.add("where", whereStr); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = selectStr.split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); map.put(fields[j], String.valueOf(record.get(fields[j]))); } list.add(map); map = null; } restVO.setResult(list); } // 파싱 끝 return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(String selectStr, String fromStr, String whereStr,String limit) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://172.16.17.32:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", selectStr); paramMap.add("from", fromStr); paramMap.add("where", whereStr); paramMap.add("limit", limit); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = selectStr.split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); if(fields[j].equals("count(*)")){ map.put("cnt", String.valueOf(record.get(fields[j]))); }else if(fields[j].equals("area_bcode")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("area_bcode_nm",GlobalConstant.AREA_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); map.put("area_mcode_nm",GlobalConstant.AREA_MCODE_MAP.get(String.valueOf(record.get(fields[j])).substring(0,3)+"000")); }else if(fields[j].equals("jikjong_cd")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("jikjong_nm", GlobalConstant.JIK_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); }else{ map.put(fields[j], String.valueOf(record.get(fields[j]))); } } list.add(map); map = null; } restVO.setResult(list); } return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * searchAPI (selectColumn, fromString, whereString) * @param selectStr * @param fromStr * @param whereStr * @return */ public RestResultVO searchAPI(SearchQueryBuilder query) { RestResultVO restVO = new RestResultVO(); //String apiUrl = "http://172.16.17.32:6166/search"; String apiUrl = env.getProperty("rest.url"); try { MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<String,String>(); paramMap.add("select", query.getSelectCloumn()); paramMap.add("from", query.getFrom()); paramMap.add("where", common.null2Str(query.getWhereClause().toString(), "") +" " + common.null2Str(query.getSortingClause().toString(),"") ); paramMap.add("limit", String.valueOf(query.getPageSize())); String rest = restTemplate.postForObject(apiUrl, paramMap, String.class); JSONObject jsonObj = (JSONObject) new JSONParser().parse(rest.toString()); restVO.setStatus((String)jsonObj.get("status")); log.info(jsonObj.toJSONString()); if(restVO.getStatus().equals("Failed")){ throw new IOException("Konan Rest Search Failed:" + (String)jsonObj.get("message")); } JSONObject resultObj = (JSONObject) jsonObj.get("result"); restVO.setTotal((long)resultObj.get("total_count")); JSONArray arr = (JSONArray) resultObj.get("rows"); int arrCnt = arr.size(); int fieldCnt = 0; if(arr != null && arrCnt > 0) { String[] fields = query.getSelectCloumn().split(","); HashMap<String, String> map; List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>> (); JSONObject result; JSONObject record; fieldCnt = fields.length; for(int i=0; i<arrCnt; i++) { map = new HashMap<String, String> (); result = (JSONObject) arr.get(i); record = (JSONObject) result.get("fields"); for(int j=0; j<fieldCnt; j++) { //log.info(fields[j].toString() + " ::::" + record.get(fields[j]).toString()); if(fields[j].equals("count(*)")){ map.put("cnt", String.valueOf(record.get(fields[j]))); }else if(fields[j].equals("area_bcode")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("area_bcode_nm",GlobalConstant.AREA_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); map.put("area_mcode_nm",GlobalConstant.AREA_MCODE_MAP.get(String.valueOf(record.get(fields[j])).substring(0,3)+"000")); }else if(fields[j].equals("jikjong_cd")){ map.put(fields[j], String.valueOf(record.get(fields[j]))); map.put("jikjong_nm", GlobalConstant.JIK_BCODE_NM_MAP.get(String.valueOf(record.get(fields[j])))); }else{ map.put(fields[j], String.valueOf(record.get(fields[j]))); } } list.add(map); map = null; } restVO.setResult(list); } return restVO; } catch (IOException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return null; } public BufferedReader getBufferedReader(String apiUrl) { try { URL url = new URL(apiUrl); return new BufferedReader(new InputStreamReader(url.openStream(),GlobalConstant.CHARSET_UTF8)); } catch (IOException e) { e.printStackTrace(); } return null; } public StringBuffer readerToStrBuff(BufferedReader reader) { StringBuffer sb = new StringBuffer(); String tmp; try { while ( (tmp = reader.readLine()) != null){ sb.append(tmp); sb.append(System.lineSeparator()); } } catch (IOException e) { log.error("BufferRead Error : ",e); } return sb; } }
9,965
0.636637
0.629013
311
30.051447
27.70116
147
false
false
0
0
0
0
0
0
3.70418
false
false
15
1c0f20d4e9e333d189762e3d1a75fb8ee799b810
35,227,321,792,339
6682531b416b1d400c5ea2fb7b738d8ed61fd34d
/SpringBoot/restauranteWEB/restauranteWEB/src/main/java/com/restauranteWeb/service/course/CourseService.java
e8f8ce817b327defe121e1b91a22fd76ba209287
[]
no_license
vladern/restauranteWEB
https://github.com/vladern/restauranteWEB
be8c4583bf328583a2b8cb54c991ad4f72a53dbd
8e9dd1db348c1149f561902de062f3e1407fbcc3
refs/heads/master
2020-06-03T09:52:35.269000
2019-06-16T20:41:22
2019-06-16T20:41:22
191,527,495
0
0
null
false
2020-09-09T07:13:23
2019-06-12T08:12:32
2019-06-16T20:41:24
2020-09-09T07:13:22
564
0
0
7
Java
false
false
package com.restauranteWeb.service.course; import com.restauranteWeb.dao.ICourseDAO; import com.restauranteWeb.dto.ApiDTOBuilder; import com.restauranteWeb.dto.course.CourseDTO; import com.restauranteWeb.dto.course.CreateNewCourseRequest; import com.restauranteWeb.dto.course.CreateNewCourseResponse; import com.restauranteWeb.dto.course.ObtainAllCoursesResponse; import com.restauranteWeb.entities.Course; import com.restauranteWeb.entities.CourseCategories; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CourseService implements ICourseService { @Autowired ICourseDAO courseDAO; private List<CourseDTO> getAllCourses() { List<Course> courseList = courseDAO.findAll(); List<CourseDTO> courseDTOList = new ArrayList<CourseDTO>(); for (Course course: courseList ) { courseDTOList.add(ApiDTOBuilder.courseToCourseDTO(course)); } return courseDTOList; } private void createNewCurse(Course course) { courseDAO.save(course); } private void deleteACourseById(int id){ courseDAO.delete(courseDAO.getOne(id)); } public ResponseEntity<ObtainAllCoursesResponse> obtainAllCourses() { ObtainAllCoursesResponse res = new ObtainAllCoursesResponse(); try { res.courseDTOList = this.getAllCourses(); res.message = "OK"; return new ResponseEntity<>(res, HttpStatus.OK); }catch (Exception ex) { res.message = "No se han podido obtener los platos"; return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); } } public ResponseEntity<CreateNewCourseResponse> createANewCourse(CreateNewCourseRequest request) { CreateNewCourseResponse res = new CreateNewCourseResponse(); try { Course newCourse = new Course(); newCourse.setName(request.name); newCourse.setDescription(request.description); switch (request.category) { case 0: newCourse.setCategory(CourseCategories.FIRST); break; case 1: newCourse.setCategory(CourseCategories.SECOND); break; default: newCourse.setCategory(CourseCategories.DESERT); } res.course = ApiDTOBuilder.courseToCourseDTO(courseDAO.save(newCourse)); res.message = "OK"; return new ResponseEntity<>(res, HttpStatus.OK); } catch (Exception e) { res.message = "No se ha podido crear el plato"; return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); } } }
UTF-8
Java
2,911
java
CourseService.java
Java
[]
null
[]
package com.restauranteWeb.service.course; import com.restauranteWeb.dao.ICourseDAO; import com.restauranteWeb.dto.ApiDTOBuilder; import com.restauranteWeb.dto.course.CourseDTO; import com.restauranteWeb.dto.course.CreateNewCourseRequest; import com.restauranteWeb.dto.course.CreateNewCourseResponse; import com.restauranteWeb.dto.course.ObtainAllCoursesResponse; import com.restauranteWeb.entities.Course; import com.restauranteWeb.entities.CourseCategories; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CourseService implements ICourseService { @Autowired ICourseDAO courseDAO; private List<CourseDTO> getAllCourses() { List<Course> courseList = courseDAO.findAll(); List<CourseDTO> courseDTOList = new ArrayList<CourseDTO>(); for (Course course: courseList ) { courseDTOList.add(ApiDTOBuilder.courseToCourseDTO(course)); } return courseDTOList; } private void createNewCurse(Course course) { courseDAO.save(course); } private void deleteACourseById(int id){ courseDAO.delete(courseDAO.getOne(id)); } public ResponseEntity<ObtainAllCoursesResponse> obtainAllCourses() { ObtainAllCoursesResponse res = new ObtainAllCoursesResponse(); try { res.courseDTOList = this.getAllCourses(); res.message = "OK"; return new ResponseEntity<>(res, HttpStatus.OK); }catch (Exception ex) { res.message = "No se han podido obtener los platos"; return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); } } public ResponseEntity<CreateNewCourseResponse> createANewCourse(CreateNewCourseRequest request) { CreateNewCourseResponse res = new CreateNewCourseResponse(); try { Course newCourse = new Course(); newCourse.setName(request.name); newCourse.setDescription(request.description); switch (request.category) { case 0: newCourse.setCategory(CourseCategories.FIRST); break; case 1: newCourse.setCategory(CourseCategories.SECOND); break; default: newCourse.setCategory(CourseCategories.DESERT); } res.course = ApiDTOBuilder.courseToCourseDTO(courseDAO.save(newCourse)); res.message = "OK"; return new ResponseEntity<>(res, HttpStatus.OK); } catch (Exception e) { res.message = "No se ha podido crear el plato"; return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); } } }
2,911
0.669873
0.669186
79
35.848103
25.162302
101
false
false
0
0
0
0
0
0
0.582278
false
false
15
ea897a63efa7501982809949d650c739b7d79638
34,239,479,335,748
6d25b624aee38254aeca432fb578e92891e95cf9
/sources/p004o/C1327.java
edd339496103f1f6e654c99490b85b899ba44429
[]
no_license
holic-cat/andro
https://github.com/holic-cat/andro
215e9bf627591596ee51a3e4a5873199bad77155
cd3d6fed2640bc7dd414a03ee6912acfd1f188a7
refs/heads/master
2023-03-05T06:05:01.933000
2020-04-08T12:11:09
2020-04-08T12:11:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p004o; /* renamed from: o.આ */ class C1327 { /* renamed from: ˮ͈ */ C1992 f6631; /* renamed from: 櫯 */ int f6632; /* renamed from: 鷭 */ int f6633; C1327() { } }
UTF-8
Java
214
java
C1327.java
Java
[]
null
[]
package p004o; /* renamed from: o.આ */ class C1327 { /* renamed from: ˮ͈ */ C1992 f6631; /* renamed from: 櫯 */ int f6632; /* renamed from: 鷭 */ int f6633; C1327() { } }
214
0.495146
0.364078
17
11.117647
9.584806
26
false
false
0
0
0
0
0
0
0.235294
false
false
15
773b36e9085a2598028e3407d1b3b2a819f18f05
36,180,804,533,803
a1e54f66087c334c7bbbbdb6205258b90b72f1a5
/CmriSeWeb-1.0/src/main/java/com/cmrise/jpa/dao/exams/MrqsGrupoHdrDao.java
65905ef48e3623a8f776848cf6ee3c508d543ba2
[]
no_license
FranciscoSosa25/CmriSeWeb
https://github.com/FranciscoSosa25/CmriSeWeb
f59e90fea88c617ae035b6a4313aa6911b7094fa
0a6c1a38f9a5ef482c52c0ddcd674ce6d27bbeab
refs/heads/master
2023-03-05T16:05:16.041000
2022-06-04T16:57:12
2022-06-04T16:57:12
228,455,133
2
3
null
false
2023-02-22T07:54:53
2019-12-16T19:00:33
2022-02-08T23:44:48
2023-02-22T07:54:52
49,524
1
2
3
JavaScript
false
false
package com.cmrise.jpa.dao.exams; import java.util.List; import com.cmrise.jpa.dto.exams.MrqsGrupoHdrDto; import com.cmrise.jpa.dto.exams.MrqsGrupoHdrV1Dto; public interface MrqsGrupoHdrDao { public long insert(MrqsGrupoHdrDto pMrqsGrupoHdrDto); public List<MrqsGrupoHdrDto> findByNumeroExamen(long pNumeroExamen); public MrqsGrupoHdrDto findByNumero(long pNumero); public void delete(long pNumero); public void update(long pNumero,MrqsGrupoHdrDto pMrqsGrupoHdrDto); public List<MrqsGrupoHdrV1Dto> findByNumeroExamenWD(long pNumero); public MrqsGrupoHdrV1Dto findByNumeroWD(long pNumeroMrqsGrupo); }
UTF-8
Java
619
java
MrqsGrupoHdrDao.java
Java
[]
null
[]
package com.cmrise.jpa.dao.exams; import java.util.List; import com.cmrise.jpa.dto.exams.MrqsGrupoHdrDto; import com.cmrise.jpa.dto.exams.MrqsGrupoHdrV1Dto; public interface MrqsGrupoHdrDao { public long insert(MrqsGrupoHdrDto pMrqsGrupoHdrDto); public List<MrqsGrupoHdrDto> findByNumeroExamen(long pNumeroExamen); public MrqsGrupoHdrDto findByNumero(long pNumero); public void delete(long pNumero); public void update(long pNumero,MrqsGrupoHdrDto pMrqsGrupoHdrDto); public List<MrqsGrupoHdrV1Dto> findByNumeroExamenWD(long pNumero); public MrqsGrupoHdrV1Dto findByNumeroWD(long pNumeroMrqsGrupo); }
619
0.82391
0.819063
19
31.578947
26.697754
70
false
false
0
0
0
0
0
0
1.105263
false
false
15
fa7a378535c7f91faba5becf91362ef34298449e
12,678,743,505,057
1bc522af18e297e1af2ea11786821418e1eadf5e
/Calculator.java
ea09c5438f1d7fd512d46d48914428cf76d93764
[]
no_license
osliken/Calculator
https://github.com/osliken/Calculator
bff86d5c08422cf2c9878701151295335aabfc4e
a3c125a3655843337d5d1ec1f57a36e2a8a98673
refs/heads/master
2023-03-24T23:12:46.796000
2021-03-28T13:26:58
2021-03-28T13:26:58
352,327,816
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prog.calculator; public class Calculator { public String[] arabicNumbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; public String[] operations = {"+", "-", "*", "/"}; public int result = 0; public boolean check(String[] array, String value) { boolean test = false; for (String element : array) { if (element.equals(value)) { test = true; break; } } return test; } public void calculate(String valueX, String valueY, String operation) throws CalculatorException { if (check(arabicNumbers, valueX) && check(arabicNumbers, valueY)) { int x = Integer.parseInt(valueX); int y = Integer.parseInt(valueY); if (check(operations, operation)) { switch (operation) { case "+": { result = x + y; break; } case "-": { result = x - y; break; } case "*": { result = x * y; break; } case "/": { result = x / y; break; } } } } else throw new CalculatorException("Введите числа от 1 до 10"); } }
UTF-8
Java
1,484
java
Calculator.java
Java
[]
null
[]
package prog.calculator; public class Calculator { public String[] arabicNumbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; public String[] operations = {"+", "-", "*", "/"}; public int result = 0; public boolean check(String[] array, String value) { boolean test = false; for (String element : array) { if (element.equals(value)) { test = true; break; } } return test; } public void calculate(String valueX, String valueY, String operation) throws CalculatorException { if (check(arabicNumbers, valueX) && check(arabicNumbers, valueY)) { int x = Integer.parseInt(valueX); int y = Integer.parseInt(valueY); if (check(operations, operation)) { switch (operation) { case "+": { result = x + y; break; } case "-": { result = x - y; break; } case "*": { result = x * y; break; } case "/": { result = x / y; break; } } } } else throw new CalculatorException("Введите числа от 1 до 10"); } }
1,484
0.393733
0.383515
47
30.212767
22.259529
102
false
false
0
0
0
0
0
0
0.787234
false
false
15
58013868ea3de0328de1560bd12eaa7dc029a698
7,258,494,767,705
8d576f25843272fb82dec2210749553a168ad7aa
/src/javaadvancedoctubre/Miercoles/carrera/Liebre.java
c37a8c6e604ec8b44593a34f5831cd727e27b26b
[ "Apache-2.0" ]
permissive
EliseoRoman/JavaAdvancedOctubre
https://github.com/EliseoRoman/JavaAdvancedOctubre
fe8e46cdebe765c4652f9b04bd597a0e51e2c808
17fa6a81e0944eebbc7d9766d9670a7081584972
refs/heads/master
2021-07-15T09:49:56.621000
2017-10-20T22:24:17
2017-10-20T22:24:17
107,202,382
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaadvancedoctubre.Miercoles.carrera; public class Liebre implements Runnable{ public void run(){ int i = 0; System.out.println("Inicia la Liebre"); while(i <= 5){ try { Thread.sleep(250); System.out.println("Da un paso la Liebre"); } catch (InterruptedException ie) { System.out.println(ie); } i++; } System.out.println("Ya llego la Liebre"); } }
UTF-8
Java
511
java
Liebre.java
Java
[]
null
[]
package javaadvancedoctubre.Miercoles.carrera; public class Liebre implements Runnable{ public void run(){ int i = 0; System.out.println("Inicia la Liebre"); while(i <= 5){ try { Thread.sleep(250); System.out.println("Da un paso la Liebre"); } catch (InterruptedException ie) { System.out.println(ie); } i++; } System.out.println("Ya llego la Liebre"); } }
511
0.504892
0.495108
19
25.894737
17.961639
59
false
false
0
0
0
0
0
0
0.421053
false
false
15
faa9f65c88291fdae9b6ed75d8fb191606da711e
27,144,193,372,484
f35ddf002ec85e37e92022cf333d5c073c80c978
/asmack-android-8-source-4.0.7/org/jivesoftware/smackx/iqversion/VersionManager.java
ea9ee8c690f16cd858864706acb545fb37ef8d9a
[ "OLDAP-2.8", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
victoryckl/asmack-android-8-4.0.7
https://github.com/victoryckl/asmack-android-8-4.0.7
cb344361f893470ba795b9fbca8bb1d229435789
b5c2295408a7a2a13ccaf8723fe3cb916449d3d5
refs/heads/master
2016-09-05T21:10:23.521000
2015-03-27T06:01:19
2015-03-27T06:01:19
32,969,681
5
3
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * * Copyright 2014 Georg Lukas. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.iqversion; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.IQTypeFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.iqversion.packet.Version; /** * A Version Manager that automatically responds to version IQs with a predetermined reply. * * <p> * The VersionManager takes care of handling incoming version request IQs, according to * XEP-0092 (Software Version). You can configure the version reply for a given connection * by running the following code: * </p> * * <pre> * Version MY_VERSION = new Version("My Little XMPP Application", "v1.23", "OS/2 32-bit"); * VersionManager.getInstanceFor(mConnection).setVersion(MY_VERSION); * </pre> * * @author Georg Lukas */ public class VersionManager extends Manager { private static final Map<XMPPConnection, VersionManager> instances = Collections.synchronizedMap(new WeakHashMap<XMPPConnection, VersionManager>()); private Version own_version; private VersionManager(final XMPPConnection connection) { super(connection); instances.put(connection, this); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); sdm.addFeature(Version.NAMESPACE); connection.addPacketListener(new PacketListener() { /** * Sends a Version reply on request * @throws NotConnectedException */ public void processPacket(Packet packet) throws NotConnectedException { if (own_version == null) return; Version reply = new Version(own_version); reply.setPacketID(packet.getPacketID()); reply.setTo(packet.getFrom()); connection().sendPacket(reply); } } , new AndFilter(new PacketTypeFilter(Version.class), new IQTypeFilter(Type.GET))); } public static synchronized VersionManager getInstanceFor(XMPPConnection connection) { VersionManager versionManager = instances.get(connection); if (versionManager == null) { versionManager = new VersionManager(connection); } return versionManager; } public void setVersion(Version v) { own_version = v; } }
UTF-8
Java
3,394
java
VersionManager.java
Java
[ { "context": "/**\n *\n * Copyright 2014 Georg Lukas.\n *\n * Licensed under the Apache License, Version", "end": 36, "score": 0.9998028874397278, "start": 25, "tag": "NAME", "value": "Georg Lukas" }, { "context": "n).setVersion(MY_VERSION);\n * </pre>\n *\n * @author Georg Lukas\n */\npublic class VersionManager extends Manager {", "end": 1827, "score": 0.9997724294662476, "start": 1816, "tag": "NAME", "value": "Georg Lukas" } ]
null
[]
/** * * Copyright 2014 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.iqversion; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.IQTypeFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.iqversion.packet.Version; /** * A Version Manager that automatically responds to version IQs with a predetermined reply. * * <p> * The VersionManager takes care of handling incoming version request IQs, according to * XEP-0092 (Software Version). You can configure the version reply for a given connection * by running the following code: * </p> * * <pre> * Version MY_VERSION = new Version("My Little XMPP Application", "v1.23", "OS/2 32-bit"); * VersionManager.getInstanceFor(mConnection).setVersion(MY_VERSION); * </pre> * * @author <NAME> */ public class VersionManager extends Manager { private static final Map<XMPPConnection, VersionManager> instances = Collections.synchronizedMap(new WeakHashMap<XMPPConnection, VersionManager>()); private Version own_version; private VersionManager(final XMPPConnection connection) { super(connection); instances.put(connection, this); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); sdm.addFeature(Version.NAMESPACE); connection.addPacketListener(new PacketListener() { /** * Sends a Version reply on request * @throws NotConnectedException */ public void processPacket(Packet packet) throws NotConnectedException { if (own_version == null) return; Version reply = new Version(own_version); reply.setPacketID(packet.getPacketID()); reply.setTo(packet.getFrom()); connection().sendPacket(reply); } } , new AndFilter(new PacketTypeFilter(Version.class), new IQTypeFilter(Type.GET))); } public static synchronized VersionManager getInstanceFor(XMPPConnection connection) { VersionManager versionManager = instances.get(connection); if (versionManager == null) { versionManager = new VersionManager(connection); } return versionManager; } public void setVersion(Version v) { own_version = v; } }
3,384
0.708309
0.703005
96
34.354168
29.186533
91
false
false
0
0
0
0
0
0
0.479167
false
false
15
4aa71076754fd481bbec44134ed518fc6f80d8c7
30,116,310,712,158
b98e87fc4c2083b1b7fa7129090f9361b34e3792
/src/main/java/cn/xpbootcamp/locker_robot/exception/TicketIsInvalidForRobotException.java
c43942eb448811b1a14f201ddff5353a408069a1
[ "Apache-2.0" ]
permissive
wangyuanhui/tdd-locker-robot-java
https://github.com/wangyuanhui/tdd-locker-robot-java
582f48abb3ac875a62d9f53195c557a502f61acb
99c6f514815dff9dff80c48f145a0d13046b013c
refs/heads/master
2022-09-12T16:23:43.315000
2020-05-29T13:33:05
2020-05-29T13:33:05
262,015,235
0
0
Apache-2.0
true
2020-05-07T10:04:58
2020-05-07T10:04:57
2020-05-06T07:37:34
2020-05-06T07:37:32
57
0
0
0
null
false
false
package cn.xpbootcamp.locker_robot.exception; public class TicketIsInvalidForRobotException extends RuntimeException{ public TicketIsInvalidForRobotException() { super("Ticket is invalid for this robot"); } }
UTF-8
Java
226
java
TicketIsInvalidForRobotException.java
Java
[]
null
[]
package cn.xpbootcamp.locker_robot.exception; public class TicketIsInvalidForRobotException extends RuntimeException{ public TicketIsInvalidForRobotException() { super("Ticket is invalid for this robot"); } }
226
0.774336
0.774336
7
31.285715
26.590622
71
false
false
0
0
0
0
0
0
0.285714
false
false
15
8e9bec4756cd4148e67c33554833a9990e43a50a
29,738,353,571,075
4d7d8f99d2e5c5f515169ca530383d9a4b075130
/src/main/java/cuberite/api/hooks/hHOOK_EXECUTE_COMMAND.java
3d5596e5a861f5abfe6327cc584a4fe60f42a1ad
[ "MIT" ]
permissive
KrystilizeNevaDies/CuberitePluginAPI
https://github.com/KrystilizeNevaDies/CuberitePluginAPI
093e29efcbc88befec008a20edef178735277d04
50232c41f3721d97d89f49ceff95cdf56b1b337c
refs/heads/main
2023-02-01T07:42:53.965000
2020-12-17T12:38:37
2020-12-17T12:38:37
322,286,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cuberite.api.hooks; import org.luaj.vm2.LuaValue; import cuberite.api.cPlayer; import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.event.player.PlayerCommandEvent; import net.minestom.server.network.packet.client.ClientPlayPacket; public enum hHOOK_EXECUTE_COMMAND implements Hook { INSTANCE; private LuaValue[] hookList = {}; @Override public LuaValue[] getFunctions() { return this.hookList; } @Override public void setFunctions(LuaValue[] newFunctions) { this.hookList = newFunctions; } @Override public void start() { // Setup hook logic MinecraftServer.getConnectionManager().addPlayerInitialization((player) -> { player.addEventCallback(PlayerCommandEvent.class, (event) -> { String command = event.getCommand(); String[] stringSplit = command.split(""); LuaValue[] split = {}; for (int i = 0; i < stringSplit.length; i++) { split[i] = LuaValue.valueOf(stringSplit[i]); } LuaValue[] args = { new cPlayer(player).luaValue, LuaValue.tableOf(split), LuaValue.valueOf(command) }; call(args); }); }); } @Override public Boolean packetEvent(ClientPlayPacket packet, Player player) { // TODO Auto-generated method stub return null; } /////////////////////////////////////// // hHOOK_EXECUTE_COMMAND // /////////////////////////////////////// }
UTF-8
Java
1,396
java
hHOOK_EXECUTE_COMMAND.java
Java
[]
null
[]
package cuberite.api.hooks; import org.luaj.vm2.LuaValue; import cuberite.api.cPlayer; import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.event.player.PlayerCommandEvent; import net.minestom.server.network.packet.client.ClientPlayPacket; public enum hHOOK_EXECUTE_COMMAND implements Hook { INSTANCE; private LuaValue[] hookList = {}; @Override public LuaValue[] getFunctions() { return this.hookList; } @Override public void setFunctions(LuaValue[] newFunctions) { this.hookList = newFunctions; } @Override public void start() { // Setup hook logic MinecraftServer.getConnectionManager().addPlayerInitialization((player) -> { player.addEventCallback(PlayerCommandEvent.class, (event) -> { String command = event.getCommand(); String[] stringSplit = command.split(""); LuaValue[] split = {}; for (int i = 0; i < stringSplit.length; i++) { split[i] = LuaValue.valueOf(stringSplit[i]); } LuaValue[] args = { new cPlayer(player).luaValue, LuaValue.tableOf(split), LuaValue.valueOf(command) }; call(args); }); }); } @Override public Boolean packetEvent(ClientPlayPacket packet, Player player) { // TODO Auto-generated method stub return null; } /////////////////////////////////////// // hHOOK_EXECUTE_COMMAND // /////////////////////////////////////// }
1,396
0.675501
0.674069
57
23.491228
24.563646
107
false
false
0
0
0
0
0
0
1.684211
false
false
15
9ec08405575188f0a1d517a61b541dd5dd1db280
32,315,333,939,593
8dc9d58d0ef54c14c2250f2b6a5b9219716c63de
/src/test04/FileDemo2.java
2841412519794b9807148c825601e4dc6299fb50
[]
no_license
IvanLu1024/FileIOTest
https://github.com/IvanLu1024/FileIOTest
af0dc36672f7dc031aea7ad70ea280287a3b8224
de7cc06131f5021c65433c356e5f0509bd33c0b3
refs/heads/master
2020-03-28T03:15:31.510000
2018-09-13T10:07:37
2018-09-13T10:07:37
147,632,067
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test04; import java.io.File; import java.io.FilenameFilter; /** * 使用FileFilter来实现获取指定后缀名的文件对象 */ public class FileDemo2 { public static void main(String[] args) { File file=new File("D://"); File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return new File(dir,name).isFile()&&name.endsWith(""); } }); for (File f:files){ System.out.println(f.getName()); } } }
UTF-8
Java
581
java
FileDemo2.java
Java
[]
null
[]
package test04; import java.io.File; import java.io.FilenameFilter; /** * 使用FileFilter来实现获取指定后缀名的文件对象 */ public class FileDemo2 { public static void main(String[] args) { File file=new File("D://"); File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return new File(dir,name).isFile()&&name.endsWith(""); } }); for (File f:files){ System.out.println(f.getName()); } } }
581
0.559415
0.553931
24
21.791666
20.564896
70
false
false
0
0
0
0
0
0
0.375
false
false
15
aa0844386734a7c31703f2448b11ddde5f2158c0
20,177,756,421,726
b7351a39542e60edcda48515753c8a78ccd6b9e2
/src/main/java/pyokagan/cs4212/LivePass.java
60e787f7f4f3f85fcee6837946fd457ea668091d
[]
no_license
pyokagan/CS4212-Compiler
https://github.com/pyokagan/CS4212-Compiler
59050edee433ccb4fff0daa93e9f8666bce34b61
bf8191b5c7e8c234cce81528eee1691068610e4f
refs/heads/master
2020-04-09T18:58:45.029000
2018-12-05T14:17:24
2018-12-05T14:17:24
160,530,262
10
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package pyokagan.cs4212; import java.util.*; /** * Global liveness analysis. */ public class LivePass { private final Ir.Meth meth; private HashMap<Ir.Block, HashSet<Ir.Var>> liveIns = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> liveOuts = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> blockUses = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> blockDefs = new HashMap<>(); private HashMap<Ir.Block, HashMap<Ir.Var, Ir.Stmt>> lastUses = new HashMap<>(); public LivePass(Ir.Meth meth) { this.meth = meth; for (Ir.Block block : meth.blocks) { liveIns.put(block, new HashSet<>()); liveOuts.put(block, new HashSet<>()); } // Compute blockUses and blockDefs for (Ir.Block block : meth.blocks) { HashSet<Ir.Var> blockUses = new HashSet<>(); HashSet<Ir.Var> blockDefs = new HashSet<>(); HashMap<Ir.Var, Ir.Stmt> blockLastUses = new HashMap<>(); for (int i = block.stmts.size() - 1; i >= 0; i--) { Ir.Stmt stmt = block.stmts.get(i); for (Ir.Var v : stmt.getDefs()) blockUses.remove(v); // Compute stmt uses HashSet<Ir.Var> uses = new HashSet<>(stmt.getUses()); if (stmt instanceof Ir.JumpStmt) uses.addAll(getJumpUses(block)); for (Ir.Var v : uses) { if (!blockLastUses.containsKey(v)) blockLastUses.put(v, stmt); } blockUses.addAll(uses); blockDefs.addAll(stmt.getDefs()); } this.blockUses.put(block, blockUses); this.blockDefs.put(block, blockDefs); this.lastUses.put(block, blockLastUses); } // Iteration boolean hasChange = true; while (hasChange) { hasChange = false; for (Ir.Block block : meth.blocksPo) { HashSet<Ir.Var> liveOut = liveOuts.get(block); HashSet<Ir.Var> liveIn = liveIns.get(block); // OUT[block] = union of IN[succ] + their PHI nodes for (Ir.Block succ : block.getOutgoing()) liveOut.addAll(liveIns.get(succ)); liveOut.addAll(getJumpUses(block)); // IN[block] = f(OUT[block]) HashSet<Ir.Var> newLiveIn = new HashSet<>(); newLiveIn.addAll(liveOut); newLiveIn.removeAll(blockDefs.get(block)); newLiveIn.addAll(blockUses.get(block)); if (!hasChange && !newLiveIn.equals(liveIn)) hasChange = true; liveIns.put(block, newLiveIn); } } } public Set<Ir.Var> getLiveIn(Ir.Block block) { return liveIns.get(block); } public Set<Ir.Var> getLiveOut(Ir.Block block) { return liveOuts.get(block); } public Ir.Stmt getLastUse(Ir.Block block, Ir.Var v) { return lastUses.get(block).get(v); } @Override public String toString() { return "LivePass(IN=" + liveIns + ", OUT=" + liveOuts + ")"; } /** * Return union of vars that phi nodes in successive blocks use. */ public static Set<Ir.Var> getJumpUses(Ir.Block block) { HashSet<Ir.Var> uses = new HashSet<>(); for (Ir.Block succ : block.getOutgoing()) { int incomingIdx = succ.incoming.indexOf(block); for (Ir.Stmt stmt : succ.stmts) { if (!(stmt instanceof Ir.PhiStmt)) break; Ir.PhiStmt phiStmt = (Ir.PhiStmt) stmt; if (!phiStmt.memory && phiStmt.args.get(incomingIdx) != null) uses.add(phiStmt.args.get(incomingIdx)); } } return uses; } }
UTF-8
Java
3,927
java
LivePass.java
Java
[]
null
[]
package pyokagan.cs4212; import java.util.*; /** * Global liveness analysis. */ public class LivePass { private final Ir.Meth meth; private HashMap<Ir.Block, HashSet<Ir.Var>> liveIns = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> liveOuts = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> blockUses = new HashMap<>(); private HashMap<Ir.Block, HashSet<Ir.Var>> blockDefs = new HashMap<>(); private HashMap<Ir.Block, HashMap<Ir.Var, Ir.Stmt>> lastUses = new HashMap<>(); public LivePass(Ir.Meth meth) { this.meth = meth; for (Ir.Block block : meth.blocks) { liveIns.put(block, new HashSet<>()); liveOuts.put(block, new HashSet<>()); } // Compute blockUses and blockDefs for (Ir.Block block : meth.blocks) { HashSet<Ir.Var> blockUses = new HashSet<>(); HashSet<Ir.Var> blockDefs = new HashSet<>(); HashMap<Ir.Var, Ir.Stmt> blockLastUses = new HashMap<>(); for (int i = block.stmts.size() - 1; i >= 0; i--) { Ir.Stmt stmt = block.stmts.get(i); for (Ir.Var v : stmt.getDefs()) blockUses.remove(v); // Compute stmt uses HashSet<Ir.Var> uses = new HashSet<>(stmt.getUses()); if (stmt instanceof Ir.JumpStmt) uses.addAll(getJumpUses(block)); for (Ir.Var v : uses) { if (!blockLastUses.containsKey(v)) blockLastUses.put(v, stmt); } blockUses.addAll(uses); blockDefs.addAll(stmt.getDefs()); } this.blockUses.put(block, blockUses); this.blockDefs.put(block, blockDefs); this.lastUses.put(block, blockLastUses); } // Iteration boolean hasChange = true; while (hasChange) { hasChange = false; for (Ir.Block block : meth.blocksPo) { HashSet<Ir.Var> liveOut = liveOuts.get(block); HashSet<Ir.Var> liveIn = liveIns.get(block); // OUT[block] = union of IN[succ] + their PHI nodes for (Ir.Block succ : block.getOutgoing()) liveOut.addAll(liveIns.get(succ)); liveOut.addAll(getJumpUses(block)); // IN[block] = f(OUT[block]) HashSet<Ir.Var> newLiveIn = new HashSet<>(); newLiveIn.addAll(liveOut); newLiveIn.removeAll(blockDefs.get(block)); newLiveIn.addAll(blockUses.get(block)); if (!hasChange && !newLiveIn.equals(liveIn)) hasChange = true; liveIns.put(block, newLiveIn); } } } public Set<Ir.Var> getLiveIn(Ir.Block block) { return liveIns.get(block); } public Set<Ir.Var> getLiveOut(Ir.Block block) { return liveOuts.get(block); } public Ir.Stmt getLastUse(Ir.Block block, Ir.Var v) { return lastUses.get(block).get(v); } @Override public String toString() { return "LivePass(IN=" + liveIns + ", OUT=" + liveOuts + ")"; } /** * Return union of vars that phi nodes in successive blocks use. */ public static Set<Ir.Var> getJumpUses(Ir.Block block) { HashSet<Ir.Var> uses = new HashSet<>(); for (Ir.Block succ : block.getOutgoing()) { int incomingIdx = succ.incoming.indexOf(block); for (Ir.Stmt stmt : succ.stmts) { if (!(stmt instanceof Ir.PhiStmt)) break; Ir.PhiStmt phiStmt = (Ir.PhiStmt) stmt; if (!phiStmt.memory && phiStmt.args.get(incomingIdx) != null) uses.add(phiStmt.args.get(incomingIdx)); } } return uses; } }
3,927
0.531958
0.53043
114
33.447369
24.578943
83
false
false
0
0
0
0
0
0
0.561404
false
false
15
aaf534961808d6e5a288dd4eeba0c82d2c327b76
23,132,693,910,678
88597d90633f67ce4f004df8ce2cf380ccf27dda
/1_Fundamentals/1_5_CaseStudyUnion-Find/UF2.java
61cc97cf8da95f05b0b66dc96791c339d5c1f0a1
[]
no_license
hdonghong/Alogorithms4Exercise
https://github.com/hdonghong/Alogorithms4Exercise
c8b6fb32226b1a9e699a7bc307eaba9b05243fb8
032f342bc5ac3e8772d7102212d97e0d2399a9e9
refs/heads/master
2021-12-27T21:44:27.907000
2018-02-09T05:02:22
2018-02-09T05:02:22
118,057,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @ClassName UF1 * @Description quick-union算法 * @author hdonghong * @version v1.0 * @since 2018/01/28 07:37:49 */ public class UF2 { private int[] id; // 分量id private int count; // 分量数量 public UF2(int N) { // 初始化N个连通分量的id数组 count = N; id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } /** * 返回连通分量的数量 * @return */ public int count() { return count; } /** * 获取p所在分量的标识符,标识符为分量中某个触点的名称 * @param p * @return */ public int find(int p) { while (p != id[p]) p = id[p]; return p; } /** * 判断p和q两个触点是否连通,即是否属于同一个分量 * @param p * @param q * @return */ public boolean connected(int p, int q) { return find(p) == find(q); } /** * 在p,q间增加一条连接 * @param p * @param q */ public void union(int p, int q) { int pRoot = find(p); int qRoot = find(q); // p,q已经连通,停止继续执行 if (pRoot == qRoot) return; // 连通p,q id[pRoot] = qRoot; // 减少一个分量 count--; } /** * 测试用例 * @param args */ public static void main(String[] args) { int N = StdIn.readInt(); // 读取触点数量 UF2 uf = new UF2(N); // 初始化N个分量 Stopwatch timeCounter = new Stopwatch();// 计时器,开始计时 while (!StdIn.isEmpty()) { int p = StdIn.readInt(); // 读取整数对 int q = StdIn.readInt(); if (uf.connected(p, q)) continue; // 如果已经连通则忽略 uf.union(p, q); // 连通归并分量 StdOut.println(p + " " + q); // 打印新连接 } StdOut.println("用时" + timeCounter.elapsedTime() + "s"); StdOut.println(uf.count() + "个连通分量"); } }
UTF-8
Java
1,813
java
UF2.java
Java
[ { "context": "ame\tUF1\n * @Description\tquick-union算法\n * @author\t\thdonghong\n * @version \tv1.0 \n * @since\t\t2018/01/28 07:37:49", "end": 74, "score": 0.9978907704353333, "start": 65, "tag": "USERNAME", "value": "hdonghong" } ]
null
[]
/** * @ClassName UF1 * @Description quick-union算法 * @author hdonghong * @version v1.0 * @since 2018/01/28 07:37:49 */ public class UF2 { private int[] id; // 分量id private int count; // 分量数量 public UF2(int N) { // 初始化N个连通分量的id数组 count = N; id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } /** * 返回连通分量的数量 * @return */ public int count() { return count; } /** * 获取p所在分量的标识符,标识符为分量中某个触点的名称 * @param p * @return */ public int find(int p) { while (p != id[p]) p = id[p]; return p; } /** * 判断p和q两个触点是否连通,即是否属于同一个分量 * @param p * @param q * @return */ public boolean connected(int p, int q) { return find(p) == find(q); } /** * 在p,q间增加一条连接 * @param p * @param q */ public void union(int p, int q) { int pRoot = find(p); int qRoot = find(q); // p,q已经连通,停止继续执行 if (pRoot == qRoot) return; // 连通p,q id[pRoot] = qRoot; // 减少一个分量 count--; } /** * 测试用例 * @param args */ public static void main(String[] args) { int N = StdIn.readInt(); // 读取触点数量 UF2 uf = new UF2(N); // 初始化N个分量 Stopwatch timeCounter = new Stopwatch();// 计时器,开始计时 while (!StdIn.isEmpty()) { int p = StdIn.readInt(); // 读取整数对 int q = StdIn.readInt(); if (uf.connected(p, q)) continue; // 如果已经连通则忽略 uf.union(p, q); // 连通归并分量 StdOut.println(p + " " + q); // 打印新连接 } StdOut.println("用时" + timeCounter.elapsedTime() + "s"); StdOut.println(uf.count() + "个连通分量"); } }
1,813
0.550637
0.535882
84
16.738094
14.176707
57
false
false
0
0
0
0
0
0
2.047619
false
false
15
cc8626320cf09305e76b066be1b48c4c819d96a2
26,199,300,512,918
2817f85281b2d34901095b1a118179928fedbd6c
/src/partie2/exercice1/postfix.java
1e67718eee5f5eb32aa96c0abb458408024d5526
[]
no_license
mehdimidox/java
https://github.com/mehdimidox/java
0d7e7adcb910ee1d73c89ad9bcde93eac07372f4
ff59b54a3fbbb874297a44c84e3e6ebe645283f4
refs/heads/master
2021-01-01T22:34:41.103000
2020-03-01T17:42:57
2020-03-01T17:42:57
239,372,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package partie2.exercice1; import java.*; import java.util.Scanner; import java.util.Stack; public class postfix { //static Stack<Double> operande = new Stack<Double>(); static Stack<Character> operateur = new Stack<Character>(); static Stack<String> myStack = new Stack<String>(); static Stack<String> rMyStack = new Stack<String>(); static Stack<Integer> finalStack = new Stack<Integer>(); public static void main(String[] argv) { Scanner sn = new Scanner(System.in); myGetStack(sn.nextLine()); stacCalcul(); } public static void myGetStack(String arg) { String str = ""; int i = 0; try { while (i < arg.length()) { if (arg.charAt(i) == '+' || arg.charAt(i) == '-' || arg.charAt(i) == '*' || arg.charAt(i) == '/' || arg.charAt(i) == '(' || arg.charAt(i) == ')') { if(arg.charAt(i) != '(' && arg.charAt(i) != ')') { operateur.push(arg.charAt(i)); } if(arg.charAt(i) != '(') { if(str.length() > 0) myStack.push(str); str =""; } if(arg.charAt(i) == ')') { str+=operateur.pop(); if(str.length() > 0) myStack.push(str); str=""; } } else { str+=arg.charAt(i); } i++; } if(str.length() > 0) myStack.push(str); while(!operateur.empty()) { str=""; myStack.push(str+=operateur.pop()); } System.out.println(myStack); } catch (Exception e) { System.out.println("please enter quelque chose"); } } public static void stacCalcul() { String str; while(!myStack.empty()) { rMyStack.push(myStack.pop()); } while (!rMyStack.empty()) { str = rMyStack.pop(); if(str.contentEquals("+")) { finalStack.push(finalStack.pop() + finalStack.pop()); } else { if(str.contentEquals("-")) { finalStack.push(finalStack.pop() - finalStack.pop()); } else { if(str.contentEquals("*")) { finalStack.push(finalStack.pop() * finalStack.pop()); } else { if(str.contentEquals("/")) { finalStack.push(finalStack.pop() / finalStack.pop()); } else { int x = Integer.valueOf(str); if(x >= 0) finalStack.push(x); } } } } } System.out.println(finalStack.pop()); } }
UTF-8
Java
2,317
java
postfix.java
Java
[]
null
[]
package partie2.exercice1; import java.*; import java.util.Scanner; import java.util.Stack; public class postfix { //static Stack<Double> operande = new Stack<Double>(); static Stack<Character> operateur = new Stack<Character>(); static Stack<String> myStack = new Stack<String>(); static Stack<String> rMyStack = new Stack<String>(); static Stack<Integer> finalStack = new Stack<Integer>(); public static void main(String[] argv) { Scanner sn = new Scanner(System.in); myGetStack(sn.nextLine()); stacCalcul(); } public static void myGetStack(String arg) { String str = ""; int i = 0; try { while (i < arg.length()) { if (arg.charAt(i) == '+' || arg.charAt(i) == '-' || arg.charAt(i) == '*' || arg.charAt(i) == '/' || arg.charAt(i) == '(' || arg.charAt(i) == ')') { if(arg.charAt(i) != '(' && arg.charAt(i) != ')') { operateur.push(arg.charAt(i)); } if(arg.charAt(i) != '(') { if(str.length() > 0) myStack.push(str); str =""; } if(arg.charAt(i) == ')') { str+=operateur.pop(); if(str.length() > 0) myStack.push(str); str=""; } } else { str+=arg.charAt(i); } i++; } if(str.length() > 0) myStack.push(str); while(!operateur.empty()) { str=""; myStack.push(str+=operateur.pop()); } System.out.println(myStack); } catch (Exception e) { System.out.println("please enter quelque chose"); } } public static void stacCalcul() { String str; while(!myStack.empty()) { rMyStack.push(myStack.pop()); } while (!rMyStack.empty()) { str = rMyStack.pop(); if(str.contentEquals("+")) { finalStack.push(finalStack.pop() + finalStack.pop()); } else { if(str.contentEquals("-")) { finalStack.push(finalStack.pop() - finalStack.pop()); } else { if(str.contentEquals("*")) { finalStack.push(finalStack.pop() * finalStack.pop()); } else { if(str.contentEquals("/")) { finalStack.push(finalStack.pop() / finalStack.pop()); } else { int x = Integer.valueOf(str); if(x >= 0) finalStack.push(x); } } } } } System.out.println(finalStack.pop()); } }
2,317
0.537764
0.534743
113
19.513275
17.714109
60
false
false
0
0
0
0
0
0
3.80531
false
false
15
e1b9a5727c24c6b03964d118e05c90c960c50b0f
14,783,277,436,955
6081ecb0c81caf3d6b7298448762319c7674ffef
/ParkingLot/UnparkCommand.java
f9e8856b6b553c57acdf0167eff618b38bd6badc
[]
no_license
LingFZhou/Projects
https://github.com/LingFZhou/Projects
975580e5236b38a4fed52742cb50da27d373d54b
15a311bf934a99496ef942fd0093e43ddeab7fed
refs/heads/master
2021-01-25T06:25:42.719000
2017-06-07T00:40:07
2017-06-07T00:40:07
93,574,234
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Parkinglot; class UnparkCommand implements CommandInterface{ ParkAction parkingspot; Level level; public UnparkCommand(ParkAction i, Level c){ parkingspot = i; level = c; } public void execute(){ parkingspot.unpark(level); level.unpark(parkingspot); } }
UTF-8
Java
318
java
UnparkCommand.java
Java
[]
null
[]
package Parkinglot; class UnparkCommand implements CommandInterface{ ParkAction parkingspot; Level level; public UnparkCommand(ParkAction i, Level c){ parkingspot = i; level = c; } public void execute(){ parkingspot.unpark(level); level.unpark(parkingspot); } }
318
0.650943
0.650943
16
18
15.491934
48
false
false
0
0
0
0
0
0
1.1875
false
false
15
5abd39614a93e50adad667a0b81cef2b8861f6b4
30,124,900,644,148
efaf0b235fd0cdee92783f15d36a2d20d551bc16
/examples/src/main/java/net/crate/examples/Anaconda.java
c69fd31aae38e2a000a6ee261407d63c6437c3ff
[]
no_license
h908714124/crate
https://github.com/h908714124/crate
38ba13d36b9fea1fa45086caecf0c87c12f4b75c
137c7c2650f60cf8aebe86a8da13d07048e18687
refs/heads/master
2020-12-30T12:55:08.873000
2017-07-01T14:07:06
2017-07-01T14:07:06
91,365,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.crate.examples; import com.google.auto.value.AutoValue; import net.crate.AutoCrate; @AutoValue @AutoCrate abstract class Anaconda { abstract String name(); abstract boolean good(); static Anaconda_Crate builder() { return Anaconda_Crate.builder(); } }
UTF-8
Java
281
java
Anaconda.java
Java
[]
null
[]
package net.crate.examples; import com.google.auto.value.AutoValue; import net.crate.AutoCrate; @AutoValue @AutoCrate abstract class Anaconda { abstract String name(); abstract boolean good(); static Anaconda_Crate builder() { return Anaconda_Crate.builder(); } }
281
0.736655
0.736655
17
15.529411
14.422685
39
false
false
0
0
0
0
0
0
0.352941
false
false
15
979b6da8dcabe3ee3c11dc72720bda4d53e660a6
20,186,346,327,283
32f4fdd0d844f4191a72aea54e30805f5d15d38b
/app/src/test/java/com/example/servehumanity/UserBLLTest.java
e3b3306038e641b9140084495a1a1e359b65a272
[]
no_license
Bikash101kr/BloodDonation-Andriod-APP
https://github.com/Bikash101kr/BloodDonation-Andriod-APP
3ca092c6ddda1b07af58bb96d2a8250457a2445a
5c0447d0e42b16645f16ed1384f179bff51b9f86
refs/heads/master
2023-05-12T08:22:56.485000
2021-06-07T02:35:15
2021-06-07T02:35:15
374,509,030
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.servehumanity; import com.example.servehumanity.bll.ProfileBLL; import com.example.servehumanity.bll.UserBLL; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class UserBLLTest { String Id; @Before public void setUp(){ ProfileBLL profileBLL = new ProfileBLL("bikash", "dhakal", "2020-12-12", "address2", "Chitwan", "1234", "male", "B+", "image.jepg"); boolean res = profileBLL.addProfile(); if (res) { Id = ProfileBLL.id; } } @Test public void checkLogin() { UserBLL userBLL = new UserBLL("bikash", "12345" ); boolean res = userBLL.loginUser(); assertEquals(true, res); } @Test public void checkUserRegister() { UserBLL userBLL = new UserBLL("Bikash6", "password", "bikash33@gmail.com", Id); boolean res = userBLL.registerUser(); assertEquals(true, res); } }
UTF-8
Java
1,028
java
UserBLLTest.java
Java
[ { "context": "{\n ProfileBLL profileBLL = new ProfileBLL(\"bikash\", \"dhakal\", \"2020-12-12\",\n \"addres", "end": 402, "score": 0.9990763068199158, "start": 396, "tag": "USERNAME", "value": "bikash" }, { "context": "ProfileBLL profileBLL = new ProfileBLL(\"bikash\", \"dhakal\", \"2020-12-12\",\n \"address2\", \"Chit", "end": 412, "score": 0.9988219141960144, "start": 406, "tag": "USERNAME", "value": "dhakal" }, { "context": "kLogin() {\n UserBLL userBLL = new UserBLL(\"bikash\", \"12345\" );\n boolean res = userBLL.login", "end": 706, "score": 0.9995301365852356, "start": 700, "tag": "USERNAME", "value": "bikash" }, { "context": "gister() {\n UserBLL userBLL = new UserBLL(\"Bikash6\", \"password\", \"bikash33@gmail.com\", Id);\n ", "end": 898, "score": 0.999651312828064, "start": 891, "tag": "USERNAME", "value": "Bikash6" }, { "context": "BLL userBLL = new UserBLL(\"Bikash6\", \"password\", \"bikash33@gmail.com\", Id);\n boolean res = userBLL.registerUser", "end": 932, "score": 0.9834593534469604, "start": 914, "tag": "EMAIL", "value": "bikash33@gmail.com" } ]
null
[]
package com.example.servehumanity; import com.example.servehumanity.bll.ProfileBLL; import com.example.servehumanity.bll.UserBLL; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class UserBLLTest { String Id; @Before public void setUp(){ ProfileBLL profileBLL = new ProfileBLL("bikash", "dhakal", "2020-12-12", "address2", "Chitwan", "1234", "male", "B+", "image.jepg"); boolean res = profileBLL.addProfile(); if (res) { Id = ProfileBLL.id; } } @Test public void checkLogin() { UserBLL userBLL = new UserBLL("bikash", "12345" ); boolean res = userBLL.loginUser(); assertEquals(true, res); } @Test public void checkUserRegister() { UserBLL userBLL = new UserBLL("Bikash6", "password", "<EMAIL>", Id); boolean res = userBLL.registerUser(); assertEquals(true, res); } }
1,017
0.596304
0.575875
37
26.756756
24.307051
87
false
false
0
0
0
0
0
0
0.810811
false
false
15
0e96a4b41e8395bece843c72e3ecdda803af9dc5
4,947,802,357,834
49aac4867a44945874595c0dc2b544818276bd52
/Handy_Projects/UC5.0/vysper-core/src/main/java/com/hs/uc/protocol/http/impl/HttpIoHandlerAdapter.java
7965675729529ace7761b603862e15a30d8a6108
[]
no_license
inter999/milkyway
https://github.com/inter999/milkyway
d24c5596f6e66a9ce252bc652076764469bdfdde
e22e8a37f3616a828e0a9589d6aa7747480a82e4
refs/heads/master
2016-09-11T10:04:40.672000
2014-08-20T08:19:44
2014-08-20T08:19:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hs.uc.protocol.http.impl; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.vysper.xmpp.protocol.SessionStateHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hs.uc.protocol.HttpCommandProcessor; import com.hs.uc.protocol._native.NativeSessionContext; import com.hs.uc.protocol._native.command.NativeCommand; import com.hs.uc.server.ServerRuntimeContext; import com.hs.uc.server.SessionContext; import com.hs.uc.server.SessionContext.SessionTerminationCause; /** * @author kklim * @version 1.0 * @created 29-3-2013 오전 11:47:57 */ public class HttpIoHandlerAdapter implements IoHandler { private ServerRuntimeContext serverRuntimeContext; public static final String ATTRIBUTE_HTTP_SESSION_CONTEXT= "httpSessionContext"; public static final String ATTRIBUTE_HTTP_SESSIONSTATEHOLDER = "httpSessionStateHolder"; private Logger logger = LoggerFactory.getLogger(HttpIoHandlerAdapter.class); private static HttpIoHandlerAdapter thisInstance = null; public static synchronized HttpIoHandlerAdapter getInstance() { if(thisInstance == null) { thisInstance = new HttpIoHandlerAdapter(); } return thisInstance; } private HttpIoHandlerAdapter(){ } public ServerRuntimeContext getServerRuntimeContext() { return serverRuntimeContext; } public void setServerRuntimeContext(ServerRuntimeContext serverRuntimeContext) { this.serverRuntimeContext = serverRuntimeContext; } public void sessionCreated(IoSession session) throws Exception { SessionStateHolder stateHolder = new SessionStateHolder(); SessionContext nativeSessionContext = new NativeSessionContext(serverRuntimeContext, stateHolder, session); session.setAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT, nativeSessionContext); } public void sessionOpened(IoSession session) throws Exception { logger.info("new session from {} has been opened", session.getRemoteAddress()); } public void sessionClosed(IoSession session) throws Exception { SessionContext nativeSessionContext = (SessionContext) session.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT); if(nativeSessionContext !=null){ nativeSessionContext.endSession(SessionTerminationCause.CLIENT_BYEBYE); } } public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("session {} is idle", ((SessionContext) session.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT)).getSessionId()); } public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // TODO Auto-generated method stub } public void messageReceived(IoSession ioSession, Object message) throws Exception { if (!(message instanceof NativeCommand)){ logger.warn("Received a wrong http command: "+ message.toString()); } HttpCommand httpCommand = (HttpCommand) message; SessionContext sessionContext = (SessionContext) ioSession.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT); SessionStateHolder stateHolder = (SessionStateHolder) ioSession.getAttribute(ATTRIBUTE_HTTP_SESSIONSTATEHOLDER); // TODO - Need to review the the input string for getCommandProcessor() ((HttpCommandProcessor) serverRuntimeContext.getCommandProcessor(ServerRuntimeContext.PROTOCOL_HTTP)).processHttpCommand(serverRuntimeContext, sessionContext, httpCommand, stateHolder); } public void messageSent(IoSession session, Object message) throws Exception { // TODO Auto-generated method stub } }
UTF-8
Java
3,672
java
HttpIoHandlerAdapter.java
Java
[ { "context": "ontext.SessionTerminationCause;\r\n\r\n/**\r\n * @author kklim\r\n * @version 1.0\r\n * @created 29-3-2013 오전 11:47:", "end": 645, "score": 0.9995777606964111, "start": 640, "tag": "USERNAME", "value": "kklim" } ]
null
[]
package com.hs.uc.protocol.http.impl; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.vysper.xmpp.protocol.SessionStateHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hs.uc.protocol.HttpCommandProcessor; import com.hs.uc.protocol._native.NativeSessionContext; import com.hs.uc.protocol._native.command.NativeCommand; import com.hs.uc.server.ServerRuntimeContext; import com.hs.uc.server.SessionContext; import com.hs.uc.server.SessionContext.SessionTerminationCause; /** * @author kklim * @version 1.0 * @created 29-3-2013 오전 11:47:57 */ public class HttpIoHandlerAdapter implements IoHandler { private ServerRuntimeContext serverRuntimeContext; public static final String ATTRIBUTE_HTTP_SESSION_CONTEXT= "httpSessionContext"; public static final String ATTRIBUTE_HTTP_SESSIONSTATEHOLDER = "httpSessionStateHolder"; private Logger logger = LoggerFactory.getLogger(HttpIoHandlerAdapter.class); private static HttpIoHandlerAdapter thisInstance = null; public static synchronized HttpIoHandlerAdapter getInstance() { if(thisInstance == null) { thisInstance = new HttpIoHandlerAdapter(); } return thisInstance; } private HttpIoHandlerAdapter(){ } public ServerRuntimeContext getServerRuntimeContext() { return serverRuntimeContext; } public void setServerRuntimeContext(ServerRuntimeContext serverRuntimeContext) { this.serverRuntimeContext = serverRuntimeContext; } public void sessionCreated(IoSession session) throws Exception { SessionStateHolder stateHolder = new SessionStateHolder(); SessionContext nativeSessionContext = new NativeSessionContext(serverRuntimeContext, stateHolder, session); session.setAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT, nativeSessionContext); } public void sessionOpened(IoSession session) throws Exception { logger.info("new session from {} has been opened", session.getRemoteAddress()); } public void sessionClosed(IoSession session) throws Exception { SessionContext nativeSessionContext = (SessionContext) session.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT); if(nativeSessionContext !=null){ nativeSessionContext.endSession(SessionTerminationCause.CLIENT_BYEBYE); } } public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("session {} is idle", ((SessionContext) session.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT)).getSessionId()); } public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // TODO Auto-generated method stub } public void messageReceived(IoSession ioSession, Object message) throws Exception { if (!(message instanceof NativeCommand)){ logger.warn("Received a wrong http command: "+ message.toString()); } HttpCommand httpCommand = (HttpCommand) message; SessionContext sessionContext = (SessionContext) ioSession.getAttribute(ATTRIBUTE_HTTP_SESSION_CONTEXT); SessionStateHolder stateHolder = (SessionStateHolder) ioSession.getAttribute(ATTRIBUTE_HTTP_SESSIONSTATEHOLDER); // TODO - Need to review the the input string for getCommandProcessor() ((HttpCommandProcessor) serverRuntimeContext.getCommandProcessor(ServerRuntimeContext.PROTOCOL_HTTP)).processHttpCommand(serverRuntimeContext, sessionContext, httpCommand, stateHolder); } public void messageSent(IoSession session, Object message) throws Exception { // TODO Auto-generated method stub } }
3,672
0.770447
0.765812
102
33.960785
36.742058
187
false
false
0
0
0
0
0
0
1.5
false
false
15
e670e5b06a76eaf87d7a30548669c2d15182517c
32,573,032,005,567
eab084584e34ec065cd115139c346180e651c1c2
/src/test/java/v1/mst/MST10_01Test.java
64b44bf8367d2b24e9a57e71a6ffe66c8dc0a21f
[]
no_license
zhouyuan93/leetcode
https://github.com/zhouyuan93/leetcode
5396bd3a01ed0f127553e1e175bb1f725d1c7919
cc247bc990ad4d5aa802fc7a18a38dd46ed40a7b
refs/heads/master
2023-05-11T19:11:09.322000
2023-05-05T09:12:53
2023-05-05T09:12:53
197,735,845
0
0
null
false
2020-04-05T09:17:34
2019-07-19T08:38:17
2019-10-03T09:00:24
2020-04-05T09:17:33
42
0
0
0
Java
false
false
package v1.mst; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MST10_01Test { MST10_01 t; @BeforeEach void setUp() { t = new MST10_01(); } @Test void test_1() { int[] a = {1, 2, 3, 0, 0, 0}; int m = 3; int[] b = {2, 5, 6}; int n = 3; t.merge(a, m, b, n); int[] expected = {1, 2, 2, 3, 5, 6}; assertArrayEquals(expected, a); } @Test void test_2() { int[] a = {0}; int m = 0; int[] b = {1}; int n = 1; t.merge(a, m, b, n); int[] expected = {1}; assertArrayEquals(expected, a); } }
UTF-8
Java
730
java
MST10_01Test.java
Java
[]
null
[]
package v1.mst; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MST10_01Test { MST10_01 t; @BeforeEach void setUp() { t = new MST10_01(); } @Test void test_1() { int[] a = {1, 2, 3, 0, 0, 0}; int m = 3; int[] b = {2, 5, 6}; int n = 3; t.merge(a, m, b, n); int[] expected = {1, 2, 2, 3, 5, 6}; assertArrayEquals(expected, a); } @Test void test_2() { int[] a = {0}; int m = 0; int[] b = {1}; int n = 1; t.merge(a, m, b, n); int[] expected = {1}; assertArrayEquals(expected, a); } }
730
0.468493
0.417808
38
18.236841
13.965058
49
false
false
0
0
0
0
0
0
1.052632
false
false
15
6585c8b57ea8688405c9b84ef256e6df2b9f0c30
16,870,631,578,137
3fc6c0bf6525d2e1dd89221149c708f8f6136ea2
/src/main/java/ee/uustal/udisctransformer/configuration/WebConfiguration.java
4d9f3c55726e883b60ee11300dc2ed426036b2bb
[]
no_license
cardouken/udisctransformer
https://github.com/cardouken/udisctransformer
06378c26b7a50243d866f2ccdd2804b731579327
7e53e89240b852635105fbddbb36d71a32f413dd
refs/heads/master
2022-10-02T01:55:40.689000
2020-06-09T17:30:09
2020-06-09T17:30:09
270,727,789
1
0
null
false
2020-06-09T17:30:10
2020-06-08T15:49:49
2020-06-09T15:33:07
2020-06-09T17:30:10
96
0
0
0
Java
false
false
package ee.uustal.udisctransformer.configuration; import com.fasterxml.jackson.databind.ObjectMapper; import ee.uustal.udisctransformer.util.JsonUtility; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @EnableWebMvc @Configuration public class WebConfiguration implements WebMvcConfigurer { @Bean public ObjectMapper jacksonObjectMapper() { return JsonUtility.getSimpleMapper(); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MappingJackson2HttpMessageConverter(JsonUtility.getSimpleMapper())); } }
UTF-8
Java
993
java
WebConfiguration.java
Java
[]
null
[]
package ee.uustal.udisctransformer.configuration; import com.fasterxml.jackson.databind.ObjectMapper; import ee.uustal.udisctransformer.util.JsonUtility; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @EnableWebMvc @Configuration public class WebConfiguration implements WebMvcConfigurer { @Bean public ObjectMapper jacksonObjectMapper() { return JsonUtility.getSimpleMapper(); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MappingJackson2HttpMessageConverter(JsonUtility.getSimpleMapper())); } }
993
0.823766
0.821752
27
35.777779
30.889688
95
false
false
0
0
0
0
0
0
0.444444
false
false
15
02e92905ba4524ef0e2194d323c9fd8289a207a6
7,172,595,412,887
7e58ab664a481b926491d748878c1ef63dead120
/src/main/java/com/employee/EmployeeManagementWithEmbededDatabaseApplication.java
5255f5d9694fafb97fd1ebc0d18a6fdfa16b5ddf
[]
no_license
sunildora111/SpringBoot-Examples
https://github.com/sunildora111/SpringBoot-Examples
ff2f9ac0832d65ebdaa7830b313b2fa822d73b24
93216a5ac116f5484cbbf4f051a19bb08da8e881
refs/heads/springBoot-Derby-database-Example
2020-07-15T06:31:09.641000
2019-08-31T07:45:59
2019-08-31T07:45:59
205,500,635
0
0
null
false
2019-08-31T07:46:00
2019-08-31T05:35:00
2019-08-31T07:37:50
2019-08-31T07:45:59
0
0
0
0
Java
false
false
package com.employee; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.employee.entities.Employee; import com.employee.service.EmployeeService; @SpringBootApplication public class EmployeeManagementWithEmbededDatabaseApplication { public static void main(String[] args) { ConfigurableApplicationContext applicationContext=SpringApplication.run(EmployeeManagementWithEmbededDatabaseApplication.class, args); EmployeeService employeeservice=applicationContext.getBean("employeeService",EmployeeService.class); Employee emp=new Employee(); emp.setEmpName("omm sai"); emp.setEmpSalary(10000); employeeservice.createEmployee(emp); } }
UTF-8
Java
798
java
EmployeeManagementWithEmbededDatabaseApplication.java
Java
[ { "context": "\n\t\tEmployee emp=new Employee();\n\t\temp.setEmpName(\"omm sai\");\n\t\temp.setEmpSalary(10000);\n\t\temployeeservice.c", "end": 722, "score": 0.9755353331565857, "start": 715, "tag": "NAME", "value": "omm sai" } ]
null
[]
package com.employee; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.employee.entities.Employee; import com.employee.service.EmployeeService; @SpringBootApplication public class EmployeeManagementWithEmbededDatabaseApplication { public static void main(String[] args) { ConfigurableApplicationContext applicationContext=SpringApplication.run(EmployeeManagementWithEmbededDatabaseApplication.class, args); EmployeeService employeeservice=applicationContext.getBean("employeeService",EmployeeService.class); Employee emp=new Employee(); emp.setEmpName("<NAME>"); emp.setEmpSalary(10000); employeeservice.createEmployee(emp); } }
797
0.847118
0.840852
22
35.272728
34.88446
136
false
false
0
0
0
0
0
0
1.272727
false
false
15
efc3d4ef269e2b2f18851f355055ba03c2dc3afa
2,095,944,087,391
4644f9a6d529cab95d70d540679898b28f7ae51e
/Service/app/src/main/java/com/aclass/shishir/service/IntentServiceExample.java
dd82501861bd972c9163e9f28dc4fef9dcec466b
[]
no_license
shishirshivGitHub/Service
https://github.com/shishirshivGitHub/Service
9925fc41bc4b2dbbc43f3e2e1d5792099193d5c6
d56d0e984a4aac409098f384fa7cc21d435255d3
refs/heads/master
2021-01-19T21:01:53.433000
2017-04-18T07:28:03
2017-04-18T07:28:03
88,594,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aclass.shishir.service; import android.app.IntentService; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.ResultReceiver; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Button; /** * Created by pc on 4/4/2017. */ public class IntentServiceExample extends IntentService { public IntentServiceExample() { super("WorkerThread"); } @Override public void onCreate() { super.onCreate(); Log.e(" IntentService class " , Thread.currentThread().getName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { // Long Running Task Here ResultReceiver resultReceiver = intent.getParcelableExtra("resultReceiver"); Log.e(" IntentService class " , Thread.currentThread().getName()); int ctr = 0; do{ try { Thread.sleep(1000); } catch (InterruptedException e) { } ctr++; Log.e("increment the value -->> ", ctr + " "); }while (ctr < 10); Bundle bundle = new Bundle(); bundle.putString("value"," Counter Stops at " + ctr +" "); resultReceiver.send(18,bundle); } @Override public void onDestroy() { super.onDestroy(); Log.e(" IntentService class " , Thread.currentThread().getName()); } }
UTF-8
Java
1,489
java
IntentServiceExample.java
Java
[ { "context": ";\nimport android.widget.Button;\n\n/**\n * Created by pc on 4/4/2017.\n */\n\npublic class IntentServiceExamp", "end": 358, "score": 0.9901695847511292, "start": 356, "tag": "USERNAME", "value": "pc" } ]
null
[]
package com.aclass.shishir.service; import android.app.IntentService; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.ResultReceiver; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Button; /** * Created by pc on 4/4/2017. */ public class IntentServiceExample extends IntentService { public IntentServiceExample() { super("WorkerThread"); } @Override public void onCreate() { super.onCreate(); Log.e(" IntentService class " , Thread.currentThread().getName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { // Long Running Task Here ResultReceiver resultReceiver = intent.getParcelableExtra("resultReceiver"); Log.e(" IntentService class " , Thread.currentThread().getName()); int ctr = 0; do{ try { Thread.sleep(1000); } catch (InterruptedException e) { } ctr++; Log.e("increment the value -->> ", ctr + " "); }while (ctr < 10); Bundle bundle = new Bundle(); bundle.putString("value"," Counter Stops at " + ctr +" "); resultReceiver.send(18,bundle); } @Override public void onDestroy() { super.onDestroy(); Log.e(" IntentService class " , Thread.currentThread().getName()); } }
1,489
0.627938
0.617864
59
24.237288
23.669575
87
false
false
0
0
0
0
0
0
0.525424
false
false
15
a5c83748025acf89bb753dfa80e271d3b662fddb
15,874,199,171,722
cc93bbb1188269841671fbb754e478d13d3219c1
/app/src/main/java/com/example/dijonkariz/fotomwa/other/BottomNavigationViewBehaviour.java
23259b63d98dd0dcb0300106f341a621b9994099
[]
no_license
Dav1dMwang1/Fotomwa-Android
https://github.com/Dav1dMwang1/Fotomwa-Android
7a14ad1fe4edd43bb00e1b90edf687bf9ec998e1
80e34710aaf755107cfdba99780962c99d8a58c4
refs/heads/master
2020-08-05T07:11:24.335000
2019-11-23T18:17:42
2019-11-23T18:17:42
212,441,791
0
0
null
true
2019-10-02T21:09:26
2019-10-02T21:09:25
2019-09-17T13:26:57
2019-09-17T13:26:55
562
0
0
0
null
false
false
package com.example.dijonkariz.fotomwa.other; import android.content.Context; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.logging.Logger; public class BottomNavigationViewBehaviour extends CoordinatorLayout.Behavior<BottomNavigationView> { // private int height; final private static Logger log = Logger.getLogger(BottomNavigationViewBehaviour.class.getName()); public BottomNavigationViewBehaviour(Context context, AttributeSet attrs) { super(context, attrs); } public BottomNavigationViewBehaviour() { } // @Override // public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull BottomNavigationView child, int layoutDirection) { // height = child.getHeight(); // return super.onLayoutChild(parent, child, layoutDirection); // } @Override public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { return axes == ViewCompat.SCROLL_AXIS_VERTICAL; } // @Override // public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { // if (dyConsumed > 0) { // slideDown(child); // } else if (dyConsumed < 0) { // slideUp(child); // } // super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type); // } @Override public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type); child.setTranslationY(Math.max(0f, Math.min(child.getHeight(), child.getTranslationY() + dy))); } @Override public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull BottomNavigationView child, @NonNull View dependency) { if(dependency instanceof Snackbar.SnackbarLayout) { updateSnackbar(child, (Snackbar.SnackbarLayout)dependency); } return super.layoutDependsOn(parent, child, dependency); } private void updateSnackbar(View child, Snackbar.SnackbarLayout snackbarLayout) { if(snackbarLayout.getLayoutParams() instanceof CoordinatorLayout.LayoutParams) { CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams)snackbarLayout.getLayoutParams(); params.setAnchorId(child.getId()); params.anchorGravity = Gravity.TOP; params.gravity = Gravity.TOP; snackbarLayout.setLayoutParams(params); child.setVisibility(View.GONE); } } // private void slideUp(BottomNavigationView child) { // child.clearAnimation(); // child.animate().translationY(0).setDuration(200); // } // // private void slideDown(BottomNavigationView child) { // child.clearAnimation(); // child.animate().translationY(height).setDuration(200); // } }
UTF-8
Java
3,566
java
BottomNavigationViewBehaviour.java
Java
[ { "context": "package com.example.dijonkariz.fotomwa.other;\n\nimport android.content.Context;\ni", "end": 30, "score": 0.9984958171844482, "start": 20, "tag": "USERNAME", "value": "dijonkariz" } ]
null
[]
package com.example.dijonkariz.fotomwa.other; import android.content.Context; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.logging.Logger; public class BottomNavigationViewBehaviour extends CoordinatorLayout.Behavior<BottomNavigationView> { // private int height; final private static Logger log = Logger.getLogger(BottomNavigationViewBehaviour.class.getName()); public BottomNavigationViewBehaviour(Context context, AttributeSet attrs) { super(context, attrs); } public BottomNavigationViewBehaviour() { } // @Override // public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull BottomNavigationView child, int layoutDirection) { // height = child.getHeight(); // return super.onLayoutChild(parent, child, layoutDirection); // } @Override public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { return axes == ViewCompat.SCROLL_AXIS_VERTICAL; } // @Override // public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { // if (dyConsumed > 0) { // slideDown(child); // } else if (dyConsumed < 0) { // slideUp(child); // } // super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type); // } @Override public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type); child.setTranslationY(Math.max(0f, Math.min(child.getHeight(), child.getTranslationY() + dy))); } @Override public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull BottomNavigationView child, @NonNull View dependency) { if(dependency instanceof Snackbar.SnackbarLayout) { updateSnackbar(child, (Snackbar.SnackbarLayout)dependency); } return super.layoutDependsOn(parent, child, dependency); } private void updateSnackbar(View child, Snackbar.SnackbarLayout snackbarLayout) { if(snackbarLayout.getLayoutParams() instanceof CoordinatorLayout.LayoutParams) { CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams)snackbarLayout.getLayoutParams(); params.setAnchorId(child.getId()); params.anchorGravity = Gravity.TOP; params.gravity = Gravity.TOP; snackbarLayout.setLayoutParams(params); child.setVisibility(View.GONE); } } // private void slideUp(BottomNavigationView child) { // child.clearAnimation(); // child.animate().translationY(0).setDuration(200); // } // // private void slideDown(BottomNavigationView child) { // child.clearAnimation(); // child.animate().translationY(height).setDuration(200); // } }
3,566
0.722378
0.719574
85
40.952942
46.351574
217
false
false
0
0
0
0
0
0
0.929412
false
false
15
90903c1bcea6b43b508a1f0f61b5e9471e8d0ffa
30,107,720,755,942
badd49b1ab4cb1f2f0bfc0485918d9dd4abb9fa3
/src/main/java/com/codecool/networking/modes/MagicWords.java
b7f2051e0a9fecab3e95ce072cdafb551f144cc4
[]
no_license
jarqprog/netchat-project
https://github.com/jarqprog/netchat-project
bf7d87c1da90767cb259a98e75529b5c5603052f
c3c51a1bf2df48dd55cfc8414104885cdb094440
refs/heads/master
2020-07-08T19:13:12.274000
2018-07-31T14:33:09
2018-07-31T14:33:09
203,753,204
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codecool.networking.modes; public enum MagicWords { QUIT_CHAT_WORD(".END"); private String word; MagicWords(String word) { this.word = word; } public String getWord() { return word; } }
UTF-8
Java
243
java
MagicWords.java
Java
[]
null
[]
package com.codecool.networking.modes; public enum MagicWords { QUIT_CHAT_WORD(".END"); private String word; MagicWords(String word) { this.word = word; } public String getWord() { return word; } }
243
0.600823
0.600823
16
14.1875
13.375438
38
false
false
0
0
0
0
0
0
0.3125
false
false
15
f50f68bc32cf129507738f667d7430d09dfe7248
29,111,288,375,089
c9f8c84e8463b4c7920d91ba165a5df1d36db69d
/loriandroid/loriandroid-api/src/main/java/com/egorpetruchcho/loriandroid_api/model/Locale.java
612683989290ee790e49a9b46f7f644bb7c1e3ae
[ "Apache-2.0" ]
permissive
samara-university/lori-mobile-ponomarev
https://github.com/samara-university/lori-mobile-ponomarev
4b377739989584661887847cc1171d1b70bfc0e4
d7e2657e737966dbca253f4bd8a7e3e016385177
refs/heads/master
2020-02-29T10:16:12.582000
2016-12-17T07:42:54
2016-12-17T07:42:54
76,059,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.egorpetruchcho.loriandroid_api.model; public enum Locale { RU, EN }
UTF-8
Java
89
java
Locale.java
Java
[ { "context": "package com.egorpetruchcho.loriandroid_api.model;\n\npublic enum Local", "end": 18, "score": 0.7054132223129272, "start": 13, "tag": "USERNAME", "value": "gorpe" }, { "context": "package com.egorpetruchcho.loriandroid_api.model;\n\npublic enum Locale {\n ", "end": 26, "score": 0.547339916229248, "start": 20, "tag": "USERNAME", "value": "uchcho" } ]
null
[]
package com.egorpetruchcho.loriandroid_api.model; public enum Locale { RU, EN }
89
0.707865
0.707865
6
13.833333
17.023676
49
false
false
0
0
0
0
0
0
0.333333
false
false
15
07238d44d93ae8dfbe62280f62a007d78812ed53
19,172,734,053,477
d3339a361d0633ef9363ee5a11f81fad193b198e
/FileUpload/src/main/java/ssm/handle/JMSProducer.java
1e96a2991905b21b69fd5e38f0ffb7989028f916
[]
no_license
weiyangli/lwyCodeAdress
https://github.com/weiyangli/lwyCodeAdress
56bb5e9e5b2b221ae9a0dc26f8c5ee6c82f2d64d
d5a579827d46b273cb5fce7588b5e5d0b6dbfd66
refs/heads/master
2020-04-02T17:04:16.118000
2019-03-06T07:08:46
2019-03-06T07:08:46
154,642,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ssm.handle; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQObjectMessage; import ssm.bean.Student; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import java.io.Serializable; public class JMSProducer { //默认连接用户名 private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; //默认连接密码 private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; //默认连接地址 private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL; //发送的消息数量 private static final int SENDNUM = 1; public static void producerMessages(Student student) { //连接工厂 ConnectionFactory connectionFactory; //连接 Connection connection = null; //会话,接收或者发送消息的线程 Session session; //消息的目的地 Destination destination; //消息生产者 MessageProducer messageProducer; //实例化连接工厂 connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKERURL); try { //通过连接工厂获取连接 connection = connectionFactory.createConnection(); //启动连接 connection.start(); //创建session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); //创建一个名称为Hello World!的消息队列 destination = session.createQueue("student"); //创建消息生产者 messageProducer = session.createProducer(destination); //发送消息 sendMessage(session,messageProducer,student); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally{ if(connection != null){ try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } /** * 发送消息 * @param session * @param messageProducer 消息生产者 * @throws Exception */ public static void sendMessage(Session session,MessageProducer messageProducer, Student student) throws Exception{ for (int i = 0; i < JMSProducer.SENDNUM; i++) { //创建一条文本消息 ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage(); msg.setObject((Serializable) student); // TextMessage message = session.createTextMessage("activemq 发送消息:" + Text); System.err.println(student.getNickName()+"发送消息:activemq 发送消息:" + i); //通过消息生产者发出消息 messageProducer.send(msg); } } }
UTF-8
Java
3,117
java
JMSProducer.java
Java
[]
null
[]
package ssm.handle; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQObjectMessage; import ssm.bean.Student; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import java.io.Serializable; public class JMSProducer { //默认连接用户名 private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; //默认连接密码 private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; //默认连接地址 private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL; //发送的消息数量 private static final int SENDNUM = 1; public static void producerMessages(Student student) { //连接工厂 ConnectionFactory connectionFactory; //连接 Connection connection = null; //会话,接收或者发送消息的线程 Session session; //消息的目的地 Destination destination; //消息生产者 MessageProducer messageProducer; //实例化连接工厂 connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKERURL); try { //通过连接工厂获取连接 connection = connectionFactory.createConnection(); //启动连接 connection.start(); //创建session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); //创建一个名称为Hello World!的消息队列 destination = session.createQueue("student"); //创建消息生产者 messageProducer = session.createProducer(destination); //发送消息 sendMessage(session,messageProducer,student); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally{ if(connection != null){ try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } /** * 发送消息 * @param session * @param messageProducer 消息生产者 * @throws Exception */ public static void sendMessage(Session session,MessageProducer messageProducer, Student student) throws Exception{ for (int i = 0; i < JMSProducer.SENDNUM; i++) { //创建一条文本消息 ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage(); msg.setObject((Serializable) student); // TextMessage message = session.createTextMessage("activemq 发送消息:" + Text); System.err.println(student.getNickName()+"发送消息:activemq 发送消息:" + i); //通过消息生产者发出消息 messageProducer.send(msg); } } }
3,117
0.63078
0.630074
87
31.563219
26.470848
125
false
false
0
0
0
0
0
0
0.54023
false
false
15
2975ad53057f62f40c63d120ad2cd0093f89e8dd
29,472,065,609,229
928b95703aac5ae7ce30e3a7d30cce34d3b41275
/HW3_RecyclerView/app/src/main/java/inc0n3ck/hw3_recyclerview/Posts.java
99691af0241c3a6849bec3e0bffc69f9df8ad17e
[]
no_license
nobodylovesm3/homeworks
https://github.com/nobodylovesm3/homeworks
ddb69dab209f37ab47a1bc18344f25d64f592811
535732ac52834063dddf749b79398b296f1b41a5
refs/heads/master
2020-03-18T07:12:53.793000
2018-07-01T11:49:59
2018-07-01T11:49:59
134,439,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inc0n3ck.hw3_recyclerview; import android.graphics.drawable.Drawable; import android.widget.ImageButton; class Posts { public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getNumberOfLikes() { return numberOfLikes; } public String setNumberOfLikes(String numberOfLikes) { this.numberOfLikes = numberOfLikes; return numberOfLikes; } public String getNumberOfComments() { return numberOfComments; } public void setNumberOfComments(String numberOfComments) { this.numberOfComments = numberOfComments; } public Drawable getPicture() { return picture; } public void setPicture(Drawable picture) { this.picture = picture; } private String title; private String numberOfLikes; private String numberOfComments; private Drawable picture; public ImageButton getBtnCommentPost() { return btnCommentPost; } public void setBtnCommentPost(ImageButton btnCommentPost) { this.btnCommentPost = btnCommentPost; } private ImageButton btnCommentPost; public int getPictureId() { return pictureId; } public void setPictureId(int pictureId) { this.pictureId = pictureId; } private int pictureId; public Posts(String title, String numberOfLikes, String numberOfComments, int pictureId) { this.title = title; this.numberOfLikes = numberOfLikes; this.numberOfComments = numberOfComments; this.pictureId = pictureId; } }
UTF-8
Java
1,650
java
Posts.java
Java
[]
null
[]
package inc0n3ck.hw3_recyclerview; import android.graphics.drawable.Drawable; import android.widget.ImageButton; class Posts { public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getNumberOfLikes() { return numberOfLikes; } public String setNumberOfLikes(String numberOfLikes) { this.numberOfLikes = numberOfLikes; return numberOfLikes; } public String getNumberOfComments() { return numberOfComments; } public void setNumberOfComments(String numberOfComments) { this.numberOfComments = numberOfComments; } public Drawable getPicture() { return picture; } public void setPicture(Drawable picture) { this.picture = picture; } private String title; private String numberOfLikes; private String numberOfComments; private Drawable picture; public ImageButton getBtnCommentPost() { return btnCommentPost; } public void setBtnCommentPost(ImageButton btnCommentPost) { this.btnCommentPost = btnCommentPost; } private ImageButton btnCommentPost; public int getPictureId() { return pictureId; } public void setPictureId(int pictureId) { this.pictureId = pictureId; } private int pictureId; public Posts(String title, String numberOfLikes, String numberOfComments, int pictureId) { this.title = title; this.numberOfLikes = numberOfLikes; this.numberOfComments = numberOfComments; this.pictureId = pictureId; } }
1,650
0.670909
0.669091
74
21.297297
20.625837
94
false
false
0
0
0
0
0
0
0.391892
false
false
15