blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
049cc82e516ed7c5fb6d66e943d17f809455b1cc
26c6c550ba3bd7820f6db88ae7623ebff5fd5043
/src/test/java/org/lightchurch/ArchTest.java
f68291ab8af2ccb4fa2249ae30a82673c31dd52b
[]
no_license
thomas-mwania/lightchurch
0d1f1898a2f901a022ec91df6d371016a2b4208d
e761834dd679fa90ab3fa6287c63356a3275b5c4
refs/heads/main
2023-07-06T15:40:10.915993
2021-08-25T15:52:49
2021-08-25T15:52:49
397,502,428
0
0
null
2021-08-18T07:01:25
2021-08-18T06:52:54
Java
UTF-8
Java
false
false
1,012
java
package org.lightchurch; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import org.junit.jupiter.api.Test; class ArchTest { @Test void servicesAndRepositoriesShouldNotDependOnWebLayer() { JavaClasses importedClasses = new ClassFileImporter() .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) .importPackages("org.lightchurch"); noClasses() .that() .resideInAnyPackage("org.lightchurch.service..") .or() .resideInAnyPackage("org.lightchurch.repository..") .should() .dependOnClassesThat() .resideInAnyPackage("..org.lightchurch.web..") .because("Services and repositories should not depend on web layer") .check(importedClasses); } }
33108776522f335b62d983b80d0bceb64d40d57c
8e18afe58aa67ae847939d8cd4d556b0deda5ddf
/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/androidx/transition/R.java
ad4a7e59995cd26a06e3341a7284426402afde08
[]
no_license
Arab1997/TravelMantic
e496bc82b0b30d01b80b50299b6c8229f224dba4
0e0ec646a7110c28c71c445a7ea68b5b4374aabb
refs/heads/master
2022-11-26T14:35:24.548419
2019-08-04T11:52:48
2019-08-04T11:52:48
285,231,407
0
0
null
null
null
null
UTF-8
Java
false
false
11,116
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.transition; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f030027; public static final int font = 0x7f030103; public static final int fontProviderAuthority = 0x7f030105; public static final int fontProviderCerts = 0x7f030106; public static final int fontProviderFetchStrategy = 0x7f030107; public static final int fontProviderFetchTimeout = 0x7f030108; public static final int fontProviderPackage = 0x7f030109; public static final int fontProviderQuery = 0x7f03010a; public static final int fontStyle = 0x7f03010b; public static final int fontVariationSettings = 0x7f03010c; public static final int fontWeight = 0x7f03010d; public static final int ttcIndex = 0x7f03024a; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050083; public static final int notification_icon_bg_color = 0x7f050084; public static final int ripple_material_light = 0x7f05008f; public static final int secondary_text_default_material_light = 0x7f050091; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f060053; public static final int compat_button_inset_vertical_material = 0x7f060054; public static final int compat_button_padding_horizontal_material = 0x7f060055; public static final int compat_button_padding_vertical_material = 0x7f060056; public static final int compat_control_corner_material = 0x7f060057; public static final int compat_notification_large_icon_max_height = 0x7f060058; public static final int compat_notification_large_icon_max_width = 0x7f060059; public static final int notification_action_icon_size = 0x7f0600d2; public static final int notification_action_text_size = 0x7f0600d3; public static final int notification_big_circle_margin = 0x7f0600d4; public static final int notification_content_margin_start = 0x7f0600d5; public static final int notification_large_icon_height = 0x7f0600d6; public static final int notification_large_icon_width = 0x7f0600d7; public static final int notification_main_column_padding_top = 0x7f0600d8; public static final int notification_media_narrow_margin = 0x7f0600d9; public static final int notification_right_icon_size = 0x7f0600da; public static final int notification_right_side_padding_top = 0x7f0600db; public static final int notification_small_icon_background_padding = 0x7f0600dc; public static final int notification_small_icon_size_as_large = 0x7f0600dd; public static final int notification_subtext_size = 0x7f0600de; public static final int notification_top_pad = 0x7f0600df; public static final int notification_top_pad_large_text = 0x7f0600e0; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f07009f; public static final int notification_bg = 0x7f0700a0; public static final int notification_bg_low = 0x7f0700a1; public static final int notification_bg_low_normal = 0x7f0700a2; public static final int notification_bg_low_pressed = 0x7f0700a3; public static final int notification_bg_normal = 0x7f0700a4; public static final int notification_bg_normal_pressed = 0x7f0700a5; public static final int notification_icon_background = 0x7f0700a6; public static final int notification_template_icon_bg = 0x7f0700a7; public static final int notification_template_icon_low_bg = 0x7f0700a8; public static final int notification_tile_bg = 0x7f0700a9; public static final int notify_panel_notification_icon_bg = 0x7f0700aa; } public static final class id { private id() {} public static final int action_container = 0x7f090032; public static final int action_divider = 0x7f090035; public static final int action_image = 0x7f090036; public static final int action_text = 0x7f09003d; public static final int actions = 0x7f09003e; public static final int async = 0x7f090047; public static final int blocking = 0x7f09004b; public static final int chronometer = 0x7f090063; public static final int forever = 0x7f09009f; public static final int ghost_view = 0x7f0900a2; public static final int icon = 0x7f0900ac; public static final int icon_group = 0x7f0900ad; public static final int info = 0x7f0900b1; public static final int italic = 0x7f0900b5; public static final int line1 = 0x7f0900bb; public static final int line3 = 0x7f0900bc; public static final int normal = 0x7f0900cf; public static final int notification_background = 0x7f0900d0; public static final int notification_main_column = 0x7f0900d1; public static final int notification_main_column_container = 0x7f0900d2; public static final int parent_matrix = 0x7f0900dc; public static final int right_icon = 0x7f0900eb; public static final int right_side = 0x7f0900ec; public static final int save_image_matrix = 0x7f0900ef; public static final int save_non_transition_alpha = 0x7f0900f0; public static final int save_scale_type = 0x7f0900f1; public static final int tag_transition_group = 0x7f090125; public static final int tag_unhandled_key_event_manager = 0x7f090126; public static final int tag_unhandled_key_listeners = 0x7f090127; public static final int text = 0x7f090128; public static final int text2 = 0x7f090129; public static final int time = 0x7f090132; public static final int title = 0x7f090133; public static final int transition_current_scene = 0x7f09013b; public static final int transition_layout_save = 0x7f09013c; public static final int transition_position = 0x7f09013d; public static final int transition_scene_layoutid_cache = 0x7f09013e; public static final int transition_transform = 0x7f09013f; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f0a0010; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0c004b; public static final int notification_action_tombstone = 0x7f0c004c; public static final int notification_template_custom_big = 0x7f0c0053; public static final int notification_template_icon_group = 0x7f0c0054; public static final int notification_template_part_chronometer = 0x7f0c0058; public static final int notification_template_part_time = 0x7f0c0059; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f1000b4; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f110143; public static final int TextAppearance_Compat_Notification_Info = 0x7f110144; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f110146; public static final int TextAppearance_Compat_Notification_Time = 0x7f110149; public static final int TextAppearance_Compat_Notification_Title = 0x7f11014b; public static final int Widget_Compat_NotificationActionContainer = 0x7f1101f5; public static final int Widget_Compat_NotificationActionText = 0x7f1101f6; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f030105, 0x7f030106, 0x7f030107, 0x7f030108, 0x7f030109, 0x7f03010a }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f030103, 0x7f03010b, 0x7f03010c, 0x7f03010d, 0x7f03024a }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
e67bb628b3b98f12e99db2fcff4fbbf94599ab26
54c9f7f2f7afadcdddba1d5ffe1b97e1694e4c29
/bootx-api/src/main/java/com/bootx/app/zhishifufei/pojo/All.java
c31fbc255e57c0c9240a6b8c2624ffbb0daec50c
[]
no_license
blackboy1987/min-program
37cf2630a91a166b7b409178273f176f0fc10ab8
0babf400000c890d1dcc3fadc58c2fae34c005d6
refs/heads/master
2023-04-23T12:52:07.208957
2021-05-11T15:02:59
2021-05-11T15:02:59
351,773,393
0
0
null
null
null
null
UTF-8
Java
false
false
3,304
java
package com.bootx.app.zhishifufei.pojo; import com.bootx.util.HtmlParseUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class All implements Serializable { private String code; private List<Msg> msg; public void setCode(String code) { this.code = code; } public String getCode() { return code; } public void setMsg(List<Msg> msg) { this.msg = msg; } public List<Msg> getMsg() { return msg; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Msg implements Serializable { private Long id; private Integer type; private Long tid; private Integer hot; private String title; private String picname; private String content; private Integer count; private String dizhi; private BigDecimal price; private Date addtime; private Integer status; private Integer fenxiang; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setType(Integer type) { this.type = type; } public Integer getType() { return type; } public void setTid(Long tid) { this.tid = tid; } public Long getTid() { return tid; } public void setHot(Integer hot) { this.hot = hot; } public Integer getHot() { return hot; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setPicname(String picname) { this.picname = picname; } public String getPicname() { return picname; } public void setContent(String content) { this.content = HtmlParseUtils.parse(content); } public String getContent() { return HtmlParseUtils.parse(content); } public void setCount(Integer count) { this.count = count; } public Integer getCount() { return count; } public void setDizhi(String dizhi) { this.dizhi = dizhi; } public String getDizhi() { return dizhi; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getPrice() { return price; } public void setAddtime(Date addtime) { this.addtime = new Date(addtime.getTime()*1000); } public Date getAddtime() { return addtime; } public void setStatus(Integer status) { this.status = status; } public Integer getStatus() { return status; } public void setFenxiang(Integer fenxiang) { this.fenxiang = fenxiang; } public Integer getFenxiang() { return fenxiang; } } }
[ "Liziyi521521" ]
Liziyi521521
b90e0bbd06f95ed30fe1b30e9ca2d39c3c0bed9c
eb06d6fdb4975eac4dd682355724faf1345329cc
/union-ejemplo/src/crawling/NodoPagina.java
d6256fac6be25f93a8c3d26cb28406e6f8d01db6
[]
no_license
ikariset/tesis-manuel
f885e2d1c567bf54f9042fff6884298373f4c079
83c475d961b3044974ea2eb11d286ba66a35a7d6
refs/heads/master
2020-03-09T14:58:35.552533
2018-04-10T00:50:07
2018-04-10T00:50:07
128,848,479
1
0
null
null
null
null
UTF-8
Java
false
false
4,304
java
package crawling; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Scanner; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class NodoPagina { //Cantidad de nodos hijos que se poseen private int CantNodos = 0; //Sitio web actual en el nodo private Document website; //Arreglo de elementos que la página puede tener private Elements librerias; //Librerías utilizadas private Elements links; //Vínculos utilizados en página private Elements medios; //Recursos de medios usados //Directorios en donde se alojarán la información de los links private String dirPadre; private String dirCache; //Nodos hijos del nodo actual private ArrayList <NodoPagina> hijos; public NodoPagina(String link, String dirPadre, String dirCache) throws IOException { /*1. Se conecta al nodo pedido *2. Vuelca los recursos requeridos del nodo *3. Genera el documento actual *4. Si links.lenght es mayor que cero, por cada link *4.1. Crea el directorio hijo donde se alojarán los nodos hijo *4.1. Crea un Nodo nuevo por cada link hijo *4. Si no *4.2. Hace nada*/ //1 this.website = Jsoup.connect(link).get(); //2 this.links = this.website.select("a[href]"); this.librerias = this.website.select("links[href]"); this.medios = this.website.select("[src]"); this.dirPadre = dirPadre + website.title() + File.separator; this.dirCache = dirCache + File.separator; //this.createDirPadre(); this.createParsedDoc(); this.createChildsNodes(); } private Boolean createParsedDoc() throws IOException { Boolean resultado = false; File salida = new File(dirPadre + File.separator + website.title() + ".txt"); FileOutputStream content = new FileOutputStream(salida); salida.canWrite(); content.write( this.website.select(".container").text().getBytes(Charset.forName("UTF-8")) ); if(salida.createNewFile()) resultado = true; //System.out.println(salida.getCanonicalPath()); content.close(); return resultado; } private void createDirSons(String sondir){ File salida = new File(dirPadre + File.separator + sondir); salida.getParentFile().mkdirs(); } private void createChildsNodes() { try { if(!this.links.isEmpty()) { for(Element link: this.links) { if(this.CantNodos == 0) createDirSons(link.text() + "_childs"); NodoPagina aux = new NodoPagina(link.attr("abs:href"), this.dirPadre + File.separator + link.text() + "_childs" + File.separator, this.dirCache); if(this.writeToCache(aux.website.text())){ this.hijos.add(aux); System.out.println("Enlace " + link.attr("abs:href") + " agregado exitosamente"); } else System.out.println("Enlace " + link.attr("abs:href") + " no agregado a hijos, se encuentra en caché"); //System.out.println("text: " + link.text() + "\n"); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Boolean writeToCache(String link) { File cache = new File(this.dirCache + "vispags.txt"); Boolean resultado = false; try { Scanner rc = new Scanner(this.dirCache + "vispags.txt"); FileOutputStream wc = new FileOutputStream(cache); Boolean cont = true; cache.canWrite(); cache.canRead(); do { if(!rc.nextLine().equals(link)) { Files.write( Paths.get(this.dirCache + "vispags.txt"), link.getBytes(Charset.forName("UTF-8")), StandardOpenOption.APPEND ); cont = false; resultado = true; } } while(rc.hasNextLine() && cont); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultado; } public Elements getLinks() { return this.links; } public Document getWebsite() { return website; } public String getDirPadre() { return dirPadre; } }
ef81b390f262941351f768067ff0394da062e216
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_26648.java
e1fc0271f66fcb789dc2af95fb38573d2309a364
[]
no_license
P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606717
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
232
java
@Override @Nullable public Choice<Unifier> visitDoWhileLoop(DoWhileLoopTree loop,@Nullable Unifier unifier){ return getStatement().unify(loop.getStatement(),unifier).thenChoose(unifications(getCondition(),loop.getCondition())); }
939ed1239d9aa7a1843d82ec0cb23570c3c06cab
66996eb68c6e0ac6cd86e15ea9e95b165ae4786f
/app/src/main/java/com/bbk/open/helloretrofit/retrofit/activity/RetrofitActivity.java
89ce4c4cc621abb6b661b7070cfd516bbc2ab107
[]
no_license
ProHzen/HelloRetrofit
b0b55f9fe1351d66a136ed29a4b42fac81d57ffc
f88e3004bf1369bf8880e8f7c56b540cb8073998
refs/heads/master
2021-01-19T04:24:39.888548
2016-08-20T09:33:30
2016-08-20T09:33:30
65,470,719
0
0
null
null
null
null
UTF-8
Java
false
false
4,500
java
package com.bbk.open.helloretrofit.retrofit.activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.bbk.open.helloretrofit.R; import com.bbk.open.helloretrofit.retrofit.subscribers.ProgressSubscriber; import com.bbk.open.helloretrofit.retrofit.entity.RetrofitEnity; import com.bbk.open.helloretrofit.retrofit.entity.Subject; import com.bbk.open.helloretrofit.retrofit.entity.SubjectPost; import com.bbk.open.helloretrofit.retrofit.http.HttpManager; import com.bbk.open.helloretrofit.retrofit.http.HttpService; import com.bbk.open.helloretrofit.retrofit.listener.HttpOnNextListener; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Administrator on 2016/8/12. */ public class RetrofitActivity extends AppCompatActivity implements View.OnClickListener { private TextView tvMsg; private static final String TAG = "RetrofitActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrofit); tvMsg = (TextView) findViewById(R.id.tv_msg); ((Button)findViewById(R.id.btn_simple)).setOnClickListener(this); ((Button)findViewById(R.id.btn_rx)).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_simple: onButtonClick(); break; case R.id.btn_rx: simpleDo(); break; } } /** * Retrofit 加入RxJava實現http请求 */ private void onButtonClick() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(5, TimeUnit.SECONDS); Retrofit retrofit = new Retrofit.Builder() .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(HttpManager.BASE_URL) .build(); final ProgressDialog pd = new ProgressDialog(this); HttpService apiService = retrofit.create(HttpService.class); Observable<RetrofitEnity> observable = apiService.getAllVideoBy(true); observable.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<RetrofitEnity>() { @Override public void onCompleted() { if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onError(Throwable e) { Log.e(TAG, "onError: " + e.toString() ); if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onNext(RetrofitEnity retrofitEnity) { tvMsg.setText("无封装:\n" + retrofitEnity.getData().toString()); } @Override public void onStart() { super.onStart(); pd.show(); } }); } HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<List<Subject>>() { @Override public void onNext(List<Subject> subjects) { tvMsg.setText("已封装:\n" + subjects.toString()); } }; /** * 完美封装简化版 */ private void simpleDo() { SubjectPost postEntity = new SubjectPost( new ProgressSubscriber(simpleOnNextListener, this), true); HttpManager manager = HttpManager.getInstance(); manager.doHttpDeal(postEntity); } }
ee544cc47f30d03bfb7d34b331dcc427a7b6c7cc
bbaca79c775974b9042062acb180d6e076a52de6
/src/tr/org/linux/kamp/string/HelloString.java
bb088348ca7c34a3665418dd41243c7054748929
[]
no_license
ozakdeniz/LYK17.2
f2a00b01a259d4386a84f4cad67d413e88ec6646
c25d5b41ed66e277718169df8a244e4315729b26
refs/heads/master
2021-01-01T18:24:07.480469
2017-07-25T17:01:29
2017-07-25T17:01:29
98,325,698
0
0
null
null
null
null
UTF-8
Java
false
false
3,212
java
package tr.org.linux.kamp.string; public class HelloString { public static void main(String[] args) { // TODO Auto-generated method stub String str = Integer.toString(1555579256); System.out.println(str); String hello = "Hello world!"; System.out.println(hello); System.out.println(hello.toUpperCase()); System.out.println(hello); String a = "hello"; String b = "hello"; boolean karsi = "hello" == "hello" ; boolean karsiab = a == b; System.out.println(karsi); System.out.println(karsiab); String c = new String("hello"); String d = new String("hello"); System.out.println(c==d); System.out.println(hello.substring(hello.indexOf(' ')+1,hello.length())); System.out.println(hello.indexOf(' ')); System.out.println(hello.charAt(hello.length()-1)); System.out.println(hello.indexOf('e')); //ilk e nin değerini verir. System.out.println(hello.indexOf('l',3)); } } /*public class HelloString { public static void main(String[] args) { String str = "hello,world"; /*String str = Integer.toString(115); System.out.println(str);*/ /*System.out.println(str.charAt(11)); String str = "hello world"; System.out.println(str.substring(0, 11)); System.out.println(str.indexOf("eleman")); System.out.println(str.indexOf("el")); System.out.println(str.indexOf("tri")); System.out.println(str.substring(str.indexOf(" ")+ 1, str.lastIndexOf(" "))); System.out.println(str.substring(0, 2)=="he"); System.out.println(str.substring(0, 2).equals("he"));//equalsı tercih etmeliyiz //System.out.println(reverseString(str)); System.out.println(ourToUpperCase(str).equals(str.toUpperCase())); public static String ourToUpperCase(String str) { String result = ""; for(int i=0 ; i<str.length() ; i++) { result += Character.toUpperCase(str.charAt(i)); } return result; } public static String reverseString(String str) { String result = ""; /*for(int i =str.length()-1; i>= 0; i--) { result += str.charAt(i); } for(int i=0; i<str.length(); i++) { result+= str.charAt(str.length()-1-1); } return result; } } /////////// public class Stiring { public static void main(String[] args) { // TODO Auto-generated method stub String str = Integer.toString(1555579256); System.out.println(str); String hello = "hello world!"; System.out.println(hello); System.out.println(hello.toUpperCase()); System.out.println(hello); String a = "hello"; String b = "hello"; boolean karsi = "hello" == "hello" ; boolean karsiab = a == b; //System.out.println(karsi); System.out.println(karsiab); String c = new String("hello"); String d = new String("hello"); System.out.println(c==d); System.out.println(hello.substring(hello.indexOf(' ')+1,hello.length())); System.out.println(hello.indexOf(' ')); System.out.println(hello.charAt(hello.length()-1)); System.out.println(hello.indexOf('e')); //ilk e nin değerini verir. System.out.println(hello.indexOf('l',3)); System.out.println(hello.substring(0,2) == "he"); System.out.println(hello.substring(0,2).equals("he")); } } */
b843412d6a843c880fe23ece0fa30aa50eb966e2
4dc05ed9011c1fe1f7e27c70cd193cc3be88076a
/core/src/main/java/com/dajudge/buql/analyzer/select/BaseSelectAnalyzer.java
62b5c7e36da289b7e631ed56a59ee5b78e7abe1d
[]
no_license
dajudge/BuQL
4742b5e3c358cff924ecbd481bdeba66f7bc94e4
3bc42d19f567fa891775c9b08f99cfd951b83e32
refs/heads/master
2020-07-13T04:12:21.138138
2019-10-30T21:20:33
2019-10-30T21:20:33
204,985,661
1
0
null
null
null
null
UTF-8
Java
false
false
2,881
java
package com.dajudge.buql.analyzer.select; import com.dajudge.buql.analyzer.api.Analyzer; import com.dajudge.buql.analyzer.methodmatcher.MethodMatcher; import com.dajudge.buql.analyzer.methodmatcher.MethodMatcherResult; import com.dajudge.buql.reflector.ReflectSelectQuery; import com.dajudge.buql.reflector.model.select.MethodSelectModel; import com.dajudge.buql.reflector.model.select.ResultTypeModel; import com.dajudge.buql.reflector.predicate.ReflectorPredicate; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.regex.Matcher; import static com.dajudge.buql.reflector.model.select.SelectMethodModelTranslator.translateMethodModelToQuery; import static com.dajudge.buql.util.StringUtils.lowercaseFirstLetter; public abstract class BaseSelectAnalyzer<Q, R> implements Analyzer { private final MethodMatcher methodMatcher; BaseSelectAnalyzer(final MethodMatcher methodMatcher) { this.methodMatcher = methodMatcher; } @Override public Optional<ReflectSelectQuery<?, ?>> convert(final String tableName, final Method method) { return methodMatcher.match(method).map(result -> createQuery(tableName, result)); } private ReflectSelectQuery<Q, R> createQuery(final String tableName, final MethodMatcherResult methodMatcherResult) { final Matcher methodNameMatcher = methodMatcherResult.methodNameMatcher(); final Class<Q> actualQueryClass = (Class<Q>) methodMatcherResult.getParameterType(0); final Class<R> actualResultClass = (Class<R>) methodMatcherResult.getReturnType(); final String queryFieldName = lowercaseFirstLetter(methodNameMatcher.group(2)); final ReflectorPredicate predicate = createPredicate(actualQueryClass, queryFieldName); final String resultFieldName = lowercaseFirstLetter(methodNameMatcher.group(1)); final ResultTypeModel<R> resultFieldsModel = createResultFieldsModel(actualResultClass, resultFieldName); final MethodSelectModel<Q, R> model = new MethodSelectModel<>( predicate, tableName, resultFieldsModel.getResultFields(), resultFieldsModel::newResultInstance, createPreProcessor(), createPostProcessor() ); return translateMethodModelToQuery(model); } protected abstract Function<Object, Map<String, Q>> createPreProcessor(); protected abstract ResultTypeModel<R> createResultFieldsModel( final Class<R> clazz, final String resultFieldName ); protected abstract Function<Map<String, List<R>>, ?> createPostProcessor(); protected abstract ReflectorPredicate createPredicate( final Class<?> actualQueryClass, final String predicateName ); }
3a22814595473ee52751dd3e6d06ca867dd466eb
6c2b1450331bd8689ab32722857c6193589b7812
/src/main/java/jython/JythonDemo.java
67a8d8e1e01e9f60620fadb78b61c4a0c0a3d6a4
[]
no_license
huoyan56789/ares-fun
072d90f97c8f62c0a14007bb9cb75f0b90253a91
950fbb76c76bc6fd1a6e015499699ebb4c82a485
refs/heads/master
2020-04-07T19:54:01.640415
2018-11-16T09:28:17
2018-11-16T09:28:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,780
java
package jython; import org.python.core.Py; import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; /** * @Author Ares * @Date 2018/11/9 1:33 * @Description: * @Version JDK 1.8 */ public class JythonDemo { public static void main(String[] args) throws UnsupportedEncodingException { //python运行环境变量 PySystemState sys = Py.getSystemState(); sys.path.add("D:\\Master\\Python27\\Lib\\site-packages"); // System.out.println(sys.path.toString()); //调试第三方库 // PythonInterpreter python = new PythonInterpreter(); // python.exec("import qrcode"); String pyFile = "D:\\Projects\\PycharmProjects\\ares_fun\\test_net.py"; String[] arguments = {pyFile, ""}; PythonInterpreter.initialize(System.getProperties(), System.getProperties(), arguments); PythonInterpreter python = new PythonInterpreter(); StringWriter out = new StringWriter(); python.setOut(out); python.execfile(pyFile); //转码 String result = new String(out.toString().getBytes("iso8859-1"), "utf-8"); System.out.println(result); // 获取文件中的函数 PyFunction function = (PyFunction) python.get("hello", PyFunction.class); //调用Python中的方法 //传参有中文时设置中文编码方式 PyString pySex = Py.newStringUTF8(""); PyInteger pyage = new PyInteger(1); PyObject pyobject = function.__call__(pySex, pyage); } }
711508b3583090c1a0b9bfb7bd11f1eba3e56537
743410445012a9f8ba35a73c18a88af30ee74c7a
/app/src/test/java/com/mobileapps/brad/songscroller/ExampleUnitTest.java
799f741637a407d59f5225d81dc57bd519b42c53
[]
no_license
davidbkeith/SongScroller
395728a40f4f7c4436622249dcf20f2c7c6cc03b
f8691c2d24746591254d6b59d5987ee03dd35361
refs/heads/master
2018-09-30T18:08:16.863679
2018-06-13T21:40:16
2018-06-13T21:40:16
118,771,596
0
0
null
null
null
null
UTF-8
Java
false
false
410
java
package com.mobileapps.brad.songscroller; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
a0650886b6b8782bd090dbe336819a44e3f77605
6c8a37fff9c485377b50ff50c51413b906d37529
/yrbase/src/main/java/com/yrbase/baseactivity/utils/AppManager.java
395c7c47456499663f3f0b9867b94145e75b36a3
[]
no_license
yangruikico/BaseService
7f8501098085eba3bf8a19c9b8d2a66c112b5b4f
301596b4cd7d4e7b5c9110d7e5bd778cb43ac9fb
refs/heads/master
2020-07-09T15:02:47.116895
2020-05-07T01:37:56
2020-05-07T01:37:56
204,003,755
1
0
null
null
null
null
UTF-8
Java
false
false
4,793
java
package com.yrbase.baseactivity.utils; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import java.util.Stack; /** * activity管理 */ public class AppManager { private static Stack<Activity> activityStack; private volatile static AppManager instance; public static Context applicationContext; private AppManager() { } /** * 单一实例 */ public static AppManager getAppManager() { if (instance == null) { synchronized (AppManager.class) { if (instance == null) { instance = new AppManager(); instance.activityStack = new Stack(); } } } return instance; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack<Activity>(); } activityStack.add(activity); if (applicationContext == null) { applicationContext = activity.getApplicationContext(); } } /** * 获取栈中activity数量 */ public int getActivitySize() { if (activityStack == null) { return 0; } return activityStack.size(); } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { try { Activity activity = activityStack.lastElement(); return activity; } catch (Exception e) { // e.printStackTrace(); return null; } } /** * 获取当前Activity的前一个Activity */ public Activity preActivity() { int index = activityStack.size() - 2; if (index < 0) { return null; } Activity activity = activityStack.get(index); return activity; } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity.finish(); activity = null; } } /** * 移除指定的Activity */ public void removeActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity = null; } } /** * 结束指定类名的Activity */ public void finishActivity(Class<?> cls) { try { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } catch (Exception e) { e.printStackTrace(); } } /** * 结束所有Activity */ public void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } activityStack.clear(); } /** * 返回到指定的activity * * @param cls */ public void returnToActivity(Class<?> cls) { while (activityStack.size() != 0) if (activityStack.peek().getClass() == cls) { break; } else { finishActivity(activityStack.peek()); } } /** * 是否已经打开指定的activity * * @param cls * @return */ public boolean isOpenActivity(Class<?> cls) { if (activityStack != null) { for (int i = 0, size = activityStack.size(); i < size; i++) { if (cls == activityStack.peek().getClass()) { return true; } } } return false; } /** * 退出应用程序 * * @param context 上下文 * @param isBackground 是否开开启后台运行 */ public void AppExit(Context context, Boolean isBackground) { try { finishAllActivity(); ActivityManager activityMgr = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); activityMgr.restartPackage(context.getPackageName()); } catch (Exception e) { } finally { // 注意,如果您有后台程序运行,请不要支持此句子 if (!isBackground) { System.exit(0); } } } }
6d6e5080f70b2a413cd42798a7cfc6c9f415b014
956bfb69ec50143a6a2c62adb9883a9c5fe14623
/simplistic-rss/src/main/java/com/hahattpro/simplistic_rss/RssItem.java
4e4d068ba0cf96d03c24aea22874b46783127bd8
[]
no_license
ttpro1995/Android_RssExample
2c4bc93bd3d917094ea99b6074526a707fe6df3f
be89e5953aa279d924f0fa3e56f851c4dbc4e920
refs/heads/master
2021-07-23T23:01:19.178408
2015-08-01T14:50:39
2015-08-01T14:50:39
39,845,424
0
0
null
2020-07-21T12:10:26
2015-07-28T16:31:37
Java
UTF-8
Java
false
false
1,361
java
package com.hahattpro.simplistic_rss; /* * Copyright (C) 2014 Shirwa Mohamed <[email protected]> * * 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. */ public class RssItem { String title; String description; String link; String imageUrl; public String getDescription() { return description; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getTitle() { return title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public void setDescription(String description) { this.description = description; } public void setTitle(String title) { this.title = title; } }
99e0d712ce57a9de9a584988b7a7a594026ba91b
892098bd319450abb1a2c4e1b898997799a343a8
/Hup2/src/com/hubPlayer/ui/PlayPanel.java
35567ab6d8e80e9837fad644ba5a4ba9e52a928e
[]
no_license
Pas-demain/java-music
9fb5407cbdf330dbbafb562ab87fe2b4f55442e1
d31b1c8c6e1cbfbdeb432fdbba94d4aed3b0a7f5
refs/heads/master
2020-06-03T09:59:20.352736
2019-06-12T08:32:16
2019-06-12T08:34:26
191,529,226
0
0
null
null
null
null
GB18030
Java
false
false
21,736
java
package com.hubPlayer.ui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.HttpURLConnection; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.LayoutStyle; import javax.swing.SwingConstants; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.JFrame; import com.hubPlayer.player.HigherPlayer; import com.hubPlayer.song.SongNode; import com.hubPlayer.ui.tool.IconButton; import com.hubPlayer.ui.tool.TimeProgressBar; /* * 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. */ /** * 播放面板 使用NetBean Matisse构建.面板包含:3个标签,7个按钮,1个进度条,1个组合框和1个滑块条 * */ public class PlayPanel extends JPanel { /** * Creates new form HubPlayPanel */ public PlayPanel() { initComponents(); initPlayer(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { songName = new JLabel("VAGU Music"); download = new IconButton("下载", "icon/下载.png"); mark = new IconButton("我喜欢", "icon/爱心.png"); share = new IconButton("分享", "icon/分享h.png"); timerProgressBar = new TimeProgressBar(); mode = new JComboBox<>(); backPlay = new IconButton("上一首", "icon/上一首.png"); play = new IconButton("播放", "icon/播放.png"); play.setSelectedIcon(new ImageIcon("icon/暂停.png")); play.setDisabledSelectedIcon(new ImageIcon("icon/播放.png")); play.setMnemonic(KeyEvent.VK_ENTER); frontPlay = new IconButton("下一首", "icon/下一首.png"); voiceControl = new IconButton("静音", "icon/喇叭.png"); voiceAdjust = new JSlider(minVoice, maxVoice); voiceAdjust.setValue(suitableVoice); audioTotalTimeLabel = new JLabel("4:00"); currentTimeCountLabel = new JLabel("0:00"); setOpaque(true); setBackground(Color.PINK); setPreferredSize(new Dimension(360, 110)); download.setMaximumSize(new Dimension(3030, 3030)); download.setMinimumSize(new Dimension(30, 30)); download.setPreferredSize(new Dimension(30, 30)); mark.setPreferredSize(new Dimension(30, 30)); share.setPreferredSize(new Dimension(30, 30)); timerProgressBar.setPreferredSize(new Dimension(340, 7)); mode.setModel(new DefaultComboBoxModel(new String[] { "单曲播放", "单曲循环", "顺序播放", "列表循环", "随机播放" })); backPlay.setPreferredSize(new Dimension(30, 30)); play.setPreferredSize(new Dimension(30, 30)); frontPlay.setPreferredSize(new Dimension(30, 30)); voiceControl.setPreferredSize(new Dimension(30, 30)); voiceAdjust.setPreferredSize(new Dimension(50, 20)); audioTotalTimeLabel.setText("0:00"); currentTimeCountLabel.setText("0:00"); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent( songName, GroupLayout.PREFERRED_SIZE, 230, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( download, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( mark, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( share, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.TRAILING, false) .addGroup( layout.createSequentialGroup() .addComponent( currentTimeCountLabel) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( audioTotalTimeLabel)) .addComponent( timerProgressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( mode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent( backPlay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( play, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( frontPlay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent( voiceControl, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( voiceAdjust, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1))))) .addGap(0, 7, Short.MAX_VALUE))); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] { download, mark, share }); layout.setVerticalGroup(layout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent( download, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent( mark, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) .addComponent( share, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6)) .addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent( songName, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED))) .addComponent( timerProgressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addGap(55, 55, 55) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.CENTER) .addComponent( currentTimeCountLabel) .addComponent( audioTotalTimeLabel)))) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.CENTER) .addComponent( play, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent( backPlay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent( frontPlay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGroup( layout.createSequentialGroup() .addGap(76, 76, 76) .addComponent( voiceControl, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup( GroupLayout.Alignment.CENTER, layout.createSequentialGroup() .addGap(80, 80, 80) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent( voiceAdjust, GroupLayout.Alignment.CENTER, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent( mode, GroupLayout.Alignment.CENTER, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.linkSize(SwingConstants.VERTICAL, new Component[] { download, mark, share }); } private void initPlayer() { player = new HigherPlayer(); player.setPlayButton(play); player.setSongNameLabel(songName); player.setAudioTotalTimeLabel(audioTotalTimeLabel); player.setCurrentTimeCountLabel(currentTimeCountLabel); player.setTimerProgressBar(timerProgressBar); timerProgressBar.setTimerControl(player.IsPause); timerProgressBar.setCurrentTimeCountLabel(currentTimeCountLabel); setButtonsAction(); setOtherAction(); } public HigherPlayer getHigherPlayer() { return player; } public void setButtonsAction() { // play button play.addActionListener(event -> { if (player.getLoadSongName() == null) { return; } // 在第一次播放时 为了不进入下面一个if判断 // 如果CurrentSong==null时,则进入,终止当前歌曲播放,可是当前播放线程还没有实例 报异常 if (player.getPlayingSongName() == null) { player.setPlayingSongName(player.getLoadSongName()); } // 在播放过程切换歌曲 if (!player.getLoadSongName().equals(player.getPlayingSongName()) && !player.IsComplete) { // 终止当前歌曲播放 player.end(); player.setPlayingSongName(player.getLoadSongName()); } // 是暂停 则播放 if (player.IsPause) { if (player.NeedContinue) { // 继续播放 player.resume(); // 进度条的控制 timerProgressBar.setTimerControl(false); timerProgressBar.resumeTimer(); play.setIcon(play.getSelectedIcon()); play.setToolTipText("暂停"); return; } // 进度条的控制 timerProgressBar.setTimerControl(false); // 播放歌曲 player.open(); // 声音控制 voiceAdjust.setValue(suitableVoice); songName.setText(player.getPlayingSongName()); play.setIcon(play.getSelectedIcon()); play.setToolTipText("暂停"); player.IsPause = false; } else { // 是播放 则暂停 player.IsPause = true; timerProgressBar.setTimerControl(true); play.setIcon(play.getDisabledSelectedIcon()); play.setToolTipText("播放"); } songName.updateUI(); play.updateUI(); parentFrame.setVisible(true); }); // backPlay button backPlay.addActionListener(event -> { if (player.getLoadSongName() == null) { return; } player.IsPlayNextSong = false; player.next(); play.doClick(); }); // frontPlay button frontPlay.addActionListener(event -> { if (player.getLoadSongName() == null) { return; } player.IsPlayNextSong = true; player.next(); play.doClick(); }); // voiceControl button voiceControl.addActionListener(event -> { if (!player.IsPause) { if (voiceAdjust.getValue() != minVoice) { player.setVoiceValue(minVoice); voiceAdjust.setValue(minVoice); } else { player.setVoiceValue(suitableVoice); voiceAdjust.setValue(suitableVoice); } } }); // download button // 这里存在错误 当list获取焦点后 再添加歌曲 出错 download.addActionListener(event -> { // 无载入歌时 if (player.getLoadSongName() == null) { return; } if (!player.audio.toString().startsWith("http://")) { JOptionPane.showMessageDialog(null, "播放中歌曲是本地资源,无需下载 ", "", JOptionPane.PLAIN_MESSAGE); return; } SongNode playedSong = (SongNode) player.getPlayingSong(); // 下载面板"下载中"列表添加播放中的歌曲 addSongNodeToTreeList(trees[2], 0, playedSong); JOptionPane.showMessageDialog(null, "已成功添加到下载列表", null, JOptionPane.PLAIN_MESSAGE, null); download(playedSong); }); // mark button // 这里存在错误 当list获取焦点后 再添加歌曲 出错 mark.addActionListener(event -> { if (player.getLoadSongName() == null) { return; } SongNode playedSong = (SongNode) player.getPlayingSong(); // 加入标记列表 addSongNodeToTreeList(trees[1], 1, playedSong); JOptionPane.showMessageDialog(null, "已成功添加到收藏列表", null, JOptionPane.PLAIN_MESSAGE, null); }); } public void setOtherAction() { timerProgressBar.addChangeListener(event -> { }); voiceAdjust.addChangeListener(event -> { if (!player.IsPause) { player.setVoiceValue(voiceAdjust.getValue()); } }); mode.addActionListener(event -> { player.mode = mode.getSelectedIndex(); }); } // 下载歌曲 public void download(SongNode songNode) { new Thread( () -> { try { // 打开资源链接 HttpURLConnection httpURLConnection = (HttpURLConnection) player.audio .openConnection(); // 开启IO流 读写数据 BufferedInputStream inputStream = new BufferedInputStream( httpURLConnection.getInputStream()); BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File("E:/Hub/download/" + player.getLoadSongName()))); byte[] buff = new byte[1024]; int onceRead = 0; while ((onceRead = inputStream.read(buff, 0, buff.length)) > 0) { outputStream.write(buff, 0, onceRead); } outputStream.flush(); outputStream.close(); inputStream.close(); // 下载中列表移除节点 removeSongNodeInTreeList(trees[2], 0, songNode); // 下载完成列表加入节点 addSongNodeToTreeList(trees[2], 1, songNode); JOptionPane.showMessageDialog(null, "下载完成,文件存至F:/music图片", "", JOptionPane.PLAIN_MESSAGE); } catch (Exception e) { e.printStackTrace(); } }).start(); } public void addSongNodeToTreeList(JTree tree, int index, SongNode songNode) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel() .getRoot(); DefaultMutableTreeNode list = (DefaultMutableTreeNode) root .getChildAt(index); list.add(songNode); // 列表名更新 String listName = (String) list.getUserObject(); listName = listName.substring(0, listName.lastIndexOf("[")) + "[" + list.getChildCount() + "]"; list.setUserObject(listName); // 如果这里不更新树的话 会不正确显示 tree.updateUI(); } public void removeSongNodeInTreeList(JTree tree, int index, SongNode songNode) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel() .getRoot(); DefaultMutableTreeNode list = (DefaultMutableTreeNode) root .getChildAt(index); list.remove(songNode); // 列表名更新 String listName = (String) list.getUserObject(); listName = listName.substring(0, listName.lastIndexOf("[")) + "[" + list.getChildCount() + "]"; list.setUserObject(listName); // 如果这里不更新树的话 会不正确显示 tree.updateUI(); } public void setTrees(JTree[] trees) { this.trees = trees; } public void setLrcPanelTextArea(JTextArea textArea) { timerProgressBar.setLrcPanelTextArea(textArea); } public void setParentFrame(JFrame frame) { this.parentFrame = frame; } // Variables declaration - do not modify private JLabel songName; private JButton download; private JButton mark; private JButton share; private TimeProgressBar timerProgressBar; private JLabel currentTimeCountLabel; private JLabel audioTotalTimeLabel; private JComboBox<String> mode; private JButton backPlay; private JButton play; private JButton frontPlay; private JSlider voiceAdjust; private JButton voiceControl; private JTree[] trees; private JFrame parentFrame; private HigherPlayer player; // 由FloatControl.Type.MASTER_GAIN得到的数据 private final int minVoice = -80; private final int maxVoice = 6; private final int suitableVoice = -20; // End of variables declaration }
d99ed7a9312ab952b466a197d89b1e0bd4023384
3db8504f43ae39ad43359c2e4bc083554e9746fd
/src/main/java/com/java/kvashchuk/HashMapToOut.java
aea171aa0f12c08ea6b943cbd2a3486730267016
[]
no_license
Stanislavk1982/Lesson31
5def76fdace17cf0747aebfcdcde87af0555f8a9
887ce09c98971c63afe824399472e2c13d7c3c32
refs/heads/master
2021-01-20T20:53:07.106145
2016-07-19T19:37:41
2016-07-19T19:37:41
63,722,623
0
0
null
null
null
null
UTF-8
Java
false
false
795
java
package com.java.kvashchuk; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Map; public class HashMapToOut { private Map<String, Integer> words; private String path; public HashMapToOut(Map<String, Integer> words, String path) { this.words = words; this.path = path; } public void toFileFromHashMap() throws IOException { FileWriter fileWriter = new FileWriter(path); BufferedWriter writer = new BufferedWriter(fileWriter); for (String key : words.keySet()) { Integer value = words.get(key); writer.write(key + " - " + value); writer.newLine(); System.out.println(key + " - " + value); } writer.close(); } }
dfcd4edf6f8bf1d487e30dcf3667937236edf148
27950153c2b13819a8fed22b1938e463350e6d35
/src/org/jtang/distance/ged/editpath/test/Test.java
8d28594af38db3ed3251916641281ae01f0338b0
[]
no_license
wsgan001/JTangWFR
87dd1652d23b4996aa4011a55b5dc9b04b29daff
4e71c42be878dea96fe762c25cb1ae437250e95c
refs/heads/master
2020-04-02T15:30:42.183875
2017-01-17T12:08:33
2017-01-17T12:08:33
null
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
3,484
java
package org.jtang.distance.ged.editpath.test; import java.math.BigDecimal; import org.jtang.distance.ged.editpath.EditPathFinder; import org.jtang.distance.ged.graph.DecoratedGraph; import org.jtang.distance.ged.graph.GraphConverter; import org.jtang.distance.ged.processor.CostContainer; /** * Test class. * * @author Roman Tekhov */ public class Test { public static void main(String[] args) { test(5, 5); } private static void test(int fromNodeCount, int toNodeCount) { try { double duration = 0; int n = 10; // String fromDotExpr = DotGenerator.generate(fromNodeCount, // fromNodeCount * 3, 4, "from", true); // String toDotExpr = DotGenerator.generate(toNodeCount, toNodeCount // * 3, 4, "to", true); CostContainer costContainer = new CostContainer(); Distance distance = new Distance(); String fromDotExpr = "digraph from{\n 1->2;\n 2->3;\n}"; DecoratedGraph from = GraphConverter.parse(fromDotExpr); String[] toDotExpr = new String[30]; toDotExpr[0] = "digraph to{\n 1->2;\n 2->3;\n}"; toDotExpr[1] = "digraph to{\n 1->2;\n}"; toDotExpr[2] = "digraph to{\n 2->3;\n}"; toDotExpr[3] = "digraph to{\n 1->3;\n}"; toDotExpr[4] = "digraph to{\n 1;\n}"; toDotExpr[5] = "digraph to{\n 2;\n}"; toDotExpr[6] = "digraph to{\n 3;\n}"; toDotExpr[7] = "digraph to{\n 4;\n}"; toDotExpr[8] = "digraph to{\n 1->2;\n 2->4;\n}"; toDotExpr[9] = "digraph to{\n 1->4;\n 4->3;\n}"; toDotExpr[10] = "digraph to{\n 4->2;\n 2->3;\n}"; toDotExpr[11] = "digraph from{\n 2->4;\n}"; toDotExpr[12] = "digraph from{\n 4->3;\n}"; toDotExpr[13] = "digraph from{\n 1->3;\n 3->4;\n}"; toDotExpr[14] = "digraph from{\n 2->3;\n 3->4;\n 4->5;\n}"; String toDotExpr1 = "digraph from{\n 1£»\n2;\n}"; String toDotExpr2 = "digraph from{\n 1->2;\n 1£»\n2;\n}"; String toDotExpr3 = "digraph from{\n 1->2;\n}"; String toDotExpr4 = "digraph from{\n 1->2;\n 2->3;\n 3->4;\n 1;\n 2;\n 3;\n 4\n}"; String toDotExpr5 = "digraph from{\n 1->2;\n 2->3;\n 3->4;\n}"; String toDotExpr6 = "digraph from{\n 1;\n 2;\n 3;\n 4;\n}"; String[] labelStrings = { "3" }; for (int i = 0; i < 14; i++) { DecoratedGraph to = GraphConverter.parse(toDotExpr[i]); BigDecimal graphEditDistance = EditPathFinder.find(from, to, costContainer).getCost(); distance.setGraphEditDistance(graphEditDistance.intValue()); int positionDistance = PositionDist.getPositionDist(from, to, labelStrings); distance.setPositionDistance(positionDistance); double nodeCountDistance = NodeCountDist.getNodeCountDist(from, to); distance.setNodeCountDistance(nodeCountDistance); System.out.println(i+":"+distance.getGraphEditDistance() + ";"+Math.atan(distance.getGraphEditDistance())+"..." + distance.getNodeCountDistance() + ";" + distance.getPositionDistance()); } // DecoratedGraph to = GraphConverter.parse(toDotExpr[10]); // BigDecimal graphEditDistance = EditPathFinder.find(from, to, // costContainer).getCost(); // distance.setGraphEditDistance(graphEditDistance.intValue()); // String[] labels = { "3" }; // int positionDistance = PositionDist.getPositionDist(from, to, // labels); // distance.setPositionDistance(positionDistance); // // double nodeCountDistance = NodeCountDist.getNodeCountDist(from, // to); // distance.setNodeCountDistance(nodeCountDistance); } catch (Exception e) { e.printStackTrace(); } } }
f4211250e56ad237f9546218f360fcf1d68e40b7
08f3d5d146e13583a678aba2ad50679cef46e062
/src/vmware_sdk/httpfileaccess/PutVMFiles.java
274783ce5e40b046408c86effa2ce62ff62da8dc
[ "MIT" ]
permissive
fdeclerck/vsphere-web-service-spring-server
a0f6e273a9bbd8e1438b767f3bafa263604cc492
b99dd2195382fc7b30883d3fdf500a5525659bae
refs/heads/master
2020-09-06T16:01:49.102781
2019-11-29T15:49:52
2019-11-29T15:49:52
220,468,243
0
0
null
null
null
null
UTF-8
Java
false
false
23,749
java
/* * ****************************************************** * Copyright VMware, Inc. 2010-2012. All Rights Reserved. * ****************************************************** * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS # OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY # DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY # QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. */ package com.vmware.httpfileaccess; import com.vmware.common.annotations.Action; import com.vmware.common.annotations.Option; import com.vmware.common.annotations.Sample; import com.vmware.connection.ConnectedVimServiceBase; import com.vmware.connection.KeepAlive; import com.vmware.vim25.*; import javax.xml.ws.BindingProvider; import javax.xml.ws.handler.MessageContext; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.*; /** * <pre> * PutVMFiles * * This sample puts VM files in specified Datacenter and * Datastore and register and reconfigure the particular VM * * <b>Parameters:</b> * url [required]: url of the web service. * username [required]: username for the authentication * password [required]: password for the authentication * vmname [required]: Name of the virtual machine * localpath [required]: Local path containing virtual machine files * datacentername [required]: Name of the target datacenter * datastorename [required]: Name of the target datastore * * <b>Command Line:</b> * run.bat com.vmware.httpfileaccess.PutVMFiles * --url [URLString] --username [username] --password [password] * --vmname [VM name] --localpath [local path] * --datacentername [datacenter name] * --datastorename [datastore name] * </pre> */ @Sample( name = "put-vm-files", description = "This sample puts VM files in specified Datacenter and Datastore" + " and register and reconfigure the particular VM. The VM you use, should be downloaded" + " from the vSphere you are uploading to. The name of the VM, VM folder, and VM disk files" + " should all be the same. The name of the VM should be unique and unused on the Host." + " This works best if you use a VM you obtained through GetVMFiles." ) public class PutVMFiles extends ConnectedVimServiceBase { private String cookieValue = ""; private ManagedObjectReference registeredVMRef = null; boolean verbose = true; String vmName = null; String localPath = null; String datacenter = null; String datastore = null; @Option( name = "vmname", description = "Name of the virutal machine to upload. " + "Should be unique and unused. Should be the same as the name of the vm folder and vm file names.") public void setVmName(final String vmName) { this.vmName = vmName; } @Option( name = "localpath", description = "Local path from which files will be copied. " + "This should be the path holding the virtual machine folder but not the vm folder itself." ) public void setLocalPath(final String localPath) { // the program will look in here for a virtualmachine.vm folder this.localPath = localPath; } @Option(name = "datacentername", description = "Name of the target datacenter") public void setDatacenter(final String datacenter) { this.datacenter = datacenter; } @Option(name = "datastorename", description = "Name of the target datastore") public void setDatastore(final String datastore) { this.datastore = datastore; } @Option(name = "verbose", required = false, description = "" + "defaults to 'true' and prints more information, " + "set to 'false' to print less.") public void setVerbose(final Boolean verbosity) { this.verbose = verbosity; } /** * This method returns a boolean value specifying whether the Task is * succeeded or failed. * * @param task ManagedObjectReference representing the Task. * @return boolean value representing the Task result. * @throws InvalidCollectorVersionFaultMsg * * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ boolean getTaskResultAfterDone(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { boolean retVal = false; // info has a property - state for state of the task Object[] result = waitForValues.wait(task, new String[]{"info.state", "info.error"}, new String[]{"state"}, new Object[][]{new Object[]{ TaskInfoState.SUCCESS, TaskInfoState.ERROR}}); if (result[0].equals(TaskInfoState.SUCCESS)) { retVal = true; } if (result[1] instanceof LocalizedMethodFault) { throw new PutVMFilesException( ((LocalizedMethodFault) result[1]).getLocalizedMessage()); } return retVal; } boolean customValidation() { boolean validate = false; try { if (datacenter != null && datacenter.length() != 0 && datastore != null && datastore.length() != 0 ) { ManagedObjectReference dcmor = getMOREFs.inContainerByType(serviceContent.getRootFolder(), "Datacenter").get(datacenter); if (dcmor != null) { ManagedObjectReference ds = getMOREFs.inContainerByType(dcmor, "Datastore").get(datastore); if (ds == null) { System.out.println("Specified Datastore with name " + datastore + " was not" + " found in specified Datacenter"); return validate; } validate = true; } else { System.out.println("Specified Datacenter with name " + datacenter + " not Found"); return validate; } } } catch (RuntimeFaultFaultMsg runtimeFaultFaultMsg) { throw new PutVMFilesException(runtimeFaultFaultMsg); } catch (InvalidPropertyFaultMsg invalidPropertyFaultMsg) { throw new PutVMFilesException(invalidPropertyFaultMsg); } return validate; } /** * Lists out the subdirectories and files under the localDir you specified. * * @param dir - place on the file system to look * @return - list of files under that location */ String[] getDirFiles(final File dir) { if (dir.exists() && dir.isDirectory()) { return dir.list(); } else { throw new RuntimeException("Local Path Doesn't Exist: " + dir.toString()); } } @SuppressWarnings("unchecked") void putVMFiles(final String remoteFilePath, final File localFile) { final String url = connection.getUrl(); final String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1); String httpUrl = serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore; httpUrl = httpUrl.replaceAll("\\ ", "%20"); System.out.printf("%nPutting VM File %s ", httpUrl); final URL fileURL; final HttpURLConnection conn; try { fileURL = new URL(httpUrl); conn = (HttpURLConnection) fileURL.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); } catch (MalformedURLException e) { throw new PutVMFilesException(e); } catch (IOException e) { throw new PutVMFilesException(e); } // Maintain session final List<String> cookies = (List<String>) headers.get("Set-cookie"); cookieValue = (cookies != null)?cookies.get(0):""; final StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); final String path = "$" + tokenizer.nextToken(); final String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; // set the cookie in the new request header final Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put( MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); try { conn.setRequestMethod("PUT"); } catch (ProtocolException e) { throw new PutVMFilesException(e); } conn.setRequestProperty("Content-Length", "1024"); long fileLen = localFile.length(); System.out.println("File size is: " + fileLen); // setChunkedStreamingMode to -1 turns off chunked mode // setChunkedStreamingMode to 0 asks for system default // NOTE: // larger values mean faster connections at the // expense of more heap consumption. conn.setChunkedStreamingMode(0); OutputStream out = null; InputStream in = null; try { out = conn.getOutputStream(); in = new BufferedInputStream(new FileInputStream(localFile)); int bufLen = 9 * 1024; byte[] buf = new byte[bufLen]; byte[] tmp = null; int len = 0; // this can take a very long time, so we do a keep-alive here. Thread keepAlive = KeepAlive.keepAlive(vimPort, getServiceInstanceReference()); keepAlive.start(); final String[] spinner = new String[] {"\u0008/", "\u0008-", "\u0008\\", "\u0008|" }; System.out.printf("."); int i = 0; while ((len = in.read(buf, 0, bufLen)) != -1) { tmp = new byte[len]; System.arraycopy(buf, 0, tmp, 0, len); out.write(tmp, 0, len); if (verbose) { System.out.printf("%s", spinner[i++ % spinner.length]); } } System.out.printf("\u0008"); keepAlive.interrupt(); } catch (FileNotFoundException e) { throw new PutVMFilesException(e); } catch (IOException e) { throw new PutVMFilesException(e); } finally { try { if(in!=null) in.close(); if(out!=null) out.close(); conn.getResponseCode(); } catch (IOException e) { throw new PutVMFilesException(e); } conn.disconnect(); } } /** * Copy contents of this directory up to the datastore * * @param dirName */ public void copyDir(String dirName) { System.out.print("Copying The Virtual Machine To Host..."); File dir = new File(localPath,dirName); String[] listOfFiles = getDirFiles(dir); for (int i = 0; i < listOfFiles.length; i++) { String remoteFilePath; File localFile = new File(dir,listOfFiles[i]); if (localFile.getAbsolutePath().indexOf("vdisk") != -1) { remoteFilePath = "/" + vmName + "/" + datastore + "/" + listOfFiles[i]; } else { remoteFilePath = "/" + vmName + "/" + listOfFiles[i]; } putVMFiles(remoteFilePath, localFile); if (verbose) { System.out.print("*"); } } System.out.println("...Done"); } /** * register the vmx (virtual machine file) we just placed. * * @return * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg * @throws OutOfBoundsFaultMsg * @throws DuplicateNameFaultMsg * @throws NotFoundFaultMsg * @throws VmConfigFaultFaultMsg * @throws InsufficientResourcesFaultFaultMsg * * @throws AlreadyExistsFaultMsg * @throws InvalidDatastoreFaultMsg * @throws FileFaultFaultMsg * @throws InvalidStateFaultMsg * @throws InvalidNameFaultMsg * @throws InvalidCollectorVersionFaultMsg * */ boolean registerVirtualMachine() throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg, OutOfBoundsFaultMsg, DuplicateNameFaultMsg, NotFoundFaultMsg, VmConfigFaultFaultMsg, InsufficientResourcesFaultFaultMsg, AlreadyExistsFaultMsg, InvalidDatastoreFaultMsg, FileFaultFaultMsg, InvalidStateFaultMsg, InvalidNameFaultMsg, InvalidCollectorVersionFaultMsg { boolean registered = false; System.out.print("Registering The Virtual Machine ..."); ManagedObjectReference hostmor = null; // Get the Datacenter final ManagedObjectReference dcmor = getMOREFs.inContainerByType(serviceContent.getRootFolder(), "Datacenter").get(datacenter); // Get the Datastore final ManagedObjectReference dsmor = getMOREFs.inContainerByType(dcmor, "Datastore").get(datastore); final List<DatastoreHostMount> hostmounts = ((ArrayOfDatastoreHostMount) getMOREFs.entityProps(dsmor, new String[]{"host"}).get("host")).getDatastoreHostMount(); for (DatastoreHostMount datastoreHostMount : hostmounts) { if (datastoreHostMount == null) { throw new PutVMFilesException("datastore " + datastore + " has no host mounts!"); } HostMountInfo mountInfo = datastoreHostMount.getMountInfo(); if (mountInfo == null) { throw new PutVMFilesException("datastoreHostMount on " + datastore + " has no info!"); } final Boolean accessible = mountInfo.isAccessible(); // the values "accessible" and "mounted" need not be set by the server. final Boolean mounted = mountInfo.isMounted(); // if mounted is not set, assume it is true if ((accessible != null && accessible) && (mounted == null || mounted)) { hostmor = datastoreHostMount.getKey(); break; } if (verbose) { System.out.print("."); } } if (hostmor == null) { throw new PutVMFilesException("No host connected to the datastore " + datastore); } final ManagedObjectReference crmor = (ManagedObjectReference) getMOREFs.entityProps(hostmor, new String[]{"parent"}).get("parent"); final ManagedObjectReference resourcePoolRef = (ManagedObjectReference) getMOREFs.entityProps(crmor, new String[]{"resourcePool"}).get("resourcePool"); final ManagedObjectReference vmFolderMor = (ManagedObjectReference) getMOREFs.entityProps(dcmor, new String[]{"vmFolder"}).get("vmFolder"); // Get The vmx path final String vmxPath = "[" + datastore + "] " + vmName + "/" + vmName + ".vmx"; System.out.printf("...trying to register: %s ...", vmxPath); // Registering The Virtual machine final ManagedObjectReference taskmor = vimPort.registerVMTask(vmFolderMor, vmxPath, vmName, false, resourcePoolRef, hostmor); if (getTaskResultAfterDone(taskmor)) { System.out.print("*"); registered = true; registeredVMRef = (ManagedObjectReference) getMOREFs.entityProps(taskmor, new String[]{"info.result"}).get("info.result"); System.out.print("VM registered with value " + registeredVMRef.getValue()); System.out.println("...Done."); } else { System.out.print("Some Exception While Registering The VM"); registered = false; System.out.println(" FAILED!"); } return registered; } /** * Reconfigure the virtual machine we placed on the datastore * * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg * @throws InvalidCollectorVersionFaultMsg * * @throws DuplicateNameFaultMsg * @throws TaskInProgressFaultMsg * @throws VmConfigFaultFaultMsg * @throws InsufficientResourcesFaultFaultMsg * * @throws InvalidDatastoreFaultMsg * @throws FileFaultFaultMsg * @throws ConcurrentAccessFaultMsg * @throws InvalidStateFaultMsg * @throws InvalidNameFaultMsg */ void reconfigVirtualMachine() { try { System.out.println("ReConfigure The Virtual Machine .........."); VirtualMachineFileInfo vmFileInfo = new VirtualMachineFileInfo(); vmFileInfo.setLogDirectory("[" + datastore + "] " + vmName); vmFileInfo.setSnapshotDirectory("[" + datastore + "] " + vmName); vmFileInfo.setSuspendDirectory("[" + datastore + "] " + vmName); vmFileInfo.setVmPathName("[" + datastore + "] " + vmName + "/" + vmName + ".vmx"); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec.setFiles(vmFileInfo); ManagedObjectReference taskmor = vimPort.reconfigVMTask(registeredVMRef, vmConfigSpec); if (getTaskResultAfterDone(taskmor)) { System.out.println("ReConfigure The Virtual Machine .......... Done"); } else { System.out.println("Some Exception While Reconfiguring The VM "); } } catch (Exception e) { throw new PutVMFilesException(e); } } /** * Put files onto remote datastore * * @throws DuplicateNameFaultMsg * @throws RuntimeFaultFaultMsg * @throws TaskInProgressFaultMsg * @throws InsufficientResourcesFaultFaultMsg * * @throws VmConfigFaultFaultMsg * @throws InvalidDatastoreFaultMsg * @throws InvalidPropertyFaultMsg * @throws FileFaultFaultMsg * @throws ConcurrentAccessFaultMsg * @throws InvalidStateFaultMsg * @throws InvalidCollectorVersionFaultMsg * * @throws InvalidNameFaultMsg * @throws OutOfBoundsFaultMsg * @throws NotFoundFaultMsg * @throws AlreadyExistsFaultMsg * @throws IOException */ void putVMFiles() throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { boolean validated = customValidation(); if (getMOREFs.inContainerByType(serviceContent.getRootFolder(), "VirtualMachine").containsKey(vmName)) { throw new PutVMFilesException(String.format("A VM with the name %s already exists!", vmName)); } if (validated) { int found = 0; String[] listOfDir = getDirFiles(new File(localPath)); if (listOfDir != null && listOfDir.length != 0) { // Dumping All The Data for (int i = 0; i < listOfDir.length; i++) { if (!validateDir(listOfDir[i], localPath)) { continue; } // made it here, we found something to upload found++; // go ahead and copy this up to the server copyDir(listOfDir[i]); // Register The Virtual Machine boolean reconFlag = false; try { reconFlag = registerVirtualMachine(); //Reconfigure the disks if (reconFlag) { reconfigVirtualMachine(); } } catch (Exception e) { throw new PutVMFilesException(e); } } } if (found == 0) { System.out.printf( "There are no suitable VM Directories available at location %s " + "did you use GetVMFiles first?", this.localPath ); System.out.println(); } } } /** * Checks a directory name against rules. * * * @param directoryName - directory to examine * @param localPath * @return true if usable, false if not */ boolean validateDir(final String directoryName, final String localPath) { // short-circut this method if no name set if (directoryName == null) { return false; } // using data-structure to avoid repeated calls int message = 0; final String[] messages = { "", String.format("The directory %s does not contain a matching %s.vmx file to register.%n", directoryName, vmName), String.format("Skipping: %s is a hidden name", directoryName), String.format("Skipping: %s is not a directory.", directoryName), String.format("Skipping: Name %s does not contain the --vmname %s", directoryName, vmName), }; message = (!new File(new File(localPath,directoryName), String.format("%s.vmx", vmName)).exists()) ? 1 : message; message = (directoryName.startsWith(".")) ? 2 : message; message = (!new File(localPath,directoryName).isDirectory()) ? 3 : message; message = (!directoryName.contains(vmName)) ? 4 : message; if (verbose) { System.out.println(messages[message]); } return message == 0; } /** * main method * * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ @Action public void run() throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { try { putVMFiles(); } catch (PutVMFilesException cme) { System.out.println(cme.getMessage()); } } /** * For exceptions thrown internal to this sample only. Specifically for internal error handling. */ class PutVMFilesException extends RuntimeException { private static final long serialVersionUID = 1L; public PutVMFilesException(final String message) { super(message); } public PutVMFilesException(final Throwable throwable) { super(throwable); } } }
d81b9ba25525f01dd9e6361db6c0a6a45d4bbe1a
57155831affeb12886f35173abeaa916882bb95a
/db-service/src/main/java/com/stock/dbservice/resource/DbServiceResource.java
e04698c346ebf38615ba9cb937c620777977bc7e
[]
no_license
manan012/stock-price-viewer
305d0c7b05ca6c20685ac128eaea22ff845c43a8
6a5021b1cd6326fe14f1a7704305cbdc6df93340
refs/heads/master
2022-11-14T19:56:23.228869
2020-07-02T11:43:41
2020-07-02T11:43:41
276,630,360
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package com.stock.dbservice.resource; import java.util.List; import java.util.stream.Collectors; import com.stock.dbservice.model.Quote; import com.stock.dbservice.repository.QuotesRepository; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/rest/db") public class DbServiceResource { private QuotesRepository quotesRepository; @GetMapping("/{username}") public List<String> getQuotes(@PathVariable("username") final String username) { return quotesRepository.findByUserName(username) .stream() .map(Quote::getQuote) .collect(Collectors.toList()); } }
1d0e443d0007240b0c921c6d6dafa7f25f996ca6
0c4ad07e924c4e6a06a41792779ff89ff5912a4b
/MOBILEDESIGN/src/digi/mobile/activity/CropActivity.java
f87e160cc669c896e157f151e91aa2fd50a82ee7
[]
no_license
NguyenVanThai/DIGITEXX-UPLOAD
70c7c5a7cf3a2954b47defdcd23dc82ff0eb808a
1e33b47ab5efa67726705d409d0f66cf7b747338
refs/heads/master
2021-01-22T18:24:01.866621
2015-06-11T18:02:16
2015-06-11T18:02:16
37,071,299
0
0
null
null
null
null
UTF-8
Java
false
false
2,795
java
package digi.mobile.activity; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.edmodo.cropper.CropImageView; import digi.mobile.util.Constant; public class CropActivity extends Activity { // Static final constants private static final int DEFAULT_ASPECT_RATIO_VALUES = 10; private static final int ROTATE_NINETY_DEGREES = 90; private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X"; private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y"; private static final int ON_TOUCH = 1; // Instance variables private int mAspectRatioX = DEFAULT_ASPECT_RATIO_VALUES; private int mAspectRatioY = DEFAULT_ASPECT_RATIO_VALUES; Bitmap croppedImage; private CropImageView cropImageView; // Saves the state upon rotating the screen/restarting the activity @Override protected void onCreate(Bundle savedInstanceState) { // this.requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_crop); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); cropImageView = (CropImageView) findViewById(R.id.CropImageView); cropImageView.setImageBitmap(Constant.bitmap); } @Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putInt(ASPECT_RATIO_X, mAspectRatioX); bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY); } // Restores the state upon rotating the screen/restarting the activity @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); mAspectRatioX = bundle.getInt(ASPECT_RATIO_X); mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.actionbar_crop_activity, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub int id = item.getItemId(); switch (id) { case R.id.itemSave: croppedImage = cropImageView.getCroppedImage(); Constant.updateBitmap(croppedImage); Constant.INPUT_BITMAP = 1; finish(); break; case R.id.itemRotateLeft: cropImageView.rotateImage(-90); break; case R.id.itemRotateRight: cropImageView.rotateImage(90); break; case R.id.itemHome: Intent intentHome = new Intent(CropActivity.this, DigiMobiActivity.class); startActivity(intentHome); finish(); break; } return super.onOptionsItemSelected(item); } }
48adf9323987f219ba67985165bde4767bc9c39e
4b0090b74d1d7868637e7988acdc47651d31dbb9
/gaecompat-awt-imaging/src/awt-windowing/com/google/code/appengine/awt/event/PaintEvent.java
17e3993bd5f83803d5e3abfa15add842a3b9e889
[ "Apache-2.0" ]
permissive
mike10004/appengine-imaging
32c0b328e2b2cfb257cd5ea730a2872d7c11e650
fd21dff2a9f2540bbfc24df5ab1cd7f9a2285b43
refs/heads/master
2021-01-01T17:37:15.167538
2014-01-18T00:12:10
2014-01-18T00:12:10
15,979,739
1
1
null
null
null
null
UTF-8
Java
false
false
2,529
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Michael Danilov */ package com.google.code.appengine.awt.event; import com.google.code.appengine.awt.Component; import com.google.code.appengine.awt.Rectangle; import com.google.code.appengine.awt.event.ComponentEvent; public class PaintEvent extends ComponentEvent { private static final long serialVersionUID = 1267492026433337593L; public static final int PAINT_FIRST = 800; public static final int PAINT_LAST = 801; public static final int PAINT = 800; public static final int UPDATE = 801; private Rectangle updateRect; public PaintEvent(Component source, int id, Rectangle updateRect) { super(source, id); this.updateRect = updateRect; } public Rectangle getUpdateRect() { return updateRect; } public void setUpdateRect(Rectangle updateRect) { this.updateRect = updateRect; } @Override public String paramString() { /* The format is based on 1.5 release behavior * which can be revealed by the following code: * * PaintEvent e = new PaintEvent(new Component(){}, * PaintEvent.PAINT, new Rectangle(0, 0, 10, 20)); * System.out.println(e); */ String typeString = null; switch (id) { case PAINT: typeString = "PAINT"; //$NON-NLS-1$ break; case UPDATE: typeString = "UPDATE"; //$NON-NLS-1$ break; default: typeString = "unknown type"; //$NON-NLS-1$ } return typeString + ",updateRect=" + updateRect; //$NON-NLS-1$ } }
[ "[email protected]@5f7de8e2-cdbf-b71b-c2d4-367828be1c57" ]
[email protected]@5f7de8e2-cdbf-b71b-c2d4-367828be1c57
1241958f2905c7e46e8634bf883182008e036db4
4c202c28edd053b624b983f3dc8fe84989a7042e
/TreeSumming.java
f5dee2a582a380004e327f70fde5df688f14432a
[]
no_license
RichCherng/ACM-ICPC
781db1cf1a5c1121ac457d9be75a14466fa710c5
0a45bb2cb02daf25f253076a2215cdd11f228003
refs/heads/master
2020-04-06T03:41:51.168937
2017-10-25T05:40:47
2017-10-25T05:40:47
42,888,269
0
0
null
null
null
null
UTF-8
Java
false
false
441
java
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class TreeSumming { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("input.txt")); String read = ""; while(input.hasNextLine()) { String data = input.nextLine(); read += data; } System.out.println(read); } }
c8e99e2208ecab5bf891874e1d1f211b7bf23ea6
b2c608751b1d986706c1596819e713d19c60ef17
/portal/src/main/java/com/taotao/portal/pojo/Order.java
2e059e385aeed10e99555f077437150e86b258c1
[]
no_license
HelloWangXiangDong/goshopping
9a101645e215fa322dee77906be2e190bd595d1d
0853d1af7fd3d0d47007588c4f6e4e5fc035ee3a
refs/heads/master
2020-12-01T16:28:25.183772
2016-08-31T09:58:59
2016-08-31T09:58:59
67,024,135
0
1
null
null
null
null
UTF-8
Java
false
false
731
java
package com.taotao.portal.pojo; import com.taotao.pojo.TbOrder; import com.taotao.pojo.TbOrderItem; import com.taotao.pojo.TbOrderShipping; import java.util.List; /** * Created by XDStation on 2016/8/18 0018. */ public class Order extends TbOrder { private List<TbOrderItem> orderItems; private TbOrderShipping orderShipping; public List<TbOrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<TbOrderItem> orderItems) { this.orderItems = orderItems; } public TbOrderShipping getOrderShipping() { return orderShipping; } public void setOrderShipping(TbOrderShipping orderShipping) { this.orderShipping = orderShipping; } }
20f43e3e0aaf5c267720972b7d56228d56d2f209
79bee1a60b8183b385bc14e6175c6414cff18157
/TM03/Packages/src/com/automobile/fourwheeler/Ford.java
33fb7c70bd341c350416c92301a93f4db077c050
[]
no_license
visoredd/PBL-APP-Wipro
012035339c9d20cdec1e0df50a97a0949b484572
297435340db38ebddd590867935bec8ce498ff31
refs/heads/master
2022-04-20T19:44:00.697295
2020-04-24T17:18:10
2020-04-24T17:18:10
258,570,756
6
0
null
null
null
null
UTF-8
Java
false
false
781
java
package com.automobile.fourwheeler; import com.automobile.*; public class Ford extends Vehicle{ private String modelName; private String regisName; private String OwnerName; private int speed; public Ford(String modelName,String regisName,String OwnerName,int speed){ this.modelName = modelName; this.regisName = regisName; this.OwnerName = OwnerName; this.speed = speed; } public String getModelName() { return modelName; } public String getRegistrationNumber() { return regisName; } public String getOwnerName() { return OwnerName; } public int getSpeed() { return speed; } public void tempControl() { System.out.println("Provides facility to control the air conditioning device which is available in the car"); } }
eeb923f4e6539b6e98460ee80e6861c5787e6f93
bb04751a2c46d02347cb5fc18dbcc25bc30377fd
/app/src/androidTest/java/caro/valdezg/drinksmeterapp/ExampleInstrumentedTest.java
8782a39acb9779601beff8d25a45d9e015ee101c
[]
no_license
carovaldezg/DrinksMeterApp
bcdcbcc0e19504a75ee6c3de423b0e3558eb6de3
cd0e70f432ddf8b10d9cbf7a253539ddd095e1ff
refs/heads/master
2020-05-23T03:37:37.014775
2019-05-15T11:51:31
2019-05-15T11:51:31
186,620,393
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package caro.valdezg.drinksmeterapp; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("caro.valdezg.drinksmeterapp", appContext.getPackageName()); } }
97cc3d2cffabb755f0a0ebbd814aa54d683862a2
6e55cf023a99891577cf3b5c01702e2a411fb6eb
/Algorithms and Datastructures Lab3/src/BST.java
e9797c9feee6fa720919bfb65057eedcf157af24
[ "MIT" ]
permissive
Alantrivandrum/My_Java_Projects
9f2dc5ddc07c39b30577839d1dc452a3f8592035
1cacc69c72b4edf49d23c82eb3376eafd391e297
refs/heads/master
2020-04-22T13:15:58.780672
2019-12-06T12:39:11
2019-12-06T12:39:11
170,403,088
3
0
null
null
null
null
UTF-8
Java
false
false
7,983
java
/************************************************************************* * Binary Search Tree class. * Adapted from Sedgewick and Wayne. * * @version 3.0 1/11/15 16:49:42 * * @author TODO * *************************************************************************/ import java.util.NoSuchElementException; public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST /** * Private node class. */ private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int N; // number of nodes in subtree public Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // return number of key-value pairs in BST public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node x) { if (x == null) return 0; else return x.N; } /** * Search BST for given key. * Does there exist a key-value pair with given key? * * @param key the search key * @return true if key is found and false otherwise */ public boolean contains(Key key) { return get(key) != null; } /** * Search BST for given key. * What is the value associated with given key? * * @param key the search key * @return value associated with the given key if found, or null if no such key exists. */ public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.val; } /** * Insert key-value pair into BST. * If key already exists, update with new value. * * @param key the key to insert * @param val the value associated with key */ public void put(Key key, Value val) { if (val == null) { delete(key); return; } root = put(root, key, val); } private Node put(Node x, Key key, Value val) { if (x == null) return new Node(key, val, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, val); else if (cmp > 0) x.right = put(x.right, key, val); else x.val = val; x.N = 1 + size(x.left) + size(x.right); return x; } /** * Tree height. * * Asymptotic worst-case running time using Theta notation: Theta(N) Where N is the amount of elements in the BST * * @return the number of links from the root to the deepest leaf. * * Example 1: for an empty tree this should return -1. * Example 2: for a tree with only one node it should return 0. * Example 3: for the following tree it should return 2. * B * / \ * A C * \ * D */ public int height() { return height(root); } private int height(Node node) { if(isEmpty()) { return -1; } else if(size(node) == 1) { return 0; } else if(node == null) { return 0; } else { return Math.max(height(node.left), height(node.right)) + 1 ; } } /** * Median key. * If the tree has N keys k1 < k2 < k3 < ... < kN, then their median key * is the element at position (N+1)/2 (where "/" here is integer division) * * @return the median key, or null if the tree is empty. */ public Key median() { if (isEmpty()) return null; else { int medianPosition = (size(root)-1) / 2; return median(root,medianPosition); } //TODO fill in the correct implementation. The running time should be Theta(h), where h is the height of the tree. } private Key median(Node node,int key) { int pos = rank(node.key); if(key> pos) { return median(node.right,key); } else if(key < pos) { return median(node.left,key); } else { return node.key; } } public int rank(Key key) { return rank(root,key); } private int rank(Node node,Key key) { int cmp = key.compareTo(node.key); if(cmp < 0) { return rank(node.left,key); } else if(cmp > 0) { return size(node.left) + rank(node.right,key) + 1; } else return size(node.left); } /** * Print all keys of the tree in a sequence, in-order. * That is, for each node, the keys in the left subtree should appear before the key in the node. * Also, for each node, the keys in the right subtree should appear before the key in the node. * For each subtree, its keys should appear within a parenthesis. * * Example 1: Empty tree -- output: "()" * Example 2: Tree containing only "A" -- output: "(()A())" * Example 3: Tree: * B * / \ * A C * \ * D * * output: "((()A())B(()C(()D())))" * * output of example in the assignment: (((()A(()C()))E((()H(()M()))R()))S(()X())) * * @return a String with all keys in the tree, in order, parenthesized. */ public String printKeysInOrder() { // TODO fill in the correct implementation return printKeysInOrder(root); } private String printKeysInOrder(Node node) { if(node == null) { return "()"; } return "(" + printKeysInOrder(node.left) + node.key + printKeysInOrder(node.right) + ")"; } /** * Pretty Printing the tree. Each node is on one line -- see assignment for details. * * @return a multi-line string with the pretty ascii picture of the tree. */ public String prettyPrintKeys() { //TODO fill in the correct implementation. if(isEmpty()) { return "-null\n"; } else { String output = prettyPrintKeys(root,"") + "\n" ; return output; } } private String prettyPrintKeys(Node node, String prefix) { String output = ""; if(node == null) { output = prefix + "-null"; } else { output = prefix + "-" + node.val + "\n" + prettyPrintKeys(node.left, prefix + " |") + "\n" + prettyPrintKeys(node.right, prefix + " ") ; } return output; } /** * Deteles a key from a tree (if the key is in the tree). * Note that this method works symmetrically from the Hibbard deletion: * If the node to be deleted has two child nodes, then it needs to be * replaced with its predecessor (not its successor) node. * * @param key the key to delete */ public void delete(Key key) { //TODO fill in the correct implementation. if(this.contains(key)) { if(size() == 1 && root.key == key) { root = null; } else { if(key != null ) { delete(root,key); } } } } private Node delete(Node node, Key key) { if (node == null) return null; if(key!= null) { int cmp = key.compareTo(node.key); if (cmp < 0) node.left = delete(node.left, key); else if (cmp > 0) node.right = delete(node.right, key); else { if (node.right == null) return node.left; if (node.left == null) return node.right; Node t = node; node = max(t.left); node.left = deleteMax(t.left); node.right = t.right; } node.N = size(node.left) + size(node.right) + 1; } return node; } public int max(int a, int b) { return ((a > b) ? a : b); } // find max key public Node max(Node node) { return maxNode(node); } private Node maxNode(Node node) { if (node.right != null) { node = max(node.right); } return node; } // delete maximum key public void deleteMax() { root = deleteMax(root); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = 1 + size(x.right) + size(x.left); return x; } }
4d54020866bda1a944d078873b77b24dcd053090
1802e3dde66a75cbc686ddc08b1579581d996d69
/MobilePlayer/app/src/main/java/com/example/administrator/mobileplayer/Adapter/NetAudioAdapter.java
d22e3385d70ca89139b1de87d6a2c27462f62dfb
[]
no_license
tupobi/MobilePlayer
f84cdec1b64a23124a320463a7725560c3d52f59
9c77c51e4cfe9d642a599cdc8f6aeaa0081c5c7e
refs/heads/master
2020-12-30T16:27:41.807682
2017-06-03T05:02:49
2017-06-03T05:02:49
90,988,428
0
0
null
null
null
null
UTF-8
Java
false
false
13,999
java
package com.example.administrator.mobileplayer.Adapter; import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Environment; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.example.administrator.mobileplayer.R; import com.example.administrator.mobileplayer.entity.NetAudioBean; import com.example.administrator.mobileplayer.util.DateUtil; import com.example.administrator.mobileplayer.util.DensityUtil; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; import java.io.File; import java.util.List; import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer; import pl.droidsonroids.gif.GifImageView; /** * Created by Administrator on 2017/5/13. */ public class NetAudioAdapter extends BaseAdapter { /** * 视频 */ private static final int TYPE_VIDEO = 0; /** * 图片 */ private static final int TYPE_IMAGE = 1; /** * 文字 */ private static final int TYPE_TEXT = 2; /** * GIF图片 */ private static final int TYPE_GIF = 3; /** * 软件推广 */ private static final int TYPE_AD = 4; private DateUtil dateUtil; private Context mContext; private List<NetAudioBean.ListBean> mNetAudioBeans; public NetAudioAdapter(Context context, List<NetAudioBean.ListBean> netAudioBeans) { this.mNetAudioBeans = netAudioBeans; mContext = context; dateUtil = new DateUtil(); initUniversalImageLoader(); } @Override public int getViewTypeCount() { return 5; } @Override public int getItemViewType(int position) { NetAudioBean.ListBean listBean = mNetAudioBeans.get(position); String type = listBean.getType(); int itemViewType = -1; if ("video".equals(type)) { itemViewType = TYPE_VIDEO; } else if ("image".equals(type)) { itemViewType = TYPE_IMAGE; } else if ("text".equals(type)) { itemViewType = TYPE_TEXT; } else if ("gif".equals(type)) { itemViewType = TYPE_GIF; } else { itemViewType = TYPE_AD;//广告 } return itemViewType; } @Override public int getCount() { return mNetAudioBeans.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int itemViewType = getItemViewType(i); ViewHolder viewHolder; if (view == null) { viewHolder = new ViewHolder(); switch (itemViewType) { case TYPE_VIDEO://视频 view = View.inflate(mContext, R.layout.all_video_item, null); viewHolder.tv_play_nums = (TextView) view.findViewById(R.id.tv_play_nums); viewHolder.tv_video_duration = (TextView) view.findViewById(R.id.tv_video_duration); viewHolder.iv_commant = (ImageView) view.findViewById(R.id.iv_commant); viewHolder.tv_commant_context = (TextView) view.findViewById(R.id.tv_commant_context); viewHolder.jcv_videoplayer = (JCVideoPlayer) view.findViewById(R.id.jcv_videoplayer); break; case TYPE_IMAGE://图片 view = View.inflate(mContext, R.layout.all_image_item, null); viewHolder.iv_image_icon = (ImageView) view.findViewById(R.id.iv_image_icon); break; case TYPE_TEXT://文字 view = View.inflate(mContext, R.layout.all_text_item, null); break; case TYPE_GIF://gif view = View.inflate(mContext, R.layout.all_gif_item, null); viewHolder.iv_image_gif = (GifImageView) view.findViewById(R.id.iv_image_gif); break; case TYPE_AD://软件广告 view = View.inflate(mContext, R.layout.all_ad_item, null); viewHolder.btn_install = (Button) view.findViewById(R.id.btn_install); viewHolder.iv_image_icon = (ImageView) view.findViewById(R.id.iv_image_icon); break; } switch (itemViewType) { case TYPE_VIDEO://视频 case TYPE_IMAGE://图片 case TYPE_TEXT://文字 case TYPE_GIF://gif //加载除开广告部分的公共部分视图 //user info viewHolder.iv_headpic = (ImageView) view.findViewById(R.id.iv_headpic); viewHolder.tv_name = (TextView) view.findViewById(R.id.tv_name); viewHolder.tv_time_refresh = (TextView) view.findViewById(R.id.tv_time_refresh); viewHolder.iv_right_more = (ImageView) view.findViewById(R.id.iv_right_more); //bottom viewHolder.iv_video_kind = (ImageView) view.findViewById(R.id.iv_video_kind); viewHolder.tv_video_kind_text = (TextView) view.findViewById(R.id.tv_video_kind_text); viewHolder.tv_shenhe_ding_number = (TextView) view.findViewById(R.id.tv_shenhe_ding_number); viewHolder.tv_shenhe_cai_number = (TextView) view.findViewById(R.id.tv_shenhe_cai_number); viewHolder.tv_posts_number = (TextView) view.findViewById(R.id.tv_posts_number); viewHolder.ll_download = (LinearLayout) view.findViewById(R.id.ll_download); break; } //中间公共部分 -所有的都有 viewHolder.tv_context = (TextView) view.findViewById(R.id.tv_context); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } NetAudioBean.ListBean mediaItem = mNetAudioBeans.get(i); switch (itemViewType) { case TYPE_VIDEO://视频 bindData(viewHolder, mediaItem); //第一个参数是视频播放地址,第二个参数是显示封面的地址,第三参数是标题 viewHolder.jcv_videoplayer.setUp(mediaItem.getVideo().getVideo().get(0), mediaItem.getVideo().getThumbnail().get(0), null); viewHolder.tv_play_nums.setText(mediaItem.getVideo().getPlaycount() + "次播放"); viewHolder.tv_video_duration.setText(dateUtil.stringForTime(mediaItem.getVideo().getDuration() * 1000) + ""); break; case TYPE_IMAGE://图片 bindData(viewHolder, mediaItem); viewHolder.iv_image_icon.setImageResource(R.drawable.bg_item); int height = mediaItem.getImage().getHeight() <= DensityUtil.getScreenHeight() * 0.75 ? mediaItem.getImage().getHeight() : (int) (DensityUtil.getScreenHeight() * 0.75); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.getScreenWidth(), height); viewHolder.iv_image_icon.setLayoutParams(params); if (mediaItem.getImage() != null && mediaItem.getImage().getBig() != null && mediaItem.getImage().getBig().size() > 0) { // x.image().bind(viewHolder.iv_image_icon, mediaItem.getImage().getBig().get(0)); Glide.with(mContext).load(mediaItem.getImage().getBig().get(0)).placeholder(R.drawable.bg_item).error(R.drawable.bg_item).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_image_icon); } break; case TYPE_TEXT://文字 bindData(viewHolder, mediaItem); break; case TYPE_GIF://gif bindData(viewHolder, mediaItem); System.out.println("mediaItem.getGif().getImages().get(0)" + mediaItem.getGif().getImages().get(0)); Glide.with(mContext).load(mediaItem.getGif().getImages().get(0)).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(viewHolder.iv_image_gif); break; case TYPE_AD://软件广告 break; } //设置文本 viewHolder.tv_context.setText(mediaItem.getText()); return view; } private void initUniversalImageLoader() { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(new ColorDrawable(Color.parseColor("#f0f0f0"))) .resetViewBeforeLoading(true) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) .bitmapConfig(Bitmap.Config.RGB_565) // .displayer(new FadeInBitmapDisplayer(1000)) // 设置图片渐显的时间 // .delayBeforeLoading(300) // 下载前的延迟时间 .build(); int memClass = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE)) .getMemoryClass(); // Use 1/8th of the available memory for this memory cache. int memCacheSize = 1024 * 1024 * memClass / 8; File cacheDir = new File(Environment.getExternalStorageDirectory().getPath() + "/jiecao/cache"); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext) .threadPoolSize(3) // default 线程池内加载的数量 .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级 .denyCacheImageMultipleSizesInMemory() .diskCacheFileNameGenerator(new Md5FileNameGenerator()) .memoryCache(new UsingFreqLimitedMemoryCache(memCacheSize)) // You can pass your own memory cache implementation/ .memoryCacheSize(memCacheSize) // 内存缓存的最大值 .diskCacheSize(50 * 1024 * 1024) // 50 Mb .tasksProcessingOrder(QueueProcessingType.LIFO) .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径 .imageDownloader(new BaseImageDownloader(mContext, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间 .defaultDisplayImageOptions(options) // .writeDebugLogs() // Remove for release app .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } private void bindData(ViewHolder viewHolder, NetAudioBean.ListBean mediaItem) { if (mediaItem.getU() != null && mediaItem.getU().getHeader() != null && mediaItem.getU().getHeader().get(0) != null) { // x.image().bind(viewHolder.iv_headpic, mediaItem.getU().getHeader().get(0)); Glide.with(mContext).load(mediaItem.getU().getHeader().get(0).toString()).placeholder(R.drawable.user).into(viewHolder.iv_headpic); } if (mediaItem.getU() != null && mediaItem.getU().getName() != null) { viewHolder.tv_name.setText(mediaItem.getU().getName() + ""); } viewHolder.tv_time_refresh.setText(mediaItem.getPasstime()); //设置标签 List<NetAudioBean.ListBean.TagsBean> tagsEntities = mediaItem.getTags(); if (tagsEntities != null && tagsEntities.size() > 0) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < tagsEntities.size(); i++) { buffer.append(tagsEntities.get(i).getName() + " "); } viewHolder.tv_video_kind_text.setText(buffer.toString()); } //设置点赞,踩,转发 viewHolder.tv_shenhe_ding_number.setText(mediaItem.getUp()); viewHolder.tv_shenhe_cai_number.setText(mediaItem.getDown() + ""); viewHolder.tv_posts_number.setText(mediaItem.getForward() + ""); } class ViewHolder { //user_info ImageView iv_headpic; TextView tv_name; TextView tv_time_refresh; ImageView iv_right_more; //bottom ImageView iv_video_kind; TextView tv_video_kind_text; TextView tv_shenhe_ding_number; TextView tv_shenhe_cai_number; TextView tv_posts_number; LinearLayout ll_download; //中间公共部分 -所有的都有 TextView tv_context; //Video // TextView tv_context; TextView tv_play_nums; TextView tv_video_duration; ImageView iv_commant; TextView tv_commant_context; JCVideoPlayer jcv_videoplayer; //Image ImageView iv_image_icon; // TextView tv_context; //Text // TextView tv_context; //Gif GifImageView iv_image_gif; // TextView tv_context; //软件推广 Button btn_install; // TextView iv_image_icon; //TextView tv_context; } }
7fc8d5786325598b60919893880d24af4580105e
8ec385b67b240a093578407fd971f06e819027b6
/comun-swing/src/main/java/com/kalos/visual/controles/textos/teclas/TAAgregadoSimple.java
34ead2d79a83d71ae216c6f6b530bce0c0f76c1b
[]
no_license
gdiazpromeba/griego
bddb001af52b0f187d9531fed9475fda4f53afd6
ecb5c74357e33835ce8be12712dafea1636ecc1f
refs/heads/master
2021-01-18T21:11:20.736019
2016-04-25T00:06:49
2016-04-25T00:06:49
20,869,747
0
0
null
null
null
null
UTF-8
Java
false
false
1,345
java
package com.kalos.visual.controles.textos.teclas; /** * Title: Kalos * Description: Greek verb conjugation and research tool * Copyright: Copyright (c) 2001 * Company: * @author Mariana Esplugas and Gonzalo D�az * @version 1.0 */ import java.awt.event.ActionEvent; import javax.swing.JTextField; import javax.swing.text.TextAction; import com.kalos.enumeraciones.uLetras; /** * Acci�n que se usa para la adici�n de letras simples * Asume que los caracteres que se agregan son de tipo Unicode * */ public class TAAgregadoSimple extends TextAction implements uLetras{ char m_charAgregado; JTextField m_txt; public TAAgregadoSimple(char charAgregado, JTextField txt){ super(""); m_charAgregado=charAgregado; m_txt=txt; } public void actionPerformed(ActionEvent e) { StringBuffer sAux=new StringBuffer(m_txt.getText()); int iStart=m_txt.getSelectionStart(), iEnd=m_txt.getSelectionEnd(); //si hay algo seleccionado, eliminarlo if (iStart!=iEnd) sAux.delete(iStart, iEnd); if (m_charAgregado==cUnderscore){ sAux.insert(iStart, uLetras.cLarga); }else{ //ahora sigo normalmente //sAux.insert(iStart, Unicode.carAUnicodeSiNecesario(m_charAgregado)); sAux.insert(iStart, m_charAgregado); } m_txt.setText(sAux.toString()); m_txt.setCaretPosition(iStart+1); } }
fecdb4db32366bf3812a6f70fc91f083ff42a6bf
6c46e7be22e66a9930e5e921b13d56f2f7b670e1
/lib/src/main/java/si/fri/rso/kb6750/model3dparser/lib/Model3dBinaryData.java
03d4b780888109b85e073a7f66be8067c67ffb60
[]
no_license
rsokb2020/rso-3d-model-parser
6aa665d2e63e393ec9af22a05cdd94bd157ce17e
32a76d96fdd966107a4de9ed47b5e70b2fecd0b7
refs/heads/main
2023-02-15T22:41:39.638993
2021-01-08T09:18:50
2021-01-08T09:18:50
310,568,318
0
0
null
null
null
null
UTF-8
Java
false
false
975
java
package si.fri.rso.kb6750.model3dparser.lib; public class Model3dBinaryData { public String getBinaryArrayString() { return binaryArrayString; } public void setBinaryArrayString(String binaryArrayString) { this.binaryArrayString = binaryArrayString; } private String binaryArrayString; private String assetBundleBinaryArray; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } private String title; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } private String description; public String getAssetBundleBinaryArray() { return assetBundleBinaryArray; } public void setAssetBundleBinaryArray(String assetBundleBinaryArray) { this.assetBundleBinaryArray = assetBundleBinaryArray; } }
e0a87f6958d055e8b88ebe4814bc75448cdae9a1
501d0b053db7a5802cd130a75b22984895cdbb27
/spring.boot/src/main/java/com/will/example/spring/statemachine/OrderStatus.java
de96fd390bcbde0e8324213c38c7cf0fc5f188fb
[]
no_license
198812345678/spring-boot-simple
b260d0e7968da1b2c1a8bc7fcceb55ad6c07893e
47aa5e0bf7b373d7313511f265d291a94671ac10
refs/heads/master
2022-07-17T19:39:34.982470
2021-03-18T05:11:05
2021-03-18T05:11:05
129,576,470
0
0
null
2022-06-21T02:40:36
2018-04-15T04:20:53
Java
UTF-8
Java
false
false
128
java
package com.will.example.spring.statemachine; public enum OrderStatus { WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH; }
e43440c43dd4868b61b417a72e6ad6f0e1282277
ded6e40edce64079a004d5bf910cc91d92a09f87
/src/Address.java
d43bf83ddc043ef5383edc462396d520336a4f22
[]
no_license
SudolAgata/Scanner
8f4d0d407de978f4d4f89b059793878fff635dbc
0352bdaa7e7fa066e7938ff58e9a94305455c85f
refs/heads/master
2022-07-03T01:55:10.114330
2020-05-05T17:45:09
2020-05-05T17:45:09
261,542,714
0
0
null
null
null
null
UTF-8
Java
false
false
391
java
import java.util.Scanner; class Address { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your address: "); scanner = new Scanner(System.in); String address = scanner.nextLine(); System.out.println("You live at: " + address); } }
598e0b6cb1c9a9b40402abf9da1275affc8784c7
412502dd415dbab2bcf9c0c46455861f7af682fc
/JavaStudy/src/ch03/Operation3.java
df47d13a638bbaa0bf66a1c176e9e232b7b33cc3
[]
no_license
dttdsrd/JavaStudy
c74bdde50160c478fb3c33dc9f5a7358d68520a9
f81609d8e8654937de0743452261874dc52df11b
refs/heads/master
2020-04-28T19:41:00.722371
2019-03-22T08:39:04
2019-03-22T08:39:04
175,518,982
0
0
null
null
null
null
UHC
Java
false
false
493
java
package ch03; import java.util.Scanner; public class Operation3 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("첫번째 숫자를 입력해주세요. "); int num1 = s.nextInt(); System.out.println("두번째 숫자를 입력해주세요. "); int num2 = s.nextInt(); System.out.println(num1 + " " + num2); boolean result = (num1 * num2) % 3 == 0; System.out.println(result); } }
[ "Student@DESKTOP-EF9PEQ2" ]
Student@DESKTOP-EF9PEQ2
b4980e1c37d920abf3a1457d7ab39ffbeeb1264b
838576cc2e44f590d4c59f8a4d120f629969eedf
/src/com/sino/soa/td/srv/assetsinfoupdate/model/TDSynAttributeModel.java
4d2e5f0070642db86540e3ee58725ead50af5632
[]
no_license
fancq/CQEAM
ecbfec8290fc4c213101b88365f7edd4b668fdc8
5dbb23cde5f062d96007f615ddae8fd474cb37d8
refs/heads/master
2021-01-16T20:33:40.983759
2013-09-03T16:00:57
2013-09-03T16:00:57
null
0
0
null
null
null
null
GB18030
Java
false
false
1,771
java
package com.sino.soa.td.srv.assetsinfoupdate.model; import com.sino.base.db.sql.model.SQLModel; import com.sino.base.exception.CalendarException; import com.sino.soa.util.dto.EtsMisfaUpdateBatchDTO; import com.sino.soa.util.dto.EtsMisfaUpdateLogDTO; import com.sino.soa.util.dto.SynLogDTO; import java.util.ArrayList; import java.util.List; /** * <p>Title: EtsAutoSynLogModel</p> * <p>Description:程序自动生成SQL构造器“获取ETS_ITEM_INFO表的对应属性”,请根据需要自行修改</p> * <p>Copyright: Copyright (c) 2011</p> * <p>Company: 北京思诺博信息技术有限公司</p>v * @author wangzp * @version 1.0 */ public class TDSynAttributeModel { /** * 参数:投资分类ID * 获取支撑网设备类型 * @param * @return SQLModel */ public SQLModel getCexType(String cexId) { SQLModel sqlModel = new SQLModel(); List sqlArgs = new ArrayList(); String sqlStr = "SELECT SN_CODE,\n" + " SN_NAME \n" + " FROM AMS_CEX \n" + " WHERE AMS_CEX_ID=? " ; sqlArgs.add(cexId); sqlModel.setSqlStr(sqlStr); sqlModel.setArgs(sqlArgs); return sqlModel; } /** * 获取业务平台编码,网络层次编码 * @param * @return SQLModel */ public SQLModel getOpeModel(String opeId) { SQLModel sqlModel = new SQLModel(); List sqlArgs = new ArrayList(); String sqlStr = "select AO.OPE_CODE,AO.OPE_NAME from AMS_OPE AO WHERE AO.AMS_OPE_ID= ?"; sqlArgs.add(opeId); sqlModel.setSqlStr(sqlStr); sqlModel.setArgs(sqlArgs); return sqlModel; } }
00ec89ff3174e9ca4d5104369006bc3659334f1f
c84a5b6371610e7c9326dcb7c6465a940fa3cb16
/pa5_burrows/src/main/java/burrows/MSDSuffix.java
4ce6f6933fa600aef59fad96e7c2befbd318fb06
[]
no_license
ilyarudyak/COS226
d0bc37bb99ec101cb41ac7a31c03ac871efeea74
a0f1a76132702df6f0e8a137daf0bd47047e898a
refs/heads/master
2021-01-10T09:44:32.725266
2015-12-25T10:09:01
2015-12-25T10:09:01
45,299,371
0
0
null
null
null
null
UTF-8
Java
false
false
4,336
java
package burrows; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; /** * Created by ilyarudyak on 12/25/15. */ public class MSDSuffix { private static final int R = 256; // extended ASCII alphabet size private static final int CUTOFF = 0; // cutoff to insertion sort // do not instantiate private MSDSuffix() { } /** * Rearranges the array of extended ASCII strings in ascending order. * * @param a the array to be sorted */ public static void sort(String[] a) { int N = a.length; String[] aux = new String[N]; sort(a, 0, N-1, 0, aux); } // return dth character of s, -1 if d = length of string private static int charAt(String s, int d) { assert d >= 0 && d <= s.length(); if (d == s.length()) return -1; return s.charAt(d); } private static void sort2(String s, int lo, int hi, int d, String[] aux) { // cutoff to insertion sort for small subarrays if (hi <= lo + CUTOFF) { // insertion(a, lo, hi, d); return; } int N = s.length(); // compute frequency counts int[] count = new int[R+2]; for (int i = lo; i <= hi; i++) { int c = charAt(s, (d + i) % N); count[c+2]++; } // transform counts to indicies for (int r = 0; r < R+1; r++) count[r+1] += count[r]; // distribute for (int i = lo; i <= hi; i++) { int c = charAt(s, (d + i) % N); aux[count[c+1]++] = a[i]; } // copy back for (int i = lo; i <= hi; i++) a[i] = aux[i - lo]; // recursively sort for each character (excludes sentinel -1) for (int r = 0; r < R; r++) sort2(a, lo + count[r], lo + count[r+1] - 1, d+1, aux); } // sort from a[lo] to a[hi], starting at the dth character private static void sort(String[] a, int lo, int hi, int d, String[] aux) { // cutoff to insertion sort for small subarrays if (hi <= lo + CUTOFF) { insertion(a, lo, hi, d); return; } // compute frequency counts int[] count = new int[R+2]; for (int i = lo; i <= hi; i++) { int c = charAt(a[i], d); count[c+2]++; } // transform counts to indicies for (int r = 0; r < R+1; r++) count[r+1] += count[r]; // distribute for (int i = lo; i <= hi; i++) { int c = charAt(a[i], d); aux[count[c+1]++] = a[i]; } // copy back for (int i = lo; i <= hi; i++) a[i] = aux[i - lo]; // recursively sort for each character (excludes sentinel -1) for (int r = 0; r < R; r++) sort(a, lo + count[r], lo + count[r+1] - 1, d+1, aux); } // ---------------------- insertion sort ------------------------ // insertion sort a[lo..hi], starting at dth character private static void insertion(String[] a, int lo, int hi, int d) { for (int i = lo; i <= hi; i++) for (int j = i; j > lo && less(a[j], a[j-1], d); j--) exch(a, j, j-1); } // exchange a[i] and a[j] private static void exch(String[] a, int i, int j) { String temp = a[i]; a[i] = a[j]; a[j] = temp; } // is v less than w, starting at character d private static boolean less(String v, String w, int d) { // assert v.substring(0, d).equals(w.substring(0, d)); for (int i = d; i < Math.min(v.length(), w.length()); i++) { if (v.charAt(i) < w.charAt(i)) return true; if (v.charAt(i) > w.charAt(i)) return false; } return v.length() < w.length(); } public static void main(String[] args) { In in = new In("src/main/resources/abra.txt"); String abra = in.readString(); String[] a = new String[abra.length()]; for (int i = 0; i < abra.length(); i++) { a[i] = abra.substring(i, abra.length()) + abra.substring(0, i); } StdOut.println(Arrays.toString(a)); MSDSuffix.sort(a); StdOut.println(Arrays.toString(a)); } }
483720a59fc22c4eebbff667e69ced0a620f03d7
a1f93c1433fd07d3eb417cd1c64830e7596cb930
/src/main/java/vn/bzcom/abis/faceattendance/common/model/Name.java
c1eb97c2a4f8340440f82def8931840f85b39b4c
[]
no_license
AnNguyen99/face-attendance
b1bab1c33db20b97b2b0531078173151280fe9aa
c0fcbf0767123e7aa42e2c8362702e776a53057e
refs/heads/master
2023-02-26T22:55:38.016546
2021-01-28T07:36:04
2021-01-28T07:36:04
333,490,080
0
0
null
null
null
null
UTF-8
Java
false
false
794
java
package vn.bzcom.abis.faceattendance.common.model; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) public class Name { @Column(name = "first_name", nullable = false, length = 50) private String firstName; @Column(name = "last_name", nullable = false, length = 50) private String lastName; @Builder public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void updateName(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
d266f3b9d3b366d2ba18201c1756ead59e4f28e5
c074ffe5a22f895a2478b8e5aa737ff2cf560af7
/app/src/main/java/com/yourmother/android/dayplanning/DayPlansLab.java
4bf57d9b01dd1becc98f96ec6693f2e07918d5c6
[]
no_license
e-hedgehog/DayPlanning
fe0815da6d481114027d58dd57b371828f09e301
78aff44d6fb9e53055e61675a2add709f7f3e0f3
refs/heads/master
2020-03-31T14:17:43.147232
2019-04-28T17:14:57
2019-04-28T17:14:57
152,288,201
0
0
null
null
null
null
UTF-8
Java
false
false
6,466
java
package com.yourmother.android.dayplanning; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.yourmother.android.dayplanning.database.DayPlanningBaseHelper; import com.yourmother.android.dayplanning.database.DayPlanningCursorWrapper; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import static com.yourmother.android.dayplanning.database.DayPlanningDbSchema.DayPlansTable; import static com.yourmother.android.dayplanning.database.DayPlanningDbSchema.PlanItemsTable; public class DayPlansLab { private static final String TAG = "DayPlansLab"; private static DayPlansLab sDayPlansLab; private Context mContext; private SQLiteDatabase mDatabase; public static DayPlansLab get(Context context) { if (sDayPlansLab == null) sDayPlansLab = new DayPlansLab(context); return sDayPlansLab; } private DayPlansLab(Context context) { mContext = context.getApplicationContext(); mDatabase = new DayPlanningBaseHelper(mContext) .getWritableDatabase(); } public List<PlanItem> getDatePlansList(Date date) { List<PlanItem> items = new ArrayList<>(); try (DayPlanningCursorWrapper cursor = queryPlans( DayPlansTable.Cols.DATE + " = ?", new String[]{String.valueOf(date.getTime())} )) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { items.add(cursor.getPlanItem()); cursor.moveToNext(); } } return items; } public PlanItem getPlanItem(Date date, UUID id) { try(DayPlanningCursorWrapper cursor = queryPlans( DayPlansTable.Cols.DATE + " = ? and " + PlanItemsTable.Cols.UUID + " = ?", new String[]{String.valueOf(date.getTime()), id.toString()} )) { if (cursor.getCount() == 0) return null; cursor.moveToFirst(); return cursor.getPlanItem(); } } public void deletePlanItem(Date date, PlanItem item) { mDatabase.delete( PlanItemsTable.NAME, PlanItemsTable.Cols.DATE_ID + " = ? and " + PlanItemsTable.Cols.UUID + " = ?", new String[]{String.valueOf(getDateId(date)), item.getId().toString()} ); } public void deleteDatePlans(Date date) { mDatabase.delete( PlanItemsTable.NAME, PlanItemsTable.Cols.DATE_ID + " = ?", new String[]{String.valueOf(getDateId(date))} ); mDatabase.delete( DayPlansTable.NAME, DayPlansTable.Cols.DATE + " = ?", new String[]{String.valueOf(date.getTime())} ); } public void deleteDatePlansBefore(Date date) { try (DayPlanningCursorWrapper cursor = queryDates( DayPlansTable.Cols.DATE + " < ?", new String[]{String.valueOf(date.getTime())} )) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { deleteDatePlans(cursor.getDate()); cursor.moveToNext(); } } } public void updatePlanItem(Date date, PlanItem item) { String uuidString = item.getId().toString(); ContentValues values = getContentValues(date, item); mDatabase.update(PlanItemsTable.NAME, values, PlanItemsTable.Cols.UUID + " = ?", new String[]{uuidString}); } public void addPlanItem(Date date, PlanItem item) { if (getDateId(date) == 0) addDate(date); ContentValues values = getContentValues(date, item); mDatabase.insert(PlanItemsTable.NAME, null, values); } private void addDate(Date date) { ContentValues values = getDateContentValues(date); mDatabase.insert(DayPlansTable.NAME, null, values); } private int getDateId(Date date) { try (DayPlanningCursorWrapper cursor = queryDates( DayPlansTable.Cols.DATE + " = ?", new String[]{String.valueOf(date.getTime())} )) { Log.i(TAG, "getDateId(): " + date.toString()); Log.i(TAG, cursor.getCount() == 0 ? "count = 0" : "count = ne 0"); if (cursor.getCount() == 0) return 0; cursor.moveToFirst(); return cursor.getDateId(); } } private DayPlanningCursorWrapper queryPlans(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query( DayPlansTable.NAME + " join " + PlanItemsTable.NAME + " using(" + PlanItemsTable.Cols.DATE_ID + ")", null, whereClause, whereArgs, null, null, null ); return new DayPlanningCursorWrapper(cursor); } private DayPlanningCursorWrapper queryDates(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query( DayPlansTable.NAME, null, whereClause, whereArgs, null, null, null ); return new DayPlanningCursorWrapper(cursor); } private ContentValues getContentValues(Date date, PlanItem planItem) { ContentValues values = new ContentValues(); values.put(PlanItemsTable.Cols.DATE_ID, getDateId(date)); values.put(PlanItemsTable.Cols.UUID, planItem.getId().toString()); values.put(PlanItemsTable.Cols.TITLE, planItem.getTitle()); Date time = planItem.getTime(); values.put(PlanItemsTable.Cols.TIME, time == null ? 0 : time.getTime()); values.put(PlanItemsTable.Cols.TEXT, planItem.getText()); values.put(PlanItemsTable.Cols.IS_ALARM_ON, planItem.isAlarmOn() ? 1 : 0); values.put(PlanItemsTable.Cols.STATUS, planItem.getStatus().getValue()); return values; } private ContentValues getDateContentValues(Date date) { ContentValues values = new ContentValues(); values.put(DayPlansTable.Cols.DATE, date.getTime()); return values; } }
ac86132e6782a50c4b749a904d80dc93a8ee2f38
72cbd420d57f970a6bfbf9cf4dc62f662e6a0ebb
/plugin/core/src/com/perl5/lang/pod/idea/highlighter/PodColorSettingsPage.java
e395212fff3ffe5bc82b39efefec5c0725255a88
[ "Apache-2.0" ]
permissive
xcodejoy/Perl5-IDEA
e36061de84cc1780ed76711190bb5ce4b05fa3f0
2179a9ab2e9006d4c5501a878f484293220046ac
refs/heads/master
2020-09-19T09:15:35.960543
2019-11-23T08:46:28
2019-11-23T08:46:28
224,215,081
1
0
NOASSERTION
2019-11-26T14:44:56
2019-11-26T14:44:55
null
UTF-8
Java
false
false
2,797
java
/* * Copyright 2015-2019 Alexandr Evstigneev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.perl5.lang.pod.idea.highlighter; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.perl5.PerlBundle; import com.perl5.PerlIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; public class PodColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor(PerlBundle.message("pod.color.settings.commands"), PodSyntaxHighlighter.POD_TAG_KEY), new AttributesDescriptor(PerlBundle.message("pod.color.settings.verbatim"), PodSyntaxHighlighter.POD_VERBATIM_KEY), new AttributesDescriptor(PerlBundle.message("pod.color.settings.paragraph"), PodSyntaxHighlighter.POD_TEXT_KEY), new AttributesDescriptor(PerlBundle.message("pod.color.settings.formatter"), PodSyntaxHighlighter.POD_FORMATTER_TAG_KEY), new AttributesDescriptor(PerlBundle.message("pod.color.settings.formatter.markup"), PodSyntaxHighlighter.POD_FORMATTER_MARKUP_KEY), }; @Nullable @Override public Icon getIcon() { return PerlIcons.POD_FILE; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new PodSyntaxHighlighter(null); } @NotNull @Override public String getDemoText() { return CodeStyleAbstractPanel.readFromFile(PodColorSettingsPage.class, "podColorsSample.txt"); } @Nullable @Override public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "Perl5 POD"; } }
1456e96725d57acc9b67e7cb3363efea279ef189
e371b14b7e1a154eecaae94d555733639491d6f4
/src/main/java/patrologia/translator/basicelements/WordType.java
4abb5ffc6ecf11428d3e6cecb54c598de54e0400
[]
no_license
lkloeble/translator
c2c3b1b9036ac6c1215e30faa6a323440fd71271
de08b4ce1f629c83c2dda90c48a473d6844fe92c
refs/heads/master
2023-08-17T05:51:10.451208
2023-08-04T07:41:47
2023-08-04T07:41:47
108,137,828
1
0
null
2020-10-13T09:42:04
2017-10-24T14:22:48
Java
UTF-8
Java
false
false
219
java
package patrologia.translator.basicelements; public enum WordType { PREPOSITION, NOUN, VERB, NO_TRANSLATION, UNKNOWN; public String getDefinitionString() { return toString().substring(0,4); } }
f963fb5dc242e8a9ccac9ec130f944e75c821393
700f5eb3791954eabdaf03f7473f60e75bce2a75
/Assignment 3/Tube.java
96b8c1bcd612df8df5c96253d9194d5f07a47c43
[]
no_license
gregoryj17/ProgrammingParadigms
8077a427da393f332f4e3b6320554363a1087bf7
e813efe5174d074cde7989e66dc81be72dadd742
refs/heads/master
2021-05-11T08:12:07.755444
2018-04-28T03:03:39
2018-04-28T03:03:39
118,044,091
0
1
null
null
null
null
UTF-8
Java
false
false
796
java
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class Tube{ //Tube position int x,y; final int w=55,h=400; static BufferedImage image; //Constructs a tube with a position public Tube(int x, int y){ this.x=x; this.y=y; } public Tube(Json json){ this.x=(int)json.getLong("x"); this.y=(int)json.getLong("y"); } boolean wasClicked(int clickX, int clickY){ return (clickX>=x&&clickX<=x+w&&clickY>=y&&clickY<=y+h); } Json marshal(){ Json ob = Json.newObject(); ob.add("x",x); ob.add("y",y); return ob; } BufferedImage getImage(){ try{ if(image==null){ image=ImageIO.read(new File("tube.png")); } }catch(Exception e){ e.printStackTrace(System.err); System.exit(1); } return image; } }
137f93a4a4f6549eb4671a67fc48511deca7eb5e
fbe1ea6c99a1518857c3d59f512c37b979024c67
/src/main/java/lsieun/cert/asn1/ASN1Struct.java
36072dfc0f2a402fcc00560ed115b0f389a29062
[ "MIT" ]
permissive
lsieun/learn-crypto
58b6a6cfe3abe89b588710b019aa9abf365b133b
abc9745495c605add36b6d021a6d3a4a294bc980
refs/heads/master
2022-11-27T19:02:35.071322
2020-08-01T12:40:50
2020-08-01T12:40:50
284,254,562
1
0
null
null
null
null
UTF-8
Java
false
false
890
java
package lsieun.cert.asn1; import lsieun.utils.ByteUtils; import java.util.LinkedList; import java.util.List; public class ASN1Struct { public final boolean constructed; // bit 6 of the identifier byte public final int tag_class; // bits 7-8 of the identifier byte public final int tag; // bits 1-5 of the identifier byte public final int length; public final byte[] header; public final byte[] data; public final List<ASN1Struct> children = new LinkedList<>(); public ASN1Struct(int tag, boolean constructed, int tag_class, int length, byte[] header, byte[] data) { this.tag = tag; this.constructed = constructed; this.tag_class = tag_class; this.length = length; this.header = header; this.data = data; } public byte[] toByteArray() { return ByteUtils.concatenate(header, data); } }
21e51ee44c1d20df6372ab6c12c597f2b15b524e
364bd91497a498b899c1de60e1ff028795eddbbc
/02Benchmarks/Openj9Test-Test/src/com/sun/jmx/remote/NotificationMarshalVersions/Client/ConfigKey.java
2dc5b1b0aa9a324cc515f8c0e86193565497441f
[]
no_license
JavaTailor/CFSynthesis
8485f5d94cec335bedfdf18c88ddc523e05a0567
bf9421fea49469fbac554da91169cf07aae3e08c
refs/heads/master
2023-04-15T02:37:04.252151
2021-11-12T09:57:06
2021-11-12T09:57:06
402,928,654
4
1
null
null
null
null
UTF-8
Java
false
false
1,168
java
package com.sun.jmx.remote.NotificationMarshalVersions.Client; /** * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ public enum ConfigKey { CONSTANT3, CONSTANT2; }
1bcff1e4df1906efb9c8a266ccf4fe6e9b7f8727
f774c73aae3e6b5d4411b37a8387185b7702dc35
/backend/src/main/java/com/company/backend/service/impl/UserServiceImpl.java
cff08d4a68626b9e48d047ef1c2bc1bcc550fe18
[]
no_license
entropiyaa/Monitor-sensors
beabbbc050b82c6c44bc7dd0ed05c191a098ff40
a1e60aa0d5088bdb0a1bcbb96cc35f51b8dd39be
refs/heads/main
2023-02-06T05:57:17.544005
2020-12-26T12:59:32
2020-12-26T12:59:32
308,088,052
0
0
null
null
null
null
UTF-8
Java
false
false
1,038
java
package com.company.backend.service.impl; import com.company.backend.entity.User; import com.company.backend.entity.enums.UserRole; import com.company.backend.repository.UserRepository; import com.company.backend.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserServiceImpl implements UserService { private UserRepository userRepository; @Autowired public UserServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override public User findById(Long userId) { Optional<User> optionalUser = userRepository.findById(userId); return optionalUser.orElse(null); } @Override public List<User> findAll() { return userRepository.findAll(); } @Override public User save(User user) { user.setRole(UserRole.USER); return userRepository.save(user); } }
30e6e9816e6afbab3c357f1d5c508d8b8407009c
52a612d7c6e6a608dead42d8c8c5eba24de48c91
/src/main/java/com/telkom/reacttestapp2/config/ApplicationProperties.java
2e513e2316adf13225fcb87527d9a137c6ed7aeb
[]
no_license
Ravikumara6970/ReactTestApp2
427c3df1ceb8a312e5d7c69a7d8490cf67dab1b2
076e400b0e0623e17bec57c9460d9732f5c0b53a
refs/heads/master
2022-12-21T23:29:54.928371
2019-12-04T10:33:41
2019-12-04T10:33:41
225,825,134
0
0
null
2022-12-16T04:42:08
2019-12-04T09:10:52
TypeScript
UTF-8
Java
false
false
441
java
package com.telkom.reacttestapp2.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to React Test App 2. * <p> * Properties are configured in the {@code application.yml} file. * See {@link io.github.jhipster.config.JHipsterProperties} for a good example. */ @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) public class ApplicationProperties { }
88938ae3f811ee43520243600b917392d7de56fd
ce06aa9321fc7225445d6414397558b6017fdd9c
/website/src/main/java/info/xiaomo/website/view/WorksView.java
eff3cfb1da188155fd909f0001e6fd6b33b0e52a
[]
no_license
zhuangsen/springboot-api
e50e8fae6af3cd634125a5f1534010c451171a98
ee1cfd57b7fe8dca0513eff6f85cb063db110de5
refs/heads/master
2021-03-16T04:43:18.982519
2017-06-19T01:22:00
2017-06-19T01:22:00
91,531,888
1
0
null
null
null
null
UTF-8
Java
false
false
758
java
package info.xiaomo.website.view; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! * Created by IntelliJ IDEA. * * author: xiaomo * github: https://github.com/xiaomoinfo * email: [email protected] * Date: 2016/11/21 11:12 * Copyright(©) 2015 by xiaomo. **/ public enum WorksView { LOGIN("login"), REGISTER("register"), REGISTER_INFO("info"), INDEX("/web/index"); private String name; WorksView(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
cb61174d83bf327b3b6073182e84baec7d214b0b
a668a8d0d1befdc7d1035fa2b6395d176c538ee6
/CTCI_book/treesNgraphs/Practise.java
4d1d6e8a58bb8cc9540ca2ea24e70f1ac896d3ae
[]
no_license
SameenaThab/hankerrank-leetcode-geeksforgeeks
1e8b691b3e18438f66ef695c25cafa3259cfb735
f2f638f77894c09e032d5b88a6c3e470e4afcf7a
refs/heads/master
2023-01-11T15:45:35.948252
2022-12-22T21:38:05
2022-12-22T21:38:05
132,793,048
0
3
null
null
null
null
UTF-8
Java
false
false
3,654
java
import java.util.*; class GraphNode { String name; Status status; List<GraphNode> neighbors; GraphNode(String name) { this.name = name; this.neighbors = new ArrayList<GraphNode>(); this.status = Status.BLANK; } public void addEdge(GraphNode node){ neighbors.add(node); } } enum Status { PROCESSING,COMPLETED,BLANK } class Graph { HashMap<String,GraphNode> nodes; public Graph(String[] project_names,String[][] dependencies) { this.nodes = new HashMap<String,GraphNode>(); for(String name:project_names) { nodes.put(name,new GraphNode(name)); } for(String[] dependency:dependencies) { this.nodes.get(dependency[0]).addEdge(this.nodes.get(dependency[1])); } } } class TreeNode { int data; TreeNode left; TreeNode right; // int size; TreeNode(int data){ this.data=data; this.left=null; this.right=null; // this.size=1; } TreeNode(int data,TreeNode parent){ this.data=data; this.left=null; this.right=null; // this.parent=parent; } void inOrderTraversal() { if(this.left != null) this.left.inOrderTraversal(); System.out.print(this.data+" "); if(this.right != null) this.right.inOrderTraversal(); } } class Result { TreeNode node; boolean isanncestor; Result(TreeNode node,boolean isanncestor) { this.node=node; this.isanncestor=isanncestor; } } public class Practise { public static void main(String[] args) { TreeNode root=new TreeNode(4); TreeNode left=new TreeNode(3); left.left=new TreeNode(1); left.right=new TreeNode(2); root.left=left; TreeNode right = new TreeNode(6); right.left=new TreeNode(5); right.right=new TreeNode(7); root.right=right; ArrayList<LinkedList<Integer>> result = getSequences(root); for(LinkedList<Integer> list : result) { System.out.println(list.toString()); } } public static ArrayList<LinkedList<Integer>> getSequences(TreeNode root) { ArrayList<LinkedList<Integer>> result = new ArrayList<LinkedList<Integer>>(); if(root == null){ result.add(new LinkedList<Integer>()); return result; } LinkedList<Integer> prefix = new LinkedList<Integer>(); prefix.addFirst(root.data); ArrayList<LinkedList<Integer>> leftSeq = getSequences(root.left); ArrayList<LinkedList<Integer>> rightSeq = getSequences(root.right); for(LinkedList<Integer> left:leftSeq) { for(LinkedList<Integer> right:rightSeq) { weave(left,right,result,prefix); } } return result; } public static void weave(LinkedList<Integer> left,LinkedList<Integer> right,ArrayList<LinkedList<Integer>> results,LinkedList<Integer> prefix) { if(left.size()==0||right.size()==0) { LinkedList<Integer> result = (LinkedList<Integer>) prefix.clone(); result.addAll(left); result.addAll(right); results.add(result); return; } int leftHead = left.removeFirst(); prefix.addLast(leftHead); weave(left,right,results,prefix); prefix.removeLast(); left.addFirst(leftHead); int rightHead = right.removeFirst(); prefix.addLast(rightHead); weave(left,right,results,prefix); prefix.removeLast(); right.addFirst(rightHead); } }
39c60798aaa1c8e47bb8a354c5ae91c0e488d0e4
ed9eaec84195d990b7f05623e152d75cac98769a
/src/main/java/io/stibits/config/JacksonConfiguration.java
df09f8db85a6a7c2e4c65a4da7ca9c3803fbed76
[]
no_license
BulkSecurityGeneratorProject/extract-from-blockchain
4ef3a22ea6fe49fb369144d1a18edda198803ea4
3f728325a7a17b6fb26349a59a14cf1c05945f16
refs/heads/master
2022-12-10T07:41:13.695608
2019-04-22T11:23:45
2019-04-22T11:23:45
296,582,922
0
0
null
2020-09-18T09:59:14
2020-09-18T09:59:13
null
UTF-8
Java
false
false
1,639
java
package io.stibits.config; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.problem.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate5Module hibernate5Module() { return new Hibernate5Module(); } /* * Jackson Afterburner module to speed up serialization/deserialization. */ @Bean public AfterburnerModule afterburnerModule() { return new AfterburnerModule(); } /* * Module for serialization/deserialization of RFC7807 Problem. */ @Bean ProblemModule problemModule() { return new ProblemModule(); } /* * Module for serialization/deserialization of ConstraintViolationProblem. */ @Bean ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } }
ea591c403c215109211d2d1fbec277d25adabc87
dce6846b059cd3ec43a2c9e591e70d9adc785312
/2020.11/[2588] 곱셈.java
b9e0a9517f406c9135d15b3a63d80cb198ce6d4f
[]
no_license
yebinkang/Baekjoon
fb584a6d318b5bc7d1a8de9ddfcc44e5fff58d4b
b5036380646ab55f4340c56108a7964a733d579f
refs/heads/master
2023-03-07T03:58:00.983209
2021-02-17T04:10:16
2021-02-17T04:10:16
298,847,293
0
0
null
null
null
null
UTF-8
Java
false
false
375
java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); System.out.println(a * (b % 10)); System.out.println(a * ((b / 10) % 10)); System.out.println(a * (b / 100)); System.out.println(a * b); } }
d6eb0a6f586e6f56b48dc28afe8b31444add0b6b
bceba483c2d1831f0262931b7fc72d5c75954e18
/src/qubed/corelogic/TILPAYMENTSUMMARYITEMS.java
ed45e69a1b22e6550d463076744882a3cf4043c6
[]
no_license
Nigel-Qubed/credit-services
6e2acfdb936ab831a986fabeb6cefa74f03c672c
21402c6d4328c93387fd8baf0efd8972442d2174
refs/heads/master
2022-12-01T02:36:57.495363
2020-08-10T17:26:07
2020-08-10T17:26:07
285,552,565
0
1
null
null
null
null
UTF-8
Java
false
false
5,086
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.08.05 at 04:46:29 AM CAT // package qubed.corelogic; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; /** * <p>Java class for TIL_PAYMENT_SUMMARY_ITEMS complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TIL_PAYMENT_SUMMARY_ITEMS"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TIL_PAYMENT_SUMMARY_ITEM" type="{http://www.mismo.org/residential/2009/schemas}TIL_PAYMENT_SUMMARY_ITEM" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="EXTENSION" type="{http://www.mismo.org/residential/2009/schemas}TIL_PAYMENT_SUMMARY_ITEMS_EXTENSION" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.w3.org/1999/xlink}MISMOresourceLink"/> * &lt;attGroup ref="{http://www.mismo.org/residential/2009/schemas}AttributeExtension"/> * &lt;anyAttribute processContents='lax'/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TIL_PAYMENT_SUMMARY_ITEMS", propOrder = { "tilpaymentsummaryitem", "extension" }) public class TILPAYMENTSUMMARYITEMS { @XmlElement(name = "TIL_PAYMENT_SUMMARY_ITEM") protected List<TILPAYMENTSUMMARYITEM> tilpaymentsummaryitem; @XmlElement(name = "EXTENSION") protected TILPAYMENTSUMMARYITEMSEXTENSION extension; @XmlAttribute(name = "label", namespace = "http://www.w3.org/1999/xlink") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String label; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the tilpaymentsummaryitem property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the tilpaymentsummaryitem property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTILPAYMENTSUMMARYITEM().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TILPAYMENTSUMMARYITEM } * * */ public List<TILPAYMENTSUMMARYITEM> getTILPAYMENTSUMMARYITEM() { if (tilpaymentsummaryitem == null) { tilpaymentsummaryitem = new ArrayList<TILPAYMENTSUMMARYITEM>(); } return this.tilpaymentsummaryitem; } /** * Gets the value of the extension property. * * @return * possible object is * {@link TILPAYMENTSUMMARYITEMSEXTENSION } * */ public TILPAYMENTSUMMARYITEMSEXTENSION getEXTENSION() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link TILPAYMENTSUMMARYITEMSEXTENSION } * */ public void setEXTENSION(TILPAYMENTSUMMARYITEMSEXTENSION value) { this.extension = value; } /** * Gets the value of the label property. * * @return * possible object is * {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is * {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
125adfac8fe52b9566fa479bb54d448e5b2e5ce5
2240a39c09db4a74c1c80c737bc5399bbe10a824
/app/src/main/java/com/team2052/frckrawler/bluetooth/client/ScoutPackage.java
b126f523114f6bc457e6ba1fc2ff3f94c87090d5
[ "MIT" ]
permissive
MAKtheUnknown/FRC-Krawler
96c8bccc2315cc68175ff88d1e90598fb17738a3
166052279a206e2a525812c0522d7a1b86f7711e
refs/heads/master
2020-12-25T20:43:01.165372
2016-09-16T01:36:34
2016-09-16T01:36:34
59,162,880
0
0
null
2016-05-19T01:11:43
2016-05-19T01:11:42
null
UTF-8
Java
false
false
3,443
java
package com.team2052.frckrawler.bluetooth.client; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.team2052.frckrawler.GlobalValues; import com.team2052.frckrawler.database.DBManager; import com.team2052.frckrawler.database.Schedule; import com.team2052.frckrawler.db.Event; import com.team2052.frckrawler.db.Game; import com.team2052.frckrawler.db.Match; import com.team2052.frckrawler.db.Metric; import com.team2052.frckrawler.db.Robot; import com.team2052.frckrawler.db.RobotEvent; import com.team2052.frckrawler.db.Team; import com.team2052.frckrawler.db.User; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * A object that contains all the data that is sent to the scout * Easier to manage * * @author Adam * @since 12/24/2014. */ public class ScoutPackage implements Serializable { private final ArrayList<Team> teams = new ArrayList<>(); private final Schedule schedule; private final List<Metric> metrics; private final List<User> users; private final List<RobotEvent> robot_events; private final List<Robot> robots = new ArrayList<>(); private final Event event; private final Game game; private final String TAG = ScoutPackage.class.getSimpleName(); public ScoutPackage(DBManager dbManager, Event event) { this.game = dbManager.getGamesTable().load(event.getGame_id()); this.event = event; users = dbManager.getUsersTable().loadAll(); game.resetMetricList(); metrics = game.getMetricList(); robot_events = event.getRobotEventList(); for (RobotEvent robotEvent : robot_events) { robots.add(dbManager.getRobotEvents().getRobot(robotEvent)); } schedule = new Schedule(event); for (RobotEvent robotEvent : robot_events) { teams.add(dbManager.getRobotEvents().getTeam(robotEvent)); } } public void save(final DBManager dbManager, Context context) { Log.d(TAG, "Saving"); dbManager.runInTx(() -> { for (Metric metric : metrics) { dbManager.getMetricsTable().insert(metric); } for (User user : users) { dbManager.getUsersTable().insert(user); } for (RobotEvent robotEvent : robot_events) { dbManager.getRobotEvents().insert(robotEvent); } for (Robot robot : robots) { dbManager.getRobotsTable().insert(robot); } for (Team team : teams) { dbManager.getTeamsTable().insert(team); } for (Match match : schedule.matches) { dbManager.getMatchesTable().insert(match); } dbManager.getEventsTable().insert(event); dbManager.getGamesTable().insert(game); } ); SharedPreferences sharedPreferences = context.getSharedPreferences(GlobalValues.PREFS_FILE_NAME, 0); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(GlobalValues.CURRENT_SCOUT_EVENT_ID, event.getId()); editor.apply(); } public Event getEvent() { return event; } }
9c10ef7f5649e6b0820a303b463b5b4877e4c8c0
505fc34f5a68aaf06a234213718fe66c19ffab30
/xc-service-manage-cms/src/main/java/com/xuecheng/manage_cms/ManageCmsApplication.java
28edc57ef406a1061da14fdceac95015d40ed055
[]
no_license
BossDing/EducationPlatform
d4f3e8334a4b5dc487a48d44787350aa15c694e6
bdca1a84300cfc609598aa46b06be406d12189b8
refs/heads/master
2020-06-20T12:38:36.771747
2019-07-03T06:26:22
2019-07-03T06:26:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
747
java
package com.xuecheng.manage_cms; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @EntityScan("com.xuecheng.framework.domain.cms") @ComponentScan(basePackages="com.xuecheng.framework")//扫描common工程下的类 @ComponentScan(basePackages={"com.xuecheng.api"}) @ComponentScan(basePackages = {"com.xuecheng.manage_cms"}) public class ManageCmsApplication { public static void main(String[] args) { SpringApplication.run(ManageCmsApplication.class,args); } }
11a7dc139b753505114acfd9e9a0054a61681ab6
6d80a99e48407bcd110bc65e5d92266943f67613
/PPO/Lab6/NativeLab/app/src/main/java/ru/startandroid/nativelab/MainActivity.java
d17cf1ede59e6130afd26289d014a1ae76a2dae2
[]
no_license
alexanderkurilenko/bsuir
7ced134113bcf3ddb7a7e43f2ed3d2faa6af3928
a9bfa50eb1c48053a666c9f331224dd67ccb5ebc
refs/heads/master
2021-08-31T17:29:54.436397
2017-12-22T07:53:00
2017-12-22T07:53:00
115,917,814
1
0
null
2018-01-01T12:28:13
2018-01-01T12:28:12
null
UTF-8
Java
false
false
879
java
package ru.startandroid.nativelab; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import ru.startandroid.nativelab.R; public class MainActivity extends Activity { TextView text; Button button; static { System.loadLibrary("nativelab"); } private static native String stringFromJNI(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView) findViewById(R.id.text); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.setText(stringFromJNI()); } }); } }
29e480501b592b963cf13f35d7b7280ff6fea38b
8585d258a3011c2e82d89397b5101a5aad256d79
/object_oriented/dynamic_array/DynamicArray.java
2471f865fc6e020d2f5395c8af1f59f5d220d8ee
[]
no_license
aierwa/designpatterns
c74b218269e55084f2a7014bf4da6617e6c4df8e
116a5b6f0b41ce21b3711c8d3a46ac732e9f6aef
refs/heads/master
2022-12-22T00:33:50.089985
2020-07-09T14:50:12
2020-07-09T14:50:12
249,639,277
0
1
null
2022-12-14T20:43:52
2020-03-24T07:21:07
Java
UTF-8
Java
false
false
1,467
java
import java.util.Arrays; /** * @author xuxiang * 2020/3/26 */ public class DynamicArray { private static final int DEFAULT_CAPACITY = 10; protected int size = 0; protected float factor = 0.75f; protected int capacity = DEFAULT_CAPACITY; protected Integer[] elements = new Integer[capacity]; public DynamicArray(){} public DynamicArray(int capacity){ if (capacity < 0) { throw new IllegalArgumentException("invalid capacity: " + capacity); } this.capacity = capacity; elements = new Integer[capacity]; } public int size() { return this.size; } public Integer get(int index) { return elements[index]; } public void add(Integer element) { ensureCapacity(); elements[size++] = element; } protected void ensureCapacity() { if (this.size > capacity - 1 ) { elements = Arrays.copyOf(elements, (int) (this.size / factor) + 1); } } @Override public String toString() { if (this.size == 0) { return "[]"; } StringBuilder stringBuilder= new StringBuilder("["); for (int i = 0; i < size; i++) { stringBuilder.append(elements[i]); if (i == size - 1) { return stringBuilder.append("]").toString(); } stringBuilder.append(", "); } return stringBuilder.toString(); } }
e68858e4e7fd1ced8fa487d5c03eb7e5673c65e4
20b9179aab3d44f07b05e0c7a2bb7e6491db723a
/app/src/main/java/jarvis/com/kline/WeatherBean.java
81533c9bd80e944e3c4f9ae958a6a7fbab1948c5
[]
no_license
JarvisGG/Kline
f88e25c4f00d0d296a21a187b9c9ee1ec9b7eea9
a00a9d40cbff3196876d6e6c88e2e48fb546f5ea
refs/heads/master
2020-05-29T15:33:10.632812
2019-06-03T06:10:13
2019-06-03T06:10:13
189,225,328
2
0
null
null
null
null
UTF-8
Java
false
false
1,184
java
package jarvis.com.kline; /** * Created by ccy on 2017-07-28. */ public class WeatherBean { public static final String SUN = "晴"; public static final String CLOUDY ="阴"; public static final String SNOW = "雪"; public static final String RAIN = "雨"; public static final String SUN_CLOUD = "多云"; public static final String THUNDER = "雷"; public String weather; //天气,取值为上面6种 public int temperature; //温度值 public String temperatureStr; //温度的描述值 public String time; //时间值 public WeatherBean(String weather, int temperature,String time) { this.weather = weather; this.temperature = temperature; this.time = time; this.temperatureStr = temperature + "°"; } public WeatherBean(String weather, int temperature, String temperatureStr, String time) { this.weather = weather; this.temperature = temperature; this.temperatureStr = temperatureStr; this.time = time; } public static String[] getAllWeathers(){ String[] str = {SUN,RAIN,CLOUDY,SUN_CLOUD,SNOW,THUNDER}; return str; } }
944472cbaa56c2c61eeef1ab411aea48b17d0fcc
5edd4126bded57ed129be1547761e1369477d350
/src/main/java/com/gram/user/CustomAuthenticationProvider.java
fc75d90c1398b4d977a74a54bcc48a844ef8b6d4
[]
no_license
kimjiwoong76/gram
20a53686338fb6d2af5fec4a72cc249b0867058f
2338993e3c59a0d77dcbd4e7eead79a3351f4593
refs/heads/master
2023-08-08T01:00:02.288621
2021-09-14T05:29:25
2021-09-14T05:29:25
364,568,148
2
0
null
null
null
null
UTF-8
Java
false
false
1,792
java
package com.gram.user; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; public class CustomAuthenticationProvider implements AuthenticationProvider { @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); System.out.println("111"); UserSecurityVO user = (UserSecurityVO) userService.loadUserByUsername(username); System.out.println("=== 작업중"); System.out.println(password); System.out.println(user.getPassword()); // password 일치하지 않으면! if(!passwordEncoder.matches(password, user.getPassword())){ throw new BadCredentialsException("BadCredentialsException"); } return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities()); } // 토큰 타입과 일치할 때 인증 @Override public boolean supports(Class<?> authentication) { // TODO Auto-generated method stub // return false 하면 이 클래스 안탐 return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } }
[ "cubiginc@DESKTOP-MPS60MT" ]
cubiginc@DESKTOP-MPS60MT
0f353c7287d082a7d25244b747645cb1cdb6a31b
5a561a47705f078bd8478ff422842443a8c7de06
/2011/Gamma2011/src/SolutionTest.java
66d6e917822c2c8c70257568ce8da0cd7d7f2f74
[]
no_license
chzdo/CodilityChallenge
f6757818b584b9cfcbf1b4088accf17ecbd109dd
2cfd5a986ba748937639766d95744ec7a09a51f9
refs/heads/master
2023-08-02T19:31:56.222608
2021-07-10T12:06:50
2021-07-10T12:06:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
508
java
import org.junit.Test; import org.junit.Assert; public class SolutionTest { @Test public void test1() { testInternal(6, "baababa"); } @Test public void test2() { testInternal(7, "caabbbaa"); } @Test public void test3() { testInternal(24, "abababbbabbbaba"); } private void testInternal(int expectedResult, String s) { var actualResult = new Solution().solution(s); Assert.assertEquals(expectedResult, actualResult); } }
e1bdb61fdc6baf3b35afd46a83f9eb2192b88e80
0491b8be44a000744dad0ccac3727737156c0854
/KURS/Homework/src/main/java/pl/coderslab/Servlet16.java
c8bb9c83969e17def4b76237fef26369fd293bf4
[]
no_license
slapuch85/Homework03
cb933604c4f3d6ee343b2a83c0f2f38a6c40bbbc
083935573c3ac661485b13f76dc7e20ebc2a388b
refs/heads/master
2020-04-17T01:37:19.937985
2019-03-30T11:01:27
2019-03-30T11:01:27
166,100,487
0
0
null
null
null
null
UTF-8
Java
false
false
1,107
java
package pl.coderslab; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; @WebServlet("/Servlet16") public class Servlet16 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> map = new HashMap<String, String>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } Set<Map.Entry<String, String>> entrySet = map.entrySet(); request.setAttribute("pairs", entrySet); getServletContext().getRequestDispatcher("/jsp16.jsp").forward(request, response); } }
accdfa6c18e279591ec62df07cd838b7ef21fda5
9fbc8a3b49e5f5889bb7441ddcf0e6576bab4b77
/happyparty/src/main/java/com/party/domain/Site.java
c730c92ac9ab8761707467de19c91ef45b7c4b70
[ "Apache-2.0" ]
permissive
Phapha1996/happyparty
3d1f4d56906040c423e782233996adb4de170af4
20011ff3c967e21566d71ff203fd80adb89652c4
refs/heads/master
2020-12-02T06:36:08.809214
2017-07-11T06:57:35
2017-07-11T06:57:35
96,860,837
0
0
null
null
null
null
UTF-8
Java
false
false
3,058
java
package com.party.domain; import java.math.BigDecimal; import java.util.List; public class Site { private int siid; //主键 private String title; //标题 private BigDecimal price; //价格 private Double weekPrice; //周末价格 private String city; //城市 private String address; //地址 private int room_num; //房间数 private int bed_num; //床位数 private int apply; //适合人数 private String tags; //标签 private String description; //介绍 private String facilities; //配套设施 private String reference; //补充介绍 private String remind; //温馨提示 private String wechat; //微信 private int num; //数量 private int sequence; //排序 private int admin_id; //管理员外键 private List<Img> imgs; public List<Img> getImgs() { return imgs; } public void setImgs(List<Img> imgs) { this.imgs = imgs; } public int getSiid() { return siid; } public void setSiid(int siid) { this.siid = siid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getRoom_num() { return room_num; } public void setRoom_num(int room_num) { this.room_num = room_num; } public int getBed_num() { return bed_num; } public void setBed_num(int bed_num) { this.bed_num = bed_num; } public int getApply() { return apply; } public void setApply(int apply) { this.apply = apply; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFacilities() { return facilities; } public void setFacilities(String facilities) { this.facilities = facilities; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public String getRemind() { return remind; } public void setRemind(String remind) { this.remind = remind; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public int getAdmin_id() { return admin_id; } public void setAdmin_id(int admin_id) { this.admin_id = admin_id; } public Double getWeekPrice() { return weekPrice; } public void setWeekPrice(Double weekPrice) { this.weekPrice = weekPrice; } public String getWechat() { return wechat; } public void setWechat(String wechat) { this.wechat = wechat; } }
23ba1d176438127f3ce003319c9a5dd7a392baf2
f41135abcf1ce3e23adfa7569d939de4d254f824
/algorithms/graph/cycle/johnson/all/cycles/KosarajuSharirSCCWeighted.java
e836eba11e5acb96f2b0ad05b3d8e9f2f5ffb934
[]
no_license
AmazingAnu/competitive-programming
cc2f9fbcbbe0fa763baaecde80e4047b08455c84
d1fb464c25519fea2d3821be364f157991d9c848
refs/heads/master
2022-06-16T18:12:14.192521
2020-05-09T14:32:54
2020-05-09T14:32:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,758
java
package algorithms.graph.cycle.johnson.all.cycles; import datastructures.graph.DirectedEdge; import datastructures.graph.EdgeWeightedDigraph; import java.util.ArrayList; import java.util.List; /** * Created by rene on 30/12/17. */ public class KosarajuSharirSCCWeighted { private boolean[] visited; // reached vertices private int[] id; // component identifiers private int count; // number of strong components private EdgeWeightedDigraph edgeWeightedDigraph; public KosarajuSharirSCCWeighted(EdgeWeightedDigraph edgeWeightedDigraph) { visited = new boolean[edgeWeightedDigraph.vertices()]; id = new int[edgeWeightedDigraph.vertices()]; this.edgeWeightedDigraph = edgeWeightedDigraph; DepthFirstOrderDirectedWeighted depthFirstOrder = new DepthFirstOrderDirectedWeighted(edgeWeightedDigraph.reverse()); for(int vertex : depthFirstOrder.reversePostOrder()) { if (!visited[vertex]) { dfs(edgeWeightedDigraph, vertex); count++; } } } private void dfs(EdgeWeightedDigraph edgeWeightedDigraph, int vertex) { visited[vertex] = true; id[vertex] = count; for(DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) { int neighbor = edge.to(); if (!visited[neighbor]) { dfs(edgeWeightedDigraph, neighbor); } } } @SuppressWarnings("unchecked") public List<Integer>[] getSCCs() { List<Integer>[] stronglyConnectedComponents = (List<Integer>[]) new ArrayList[count]; for(int scc = 0; scc < count; scc++) { stronglyConnectedComponents[scc] = new ArrayList<>(); } for(int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) { stronglyConnectedComponents[id(vertex)].add(vertex); } return stronglyConnectedComponents; } public EdgeWeightedDigraph getKernelDAG() { EdgeWeightedDigraph kernelDAG = new EdgeWeightedDigraph(count()); for(int vertex = 0; vertex < edgeWeightedDigraph.vertices(); vertex++) { for(DirectedEdge edge : edgeWeightedDigraph.adjacent(vertex)) { int neighbor = edge.to(); if (id(vertex) != id(neighbor)) { kernelDAG.addEdge(new DirectedEdge(id(vertex), id(neighbor), edge.weight())); } } } return kernelDAG; } public boolean stronglyConnected(int vertex1, int vertex2) { return id[vertex1] == id[vertex2]; } public int id(int vertex) { return id[vertex]; } public int count() { return count; } }
48c2c974269004ba29cb58f510b1079253e07d8c
5685374483a22cd645df7e54fb5ee5cf31d99194
/Location/Lab8_LocationLab/src/course/labs/locationlab/PlaceViewActivity.java
be3c987633908182f744bc2149d19c0ec2c48bf6
[ "MIT" ]
permissive
JacksonSildu/coursera-android
9e481dea71a20e59337cdead0b041f4b95654f4d
70cc25bc615993b28ff731ca936d00f3152212f3
refs/heads/master
2021-01-19T10:49:11.660259
2015-07-29T02:05:55
2015-07-29T02:05:55
39,867,815
0
0
null
null
null
null
UTF-8
Java
false
false
8,068
java
package course.labs.locationlab; import android.annotation.SuppressLint; import android.app.ListActivity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import android.widget.Toast; public class PlaceViewActivity extends ListActivity implements LocationListener { private static final long FIVE_MINS = 5 * 60 * 1000; private static String TAG = "Lab-Location"; // False if you don't have network access public static boolean sHasNetwork = true; private Location mLastLocationReading; private PlaceViewAdapter mAdapter; private LocationManager mLocationManager; private boolean mMockLocationOn = false; // default minimum time between new readings private long mMinTime = 5000; // default minimum distance between old and new readings. private float mMinDistance = 1000.0f; // A fake location provider used for testing private MockLocationProvider mMockLocationProvider; @SuppressLint("InflateParams") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up the app's user interface. This class is a ListActivity, // so it has its own ListView. ListView's adapter should be a PlaceViewAdapter mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); ListView placesListView = getListView(); // TODO - add a footerView to the ListView // You can use footer_view.xml to define the footer LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View footerView = inflater.inflate(R.layout.footer_view, null); // TODO - footerView must respond to user clicks, handling 3 cases: // There is no current location - response is up to you. The best // solution is to always disable the footerView until you have a // location. // There is a current location, but the user has already acquired a // PlaceBadge for this location - issue a Toast message with the text - // "You already have this location badge." // Use the PlaceRecord class' intersects() method to determine whether // a PlaceBadge already exists for a given location // There is a current location for which the user does not already have // a PlaceBadge. In this case download the information needed to make a new // PlaceBadge. footerView.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (mLastLocationReading != null) { for (PlaceRecord place : mAdapter.getList()) { if (place.intersects(mLastLocationReading)) { Toast.makeText(getApplicationContext(), getText(R.string.duplicate_location_string), Toast.LENGTH_LONG).show(); return; } } PlaceDownloaderTask t = new PlaceDownloaderTask(PlaceViewActivity.this, sHasNetwork); t.execute(mLastLocationReading); } else { Toast.makeText(getApplicationContext(), "Current Location is unavailable", Toast.LENGTH_LONG).show(); } } }); placesListView.addFooterView(footerView); mAdapter = new PlaceViewAdapter(getApplicationContext()); setListAdapter(mAdapter); } @Override protected void onResume() { super.onResume(); startMockLocationManager(); // TODO - Check NETWORK_PROVIDER for an existing location reading. // Only keep this last reading if it is fresh - less than 5 minutes old long limitAge = FIVE_MINS; Location lastLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (null != lastLocation) { long age = ageInMilliseconds(lastLocation); if (age < limitAge) { mLastLocationReading = lastLocation; } else { mLastLocationReading = null; } } // TODO - register to receive location updates from NETWORK_PROVIDER if (null != mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER)) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mMinTime, mMinDistance, PlaceViewActivity.this); // sHasNetwork = true; } } @Override protected void onPause() { // TODO - unregister for location updates if (null != mLocationManager) { mLocationManager.removeUpdates(PlaceViewActivity.this); } shutdownMockLocationManager(); super.onPause(); } // Callback method used by PlaceDownloaderTask public void addNewPlace(PlaceRecord place) { // TODO - Attempt to add place to the adapter, considering the following cases // A PlaceBadge for this location already exists - issue a Toast message // with the text - "You already have this location badge." Use the PlaceRecord // class' intersects() method to determine whether a PlaceBadge already exists // for a given location. Do not add the PlaceBadge to the adapter // The place is null - issue a Toast message with the text // "PlaceBadge could not be acquired" // Do not add the PlaceBadge to the adapter // The place has no country name - issue a Toast message // with the text - "There is no country at this location". // Do not add the PlaceBadge to the adapter // Otherwise - add the PlaceBadge to the adapter if (null == place) { Toast.makeText(this.getApplicationContext(), "PlaceBadge could not be acquired", Toast.LENGTH_LONG).show(); } else if (mAdapter.intersects(place.getLocation())) { Toast.makeText(this.getApplicationContext(), getText(R.string.duplicate_location_string), Toast.LENGTH_LONG).show(); } else if (null == place.getCountryName() || place.getCountryName().equals("")) { Toast.makeText(this.getApplicationContext(), getText(R.string.no_country_string), Toast.LENGTH_LONG).show(); } else { mAdapter.add(place); } } // LocationListener methods @Override public void onLocationChanged(Location currentLocation) { // TODO - Update location considering the following cases. // 1) If there is no last location, set the last location to the current location. // 2) If the current location is older than the last location, ignore the current location // 3) If the current location is newer than the last locations, keep the // current location. if (null != mLastLocationReading) { if (ageInMilliseconds(currentLocation) < ageInMilliseconds(mLastLocationReading)) { mLastLocationReading = currentLocation; } } else { mLastLocationReading = currentLocation; } } @Override public void onProviderDisabled(String provider) { // not implemented } @Override public void onProviderEnabled(String provider) { // not implemented } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // not implemented } // Returns age of location in milliseconds private long ageInMilliseconds(Location location) { return System.currentTimeMillis() - location.getTime(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete_badges: mAdapter.removeAllViews(); return true; case R.id.place_one: mMockLocationProvider.pushLocation(37.422, -122.084); return true; case R.id.place_no_country: mMockLocationProvider.pushLocation(0, 0); return true; case R.id.place_two: mMockLocationProvider.pushLocation(38.996667, -76.9275); return true; default: return super.onOptionsItemSelected(item); } } private void shutdownMockLocationManager() { if (mMockLocationOn) { mMockLocationProvider.shutdown(); } } private void startMockLocationManager() { if (!mMockLocationOn) { mMockLocationProvider = new MockLocationProvider(LocationManager.NETWORK_PROVIDER, this); } } }
244dd25b512ae8ba716be88f3856902ce50214e3
8df69fb68d43c6293228b02f254f777ef62c95b2
/javahomework/Forteen/src/Exercise14_12/Exercise14_12.java
a2812c10138c7c2ff42aebc26d20933cc2281f15
[]
no_license
steven-mountain/temp
63d27442e9f1eec41e193cb3d3379d495560c733
63fc6a4bc1a05e18a5edc0d9103e383cb2711295
refs/heads/master
2021-01-05T18:07:02.571533
2020-02-17T12:21:17
2020-02-17T12:21:17
241,089,109
0
0
null
null
null
null
UTF-8
Java
false
false
1,582
java
package Exercise14_12; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; public class Exercise14_12 extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); double height = 300; double paneHeight = 150; Rectangle r1 = new Rectangle(10, paneHeight - height * 0.2, 100, height * 0.2); r1.setFill(Color.RED); Text text1 = new Text(10, paneHeight - height * 0.2 - 10, "Project -- 20%"); Rectangle r2 = new Rectangle(10 + 110, paneHeight - height * 0.1, 100, height * 0.1); r2.setFill(Color.BLUE); Text text2 = new Text(10 + 110, paneHeight - height * 0.1 - 10, "Quiz -- 10%"); Rectangle r3 = new Rectangle(10 + 220, paneHeight - height * 0.3, 100, height * 0.3); r3.setFill(Color.GREEN); Text text3 = new Text(10 + 220, paneHeight - height * 0.3 - 10, "Midterm -- 30%"); Rectangle r4 = new Rectangle(10 + 330, paneHeight - height * 0.4, 100, height * 0.4); r4.setFill(Color.ORANGE); Text text4 = new Text(10 + 330, paneHeight - height * 0.4 - 10, "Final -- 40%"); pane.getChildren().addAll(r1, text1, r2, text2, r3, text3, r4, text4); Scene scene = new Scene(pane, 500, paneHeight); primaryStage.setTitle("Exercise14_12"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
ad797da90fa9318dddc8eeb4fa4dde631f4873ad
1a48c7570f8ebdeac1ae937c560b210342d5636c
/src/main/java/com/zalostation/springbootdemo/customer/CustomerConfiguration.java
ca7293469cac491f0ba2becfeebcc4f8cfafff36
[]
no_license
rabinrai44/springboot-demo
e22aa3f4eb02e9b64e33a16bc231b33471aadaa9
057077f5874f0418f6fc53b2e8875573a63f7b8b
refs/heads/master
2023-04-26T23:25:37.306375
2021-05-09T18:08:00
2021-05-09T18:08:00
363,578,337
1
0
null
null
null
null
UTF-8
Java
false
false
954
java
package com.zalostation.springbootdemo.customer; import com.zalostation.springbootdemo.infoapp.InfoApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @Configuration public class CustomerConfiguration { @Value("${info.company.name}") private String companyName; @Autowired private Environment environment; @Bean CommandLineRunner commandLineRunner(InfoApp infoApp) { return args -> { System.out.println("Command line runner hooray!"); System.out.println(companyName); System.out.println(environment.getProperty("info.app.version")); System.out.println(infoApp); }; } }
94489724d6e287bc63fcf5df23c70be7d3444bb5
20eb62855cb3962c2d36fda4377dfd47d82eb777
/newEvaluatedBugs/Jsoup_38_buggy/mutated/42/CharacterReader.java
b645fd82f294a408feb47387b015e677742b07db
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,290
java
package org.jsoup.parser; import org.jsoup.helper.Validate; import java.util.Locale; /** CharacterReader consumes tokens off a string. To replace the old TokenQueue. */ class CharacterReader { static final char EOF = (char) -1; private final char[] input; private final int length; private int pos = 0; private int mark = 0; CharacterReader(String input) { Validate.notNull(input); this.input = input.toCharArray(); this.length = this.input.length; } int pos() { return pos; } boolean isEmpty() { return pos >= length; } char current() { return isEmpty() ? EOF : input[pos]; } char consume() { char val = isEmpty() ? EOF : input[pos]; pos++; return val; } void unconsume() { pos--; } void advance() { pos++; } void mark() { mark = pos; } void rewindToMark() { pos = mark; } String consumeAsString() { return new String(input, pos++, 1); } /** * Returns the number of characters between the current position and the next instance of the input char * @param c scan target * @return offset between current position and next instance of target. -1 if not found. */ int nextIndexOf(char c) { // doesn't handle scanning for surrogates for (int i = pos; i < length; i++) { if (c == input[i]) return i - pos; } return -1; } /** * Returns the number of characters between the current position and the next instance of the input sequence * * @param seq scan target * @return offset between current position and next instance of target. -1 if not found. */ int nextIndexOf(CharSequence seq) { // doesn't handle scanning for surrogates char startChar = seq.charAt(0); for (int offset = pos; offset < length; offset++) { // scan to first instance of startchar: if (startChar != input[offset]) while(++offset < length && startChar != input[offset]); if (offset < length) { int i = offset + 1; int last = i + seq.length()-1; for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++); if (i == last) // found full sequence return offset - pos; } } return -1; } String consumeTo(char c) { int offset = nextIndexOf(c); if (offset != -1) { String consumed = new String(input, pos, offset); pos += offset; return consumed; } else { return consumeToEnd(); } } String consumeTo(String seq) { int offset = nextIndexOf(seq); if (offset != -1) { String consumed = new String(input, pos, offset); pos += offset; return consumed; } else { return consumeToEnd(); } } String consumeToAny(final char... chars) { int start = pos; OUTER: while (pos < length) { for (int i = 0; i < chars.length; i++) { if (input[pos] == chars[i]) break OUTER; } pos++; } return pos > start ? new String(input, start, pos-start) : ""; } String consumeToEnd() { String data = new String(input, pos, length-pos); pos = length; return data; } String consumeLetterSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) pos++; else break; } return new String(input, start, pos - start); } String consumeLetterThenDigitSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= 'A' && c <= 'Z') || c <= 'Z') pos++; else break; } while (!isEmpty()) { char c = input[pos]; if (c >= '0' && c <= '9') pos++; else break; } return new String(input, start, pos - start); } String consumeHexSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) pos++; else break; } return new String(input, start, pos - start); } String consumeDigitSequence() { int start = pos; while (pos < length) { char c = input[pos]; if (c >= '0' && c <= '9') pos++; else break; } return new String(input, start, pos - start); } boolean matches(char c) { return !isEmpty() && input[pos] == c; } boolean matches(String seq) { int scanLength = seq.length(); if (scanLength > length - pos) return false; for (int offset = 0; offset < scanLength; offset++) if (seq.charAt(offset) != input[pos+offset]) return false; return true; } boolean matchesIgnoreCase(String seq) { int scanLength = seq.length(); if (scanLength > length - pos) return false; for (int offset = 0; offset < scanLength; offset++) { char upScan = Character.toUpperCase(seq.charAt(offset)); char upTarget = Character.toUpperCase(input[pos + offset]); if (upScan != upTarget) return false; } return true; } boolean matchesAny(char... seq) { if (isEmpty()) return false; char c = input[pos]; for (char seek : seq) { if (seek == c) return true; } return false; } boolean matchesLetter() { if (isEmpty()) return false; char c = input[pos]; return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } boolean matchesDigit() { if (isEmpty()) return false; char c = input[pos]; return (c >= '0' && c <= '9'); } boolean matchConsume(String seq) { if (matches(seq)) { pos += seq.length(); return true; } else { return false; } } boolean matchConsumeIgnoreCase(String seq) { if (matchesIgnoreCase(seq)) { pos += seq.length(); return true; } else { return false; } } boolean containsIgnoreCase(String seq) { // used to check presence of </title>, </style>. only finds consistent case. String loScan = seq.toLowerCase(Locale.ENGLISH); String hiScan = seq.toUpperCase(Locale.ENGLISH); return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1); } @Override public String toString() { return new String(input, pos, length - pos); } }
a7868aa0a066ad893c1870d3f06a72a78304bac8
07eb40d64c0246835b84d893fbd59dbe75cf4a87
/mall-sale/src/main/java/com/hxf/mall/model/OBJECT_AV_NAME.java
9c7f6bd10e0f07f4f73edf0448c0e8a2758440a9
[]
no_license
huxiaofeng1995/xmall
58bc13f5d0a8ad9c17598b59e7c17c298f3e38e3
8f3db885d48529de897a27f493273d3ff25e6088
refs/heads/master
2020-04-26T15:58:16.018709
2019-05-05T03:22:06
2019-05-05T03:22:06
173,663,330
0
0
null
null
null
null
UTF-8
Java
false
false
382
java
package com.hxf.mall.model; public class OBJECT_AV_NAME { private String shxm_mch; private String shxzh_mch; public String getShxm_mch() { return shxm_mch; } public void setShxm_mch(String shxm_mch) { this.shxm_mch = shxm_mch; } public String getShxzh_mch() { return shxzh_mch; } public void setShxzh_mch(String shxzh_mch) { this.shxzh_mch = shxzh_mch; } }
e853dd8c9a48f1174ad5485999467e7e2c719a3d
0e06e096a9f95ab094b8078ea2cd310759af008b
/classes77-dex2jar/com/google/android/gms/internal/ads/zzacj.java
e8e9920254b7a934e7b181144bc09a76af696f13
[]
no_license
Manifold0/adcom_decompile
4bc2907a057c73703cf141dc0749ed4c014ebe55
fce3d59b59480abe91f90ba05b0df4eaadd849f7
refs/heads/master
2020-05-21T02:01:59.787840
2019-05-10T00:36:27
2019-05-10T00:36:27
185,856,424
1
2
null
2019-05-10T00:36:28
2019-05-09T19:04:28
Java
UTF-8
Java
false
false
325
java
// // Decompiled by Procyon v0.5.34 // package com.google.android.gms.internal.ads; import java.util.Map; import com.google.android.gms.ads.internal.gmsg.zzv; final class zzacj implements zzv<zzaqw> { private final /* synthetic */ zzace zzcbi; zzacj(final zzace zzcbi) { this.zzcbi = zzcbi; } }
19b952c499f5d4fe192212b4074622056dde6736
f164c89de37192c3d63bf5fafc1030b764d5b3f6
/core/src/main/java/SpriteScript/SpriteLoader.java
92036ecb9a1294a1e8b0a074a980a5e407e3419e
[]
no_license
novanupat/Event_BattleNoFeel
ed1ad09f8d567a5382f7447da16e5d402297e91c
3b2b62b8479db6262b48f230f06ee8fd541ce987
refs/heads/master
2020-04-13T20:39:14.881130
2017-02-06T14:15:48
2017-02-06T14:15:48
30,062,231
0
0
null
null
null
null
UTF-8
Java
false
false
7,363
java
/** * Copyright 2011 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package SpriteScript; import playn.core.Asserts; import playn.core.AssetWatcher; import playn.core.Image; import playn.core.Json; import playn.core.util.Callback; import static playn.core.PlayN.*; /** * Class for loading and parsing sprite sheets. * <p/> * To use, call {@link #getSprite(String imageUrl, String jsonUrl)} with an image path and json * data, or {@link #getSprite(String jsonUrl)} with json data containing image urls. */ // TODO(pdr): the two getSprite() methods are messy, clean them up. public class SpriteLoader { // prevent instantiation private SpriteLoader() { } /** * Return a {@link Sprite}, given a path to the image and a path to the json sprite description. * <p/> * json data should be in the following format: * <p/> * <pre> * { * "sprites": [ * {"id": "sprite_0", "x": 30, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_1", "x": 67, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_2", "x": 104, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_3", "x": 141, "y": 30, "w": 37, "h": 37} * ]} * </pre> */ public static Sprite getSprite(String imagePath, String jsonPath) { Image image = assets().getImage(imagePath); final Image[] images = new Image[]{image}; // temp image to prevent NPE if using the Sprite's Layer (Sprite.getLayer()) before the image // has loaded or before a sprite has been set (Sprite.setSprite()). final Image tempImage = graphics().createImage(1, 1); final Sprite sprite = new Sprite(graphics().createImageLayer(tempImage)); // load and parse json assets().getText(jsonPath, new Callback<String>() { @Override public void onSuccess(String json) { try { parseJson(images, sprite, json); } catch (Throwable err) { sprite.error(err); return; } sprite.doneLoadingData(); } @Override public void onFailure(Throwable err) { sprite.error(err); } }); // set callback for image image.addCallback(new Callback<Image>() { @Override public void onSuccess(Image resource) { sprite.doneLoadingImages(); } @Override public void onFailure(Throwable err) { sprite.error(err); } }); return sprite; } /** * Return a {@link Sprite}, given a path to the json sprite description. * <p/> * json data should be in the following format: * <p/> * <pre> * { * "urls": ["images/peasprites2.png", "images/peasprites3.png"], * "sprites": [ * {"id": "sprite_0", "url": 0, "x": 30, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_1", "url": 0, "x": 67, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_2", "url": 1, "x": 104, "y": 30, "w": 37, "h": 37}, * {"id": "sprite_3", "url": 1, "x": 141, "y": 30, "w": 37, "h": 37} * ]} * </pre> */ public static Sprite getSprite(String jsonPath) { // temp image to prevent NPE if using the Sprite's Layer (Sprite.getLayer()) before the image // has loaded or before a sprite has been set (Sprite.setSprite()). final Image tempImage = graphics().createImage(1, 1); final Sprite sprite = new Sprite(graphics().createImageLayer(tempImage)); // create asset watcher for the image assets final AssetWatcher watcher = new AssetWatcher(new AssetWatcher.Listener() { @Override public void done() { sprite.doneLoadingImages(); } @Override public void error(Throwable e) { sprite.error(e); } }); // load and parse json, then add each image parsed from the json to the asset watcher to load assets().getText(jsonPath, new Callback<String>() { @Override public void onSuccess(String json) { try { parseJson(null, sprite, json); for (SpriteImage spriteImage : sprite.spriteImages()) { watcher.add(spriteImage.image()); } watcher.start(); } catch (Throwable err) { sprite.error(err); return; } sprite.doneLoadingData(); } @Override public void onFailure(Throwable err) { sprite.error(err); } }); return sprite; } /** * Parse a json sprite sheet and add the sprite images to the sheet. * <p/> * If images is null, the images urls are parsed from the json. * * @param images Image to associate with each {@link SpriteImage}, or null to parse from the json * @param sprite Sprite to store the {@link SpriteImage}s * @param json json to parse */ private static void parseJson(Image[] images, Sprite sprite, String json) { Json.Object document = json().parse(json); // parse image urls, if necessary if (images == null || images.length == 0) { Json.Array urls = document.getArray("urls"); Asserts.checkNotNull(urls, "No urls provided for sprite images"); images = new Image[urls.length()]; for (int i = 0; i < urls.length(); i++) { images[i] = assets().getImage(urls.getString(i)); } } // parse the sprite images Json.Array spriteImages = document.getArray("sprites"); for (int i = 0; i < spriteImages.length(); i++) { Json.Object jsonSpriteImage = spriteImages.getObject(i); String id = jsonSpriteImage.getString("id"); int imageId = jsonSpriteImage.getInt("url"); // will return 0 if not specified Asserts.checkElementIndex(imageId, images.length, "URL must be an index into the URLs array"); int x = jsonSpriteImage.getInt("x"); int y = jsonSpriteImage.getInt("y"); int width = jsonSpriteImage.getInt("w"); int height = jsonSpriteImage.getInt("h"); SpriteImage spriteImage = new SpriteImage(images[imageId], x, y, width, height); sprite.addSpriteImage(id, spriteImage); } } }
ee63b1268c438e4252701d286b69e5eb668dc147
f414ba68dbf06b446406e292e4ed24849a7bbc2e
/mvc/src/main/java/com/cefothe/bgjudge/user/validation/unique/UniqueEmailValidator.java
fc585aaaee3f97841216a2c2246398bba3257b3c
[]
no_license
cefothe/BGJudge
bc7ab4239e5dabe31faf930f55ffcee48c240869
f827575a82b9e132ebc3b52dcd7734197740a78e
refs/heads/develop
2021-07-07T12:14:55.833328
2019-12-26T20:09:58
2019-12-26T20:09:58
90,044,521
0
0
null
2021-05-21T19:21:49
2017-05-02T14:45:55
JavaScript
UTF-8
Java
false
false
652
java
package com.cefothe.bgjudge.user.validation.unique; import com.cefothe.bgjudge.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> { @Autowired private UserService userService; @Override public void initialize(UniqueEmail constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { return !userService.checkForUniqueEmail(value); } }
4e11a980f9c0a340ffc49b52eed766207862c715
6879e4f96257200d63c46be82c4a41541d3d03c9
/app/src/main/java/com/dl7/mvp/module/news/main/INewsMainView.java
22584fa8cc934780366edef9f3519ce2ac7a7d91
[]
no_license
xgucs/MvpApp
616e4a8c548e6bee3fac070394c591cddf434508
3ecb7000ec308287f9ea4f94dc14ba9a1c261b47
refs/heads/master
2021-01-18T08:09:57.516141
2017-11-29T02:00:51
2017-11-29T02:00:51
84,300,812
1
0
null
2017-03-08T09:07:28
2017-03-08T09:07:28
null
UTF-8
Java
false
false
327
java
package com.dl7.mvp.module.news.main; import com.dl7.mvp.local.table.NewsTypeInfo; import java.util.List; /** * Created by long on 2016/9/1. * 主页接口 */ public interface INewsMainView { /** * 显示数据 * @param checkList 选中栏目 */ void loadData(List<NewsTypeInfo> checkList); }
5f207bac15dcbca9f058911bb6d5a5c28f53af99
cd779bcab3c375730b42dcdbb9d61bab1d0646ad
/apps/marketing-events/osb-www-marketing-events-service/src/main/java/com/liferay/osb/www/marketing/events/service/impl/SocialLinkLocalServiceImpl.java
ed1a929bf5203f2078f790ab149176a1a934733d
[]
no_license
ryanschuhler/www-workspace
ae7ca7e1e42c9e2bfa75258a80afd1485e717932
b1a6ec132d218a1633734e2809665bbae0855e02
refs/heads/master
2021-09-18T12:00:08.643727
2018-07-13T22:17:06
2018-07-13T22:17:06
111,735,849
1
8
null
2018-04-03T22:01:31
2017-11-22T21:50:29
Java
UTF-8
Java
false
false
3,491
java
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.osb.www.marketing.events.service.impl; import com.liferay.osb.www.marketing.events.exception.DuplicateSocialLinkTypeException; import com.liferay.osb.www.marketing.events.exception.SocialLinkURLException; import com.liferay.osb.www.marketing.events.model.SocialLink; import com.liferay.osb.www.marketing.events.model.SocialLinkType; import com.liferay.osb.www.marketing.events.service.base.SocialLinkLocalServiceBaseImpl; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.Validator; import java.util.Date; import java.util.List; /** * @author Joan H. Kim * @author Phillip Chan * @author Weston Hancock */ public class SocialLinkLocalServiceImpl extends SocialLinkLocalServiceBaseImpl { public SocialLink addSocialLink( long userId, long marketingEventUserId, long socialLinkTypeId, String url) throws PortalException { User user = userPersistence.findByPrimaryKey(userId); SocialLinkType socialLinkType = socialLinkTypeLocalService.getSocialLinkType(socialLinkTypeId); Date now = new Date(); validate(marketingEventUserId, socialLinkTypeId, url); long socialLinkId = counterLocalService.increment(); SocialLink socialLink = socialLinkPersistence.create(socialLinkId); socialLink.setUserId(user.getUserId()); socialLink.setUserName(user.getFullName()); socialLink.setCreateDate(now); socialLink.setModifiedDate(now); socialLink.setMarketingEventUserId(marketingEventUserId); socialLink.setSocialLinkTypeId(socialLinkType.getSocialLinkTypeId()); socialLink.setUrl(url); socialLinkPersistence.update(socialLink); return socialLink; } public List<SocialLink> getSocialLinks( long marketingEventUserId, int start, int end, OrderByComparator obc) { return socialLinkPersistence.findByMarketingEventUserId( marketingEventUserId, start, end, obc); } public SocialLink updateSocialLink( long socialLinkId, long socialLinkTypeId, String url) throws PortalException { SocialLink socialLink = socialLinkPersistence.findByPrimaryKey( socialLinkId); validate(socialLink.getMarketingEventUserId(), socialLinkTypeId, url); socialLink.setModifiedDate(new Date()); socialLink.setSocialLinkTypeId(socialLinkTypeId); socialLink.setUrl(url); socialLinkPersistence.update(socialLink); return socialLink; } protected void validate( long marketingEventUserId, long socialLinkTypeId, String url) throws PortalException { if (!Validator.isUrl(url)) { throw new SocialLinkURLException(); } if ((marketingEventUserId != 0) && (socialLinkTypeId != 0)) { int count = socialLinkPersistence.countByMEUI_SLTI( marketingEventUserId, socialLinkTypeId); if (count > 0) { throw new DuplicateSocialLinkTypeException(); } } } }
0120b725d5f40b3617420c49d8d00c41a77a03ed
98f0929887520ee8301bc2ba6a8b99003321aeef
/BroadcastBestPractice/app/src/main/java/com/example/broadcastbestpractice/MainActivity.java
f3bdf851cf9255f68de820a1bbd088f967481793
[]
no_license
Android1994/Learning-Android
4b31f44f17a54ad5749421da98ffc66854d3fca6
69cffb4f661e7d88d4d44bf4da40d4d6a97e064d
refs/heads/master
2021-01-18T03:28:18.752528
2017-04-07T13:27:02
2017-04-07T13:27:02
85,312,073
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package com.example.broadcastbestpractice; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button send_button = (Button)findViewById(R.id.send_offline); send_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcastbestpractice.FORCE_OFFLINE"); sendBroadcast(intent); } }); } }
564c761ebcab8f2e5d75fdb03ae352347d8d42ef
d4397b1764f02a79b3632bb2492b24fea0c65a45
/core/src/gameworld/GameWorld.java
216d293f660ffc3a2c56fde173ad3f4e057bf754
[]
no_license
lasred/DreadBird
6f267022a63320ce3f26420c6ac6899e4749892b
5fa26dfd33c1392595206856275f1604ce20b0e5
refs/heads/master
2020-05-17T09:19:28.572968
2015-02-01T00:57:36
2015-02-01T00:57:36
30,062,360
0
0
null
null
null
null
UTF-8
Java
false
false
4,017
java
package gameworld; import com.badlogic.gdx.math.Intersector; import gamehelpers.AssetLoader; import gameobjects.Bird; import gameobjects.ScrollHandler; import com.badlogic.gdx.math.Rectangle; /** * Created by chris on 1/23/2015. */ public class GameWorld { private Rectangle ground; private Bird bird; private ScrollHandler scroller; private int score; private GameState currentState; private int midPointY; /** * Special data type that enables a variable to be a set of predefined variables. The variable * must be equal to one of the values thave been predefined for it. */ public enum GameState { READY, RUNNING, GAMEOVER, HIGHSCORE; } public GameWorld(int midPointY) { this.midPointY = midPointY; //x, 5px above the middle of the screen bird = new Bird(33, midPointY - 5, 17, 12); // The grass should start 66 pixels below the midPointY scroller = new ScrollHandler(this, midPointY + 66); ground = new Rectangle(0, midPointY + 66, 136, 11); currentState = GameState.READY; } /** * Cascade down(pass down restart to other methods), like dominos * Should reset all the instance variables */ public void restart() { //Game should be ready to play after restart currentState = GameState.READY; score = 0; //original y position bird.onRestart(midPointY - 5); /*pass down the resetting Every instance variable that has changed throughout the flow of the game will be reset */ scroller.onRestart(); currentState = GameState.READY; } private void updateReady(float delta) { } public void update(float delta) { /* Check the current state of the game before determining which specific update method */ switch(currentState) { case READY: updateReady(delta); break; case RUNNING: updateRunning(delta); break; } } private void updateRunning(float delta) { // Add a delta cap so that if our game takes too long // to update, we will not break our collision detection. if (delta > .15f) { delta = .15f; } bird.update(delta); scroller.update(delta); //after update if ( scroller.collides(bird) && bird.isAlive()) { scroller.stop(); //play the sound once AssetLoader.dead.play(); bird.die(); //still want updates to move the bird down } if (Intersector.overlaps(bird.getBoundingCircle(), ground)) { //stop the scrolling of grass and pipe scroller.stop(); //die if it already isn't die(collide iwth ground), velocity is zero bird.die(); AssetLoader.dead.play(); //stop, should not go beyond the ground, so acceleration has no effect bird.deaccelerate(); //no more updates currentState = GameState.GAMEOVER; //going to hit the ground if (score > AssetLoader.getHighScore()) { AssetLoader.setHighScore(score); //reached a game state of a high score currentState = GameState.HIGHSCORE; } } } public boolean isHighScore() { return currentState == GameState.HIGHSCORE; } public boolean isReady() { return currentState == GameState.READY; } public boolean isGameOver() { return currentState == GameState.GAMEOVER; } public void start() { currentState = GameState.RUNNING; } public int getScore() { return score; } public void addScore(int increment) { score += increment; } public Bird getBird() { return bird; } public ScrollHandler getScroller() { return scroller; } }
e4574c640697acaa9413ba874b0cd41d3b3db585
fdb09de0a84a7e0e6017d238a2d909b4ef9faf4e
/src/main/java/com/thoughtworks/retail_in_future/sku/exception/DuplicateException.java
0534c520a24c566ebee3f21f92f4df04fbeccbde
[]
no_license
Retail-in-Future/retail_sku
c644151398563a0a6571dcab0fd8f530269219cb
2ffd42897b930e44d2341c2bda3d9e1daafc787c
refs/heads/master
2021-01-01T15:39:28.006220
2017-08-02T03:54:31
2017-08-02T03:54:31
97,668,216
0
0
null
null
null
null
UTF-8
Java
false
false
189
java
package com.thoughtworks.retail_in_future.sku.exception; public class DuplicateException extends Exception{ public DuplicateException(String message) { super(message); } }
d1b618626129b055eec1a6410edffde05030428b
80207978298a77a92bf71299d45f4f7b75c2639b
/jsmpp-client/src/main/java/main/java/mysqlconnector/qa/smppclient/session/impl/BasicSession.java
660d4053b535eb669c98c1803b5bd00befae7ed8
[]
no_license
stallewar/qamock_service
f4c3a7878dacb983f06c045bb22680db2e32941c
792a77ceafa8aa52c87be4c1bce0611b23d75566
refs/heads/master
2020-03-23T15:15:39.509163
2017-03-15T10:13:48
2017-03-15T10:13:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,703
java
package main.java.mysqlconnector.qa.smppclient.session.impl; import main.java.mysqlconnector.qa.smppclient.net.Connection; import main.java.mysqlconnector.qa.smppclient.pdu.CommandId; import main.java.mysqlconnector.qa.smppclient.pdu.CommandStatus; import main.java.mysqlconnector.qa.smppclient.pdu.Pdu; import main.java.mysqlconnector.qa.smppclient.pdu.PduException; import main.java.mysqlconnector.qa.smppclient.pdu.impl.EnquireLink; import main.java.mysqlconnector.qa.smppclient.pdu.impl.EnquireLinkResp; import main.java.mysqlconnector.qa.smppclient.pdu.impl.Unbind; import main.java.mysqlconnector.qa.smppclient.session.MessageListener; import main.java.mysqlconnector.qa.smppclient.session.Session; import main.java.mysqlconnector.qa.smppclient.session.State; import main.java.mysqlconnector.qa.smppclient.session.StateListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class BasicSession implements Session { private static final Logger logger = LoggerFactory.getLogger(BasicSession.class); private final Connection conn; private int smscResponseTimeout = DEFAULT_SMSC_RESPONSE_TIMEOUT; private int pingTimeout = DEFAULT_ENQUIRE_LINK_TIMEOUT; private int reconnectTimeout = DEFAULT_RECONNECT_TIMEOUT; private MessageListener messageListener = new DefaultMessageListener(); private StateListener stateListener = new DefaultStateListener(); private PingThread pingThread; private ReadThread readThread; private Pdu bindPdu; private volatile long sequenceNumber = 0; private volatile long lastActivity; private volatile State state = State.DISCONNECTED; private final ReentrantLock lock = new ReentrantLock(); public BasicSession(Connection conn) { this.conn = conn; } @Override public void setMessageListener(MessageListener messageListener) { this.messageListener = messageListener; } @Override public MessageListener getMessageListener() { return messageListener; } @Override public void setStateListener(StateListener stateListener) { this.stateListener = stateListener; } @Override public void setSmscResponseTimeout(int timeout) { this.smscResponseTimeout = timeout; } @Override public void setEnquireLinkTimeout(int timeout) { this.pingTimeout = timeout; } @Override public void setReconnectTimeout(int timeout) { this.reconnectTimeout = timeout; } @Override public Pdu open(Pdu pdu) throws PduException, IOException { lock.lock(); try{ bindPdu = pdu; return open(); } finally { lock.unlock(); } } @Override public long nextSequenceNumber() { lock.lock(); try{ if (sequenceNumber == 2147483647L) sequenceNumber = 1; else sequenceNumber++; return sequenceNumber; } finally { lock.unlock(); } } @Override public boolean send(Pdu pdu) throws PduException { if (State.CONNECTED != state) return false; lock.lock(); try { conn.write(pdu); return true; } catch (IOException e) { logger.debug("Send failed.", e); reconnect(e); return false; } finally { lock.unlock(); } } @Override public void close() { lock.lock(); try{ if (State.RECONNECTING == state || closeInternal(null)) updateState(State.DISCONNECTED); } finally { lock.unlock(); } } private Pdu open() throws PduException, IOException { ScheduledExecutorService es = null; lock.lock(); try { logger.trace("Opening new session..."); conn.open(); logger.trace("TCP connection established. Sending bind request."); bindPdu.setSequenceNumber(nextSequenceNumber()); conn.write(bindPdu); es = Executors.newSingleThreadScheduledExecutor(); es.schedule(new Runnable() { @Override public void run() { logger.warn("Bind response timed out."); conn.close(); } }, smscResponseTimeout, TimeUnit.MILLISECONDS); logger.trace("Bind request sent. Waiting for bind response."); Pdu bindResp = conn.read(); es.shutdownNow(); logger.trace("Bind response command status: {}.", bindResp.getCommandStatus()); if (CommandStatus.ESME_ROK == bindResp.getCommandStatus()) { updateLastActivity(); pingThread = new PingThread(); pingThread.setName("Ping"); pingThread.start(); readThread = new ReadThread(); Thread t2 = new Thread(readThread); t2.setName("Read"); t2.start(); updateState(State.CONNECTED); logger.trace("Session successfully opened."); } return bindResp; } finally { lock.unlock(); if (es != null && !es.isShutdown()) { es.shutdownNow(); } } } /** * Actually close session. * * @param reason exception, caused session close, or null * @return session closed */ private boolean closeInternal(Exception reason) { lock.lock(); try { if (State.DISCONNECTED != state) { logger.trace("Closing session..."); pingThread.stopAndInterrupt(); pingThread = null; if (!(reason instanceof IOException) && readThread.run) { try { synchronized (conn) { Pdu unbind = new Unbind(); unbind.setSequenceNumber(nextSequenceNumber()); send(unbind); conn.wait(smscResponseTimeout); } } catch (Exception e) { logger.debug("Unbind request send failed.", e); } } readThread.stop(); readThread = null; conn.close(); logger.trace("Session closed."); return true; } else { logger.trace("Session already closed."); return false; } } finally { lock.unlock(); } } private void reconnect(Exception reason) { // only one thread should do reconnect boolean doReconnect = false; lock.lock(); try{ if (State.RECONNECTING != state) { doReconnect = true; state = State.RECONNECTING; } } finally { lock.unlock(); } if (doReconnect) { closeInternal(reason); new Thread(new ReconnectThread(reason)).start(); } } private void updateLastActivity() { lastActivity = System.currentTimeMillis(); } private void updateState(State newState) { updateState(newState, null); } private void updateState(State newState, Exception e) { this.state = newState; stateListener.changed(newState, e); } private class PingThread extends Thread { private volatile boolean run = true; @Override public void run() { logger.trace("Ping thread started."); try { while (run) { logger.trace("Checking last activity."); try { if(pingTimeout <= 0) { Thread.sleep(DEFAULT_ENQUIRE_LINK_TIMEOUT); continue; } Thread.sleep(pingTimeout); if (pingTimeout < (System.currentTimeMillis() - lastActivity)) { long prevLastActivity = lastActivity; Pdu enquireLink = new EnquireLink(); enquireLink.setSequenceNumber(nextSequenceNumber()); send(enquireLink); synchronized (conn) { conn.wait(smscResponseTimeout); } if (run && lastActivity == prevLastActivity) { reconnect(new IOException("Enquire link response not received. Session closed.")); } } } catch (InterruptedException e) { logger.trace("Ping thread interrupted."); } } } catch (PduException e) { if (run) { logger.warn("EnquireLink request failed.", e); run = false; reconnect(e); } } finally { logger.trace("Ping thread stopped."); } } void stopAndInterrupt() { run = false; interrupt(); } } private class ReadThread implements Runnable { private volatile boolean run = true; @Override public void run() { logger.trace("Read thread started."); try { while (run) { Pdu request = conn.read(); updateLastActivity(); Pdu response; if (CommandId.ENQUIRE_LINK == request.getCommandId()) { logger.debug("Received ENQUIRE_LINK with seq_num={}", request.getSequenceNumber()); response = new EnquireLinkResp(); response.setSequenceNumber(request.getSequenceNumber()); send(response); logger.debug("Sent ENQUIRE_LINK_RESP with seq_num={}", response.getSequenceNumber()); } else if (CommandId.ENQUIRE_LINK_RESP == request.getCommandId()) { synchronized (conn) { conn.notifyAll(); } } else if (CommandId.UNBIND_RESP == request.getCommandId()) { synchronized (conn) { conn.notifyAll(); } stop(); } else { messageListener.received(request); } } } catch (PduException e) { if (run) { logger.warn("Incoming message parsing failed.", e); run = false; reconnect(e); } } catch (IOException e) { if (run) { logger.warn("Reading IO failure.", e); run = false; reconnect(e); } } catch(Exception e) { if(run) { logger.error("Error occured processing imcomming PDU.", e); run = false; reconnect(e); } } finally { logger.trace("Read thread stopped."); } } void stop() { run = false; } } private class ReconnectThread implements Runnable { private final Exception reason; private ReconnectThread(Exception reason) { this.reason = reason; } @Override public void run() { logger.debug("Reconnect started."); stateListener.changed(state, reason); boolean reconnectSuccessful = false; while (!reconnectSuccessful && state == State.RECONNECTING) { logger.debug("Reconnecting..."); try { conn.close(); Pdu bindResponse = open(); if (CommandStatus.ESME_ROK == bindResponse.getCommandStatus()) { reconnectSuccessful = true; } else { logger.warn("Reconnect failed. Bind response error code: {}.", bindResponse.getCommandStatus()); } } catch (Exception e) { logger.warn("Reconnect failed.", e); try { Thread.sleep(reconnectTimeout); } catch (InterruptedException e1) { logger.trace("Reconnect sleep interrupted.", e1); } } } if (reconnectSuccessful) { state = State.CONNECTED; } logger.debug("Reconnect done."); } } }
7307d6edbe79a7e900a2b893d8371c898f82ee6f
7afbe55afee96e309b8ab521a44926570a9a4ea1
/SearchResults/src/main/java/com/assetco/search/results/Hotspot.java
dbf7bf7810dd1d46c38eda7aac1a7bf700944f04
[ "Apache-2.0" ]
permissive
seguri/unit-testing-legacy-code
8e3232a7502c6cb767220f2800e4f101f1a75afa
0fd8bca0ea6b4d562b7aa06409c7305fcbb996bd
refs/heads/master
2023-03-26T20:12:53.019353
2021-03-21T11:51:36
2021-03-21T11:51:36
348,524,557
2
0
null
null
null
null
UTF-8
Java
false
false
360
java
package com.assetco.search.results; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Hotspot { private final List<Asset> members = new ArrayList<>(); public void addMember(Asset asset) { members.add(asset); } public List<Asset> getMembers() { return Collections.unmodifiableList(members); } }
1ce100f9d98a1df4175f32317d1fca0c12b4002c
75bb3a44cd23d42a4440395d5f2c9f19f0c916e0
/src/main/java/com/bourntec/apmg/entity/LaptopMovedDataItems.java
9a3fc858f4ff5412e578019f3f06072692f1f5d8
[]
no_license
Nidhikamal/entity
996a460d78bc6fe3c0278b2e5c8bed72d7ebe7ea
3013ee704efb4c99ee9e353e803db79cdead93ac
refs/heads/master
2023-01-08T08:21:47.100925
2020-10-27T14:00:12
2020-10-27T14:00:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,863
java
package com.bourntec.apmg.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity @Table(name = "laptop_moved_data_items") public class LaptopMovedDataItems { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "main_lap_id",nullable=false) private String mainLapId; @Column(name = "description",nullable=false) private String description; @Column(name = "item_code",nullable=false) private String itemCode; @Column(name = "no_pc_p",nullable=false) private Long noPcP; @Column(name = "no_pc_w",nullable=true) private Double noPcW; @Column(name = "unit_price",nullable=true) private Double unitPrice; @Column(name = "location_code",nullable=true) private String locationCode; @Column(name = "job_loose",nullable=true) private String jobLoose; @Column(name = "showcode",nullable=false) private String showcode; @Column(name = "notused_wt",nullable=true) private Double notusedWt; @Column(name = "notused_pc",nullable=true) private Long notusedPc; @Column(name = "diffpc",nullable=true) private Long diffpc; @Column(name = "diffwt",nullable=true) private Double diffwt; @Column(name = "mode_received",nullable=true) private String modeReceived; @Column(name = "merged_pieces",nullable=true) private Long mergedPieces; @Column(name = "merged_weight",nullable=true) private Double mergedWeight; @Column(name = "memo_pcs",nullable=true) private Long memoPcs; @Column(name = "memo_wt",nullable=true) private Double memoWt; @Column(name = "merged_pc",nullable=true) private Long mergedPc; }
9d6947a35bce5c9681a99d02d1706a9014c6be7c
b6fb9167c03aa9c13d036f97ebb6248fd63f3ddd
/Helios/src/helios/core/EconomicSituation.java
94d5a3f032a9abd25c14380308f46789f5ba46cc
[]
no_license
MicheleMozzanica/ProgettoHelios
9bf83daa3f5e2dbeceefeee61d6c8bb8ef496129
6f3a7c40dc35196c035e93303edcf0ff1898288e
refs/heads/main
2023-07-03T17:11:53.401618
2021-07-31T09:00:27
2021-07-31T09:00:27
358,850,776
0
0
null
null
null
null
UTF-8
Java
false
false
3,733
java
package helios.core; import java.awt.EventQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import javax.swing.JLabel; public class EconomicSituation { private JFrame frame; double totale; Future<Double> totaleCredits; Future<Double> totaleDebits; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { EconomicSituation window = new EconomicSituation(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. * @throws ExecutionException * @throws InterruptedException */ public EconomicSituation() throws InterruptedException, ExecutionException { initialize(); } /** * Initialize the contents of the frame. * @throws ExecutionException * @throws InterruptedException */ private void initialize() throws InterruptedException, ExecutionException { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Situazione Economica"); lblNewLabel.setBounds(158, 6, 137, 16); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Crediti"); lblNewLabel_1.setBounds(70, 41, 42, 16); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel_1_1 = new JLabel("Debiti"); lblNewLabel_1_1.setBounds(338, 41, 38, 16); frame.getContentPane().add(lblNewLabel_1_1); JLabel lblTotalCrediti = new JLabel("0.00 €"); lblTotalCrediti.setBounds(70, 64, 101, 16); frame.getContentPane().add(lblTotalCrediti); JLabel lblTotalDebiti = new JLabel("0.00 €"); lblTotalDebiti.setBounds(338, 64, 82, 16); frame.getContentPane().add(lblTotalDebiti); JLabel lblTaxToPay = new JLabel("Tasse da pagare"); lblTaxToPay.setBounds(170, 119, 101, 16); frame.getContentPane().add(lblTaxToPay); JLabel lblTax = new JLabel("0.00 €"); lblTax.setBounds(180, 137, 101, 16); frame.getContentPane().add(lblTax); JLabel lblTotaleNetto = new JLabel("Totale netto"); lblTotaleNetto.setBounds(180, 193, 76, 16); frame.getContentPane().add(lblTotaleNetto); JLabel lblTotalNetto = new JLabel("0.00 €"); lblTotalNetto.setBounds(180, 209, 115, 16); frame.getContentPane().add(lblTotalNetto); CalculateTotals(); lblTotalCrediti.setText(Double.toString(Math.round(totaleCredits.get()*100.0)/100.0) +" €"); lblTotalDebiti.setText(Double.toString(Math.round(totaleDebits.get()*100.0)/100.0) +" €"); double totale = totaleCredits.get()-totaleDebits.get(); lblTax.setText(Double.toString(Math.round(totale*0.15*100.0)/100.0) +" €"); lblTotalNetto.setText(Double.toString(Math.round((totale-(totale*0.15))*100.0)/100.0) +" €"); } public void CalculateTotals() { ExecutorService executor = Executors.newCachedThreadPool(); totaleCredits = executor.submit(new taskCalcFatture("Crediti")); totaleDebits = executor.submit(new taskCalcFatture("Debiti")); try { System.out.println("attempt to shutdown executor"); executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { System.err.println("tasks interrupted"); } finally { if (!executor.isTerminated()) { System.err.println("cancel non-finished tasks"); executor.shutdownNow(); } System.out.println("shutdown finished"); // TODO Auto-generated method stub } } }
6324fe0aa66be07c283dc837e0d165cad24c93b9
15685f6bfa67c6ffbb9f47656e2dbc61ea92a621
/src/main/java/vernon/ac/za/Factories/GameTitlesFactory.java
c7720348417a08ed5f272e4f30ef99259b98239d
[]
no_license
Vernon01/VernonGameAppBackEnd
cc80cda784f3f298027c67f77f58a7da4e9f96c7
ae426a8bc9815fb0c0a18c0ccb87b02259f63b95
refs/heads/master
2020-07-27T09:12:49.420906
2016-09-01T20:36:22
2016-09-01T20:36:22
67,164,225
0
0
null
null
null
null
UTF-8
Java
false
false
451
java
package vernon.ac.za.Factories; import vernon.ac.za.Domain.GameTitles; /** * Created by VERNON on 2016/04/18. */ public class GameTitlesFactory { public static GameTitles GameTitlesSetup(String title, String year, String machine) { GameTitles gt = new GameTitles .Builder("Games of Wars") .year("2013") .machine("PlayStation2") .build(); return gt; } }
5a26c747de262bad8b7df1dba21edfa52576523d
917201691a341cae0cbf90b2b5f0b2e1562b5d65
/backend/src/main/java/de/interaapps/pastefy/model/database/AuthKey.java
c681dcf886f02268503fbba5f28e89385d2400b3
[ "MIT" ]
permissive
toth2000/pastefy
7d61c3436c323c7a49744cf86493a67e4110e02d
60258a3907a43fe230d99719092e06bad73fbde1
refs/heads/master
2023-04-27T18:55:58.457011
2021-05-14T17:45:55
2021-05-14T17:45:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
916
java
package de.interaapps.pastefy.model.database; import org.apache.commons.lang3.RandomStringUtils; import org.javawebstack.orm.Model; import org.javawebstack.orm.annotation.Column; import org.javawebstack.orm.annotation.Dates; import org.javawebstack.orm.annotation.Table; import java.sql.Timestamp; @Dates @Table("auth_keys") public class AuthKey extends Model { @Column public int id; @Column(size = 60) private String key; @Column(size = 160) public String apiKey; @Column public int userId; @Column public Type type = Type.USER; @Column public Timestamp createdAt; @Column public Timestamp updatedAt; public AuthKey() { key = RandomStringUtils.random(60, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"); } public String getKey() { return key; } public enum Type { API, USER } }
9aa9850c57a076ab8c5e9601af04b6ad35da17bc
41ce0e67fd534768da41683e972bd25a7ce68164
/src/com/iteye/weimingtom/marika/mkscript/command/TextCommand.java
52a4e7cbe3611bd3d8863a9d30178a78599d2658
[]
no_license
weimingtom/marika_java
2f373b2eceb04b94f6638aaea82587f6e003a6a6
2224fca88043473673af47f828fdea414654bb2d
refs/heads/master
2021-01-13T01:44:15.550266
2017-03-07T02:21:13
2017-03-07T02:21:13
37,281,892
4
0
null
null
null
null
UTF-8
Java
false
false
1,091
java
package com.iteye.weimingtom.marika.mkscript.command; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; public class TextCommand extends Command { public short msg_len; public String message; public int nMessageTail; public ByteArrayOutputStream bytes = new ByteArrayOutputStream(); public TextCommand(byte type) { super(type); } @Override public String toString() { return super.toString() + "[TextCommand] { msg_len: " + msg_len + ", message: " + message + " }"; } public int AddMessage(String msg, int limit) { // if (msg.contains("这个部分要使用")) { // msg.length(); // } this.message = msg; this.bytes.reset(); try { this.bytes.write(this.message.getBytes("gbk")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int n = this.bytes.size() % 4; this.nMessageTail = n >= 0 ? (4 - n) : 0; for (int i = 0; i < this.nMessageTail; i++) { this.bytes.write(0); } return this.bytes.size(); } }
843af0b24d66d673ed693aef87fd2789997c1ca4
eb2c199b2e453d312a672ec4077d170953829860
/app/src/main/java/edu/uw/singhh17/project_fresh/Model/Ingredient.java
bbf20fef220291dd21bae8ac1d9a59867e91dcd9
[]
no_license
singhh213/project-fresh
bfc418fcba83f1b4c5b638a11b7b5e1b826897b0
ed5f5cb3cc692778304138db68c64224dd905105
refs/heads/master
2020-04-16T17:50:18.581714
2016-05-26T16:17:36
2016-05-26T16:17:36
55,472,073
0
0
null
null
null
null
UTF-8
Java
false
false
420
java
package edu.uw.singhh17.project_fresh.Model; /** * Created by harpreetsingh on 4/30/16. */ public class Ingredient { private String name; private String amount; public Ingredient(String name, String amount) { this.name = name; this.amount = amount; } public String getName() { return this.name; } public String getAmount() { return this.amount; } }
af50e7edc62c7bacc7f02c92a5c7780c5e65b350
bc08c052454ee6bede1e1496a2f6378b00a4a77c
/gen/com/bgryderclock/ptcountertimer/BuildConfig.java
d6fb049cfa9a266de8e66cec8f10d813c2188388
[]
no_license
bgryderclock/physical-therapy-counter-timer
c5ee03a152449efc2b2daee0188bf3170be5e761
b7ae506fbffad8ccc205af4070d7828f71f01da3
refs/heads/master
2021-01-25T08:42:30.092037
2013-07-16T04:12:12
2013-07-16T04:12:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
173
java
/** Automatically generated file. DO NOT MODIFY */ package com.bgryderclock.ptcountertimer; public final class BuildConfig { public final static boolean DEBUG = true; }
7b6d212ae706fd16c888f6012501a8eab9299611
ce15d5357eee9e201813afd4a0eab8266801d664
/app/src/main/java/com/example/mvpapp/DetailsDialog.java
98e86d00e6061c539af05b76eaef9e767dec0e4b
[]
no_license
Fahedosama/MVPApp
66cef8b70012505c988ae682e264d1486f321754
7635a4a9125d4b73b251a38da3967d7b6e33c815
refs/heads/master
2020-06-19T04:45:28.163834
2019-07-13T10:11:50
2019-07-13T10:11:50
196,566,971
0
0
null
null
null
null
UTF-8
Java
false
false
1,195
java
package com.example.mvpapp; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.TextView; import com.example.mvpapp.data.model.Names; public class DetailsDialog extends Dialog implements android.view.View.OnClickListener { public Activity c; public Dialog d; public TextView title,meaning; Names name; public DetailsDialog(Activity a, Names name) { super(a); // TODO Auto-generated constructor stub this.c = a; this.name=name; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.details_dialog); title = (TextView) findViewById(R.id.textView2); meaning = (TextView) findViewById(R.id.textView3); title.setText(name.getName_ar()); meaning.setText(name.getName_meaning()); // yes.setOnClickListener(this); // no.setOnClickListener(this); } @Override public void onClick(View v) { dismiss(); } }
c953665e138f0b120e03480123bdcc49b6a7403c
ca884b17c0b0014c29389f3b80d6ada47d7aa02d
/src/main/java/com/example/demo/service/Service.java
6af927141c2a429bc0bbe6b425923e11a76011ed
[]
no_license
abhishek150509/SpringbootTest
e55bf68a63d66a4acf6e43a18eeec6db7e5ba03c
074eb457d6a166f85db2f792adcaf74512255806
refs/heads/master
2023-06-20T01:13:02.238156
2021-07-19T19:11:37
2021-07-19T19:11:37
387,137,865
0
0
null
null
null
null
UTF-8
Java
false
false
116
java
package com.example.demo.service; import java.util.List; public interface Service { List<String> getAll(); }
3c44553757a23b94adc68e5fb605717cfe07eabb
fb449cbd238925ac05440c3c640134a5f3e78b48
/pro17/src/sec03/brd02/BoardService.java
9c8c94591852d120d5c9101ab76b7007aa7ec3e3
[]
no_license
TheRei3/JavaWebSkill
f8795e15bb65d62e6a45bf6e9a10ca119158f622
01355e62fa2001039ede6b280783915f26b5606e
refs/heads/master
2023-05-15T09:43:59.491179
2021-06-08T06:55:16
2021-06-08T06:55:16
372,388,463
1
0
null
null
null
null
UTF-8
Java
false
false
401
java
package sec03.brd02; import java.util.List; public class BoardService { BoardDAO boardDao; public BoardService() { boardDao = new BoardDAO(); } public List<ArticleVO> listArticles() { List<ArticleVO> articlesList = boardDao.selectAllArticles(); return articlesList; } public void addArticle(ArticleVO article) { boardDao.insertNewArticle(article); } }
[ "bitcamp@DESKTOP-UA6S0CR" ]
bitcamp@DESKTOP-UA6S0CR
10216a8d46473c25ad1b27e1d99d546f846735a9
4bc02b4b720b2d0e3a2fbe67ade4c36b9cb60adb
/jd1-hometask-layersarchitecture-katokoleg/src/by/htp/task1/controller/JewelController.java
ff012d1fe0ef27ebf2022e3ae1711ba97b764433
[]
no_license
Olescales/HomeTask_Java_LayersArchitecture_KatokOleg
39509e856d55afe8132b20a9450709281ffd3ec3
e25f6c78143eea9fdcbb4c74bf0e1cf157494f21
refs/heads/master
2020-06-09T06:15:49.318155
2019-06-23T19:51:02
2019-06-23T19:51:02
193,388,806
0
0
null
null
null
null
UTF-8
Java
false
false
433
java
package by.htp.task1.controller; import by.htp.task1.controller.command.Command; import by.htp.task1.controller.command.CommandProvider; public class JewelController { private CommandProvider provider = new CommandProvider(); public String doAction(String commandName) { String responce = null; Command command = provider.getCommand(commandName); responce = command.execute(); return responce; } }
cbd6f7b91edd665220dc41ba1f6be2288a7561fd
e96894c4fe2513b888090ab90e1f8f69be64ad09
/src/com/SpartanTech/schedule/SettingsActivity.java
a37d8aba8528af2e3fab6296fc1cb7be80aea85a
[]
no_license
SparkleFartsTechnology/spartan-schedule
d4913b2777b4604fb35e7598330383166d747050
c73e878204d33d194f02abd7d16da1d7e68aac7e
refs/heads/master
2020-05-17T16:27:15.118729
2014-05-30T04:11:33
2014-05-30T04:11:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
package com.SpartanTech.schedule; import android.app.Activity; import android.os.Bundle; public class SettingsActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } }
a355b8b59e720c3b9010fc426112ec8a4211c090
1f9c69b57ac8b53a11463c40c8f44778d6eacae8
/.svn/pristine/86/86c126c63c66f710f8afd74ac86fe1690d3d88da.svn-base
7315c406904103916628c497ff217626fda4b2c0
[]
no_license
prasadvishal/ResourceManager
9d1d3f27eff01d2bf9320485a620a017659fffde
cbb93924ace274044f2c117186399b1af9a111bc
refs/heads/master
2021-08-14T16:47:36.966387
2017-11-16T08:13:01
2017-11-16T08:13:01
110,942,521
1
0
null
null
null
null
UTF-8
Java
false
false
1,950
package com.mindfiresolutions.resourcemanager.resource; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; /** * Created by Vishal Prasad on 5/19/2017. */ public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { private OnItemClickListener mListener; public interface OnItemClickListener { public void onItemClick(View view, int position); public void onLongItemClick(View view, int position); } GestureDetector mGestureDetector; public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && mListener != null) { mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); return true; } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { } @Override public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){} }
1bacef86b775a1b6a7d5339644480e2070972aa5
d17a49816ac932e0a5de67bf32b13be84736d203
/src/test/java/com/innoinc/DemoApplicationTests.java
b06ac054f689d8b9d927a179550bdde9640ad054
[]
no_license
soulshelter/DSAT_USERSYNC
b27875ea895e0b669d26e8ffa6d3f3b48833e6eb
9b7e2ab08cc706ea806f7d409293f70655d9202f
refs/heads/master
2022-11-11T03:38:49.492551
2020-07-07T00:40:50
2020-07-07T00:40:50
277,676,363
0
0
null
null
null
null
UTF-8
Java
false
false
201
java
package com.innoinc; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { } }
ebabf8f5a2ba0c1c13a6f1222a32d00d83c85e75
bffe012669dddb83a1c81c7fbf2bbe2f9f21d7df
/MiniQuiz/app/src/test/java/com/zabello/miniquiz/ExampleUnitTest.java
a1adec099b90cf5cc0490943347bbf3793e3a5fb
[]
no_license
kryscinaZabela/Android_labs
e2120ae8f1085b72b21be3d465764d198e24c842
f9ce266b875e884d2b43d1555bda525ee8f5318c
refs/heads/main
2023-02-08T14:03:44.275709
2020-12-22T09:32:24
2020-12-22T09:32:24
323,579,473
0
0
null
null
null
null
UTF-8
Java
false
false
381
java
package com.zabello.miniquiz; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
0192ed10c78381099d2801398800b47321a578f0
3f022accc3061468866daa89b7a2699ce20e342f
/src/main/java/item/s264/Solution.java
b7cee04d570cc1237ba7dfb201c50cd91de1e23d
[]
no_license
coder-chi/leetcode
f103ff1032138c97a327a3014b3ef9f6d1a0d370
06c12fb5c9d401ac2d0f05fb8ca8dd8db3ebbc7b
refs/heads/master
2020-05-25T14:52:46.172715
2020-01-31T07:22:50
2020-01-31T07:22:50
187,855,594
0
0
null
null
null
null
UTF-8
Java
false
false
885
java
package item.s264; /** * created by zhangzhiyuan in 2019/11/8 */ public class Solution { public int nthUglyNumber(int n) { if (n == 0) { return 0; } int[] nums = new int[n]; nums[0] = 1; int index2 = 0; int index3 = 0; int index5 = 0; for (int i = 1; i < n; i++) { nums[i] = Math.min(Math.min(nums[index2] * 2, nums[index3] * 3), nums[index5] * 5); if (nums[i] == nums[index2] * 2) { index2++; } if (nums[i] == nums[index3] * 3) { index3++; } if (nums[i] == nums[index5] * 5) { index5++; } } return nums[n - 1]; } public static void main(String[] args) { int i = new Solution().nthUglyNumber(10); System.out.println(i); } }
05454ac2ec78682b1aee86f2d929893aa98c48bf
8f66cd63fc6085125a2987abf28195cb64991bc7
/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/MergeJoinConverterRule.java
76b051c46765899d562169ff1d244c3e064ef0c3
[ "Apache-2.0", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0", "BSD-3-Clause" ]
permissive
maojiang/ignite-3
37812afc76fd801e278af7fab3e2e4741ede488b
ab4a585c4fbc5b7df81011fc3f72bf10254dde66
refs/heads/main
2023-06-29T21:35:45.918067
2021-08-06T20:36:54
2021-08-06T20:36:54
394,493,901
1
0
Apache-2.0
2021-08-10T01:48:05
2021-08-10T01:48:04
null
UTF-8
Java
false
false
3,224
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.query.calcite.rule; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.PhysicalNode; import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.JoinInfo; import org.apache.calcite.rel.logical.LogicalJoin; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention; import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin; import static org.apache.ignite.internal.util.CollectionUtils.nullOrEmpty; /** * Ignite Join converter. */ public class MergeJoinConverterRule extends AbstractIgniteConverterRule<LogicalJoin> { /** */ public static final RelOptRule INSTANCE = new MergeJoinConverterRule(); /** * Creates a converter. */ public MergeJoinConverterRule() { super(LogicalJoin.class, "MergeJoinConverter"); } /** {@inheritDoc} */ @Override public boolean matches(RelOptRuleCall call) { LogicalJoin logicalJoin = call.rel(0); return !nullOrEmpty(logicalJoin.analyzeCondition().pairs()) && logicalJoin.analyzeCondition().isEqui(); } /** {@inheritDoc} */ @Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalJoin rel) { RelOptCluster cluster = rel.getCluster(); JoinInfo joinInfo = JoinInfo.of(rel.getLeft(), rel.getRight(), rel.getCondition()); RelTraitSet leftInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE) .replace(RelCollations.of(joinInfo.leftKeys)); RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE) .replace(RelCollations.of(joinInfo.leftKeys)); // preserve collation of the left input RelTraitSet rightInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE) .replace(RelCollations.of(joinInfo.rightKeys)); RelNode left = convert(rel.getLeft(), leftInTraits); RelNode right = convert(rel.getRight(), rightInTraits); return new IgniteMergeJoin(cluster, outTraits, left, right, rel.getCondition(), rel.getVariablesSet(), rel.getJoinType()); } }
6fc2162cd55f240e17168c6973ce1463c5ed6fe4
dd2dc6ee167bf51b0ddf28de9ea7d0d60a7c988a
/src/main/java/fr/mazure/maven/emg/traceability/TargetListReportFormatter.java
752fcf68b14d5017c13dc688bd4d85dc201d133c
[]
no_license
lmazure/emg
a723f6ba75f870629dc08f8e909fcb551444c49e
74e641a60345b6cf885a9672af284fefb31e4dbb
refs/heads/master
2020-04-23T08:10:09.407516
2019-04-21T07:07:03
2019-04-21T07:07:03
171,029,055
0
0
null
null
null
null
UTF-8
Java
false
false
1,738
java
package fr.mazure.maven.emg.traceability; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.List; public class TargetListReportFormatter extends Formatter { final private String _targetName; final private String[] _annotations; private List<BackwardTraceability> _targetTraceabilities; /** * output an annotated report of the targets * * @param targetName * @param annotations */ public TargetListReportFormatter(final String targetName, final String[] annotations) { _targetName = targetName; _annotations = annotations; } public void format(final OutputStream stream, final List<BackwardTraceability> targetTraceabilities) throws IOException { _targetTraceabilities = targetTraceabilities; super.format(stream); } @Override protected void writeContent(final PrintStream p) { p.println("<h1>" + _targetName + " report as markup</h1>"); p.println("<pre>"); p.print("h|*" + toHtml(_targetName) + "*|"); for (String annot: _annotations) { p.print("*" + toHtml(annot) + "*|"); } p.println(); for (BackwardTraceability trace: _targetTraceabilities) { p.print("|" + toHtml(trace.getTarget().getId()) + "|"); for (int i = 0; i < _annotations.length; i++) { p.print("|"); } p.println(); } p.println("</pre>"); } }
[ "Laurent@gilgamesh" ]
Laurent@gilgamesh
8299234433f9e25d8d78c8711429ffb0d5001aee
de05dff4cc5b8fb97dfbb857bad2394ed8f79ae4
/src/jd/captcha/JAntiCaptcha.java
0fd4cad82fd197c62165d42b94cd6e0e118dd662
[]
no_license
thiagocrestani/jdownloader-service
3a6c4929b808eb596c66f156812310701f4508eb
2d24d86bb97a1e5f93feb474f688a6a289447553
refs/heads/master
2020-12-24T18:12:38.941947
2010-11-16T13:34:57
2010-11-16T13:34:57
35,786,842
0
0
null
null
null
null
UTF-8
Java
false
false
79,083
java
// jDownloader - Downloadmanager // Copyright (C) 2008 JD-Team [email protected] // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jd.captcha; import java.awt.Color; import java.awt.Graphics; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.ListIterator; import java.util.Vector; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import jd.captcha.configuration.JACScript; import jd.captcha.gui.BasicWindow; import jd.captcha.gui.ImageComponent; import jd.captcha.gui.ScrollPaneWindow; import jd.captcha.pixelgrid.Captcha; import jd.captcha.pixelgrid.Letter; import jd.captcha.utils.Utilities; import jd.controlling.JDLogger; import jd.gui.userio.DummyFrame; import jd.http.Browser; import jd.nutils.Executer; import jd.nutils.JDHash; import jd.nutils.io.JDIO; import jd.parser.Regex; import jd.utils.JDUtilities; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Diese Klasse stellt alle public Methoden zur captcha Erkennung zur Verfügung. * Sie verküpft Letter und captcha Klassen. Gleichzeitig dient sie als * Parameter-Dump. * * @author JD-Team */ public class JAntiCaptcha { /** * Logger */ private static Logger logger = Utilities.getLogger(); /** * Testet die Angegebene Methode. Dabei werden analysebilder erstellt. * * @param file */ public static void testMethod(File file) { int checkCaptchas = 20; String code; String inputCode; int totalLetters = 0; int correctLetters = 0; File captchaFile; Image img; String methodName = file.getName(); File captchaDir = new File(file.getAbsolutePath() + "/captchas"); if (Utilities.isLoggerActive()) { logger.info("Test Method: " + methodName); } new JAntiCaptcha(methodName); File[] entries = captchaDir.listFiles(new FileFilter() { public boolean accept(File pathname) { // if(Utilities.isLoggerActive())logger.info(pathname.getName( // )); if (pathname.getName().endsWith(".jpg") || pathname.getName().endsWith(".png") || pathname.getName().endsWith(".gif")) { return true; } else { return false; } } }); ScrollPaneWindow w = new ScrollPaneWindow(); w.setTitle(" Test Captchas: " + file.getAbsolutePath()); w.resizeWindow(100); if (Utilities.isLoggerActive()) { logger.info("Found Testcaptchas: " + entries.length); } int testNum = Math.min(checkCaptchas, entries.length); if (Utilities.isLoggerActive()) { logger.info("Test " + testNum + " Captchas"); } int i = 0; for (i = 0; i < testNum; i++) { captchaFile = entries[(int) (Math.random() * entries.length)]; logger.info("JJJJJJJJ" + captchaFile); img = Utilities.loadImage(captchaFile); w.setText(0, i, captchaFile.getName()); w.setImage(1, i, img); w.repack(); JAntiCaptcha jac = new JAntiCaptcha(methodName); // BasicWindow.showImage(img); Captcha cap = jac.createCaptcha(img); if (cap == null) { if (Utilities.isLoggerActive()) { logger.severe("Captcha Bild konnte nicht eingelesen werden"); } continue; } w.setImage(2, i, cap.getImage()); // BasicWindow.showImage(cap.getImageWithGaps(2)); code = jac.checkCaptcha(captchaFile, cap); w.setImage(3, i, cap.getImage()); w.setText(4, i, "JAC:" + code); w.repack(); inputCode = JOptionPane.showInputDialog("Bitte Captcha Code eingeben", code); w.setText(5, i, "User:" + inputCode); w.repack(); if (code == null) { code = ""; } if (inputCode == null) { inputCode = ""; } code = code.toLowerCase(); inputCode = inputCode.toLowerCase(); for (int x = 0; x < inputCode.length(); x++) { totalLetters++; if (inputCode.length() == code.length() && inputCode.charAt(x) == code.charAt(x)) { correctLetters++; } } if (Utilities.isLoggerActive()) { logger.info("Erkennung: " + correctLetters + "/" + totalLetters + " = " + Utilities.getPercent(correctLetters, totalLetters) + "%"); } } w.setText(0, i + 1, "Erkennung: " + Utilities.getPercent(correctLetters, totalLetters) + "%"); w.setText(4, i + 1, "Richtig: " + correctLetters); w.setText(5, i + 1, "Falsch: " + (totalLetters - correctLetters)); JOptionPane.showMessageDialog(new JFrame(), "Erkennung: " + correctLetters + "/" + totalLetters + " = " + Utilities.getPercent(correctLetters, totalLetters) + "%"); } /** * Führt einen Testlauf mit den übergebenen Methoden durch * * @param methods */ public static void testMethods(File[] methods) { for (File element : methods) { JAntiCaptcha.testMethod(element); } } /** * Fenster die eigentlich nur zur Entwicklung sind um Basic GUI Elemente zu * haben */ private BasicWindow bw2; private BasicWindow bw3; private JDialog f; /** * Bildtyp. Falls dieser von jpg unterschiedlich ist, muss zuerst * konvertiert werden. */ private String imageType; /** * jas Script Instanz. Sie verarbneitet das JACScript und speichert die * Parameter */ public JACScript jas; /** * Vector mit den Buchstaben aus der MTHO File */ public ArrayList<Letter> letterDB; private int[][] letterMap = null; /** * Anzahl der Buchstaben im Captcha. Wird aus der jacinfo.xml gelesen */ private int letterNum; /** * ordnername der methode */ private String methodDirName; private boolean showDebugGui = false; private Vector<ScrollPaneWindow> spw = new Vector<ScrollPaneWindow>(); private Captcha workingCaptcha; private boolean extern; public boolean isExtern() { return extern; } private String command; private String dstFile; private String srcFile; private Image sourceImage; public JAntiCaptcha(String methodName) { JACMethod method = JACMethod.forServiceName(methodName); if (method == null) { logger.severe("no such method found! " + methodName); return; } methodDirName = method.getFileName(); getJACInfo(); jas = new JACScript(this, methodDirName); long time = System.currentTimeMillis(); loadMTHFile(); time = System.currentTimeMillis() - time; System.out.println(time); if (Utilities.isLoggerActive()) { logger.fine("letter DB loaded: Buchstaben: " + letterDB.size()); } } /** * prüft den übergebenen Captcha und gibt den Code als String zurück. Das * lettersarray des Catchas wird dabei bearbeitet. Es werden decoedvalue, * avlityvalue und parent gesetzt WICHTIG: Nach dem Decoden eines Captcha * herrscht Verwirrung. Es stehen unterschiedliche Methoden zur Verfügung um * an bestimmte Informationen zu kommen: captcha.getDecodedLetters() gibt * Die letter aus der datenbank zurück. Deren werte sind nicht fest. Auf den * Wert von getvalityvalue und getValityPercent kann man sich absolut nicht * verlassen. Einzig getDecodedValue() lässt sich zuverlässig auslesen * captcha.getLetters() gibt die Wirklichen Letter des captchas zurück. Hier * lassen sich alle wichtigen Infos abfragen. z.B. ValityValue, * ValityPercent, Decodedvalue, etc. Wer immer das hier liest sollte auf * keinen fall den fehler machen und sich auf Wert aus dem getdecodedLetters * array verlassen * * @param captcha * Captcha instanz * @return CaptchaCode */ public String checkCaptcha(File file, Captcha captcha) { if (extern) return callExtern(); workingCaptcha = captcha; // Führe prepare aus jas.executePrepareCommands(file, captcha); Letter[] letters = captcha.getLetters(getLetterNum()); if (letters == null) { captcha.setValityPercent(100.0); if (Utilities.isLoggerActive()) { logger.severe("Captcha konnte nicht erkannt werden!"); } return null; } String ret = ""; double correct = 0; LetterComperator akt; // Scannen Vector<LetterComperator> newLettersVector = new Vector<LetterComperator>(); for (int i = 0; i < letters.length; i++) { letters[i].setId(i); if (letters[i].detected != null) { akt = letters[i].detected; } else { akt = getLetter(letters[i]); } akt.getA().setId(i); newLettersVector.add(akt); } if (letters.length > getLetterNum()) { // sortieren Collections.sort(newLettersVector, new Comparator<LetterComperator>() { public int compare(LetterComperator obj1, LetterComperator obj2) { if (obj1.getValityPercent() < obj2.getValityPercent()) { return -1; } if (obj1.getValityPercent() > obj2.getValityPercent()) { return 1; } return 0; } }); // schlechte entfernen if (Utilities.isLoggerActive()) { logger.info(getLetterNum() + ""); } if (!jas.getBoolean("autoLetterNum")) { for (int i = newLettersVector.size() - 1; i >= getLetterNum(); i--) { newLettersVector.remove(i); } } // Wieder in die richtige reihenfolge sortieren Collections.sort(newLettersVector, new Comparator<LetterComperator>() { public int compare(LetterComperator obj1, LetterComperator obj2) { if (obj1.getA().getId() < obj2.getA().getId()) { return -1; } if (obj1.getA().getId() > obj2.getA().getId()) { return 1; } return 0; } }); } if (getJas().getString("useLettercomparatorFilter") != null && getJas().getString("useLettercomparatorFilter").length() > 0) { String[] ref = getJas().getString("useLettercomparatorFilter").split("\\."); if (ref.length != 2) { captcha.setValityPercent(100.0); if (Utilities.isLoggerActive()) { logger.severe("useLettercomparatorFilter should have the format Class.Method"); } return null; } String cl = ref[0]; String methodname = ref[1]; Class<?> newClass; try { newClass = Class.forName("jd.captcha.specials." + cl); Class<?>[] parameterTypes = new Class[] { newLettersVector.getClass(), this.getClass() }; Method method = newClass.getMethod(methodname, parameterTypes); Object[] arguments = new Object[] { newLettersVector, this }; Object instance = null; method.invoke(instance, arguments); } catch (Exception e) { if (Utilities.isLoggerActive()) { logger.severe("Fehler in useLettercomparatorFilter:" + e.getLocalizedMessage() + " / " + getJas().getString("useLettercomparatorFilter")); } JDLogger.exception(e); } } for (int i = 0; i < newLettersVector.size(); i++) { akt = newLettersVector.get(i); if (akt == null || akt.getValityPercent() >= 100.0) { ret += "-"; correct += 100.0; } else { ret += akt.getDecodedValue(); akt.getA().setId(i); correct += akt.getValityPercent(); } // if(Utilities.isLoggerActive())logger.finer("Validty: " + // correct); } if (newLettersVector.size() == 0) { captcha.setValityPercent(100.0); return null; } captcha.setLetterComperators(newLettersVector.toArray(new LetterComperator[] {})); if (Utilities.isLoggerActive()) { logger.finer("Vality: " + (int) (correct / newLettersVector.size())); } captcha.setValityPercent(correct / newLettersVector.size()); return ret; } /** * Exportiert die aktelle Datenbank als PNG einzelbilder */ public void exportDB() { File path = Utilities.directoryChooser(); File file; BufferedImage img; int i = 0; for (Letter letter : letterDB) { img = letter.getFullImage(); file = new File(path + "/letterDB/" + i++ + "_" + letter.getDecodedValue() + ".png"); file.mkdirs(); try { logger.info("Write Db: " + file); ImageIO.write(img, "png", file); } catch (IOException e) { JDLogger.exception(e); } } } private BufferedImage toBufferedImage(Image i) { if (i instanceof BufferedImage) { return (BufferedImage) i; } Image img; img = new ImageIcon(i).getImage(); BufferedImage b; b = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = b.createGraphics(); g.drawImage(img, 0, 0, null); g.dispose(); return b; } private String callExtern() { try { File file = JDUtilities.getResourceFile(this.srcFile); file.getParentFile().mkdirs(); String ext = JDIO.getFileExtension(this.srcFile); ImageIO.write(toBufferedImage(this.sourceImage), ext, file); } catch (Exception e) { JDLogger.exception(e); return null; } Executer exec = new Executer(JDUtilities.getResourceFile(this.command).getAbsolutePath()); exec.setRunin(JDUtilities.getResourceFile(this.command).getParent()); exec.setWaitTimeout(300); exec.start(); exec.waitTimeout(); // String ret = exec.getOutputStream() + " \r\n " + // exec.getErrorStream(); String res = JDIO.readFileToString(JDUtilities.getResourceFile(this.dstFile)); if (res == null) return null; return res.trim(); } /** * Gibt den erkannten CaptchaText zurück * * @param captchafile * Pfad zum Bild * @return CaptchaCode */ public String checkCaptcha(File captchafile) { if (Utilities.isLoggerActive()) { logger.finer("check " + captchafile); } Image captchaImage = Utilities.loadImage(captchafile); Captcha captcha = createCaptcha(captchaImage); if (captcha != null) captcha.setCaptchaFile(captchafile); // captcha.printCaptcha(); return checkCaptcha(captchafile, captcha); } /** * Factory Methode zur Captcha erstellung * * @param captchaImage * Image instanz * @return captcha */ public Captcha createCaptcha(Image captchaImage) { this.sourceImage = captchaImage; if (extern) return null; if (captchaImage.getWidth(null) <= 0 || captchaImage.getHeight(null) <= 0) { if (Utilities.isLoggerActive()) { logger.severe("Image Dimensionen zu klein. Image hat keinen Inahlt. Pfad/Url prüfen!"); } return null; } Captcha ret = Captcha.getCaptcha(captchaImage, this); if (ret == null) { return null; } ret.setOwner(this); return ret; } /** * Aus gründen der geschwindigkeit wird die MTH XMl in einen vector * umgewandelt */ private void createLetterDBFormMTH(Document mth) { letterDB = new ArrayList<Letter>(); long start1 = System.currentTimeMillis(); try { if (mth == null || mth.getFirstChild() == null) { return; } NodeList nl = mth.getFirstChild().getChildNodes(); Letter tmp; for (int i = 0; i < nl.getLength(); i++) { // Get child node Node childNode = nl.item(i); if (childNode.getNodeName().equals("letter")) { NamedNodeMap att = childNode.getAttributes(); tmp = new Letter(); tmp.setOwner(this); String id = JDUtilities.getAttribute(childNode, "id"); if (!tmp.setTextGrid(childNode.getTextContent())) { logger.severe("Error in Letters DB line: " + i + ":" + childNode.getTextContent() + " id:" + id); continue; } if (id != null) { tmp.setId(Integer.parseInt(id)); } tmp.setSourcehash(att.getNamedItem("captchaHash").getNodeValue()); tmp.setDecodedValue(att.getNamedItem("value").getNodeValue()); tmp.setBadDetections(Integer.parseInt(JDUtilities.getAttribute(childNode, "bad"))); tmp.setGoodDetections(Integer.parseInt(JDUtilities.getAttribute(childNode, "good"))); letterDB.add(tmp); } else if (childNode.getNodeName().equals("map")) { if (Utilities.isLoggerActive()) { logger.fine("Parse LetterMap"); } long start2 = System.currentTimeMillis(); String[] map = childNode.getTextContent().split("\\|"); letterMap = new int[map.length][map.length]; for (int x = 0; x < map.length; x++) { String[] row = map[x].split("\\,"); for (int y = 0; y < map.length; y++) { letterMap[x][y] = Integer.parseInt(row[y]); } } if (Utilities.isLoggerActive()) { logger.fine("LetterMap Parsing time: " + (System.currentTimeMillis() - start2)); } } } } catch (Exception e) { JDLogger.exception(e); if (Utilities.isLoggerActive()) { logger.severe("Fehler bein lesen der MTH Datei!!. Methode kann nicht funktionieren!"); } } if (Utilities.isLoggerActive()) { logger.fine("Mth Parsing time: " + (System.currentTimeMillis() - start1)); } } /** * Diese methode trainiert einen captcha * * @param captchafile * File zum Bild * @param letterNum * Anzahl der Buchstaben im captcha * @return int -1: Übersprungen Sonst: anzahl der richtig erkanten Letter */ private Document createXMLFromLetterDB() { Document xml = JDUtilities.parseXmlString("<jDownloader></jDownloader>", false); if (letterMap != null) { Element element = xml.createElement("map"); xml.getFirstChild().appendChild(element); element.appendChild(xml.createTextNode(getLetterMapString())); } int i = 0; for (Letter letter : letterDB) { Element element = xml.createElement("letter"); xml.getFirstChild().appendChild(element); element.appendChild(xml.createTextNode(letter.getPixelString())); element.setAttribute("id", i++ + ""); element.setAttribute("value", letter.getDecodedValue()); element.setAttribute("captchaHash", letter.getSourcehash()); element.setAttribute("good", letter.getGoodDetections() + ""); element.setAttribute("bad", letter.getBadDetections() + ""); } return xml; } private void destroyScrollPaneWindows() { while (spw.size() > 0) { spw.remove(0).destroy(); } } /** * Zeigt die Momentane Library an. Buchstaben können gelöscht werden */ public void displayLibrary() { if (letterDB == null || letterDB.size() == 0) { return; } // final BasicWindow w = BasicWindow.getWindow("Library: " + // letterDB.size() + " Datensätze", 400, 300); final JFrame w = new JFrame(); // w.setLayout(new GridBagLayout()); sortLetterDB(); JPanel p = new JPanel(new GridLayout(letterDB.size() + 1, 3)); w.add(new JScrollPane(p)); final Letter[] list = new Letter[letterDB.size()]; int y = 0; int i = 0; ListIterator<Letter> iter = letterDB.listIterator(letterDB.size()); final ArrayList<Integer> rem = new ArrayList<Integer>(); while (iter.hasPrevious()) { final Letter tmp = iter.previous(); list[i] = tmp; JLabel lbl = null; if ((tmp.getGoodDetections() == 0 && tmp.getBadDetections() > 3) || ((double) tmp.getBadDetections() / (double) tmp.getGoodDetections() >= 3)) { lbl = new JLabel("<html><p><font color=\"#ff0000\" " + "size=\"3\">" + tmp.getId() + ": " + tmp.getDecodedValue() + "(" + tmp.getGoodDetections() + "/" + tmp.getBadDetections() + ") Size: " + tmp.toPixelObject(0.85).getSize() + "</font> </p>" + "</html>"); } else { lbl = new JLabel(tmp.getId() + ": " + tmp.getDecodedValue() + "(" + tmp.getGoodDetections() + "/" + tmp.getBadDetections() + ") Size: " + tmp.toPixelObject(0.85).getSize()); } ImageComponent img = new ImageComponent(tmp.getImage()); final JCheckBox bt = new JCheckBox("DELETE"); final int ii = i; bt.addActionListener(new ActionListener() { public Integer id = new Integer(ii); public void actionPerformed(ActionEvent arg) { JCheckBox src = ((JCheckBox) arg.getSource()); if (src.getText().equals("DELETE")) { rem.add(id); } else { rem.remove(id); } } }); p.add(lbl); p.add(img); p.add(bt); i++; y++; // if (y > 20) { // y = 0; // x += 6; // } } JButton b = new JButton("Invoke"); p.add(b); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // System.out.println(rem + ""); ArrayList<Letter> list = new ArrayList<Letter>(); int s = letterDB.size(); for (Integer i : rem) { try { Letter let = letterDB.get(s - 1 - i); list.add(let); } catch (Exception ew) { JDLogger.exception(ew); } } for (Letter letter : list) { removeLetterFromLibrary(letter); } saveMTHFile(); displayLibrary(); } }); w.pack(); w.setVisible(true); } public String getCodeFromFileName(String name) { return new Regex(name, "captcha_(.*?)_code(.*?)\\.(.*?)").getMatch(1); } /** * Liest den captchaornder aus * * @param path * @return File Array */ public File[] getImages(String path) { File dir = new File(path); if (dir == null || !dir.exists()) { if (Utilities.isLoggerActive()) { logger.severe("Image dir nicht gefunden " + path); } } logger.info(dir + ""); File[] entries = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { if (Utilities.isLoggerActive()) { logger.info(pathname.getName()); } if (pathname.getName().endsWith(".bmp") || pathname.getName().endsWith(".jpg") || pathname.getName().endsWith(".png") || pathname.getName().endsWith(".gif")) { return true; } else { return false; } } }); return entries; } /** * @return the imageType */ public String getImageType() { return imageType; } /** * Die Methode parsed die jacinfo.xml */ private void getJACInfo() { File f = getResourceFile("jacinfo.xml"); if (!f.exists()) { if (Utilities.isLoggerActive()) { logger.severe("jacinfo.xml is missing2"); } return; } Document doc = JDUtilities.parseXmlString(JDIO.readFileToString(f), false); if (doc == null) { if (Utilities.isLoggerActive()) { logger.severe("jacinfo.xml is missing2"); } return; } NodeList nl = doc.getFirstChild().getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { // Get child node Node childNode = nl.item(i); if (childNode.getNodeName().equals("method")) { try { this.extern = JDUtilities.getAttribute(childNode, "type").equalsIgnoreCase("extern"); } catch (Exception e) { } } else if (childNode.getNodeName().equals("command")) { this.srcFile = JDUtilities.getAttribute(childNode, "src"); this.dstFile = JDUtilities.getAttribute(childNode, "dst"); this.command = JDUtilities.getAttribute(childNode, "cmd"); } else if (childNode.getNodeName().equals("format")) { try { setLetterNum(Integer.parseInt(JDUtilities.getAttribute(childNode, "letterNum"))); } catch (Exception e) { } setImageType(JDUtilities.getAttribute(childNode, "type")); } } } /** * @return JACscript Instanz */ public JACScript getJas() { return jas; } /** * Vergleicht a und b und gibt eine Vergleichszahl zurück. a und b werden * gegeneinander verschoben und b wird über die Parameter gedreht. Praktisch * heißt das, dass derjenige Treffer als gut eingestuft wird, bei dem der * Datenbank Datensatz möglichst optimal überdeckt wird. * * @param a * Original Letter * @param B * Vergleichsletter * @return int 0(super)-0xffffff (ganz übel) */ public LetterComperator getLetter(Letter letter) { if (jas.getDouble("quickScanValityLimit") <= 0) { logger.info("quickscan disabled"); return getLetterExtended(letter); } logger.info("Work on Letter:" + letter); // long startTime = Utilities.getTimer(); LetterComperator res = null; double lastPercent = 100.0; int bvX, bvY; try { if (letterDB == null) { if (Utilities.isLoggerActive()) { logger.severe("letterDB nicht vorhanden"); } return null; } LetterComperator lc; ScrollPaneWindow w = null; if (isShowDebugGui()) { w = new ScrollPaneWindow(); w.setTitle(" Letter " + letter.getId()); } bvX = jas.getInteger("borderVarianceX"); bvY = jas.getInteger("borderVarianceY"); int line = 0; lc = new LetterComperator(letter, null); lc.setScanVariance(0, 0); lc.setOwner(this); res = lc; int tt = 0; logger.info("Do quickscan"); Method preValueFilterMethod = null; Class<?>[] preValueFilterParameterTypes = null; Object[] preValueFilterArguments = new Object[] { null, this }; if (jas.getString("preValueFilter").length() > 0) { String[] ref = jas.getString("preValueFilter").split("\\."); if (ref.length != 2) { if (Utilities.isLoggerActive()) { logger.severe("preValueFilter should have the format Class.Method"); } return null; } String cl = ref[0]; String methodname = ref[1]; Class<?> newClass; try { newClass = Class.forName("jd.captcha.specials." + cl); preValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() }; preValueFilterMethod = newClass.getMethod(methodname, preValueFilterParameterTypes); } catch (Exception e) { JDLogger.exception(e); } } Method postValueFilterMethod = null; Class<?>[] postValueFilterParameterTypes = null; Object[] postValueFilterArguments = new Object[] { null, this }; if (jas.getString("postValueFilter").length() > 0) { String[] ref = jas.getString("postValueFilter").split("\\."); if (ref.length != 2) { if (Utilities.isLoggerActive()) { logger.severe("postValueFilter should have the format Class.Method"); } return null; } String cl = ref[0]; String methodname = ref[1]; Class<?> newClass; try { newClass = Class.forName("jd.captcha.specials." + cl); postValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() }; postValueFilterMethod = newClass.getMethod(methodname, postValueFilterParameterTypes); } catch (Exception e) { JDLogger.exception(e); } } for (Letter tmp : letterDB) { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); if (Math.abs(tmp.getHeight() - letter.getHeight()) > bvY || Math.abs(tmp.getWidth() - letter.getWidth()) > bvX) { continue; } lc = new LetterComperator(letter, tmp); // commented out only experimental // lc.setScanVariance(0, 0); lc.setOwner(this); if (preValueFilterMethod != null) { preValueFilterArguments[0] = tmp; preValueFilterArguments[1] = lc; if (!((Boolean) preValueFilterMethod.invoke(null, preValueFilterArguments))) { continue; } } lc.run(); tt++; if (isShowDebugGui()) { w.setText(0, line, "0° Quick " + tt); w.setImage(1, line, lc.getA().getImage(2)); w.setText(2, line, lc.getA().getDim()); w.setImage(3, line, lc.getB().getImage(2)); w.setText(4, line, lc.getB().getDim()); w.setImage(5, line, lc.getIntersectionLetter().getImage(2)); w.setText(6, line, lc.getIntersectionLetter().getDim()); w.setText(7, line, lc); line++; } postValueFilterArguments[0] = lc; if (postValueFilterMethod == null || (Boolean) postValueFilterMethod.invoke(null, postValueFilterArguments)) { if (res == null || lc.getValityPercent() < res.getValityPercent()) { if (res != null && res.getValityPercent() < lastPercent) { lastPercent = res.getValityPercent(); } res = lc; if (jas.getDouble("LetterSearchLimitPerfectPercent") >= lc.getValityPercent()) { if (Utilities.isLoggerActive()) { logger.finer(" Perfect Match: " + res.getB().getDecodedValue() + res.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + res); } res.setDetectionType(LetterComperator.QUICKSCANPERFECTMATCH); res.setReliability(lastPercent - res.getValityPercent()); return res; } // if(Utilities.isLoggerActive())logger.finer("dim " // + // lc.getA().getDim() + "|" + lc.getB().getDim() + " New // Best value: " + lc.getDecodedValue() + " " // +lc.getValityPercent() + " good:" + // tmp.getGoodDetections() + " bad: " + // tmp.getBadDetections() + " - " + lc); } else if (res != null) { if (lc.getValityPercent() < lastPercent) { lastPercent = lc.getValityPercent(); } } } } } catch (Exception e) { JDLogger.exception(e); } if (res != null && res.getB() != null) { if (Utilities.isLoggerActive()) { logger.finer(" Normal Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + res.getB().getGoodDetections() + " bad: " + res.getB().getBadDetections()); } // if (Utilities.isLoggerActive()) logger.fine("Letter erkannt // in: " + (Utilities.getTimer() - startTime) + " ms"); res.setReliability(lastPercent - res.getValityPercent()); if (res.getReliability() >= jas.getDouble("quickScanReliabilityLimit") && res.getValityPercent() < jas.getDouble("quickScanValityLimit")) { res.setDetectionType(LetterComperator.QUICKSCANMATCH); logger.info("Qickscan found " + res.getValityPercent() + "<" + jas.getDouble("quickScanValityLimit")); return res; } else { if (Utilities.isLoggerActive()) { logger.warning("Letter nicht ausreichend erkannt. Try Extended " + res.getReliability() + " - " + jas.getDouble("quickScanReliabilityLimit") + " /" + res.getValityPercent() + "-" + jas.getDouble("quickScanValityLimit")); } return getLetterExtended(letter); } } else { if (Utilities.isLoggerActive()) { logger.warning("Letter nicht erkannt. Try Extended"); } return getLetterExtended(letter); } } /** * Sucht in der MTH ANch dem besten übereinstimmenem letter * * @param letter * (refferenz) * @return Letter. Beste Übereinstimmung */ private LetterComperator getLetterExtended(Letter letter) { // long startTime = Utilities.getTimer(); LetterComperator res = null; logger.info("Extended SCAN"); double lastPercent = 100.0; JTextArea tf = null; try { if (letterDB == null) { if (Utilities.isLoggerActive()) { logger.severe("letterDB nicht vorhanden"); } return null; } Letter tmp; int leftAngle = jas.getInteger("scanAngleLeft"); int rightAngle = jas.getInteger("scanAngleRight"); if (leftAngle > rightAngle) { int temp = leftAngle; leftAngle = rightAngle; rightAngle = temp; if (Utilities.isLoggerActive()) { logger.warning("param.scanAngleLeft>paramscanAngleRight"); } } int steps = Math.max(1, jas.getInteger("scanAngleSteps")); boolean turnDB = jas.getBoolean("turnDB"); int angle; Letter orgLetter = letter; LetterComperator lc; ScrollPaneWindow w = null; if (isShowDebugGui()) { w = new ScrollPaneWindow(); w.setTitle(" Letter " + letter.getId()); } int line = 0; lc = new LetterComperator(letter, null); lc.setOwner(this); res = lc; Method preValueFilterMethod = null; Class<?>[] preValueFilterParameterTypes = null; Object[] preValueFilterArguments = new Object[] { null, this }; if (jas.getString("preValueFilter").length() > 0) { String[] ref = jas.getString("preValueFilter").split("\\."); if (ref.length != 2) { if (Utilities.isLoggerActive()) { logger.severe("preValueFilter should have the format Class.Method"); } return null; } String cl = ref[0]; String methodname = ref[1]; Class<?> newClass; try { newClass = Class.forName("jd.captcha.specials." + cl); preValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() }; preValueFilterMethod = newClass.getMethod(methodname, preValueFilterParameterTypes); } catch (Exception e) { JDLogger.exception(e); } } Method postValueFilterMethod = null; Class<?>[] postValueFilterParameterTypes = null; Object[] postValueFilterArguments = new Object[] { null, this }; if (jas.getString("postValueFilter").length() > 0) { String[] ref = jas.getString("postValueFilter").split("\\."); if (ref.length != 2) { if (Utilities.isLoggerActive()) { logger.severe("postValueFilter should have the format Class.Method"); } return null; } String cl = ref[0]; String methodname = ref[1]; Class<?> newClass; try { newClass = Class.forName("jd.captcha.specials." + cl); postValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() }; postValueFilterMethod = newClass.getMethod(methodname, postValueFilterParameterTypes); } catch (Exception e) { JDLogger.exception(e); } } for (angle = Utilities.getJumperStart(leftAngle, rightAngle); Utilities.checkJumper(angle, leftAngle, rightAngle); angle = Utilities.nextJump(angle, leftAngle, rightAngle, steps)) { if (turnDB) { letter = orgLetter; } else { letter = orgLetter.turn(angle); } // if(Utilities.isLoggerActive())logger.finer(" Angle " + // angle + " : " + letter.getDim()); int tt = 0; for (Letter ltr : letterDB) { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); if (turnDB) { tmp = ltr.turn(angle); } else { tmp = ltr; } if (Math.abs(tmp.getHeight() - letter.getHeight()) > jas.getInteger("borderVarianceY") || Math.abs(tmp.getWidth() - letter.getWidth()) > jas.getInteger("borderVarianceX")) { continue; } lc = new LetterComperator(letter, tmp); lc.setOwner(this); if (preValueFilterMethod != null) { preValueFilterArguments[0] = lc; preValueFilterArguments[1] = this; if (!((Boolean) preValueFilterMethod.invoke(null, preValueFilterArguments))) { continue; } } lc.run(); // if(Utilities.isLoggerActive())logger.info("Duration: // "+(Utilities.getTimer()-timer) +" // Loops: "+lc.loopCounter); tt++; if (isShowDebugGui()) { w.setText(0, line, angle + "° " + tt); w.setImage(1, line, lc.getA().getImage(2)); w.setText(2, line, lc.getA().getDim()); w.setImage(3, line, lc.getB().getImage(2)); w.setText(4, line, lc.getB().getDim()); w.setImage(5, line, lc.getIntersectionLetter().getImage(2)); w.setText(6, line, lc.getIntersectionLetter().getDim()); w.setComponent(7, line, tf = new JTextArea()); tf.setText(lc.toString()); if (lc.getPreValityPercent() > jas.getInteger("preScanFilter") && jas.getInteger("preScanFilter") > 0) { tf.setBackground(Color.LIGHT_GRAY); } line++; } postValueFilterArguments[0] = lc; if (postValueFilterMethod == null || (Boolean) postValueFilterMethod.invoke(null, postValueFilterArguments)) { if (res == null || lc.getValityPercent() < res.getValityPercent()) { if (res != null && res.getValityPercent() < lastPercent) { lastPercent = res.getValityPercent(); } res = lc; if (jas.getDouble("LetterSearchLimitPerfectPercent") >= lc.getValityPercent()) { res.setDetectionType(LetterComperator.PERFECTMATCH); res.setReliability(lastPercent - res.getValityPercent()); if (Utilities.isLoggerActive()) { logger.finer(" Perfect Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + res); } if (isShowDebugGui()) { tf.setBackground(Color.GREEN); } return res; } if (isShowDebugGui()) { tf.setBackground(Color.BLUE); } if (Utilities.isLoggerActive()) { logger.finer("Angle " + angle + "dim " + lc.getA().getDim() + "|" + lc.getB().getDim() + " New Best value: " + lc.getDecodedValue() + " " + lc.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + lc); } } else if (res != null) { // if (Utilities.isLoggerActive()&& // lc.getDecodedValue().equalsIgnoreCase("G")) // logger.finer("Angle " + angle + "dim " + // lc.getA().getDim() + "|" + lc.getB().getDim() + " // value: " + lc.getDecodedValue() + " " + // lc.getValityPercent() + " good:" + // tmp.getGoodDetections() + " bad: " + // tmp.getBadDetections() + " - " + lc); if (lc.getValityPercent() < lastPercent) { lastPercent = lc.getValityPercent(); } } } } // if(Utilities.isLoggerActive())logger.info("Full Angle scan // in // "+(Utilities.getTimer()-startTime2)); } // w.refreshUI(); } catch (Exception e) { JDLogger.exception(e); } if (res != null && res.getB() != null) { if (Utilities.isLoggerActive()) { logger.finer(" Normal Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + res.getB().getGoodDetections() + " bad: " + res.getB().getBadDetections()); } res.setReliability(lastPercent - res.getValityPercent()); } else { if (getJas().getInteger("preScanEmergencyFilter") > getJas().getInteger("preScanFilter")) { logger.warning("nicht erkannt. Verwende erweiterte Emergencydatenbank"); int psf = getJas().getInteger("preScanFilter"); getJas().set("preScanFilter", getJas().getInteger("preScanEmergencyFilter")); LetterComperator ret = getLetterExtended(letter); getJas().set("preScanFilter", psf); return ret; } if (Utilities.isLoggerActive()) { logger.severe("Letter entgültig nicht erkannt"); } if (isShowDebugGui() && tf != null) { tf.setBackground(Color.RED); } } return res; } /** * @return gibt die Lettermap als String zurück */ private String getLetterMapString() { StringBuilder ret = new StringBuilder(); int i = 0; for (int x = 0; x < letterMap.length; x++) { ret.append("|"); i++; for (int y = 0; y < letterMap[0].length; y++) { ret.append(letterMap[x][y]); i++; ret.append(","); i++; } ret.deleteCharAt(ret.length() - 1); if (Utilities.isLoggerActive()) { logger.fine("Db String: " + x * 100 / letterDB.size() + "%"); } } ret.deleteCharAt(0); return ret.toString(); } /** * @return the letterNum */ public int getLetterNum() { return letterNum; } /** * @return the method */ public String getMethodDirName() { return methodDirName; } /** * Gibt ein FileObject zu einem resourcestring zurück * * @param arg * @return File zu arg */ public File getResourceFile(String arg) { return JDUtilities.getResourceFile(JDUtilities.getJACMethodsDirectory() + methodDirName + "/" + arg); } public Captcha getWorkingCaptcha() { return workingCaptcha; } /** * Importiert PNG einzelbilder aus einem ordner und erstellt daraus eine * neue db */ public void importDB(File path) { String pattern = JOptionPane.showInputDialog("PATTERN", "\\d+_(.*?)\\."); if (JOptionPane.showConfirmDialog(null, "Delete old db?") == JOptionPane.OK_OPTION) letterDB = new ArrayList<Letter>(); getResourceFile("letters.mth").delete(); System.out.println("LETTERS BEFORE: " + letterDB.size()); Image image; Letter letter; File[] images = getImages(path.getAbsolutePath()); for (File element : images) { image = Utilities.loadImage(element); try { image = ImageIO.read(element); } catch (IOException e) { JDLogger.exception(e); } System.out.println(element.getAbsolutePath()); int width = image.getWidth(null); int height = image.getHeight(null); if (width <= 0 || height <= 0) { if (Utilities.isLoggerActive()) { logger.severe("ERROR: Image nicht korrekt."); } } Captcha cap = createCaptcha(image); letter = new Letter(); letter.setOwner(this); letter.setGrid(cap.grid); letter.setSourcehash(JDHash.getMD5(element)); String let = new Regex(element.getName(), pattern).getMatch(0); letter.setDecodedValue(let); letter.clean(); letter.removeSmallObjects(0.3, 0.5, 10); letter.setDecodedValue(let); letterDB.add(letter); } System.out.println("LETTERS AFTER: " + letterDB.size()); sortLetterDB(); saveMTHFile(); } /** * Prüft ob der übergeben hash in der MTH file ist * * @param captchaHash * @return true/false */ private boolean isCaptchaInMTH(String captchaHash) { if (letterDB == null) return false; for (Letter letter : letterDB) { if (letter.getSourcehash().equals(captchaHash)) return true; } return false; } /** * @return the showDebugGui */ public boolean isShowDebugGui() { return showDebugGui; } /** * MTH File wird geladen und verarbeitet * * @param f */ public void loadMTHFile(File f) { String str = null; if (f.exists()) { str = JDIO.readFileToString(f); } else { str = "<jDownloader></jDownloader>"; } Document mth = JDUtilities.parseXmlString(str, false); logger.info("Get file: " + f); if (mth == null) { if (Utilities.isLoggerActive()) { logger.severe("MTH FILE NOT AVAILABLE."); } } createLetterDBFormMTH(mth); // sortLetterDB(); } /** * MTH File wird geladen und verarbeitet */ public void loadMTHFile() { File f = getResourceFile("letters.mth"); loadMTHFile(f); // sortLetterDB(); } /** * Entfernt Buchstaben mit einem schlechetb Bad/Good verhältniss */ public void removeBadLetters() { Letter tmp; if (Utilities.isLoggerActive()) { logger.info("aktuelle DB Size: " + letterDB.size()); } ListIterator<Letter> iter = letterDB.listIterator(letterDB.size()); while (iter.hasPrevious()) { tmp = iter.previous(); if (tmp.getBadDetections() > tmp.getGoodDetections() + 2) { if (Utilities.isLoggerActive()) { logger.info("bad Letter entfernt: " + tmp.getDecodedValue() + " (" + tmp.getBadDetections() + "/" + tmp.getGoodDetections() + ")"); } iter.remove(); } } if (Utilities.isLoggerActive()) { logger.info("neue DB Size: " + letterDB.size()); } sortLetterDB(); saveMTHFile(); } protected void removeLetterFromLibrary(Letter letter) { logger.info("Remove" + letter + " : " + letterDB.remove(letter)); } /** * Speichert die MTH File */ public synchronized void saveMTHFile() { String xmlString = JDUtilities.createXmlString(createXMLFromLetterDB()); if (!JDIO.writeLocalFile(getResourceFile("letters.mth"), xmlString)) { if (Utilities.isLoggerActive()) { logger.severe("MTHO file Konnte nicht gespeichert werden"); } } } /** * @param imageType * the imageType to set */ public void setImageType(String imageType) { if (Utilities.isLoggerActive()) { logger.finer("SET PARAMETER: [imageType] = " + imageType); } this.imageType = imageType; } /** * @param letterNum * the letterNum to set */ public void setLetterNum(int letterNum) { if (Utilities.isLoggerActive()) { logger.finer("SET PARAMETER: [letterNum] = " + letterNum); } this.letterNum = letterNum; } /** * @param showDebugGui * the showDebugGui to set */ public void setShowDebugGui(boolean showDebugGui) { this.showDebugGui = showDebugGui; } public void setWorkingCaptcha(Captcha workingCaptcha) { this.workingCaptcha = workingCaptcha; } /** * Debug Methode. Zeigt den Captcha in verschiedenen bearbeitungsstadien an * * @param captchafile */ public void showPreparedCaptcha(final File captchafile) { if (!captchafile.exists()) { if (Utilities.isLoggerActive()) { logger.severe(captchafile.getAbsolutePath() + " existiert nicht"); } return; } Image captchaImage = Utilities.loadImage(captchafile); BasicWindow.showImage(captchaImage); Captcha captcha = createCaptcha(captchaImage); int skWidth = captcha.getWidth(); int skHeight = captcha.getHeight(); if (skHeight > 200 || skWidth > 200) { if (skHeight > skWidth) { skWidth = 200 * skWidth / skHeight; skHeight = 200; } else { skHeight = 200 * skHeight / skWidth; skWidth = 200; } } logger.info("CAPTCHA :_" + checkCaptcha(captchafile, captcha)); if (bw3 != null) { bw3.dispose(); } bw3 = BasicWindow.showImage(captchaImage.getScaledInstance(skWidth, skHeight, 1), "Captchas"); bw3.add(new JLabel("ORIGINAL"), Utilities.getGBC(2, 0, 2, 2)); bw3.setLocationByScreenPercent(50, 70); bw3.add(new ImageComponent(captcha.getImage(1).getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 2, 2, 2)); bw3.add(new JLabel("Farbraum Anpassung"), Utilities.getGBC(2, 2, 2, 2)); jas.executePrepareCommands(captchafile, captcha); bw3.add(new ImageComponent(captcha.getImage(1).getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 4, 2, 2)); bw3.add(new JLabel("Prepare Code ausgeführt"), Utilities.getGBC(2, 4, 2, 2)); // Hole die letters aus dem neuen captcha // Utilities.wait(40000); // prüfe auf Erfolgreiche Lettererkennung // Decoden. checkCaptcha verwendet dabei die gecachte Erkennung der // letters Letter[] letters = captcha.getLetters(letterNum); if (letters == null) { if (Utilities.isLoggerActive()) { logger.severe("2. Lettererkennung ist fehlgeschlagen!"); } return; } bw3.add(new ImageComponent(captcha.getImageWithGaps(1).getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 6, 2, 2)); bw3.add(new JLabel("Buchstaben freistellen"), Utilities.getGBC(2, 6, 2, 2)); bw3.refreshUI(); if (bw2 != null) { bw2.destroy(); } bw2 = new BasicWindow(); bw2.setTitle("Freigestellte Buchstaben"); bw2.setLayout(new GridBagLayout()); bw2.setSize(300, 300); if (Utilities.isLoggerActive()) { logger.info("display freistellen"); } bw2.setAlwaysOnTop(true); bw2.setLocationByScreenPercent(50, 5); bw2.add(new JLabel("Aus Captcha:"), Utilities.getGBC(0, 0, 2, 2)); for (int i = 0; i < letters.length; i++) { bw2.add(new ImageComponent(letters[i].getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 2, 0, 2, 2)); } bw2.setVisible(true); bw2.pack(); bw2.setSize(300, bw2.getSize().height); LetterComperator[] lcs = captcha.getLetterComperators(); for (int i = 0; i < lcs.length; i++) { if (lcs[i] == null) continue; bw2.add(new JLabel("Aus Datenbank:"), Utilities.getGBC(0, 6, 2, 2)); Letter dif = lcs[i].getDifference(); dif.removeSmallObjects(0.8, 0.8, 5); dif.clean(); if (lcs[i].getB() != null) { bw2.add(new ImageComponent(lcs[i].getB().getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 2, 6, 2, 1)); bw2.add(new ImageComponent(dif.getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 2, 7, 2, 1)); } else { bw2.add(new JLabel("B unknown"), Utilities.getGBC(i * 2 + 2, 6, 2, 2)); } bw2.add(new JLabel("Wert:"), Utilities.getGBC(0, 8, 2, 2)); bw2.add(new JLabel("Proz.:"), Utilities.getGBC(0, 10, 2, 2)); bw2.add(new JLabel(lcs[i].getValityPercent() + "%"), Utilities.getGBC(i * 2 + 2, 10, 2, 2)); } JButton bt = new JButton("Train"); bw2.add(bt, Utilities.getGBC(0, 12, 2, 2)); bw2.pack(); bw2.repack(); bt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JAntiCaptcha.this.trainCaptcha(captchafile, 4); } }); } /** * Sortiert die letterDB Nach den bad Detections. Der Sortieralgo gehört * dringend überarbeitet!!! Diese Sortieren hilft die GUten Letter zuerst zu * prüfen. * * @TODO Sortoer ALGO ändern. zu langsam!! */ public void sortLetterDB() { Collections.sort(letterDB, new Comparator<Letter>() { public int compare(Letter a, Letter b) { try { return a.getDecodedValue().compareToIgnoreCase(b.getDecodedValue()) * -1; } catch (Exception e) { e.printStackTrace(); return 0; } } }); } /** * Diese methode wird aufgerufen um alle captchas im Ordner * methods/Methodname/captchas zu trainieren * * @param path */ public void trainAllCaptchas(String path) { int successFull = 0; int total = 0; logger.info("TRain " + path); File[] images = getImages(path); if (images == null) { return; } int newLetters; for (File element : images) { if (Utilities.isLoggerActive()) { logger.fine(element.toString()); } int letternum = getLetterNum(); newLetters = trainCaptcha(element, letternum); if (Utilities.isLoggerActive()) { logger.fine("Erkannt: " + newLetters + "/" + getLetterNum()); } if (newLetters > 0) { successFull += newLetters; total += getLetterNum(); if (Utilities.isLoggerActive()) { logger.info("Erkennungsrate: " + 100 * successFull / total); } } else if (newLetters == -2) { if (f != null) { f.dispose(); } break; } } } public int trainCaptcha(final File captchafile, int letterNum) { if (!captchafile.exists()) { if (Utilities.isLoggerActive()) { logger.severe(captchafile.getAbsolutePath() + " existiert nicht"); } return -1; } if (isShowDebugGui()) { destroyScrollPaneWindows(); } // Lade das Bild // Erstelle hashwert final String captchaHash = JDHash.getMD5(captchafile); // Prüfe ob dieser captcha schon aufgenommen wurde und überspringe ihn // falls ja if (isCaptchaInMTH(captchaHash)) { if (Utilities.isLoggerActive()) { logger.fine("Captcha schon aufgenommen" + captchafile); } return -1; } // captcha erstellen Image captchaImage = Utilities.loadImage(captchafile); final Captcha captcha = createCaptcha(captchaImage); int sk1Width = captcha.getWidth(); int sk1Height = captcha.getHeight(); if (sk1Height > 200 || sk1Width > 200) { if (sk1Height > sk1Width) { sk1Width = 200 * sk1Width / sk1Height; sk1Height = 200; } else { sk1Height = 200 * sk1Height / sk1Width; sk1Width = 200; } } final int skWidth = sk1Width; final int skHeight = sk1Height; String code = null; // Zeige das OriginalBild if (f != null) { f.dispose(); } f = new JDialog(DummyFrame.getDialogParent()); f.setLocation(500, 10); f.setLayout(new GridBagLayout()); f.add(new JLabel("original captcha: " + captchafile.getName()), Utilities.getGBC(0, 0, 10, 1)); f.add(new ImageComponent(captcha.getImage().getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 1, 10, 1)); f.setSize(1400, 800); f.pack(); f.setVisible(true); // Führe das Prepare aus // jas.executePrepareCommands(captcha); // Hole die letters aus dem neuen captcha final String guess = checkCaptcha(captchafile, captcha); final Letter[] letters = captcha.getLetters(letterNum); if (letters == null) { File file = getResourceFile("detectionErrors5/" + System.currentTimeMillis() + "_" + captchafile.getName()); file.getParentFile().mkdirs(); captchafile.renameTo(file); if (Utilities.isLoggerActive()) { logger.severe("Letter detection error"); } return -1; } class MyRunnable implements Runnable { private String code = null; private int ret = 0; public void run() { if (getCodeFromFileName(captchafile.getName()) == null) { code = JOptionPane.showInputDialog("Bitte Captcha Code eingeben (Press enter to confirm " + guess, guess); if (code != null && code.equals(guess)) { code = ""; } else if (code == null) { if (JOptionPane.showConfirmDialog(new JFrame(), "Ja (yes) = beenden (close) \t Nein (no) = nächstes Captcha (next captcha)") == JOptionPane.OK_OPTION) { ret = -2; } } } else { code = getCodeFromFileName(captchafile.getName()); if (Utilities.isLoggerActive()) { logger.warning("captcha code für " + captchaHash + " verwendet: " + code); } } synchronized (this) { this.notify(); } } } MyRunnable run = new MyRunnable(); Thread inpThread = new Thread(run); inpThread.start(); // Zeige das After-prepare Bild an f.add(new JLabel("Letter Detection"), Utilities.getGBC(0, 3, 10, 1)); f.add(new ImageComponent(captcha.getImageWithGaps(1).getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 4, 10, 1)); f.add(new JLabel("Seperated"), Utilities.getGBC(0, 5, 10, 1)); for (int i = 0; i < letters.length; i++) { f.add(new ImageComponent(letters[i].getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 1, 6, 1, 1)); JLabel jl = new JLabel("|"); jl.setForeground(Color.RED); f.add(jl, Utilities.getGBC(i * 2 + 2, 6, 1, 1)); } f.pack(); // Decoden. checkCaptcha verwendet dabei die gecachte Erkennung der // letters final LetterComperator[] lcs = captcha.getLetterComperators(); if (lcs == null) { File file = getResourceFile("detectionErrors5/" + System.currentTimeMillis() + "_" + captchafile.getName()); file.getParentFile().mkdirs(); captchafile.renameTo(file); if (Utilities.isLoggerActive()) { logger.severe("Letter detection error"); } return -1; } if (lcs.length != letters.length) { logger.severe("ACHTUNG. lcs: " + lcs.length + " - letters: " + letters.length); } if (guess != null /* && guess.length() == getLetterNum() */) { f.add(new JLabel("Letter Detection"), Utilities.getGBC(0, 3, 10, 1)); f.add(new ImageComponent(captcha.getImageWithGaps(1).getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 4, 10, 1)); f.add(new JLabel("Seperated"), Utilities.getGBC(0, 5, 10, 1)); for (int i = 0; i < letters.length; i++) { f.add(new ImageComponent(letters[i].getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 1, 6, 1, 1)); JLabel jl = new JLabel("|"); jl.setForeground(Color.RED); f.add(jl, Utilities.getGBC(i * 2 + 2, 6, 1, 1)); } f.pack(); for (int i = 0; i < lcs.length; i++) { if (lcs[i] != null && lcs[i].getB() != null) { f.add(new ImageComponent(lcs[i].getB().getImage((int) Math.ceil(jas.getDouble("simplifyFaktor")))), Utilities.getGBC(i * 2 + 1, 8, 1, 1)); } else { f.add(new JLabel(""), Utilities.getGBC(i * 2 + 1, 8, 1, 1)); } JLabel jl = new JLabel("|"); jl.setForeground(Color.RED); f.add(jl, Utilities.getGBC(i * 2 + 2, 6, 1, 1)); if (lcs[i] != null && lcs[i].getB() != null) { f.add(new JLabel("" + lcs[i].getDecodedValue()), Utilities.getGBC(i * 2 + 1, 9, 1, 1)); } else { f.add(new JLabel(""), Utilities.getGBC(i * 2 + 1, 9, 1, 1)); } if (lcs[i] != null && lcs[i].getB() != null) { f.add(new JLabel("" + Math.round(10 * lcs[i].getValityPercent()) / 10.0), Utilities.getGBC(i * 2 + 1, 10, 1, 1)); } else { f.add(new JLabel(""), Utilities.getGBC(i * 2 + 1, 10, 1, 1)); } } f.pack(); } else { if (Utilities.isLoggerActive()) { logger.warning("Erkennung fehlgeschlagen"); } } f.add(new JLabel("prepared captcha"), Utilities.getGBC(0, 11, 10, 1)); f.add(new ImageComponent(captcha.getImage().getScaledInstance(skWidth, skHeight, 1)), Utilities.getGBC(0, 12, 10, 1)); f.pack(); if (Utilities.isLoggerActive()) { logger.info("Decoded Captcha: " + guess + " Vality: " + captcha.getValityPercent()); } if (inpThread.isAlive()) { synchronized (run) { try { run.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } if (run.ret == -2) return -2; code = run.code; if (code == null) { File file = getResourceFile("detectionErrors3/" + System.currentTimeMillis() + "_" + captchafile.getName()); file.getParentFile().mkdirs(); captchafile.renameTo(file); if (Utilities.isLoggerActive()) { logger.severe("Captcha Input error"); } return -1; } if (code.length() == 0) { code = guess; } if (code.length() != letters.length) { File file = getResourceFile("detectionErrors4/" + System.currentTimeMillis() + "_" + captchafile.getName()); file.getParentFile().mkdirs(); captchafile.renameTo(file); if (Utilities.isLoggerActive()) { logger.severe("Captcha Input error3"); } return -1; } if (code.indexOf("-") < 0) { String[] oldName = captchafile.getName().split("\\."); String ext = oldName[oldName.length - 1]; String newName = captchafile.getParentFile().getAbsolutePath() + "/captcha_" + getMethodDirName() + "_code" + code + "." + ext; captchafile.renameTo(new File(newName)); } int ret = 0; for (int j = 0; j < letters.length; j++) { final int i = j; if (!code.substring(i, i + 1).equals("-")) { if (guess != null && code.length() > i && guess.length() > i && code.substring(i, i + 1).equals(guess.substring(i, i + 1))) { ret++; if (lcs[i] != null) { lcs[i].getB().markGood(); } if (lcs[i].getValityPercent() > 50) { letters[i].setOwner(this); // letters[i].setTextGrid(letters[i].getPixelString()); letters[i].setSourcehash(captchaHash); letters[i].setDecodedValue(code.substring(i, i + 1)); new Thread(new Runnable() { public void run() { final BasicWindow bws = BasicWindow.showImage(letters[i].getImage(2), "" + letters[i].getDecodedValue()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bws.dispose(); } }).start(); letterDB.add(letters[i]); } if (!jas.getBoolean("TrainOnlyUnknown")) { letters[i].setOwner(this); // letters[i].setTextGrid(letters[i].getPixelString()); letters[i].setSourcehash(captchaHash); letters[i].setDecodedValue(code.substring(i, i + 1)); letterDB.add(letters[i]); f.add(new JLabel("OK+"), Utilities.getGBC(i + 1, 13, 1, 1)); } else { f.add(new JLabel("OK-"), Utilities.getGBC(i + 1, 13, 1, 1)); f.pack(); } } else { if (Utilities.isLoggerActive()) { logger.info(letterDB + " - "); } if (lcs != null && lcs[i] != null && letterDB.size() > 30 && lcs[i] != null && lcs[i].getB() != null) { lcs[i].getB().markBad(); } letters[i].setOwner(this); // letters[i].setTextGrid(letters[i].getPixelString()); letters[i].setSourcehash(captchaHash); letters[i].setDecodedValue(code.substring(i, i + 1)); letterDB.add(letters[i]); new Thread(new Runnable() { public void run() { final BasicWindow bws = BasicWindow.showImage(letters[i].getImage(2), "" + letters[i].getDecodedValue()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bws.dispose(); } }).start(); f.add(new JLabel("NO +"), Utilities.getGBC(i + 1, 13, 1, 1)); f.pack(); } } else { f.add(new JLabel("-"), Utilities.getGBC(i + 1, 13, 1, 1)); f.pack(); } // mth.appendChild(element); } sortLetterDB(); // das syncroniced kann das jetzt auch mit einem thread gemacht werden new Thread(new Runnable() { public void run() { saveMTHFile(); } }).start(); return ret; } public void cleanLibrary(double d) { ArrayList<Letter> newDB = new ArrayList<Letter>(); main: for (Letter let : letterDB) { for (Letter n : newDB) { if (let.getDecodedValue().endsWith(n.getDecodedValue())) { LetterComperator lc = new LetterComperator(let, n); lc.setOwner(this); lc.run(); n.getElementPixel(); if (lc.getValityPercent() <= d) { BasicWindow.showImage(let.getImage(), " OK "); // BasicWindow.showImage(n.getImage(), " FILTERED " + // lc.getValityPercent()); if (n.getElementPixel() > let.getElementPixel()) { newDB.remove(let); break; } else { continue main; } } } } newDB.add(let); } letterDB = newDB; this.saveMTHFile(); } public static String getCaptcha(String path, String host) { if (JACMethod.hasMethod(host)) { File file; if (path.contains("http://")) { try { file = JDUtilities.getResourceFile("captchas/jac_captcha.img"); file.deleteOnExit(); Browser.download(file, new Browser().openGetConnection(path)); } catch (IOException e) { return "Could not download captcha image"; } } else { file = new File(path); if (!file.exists()) return "File does not exist"; } try { Image captchaImage = ImageIO.read(file); JAntiCaptcha jac = new JAntiCaptcha(host); Captcha captcha = jac.createCaptcha(captchaImage); return jac.checkCaptcha(file, captcha); } catch (Exception e) { return e.getStackTrace().toString(); } } else { return "jDownloader has no method for " + host; } } }
00e35f38e2aa2d1f801655969003fc1955bc9f49
32f38cd53372ba374c6dab6cc27af78f0a1b0190
/app/src/main/java/defpackage/bya.java
13ae00749d400662d0935575531fe277b15ebf72
[ "BSD-3-Clause" ]
permissive
shuixi2013/AmapCode
9ea7aefb42e0413f348f238f0721c93245f4eac6
1a3a8d4dddfcc5439df8df570000cca12b15186a
refs/heads/master
2023-06-06T23:08:57.391040
2019-08-29T04:36:02
2019-08-29T04:36:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,261
java
package defpackage; import android.graphics.Rect; import com.autonavi.minimap.base.overlay.PointOverlay; import java.util.ArrayList; import java.util.List; /* renamed from: bya reason: default package */ /* compiled from: SearchResultOverLayHelper */ public final class bya { private bzh a; public bya(bzh bzh) { this.a = bzh; } public final void a(List<bzu> list, bbr bbr, bty bty, bxf bxf) { boolean z; boolean z2; bbr bbr2 = list.get(list.size() - 1).a; if (bbr2 != null) { boolean z3 = false; if (bbr != null && bbr2.a(bty).isEmpty()) { for (bzu next : list) { boolean z4 = next != null && next.b == 1; if (next != null) { a(next, z4, false); } } } ArrayList arrayList = new ArrayList(); ArrayList arrayList2 = new ArrayList(); if (bbr != null) { int i = 0; while (i < list.size()) { try { bbr bbr3 = list.get(i).a; if (!bbr3.equals(bbr) && Rect.intersects(a(bbr.a(bty)), bbr3.a(bty))) { a((List<bzu>) arrayList, (List<Boolean>) arrayList2, list.get(i), list.get(i).b == 1); } i++; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); return; } } } for (int i2 = 0; i2 < list.size(); i2++) { bbr bbr4 = list.get(i2).a; if (!bbr4.equals(bbr)) { int i3 = i2 + 1; while (true) { if (i3 >= list.size()) { break; } bbr bbr5 = list.get(i3).a; if (!bbr5.equals(bbr) && Rect.intersects(a(bbr4.a(bty)), bbr5.a(bty))) { boolean z5 = list.get(i3).b == 1; if (bbr5 == bbr) { a((List<bzu>) arrayList, (List<Boolean>) arrayList2, list.get(i2), z5); break; } a((List<bzu>) arrayList, (List<Boolean>) arrayList2, list.get(i3), z5); } i3++; } } } int size = list.size(); int size2 = arrayList.size(); for (int i4 = 0; i4 < size; i4++) { bzu bzu = list.get(i4); if (bzu != null) { int i5 = 0; while (true) { if (i5 >= size2) { z = true; z2 = true; break; } bzu bzu2 = (bzu) arrayList.get(i5); if (bzu2 != null && bzu != null && bzu2 != null && bzu.equals(bzu2)) { z = ((Boolean) arrayList2.get(i5)).booleanValue(); z2 = false; break; } i5++; } a(bzu, z, z2); } } if (!(bxf == null || this.a == null)) { int i6 = bxf.c; bzh bzh = this.a; if (bzh != null) { if (bzh.b != null) { List items = bzh.b.getItems(); int size3 = items.size(); if (size3 > 0 && i6 >= 0 && i6 < size3) { z3 = Rect.intersects(((bbr) items.get(0)).a(bty), ((bbr) items.get(i6)).a(bty)); } } } if (!z3) { this.a.s(); } } } } private static void a(List<bzu> list, List<Boolean> list2, bzu bzu, boolean z) { if (bzu != null) { boolean z2 = true; for (bzu equals : list) { if (equals.equals(bzu)) { z2 = false; } } if (z2) { list.add(bzu); list2.add(Boolean.valueOf(z)); } } } private void a(bzu bzu, boolean z, boolean z2) { this.a.a(bzu, z, z2); } public static bbr a(PointOverlay pointOverlay, List<bzu> list, int i) { int size = pointOverlay.getSize(); if (size > 0) { for (int i2 = 0; i2 < size; i2++) { list.add(new bzu((bbr) pointOverlay.getItem(i2), i)); } if (pointOverlay.getFocus() != null) { return (bbr) pointOverlay.getFocus(); } } return null; } private static Rect a(Rect rect) { Rect rect2 = new Rect(rect); rect2.top += 8; rect2.bottom -= 8; rect2.left += 8; rect2.right -= 8; return rect2; } }
116286345eea42cc00f345ec67e00dda83460967
ed3cb95dcc590e98d09117ea0b4768df18e8f99e
/project_1_3/src/b/a/i/a/Calc_1_3_10800.java
695da1619811c8e15edf7fc6686dc27ce04c1536
[]
no_license
chalstrick/bigRepo1
ac7fd5785d475b3c38f1328e370ba9a85a751cff
dad1852eef66fcec200df10083959c674fdcc55d
refs/heads/master
2016-08-11T17:59:16.079541
2015-12-18T14:26:49
2015-12-18T14:26:49
48,244,030
0
0
null
null
null
null
UTF-8
Java
false
false
134
java
package b.a.i.a; public class Calc_1_3_10800 { /** @return the sum of a and b */ public int add(int a, int b) { return a+b; } }
a90adc0fa145581a32dff16a5145f203495981d0
f140118cd3f1b4a79159154087e7896960ca0c88
/mllib/target/java/org/apache/spark/ml/param/DoubleParam$.java
6731b908312152ac5f84e12cae559236fb407bf5
[]
no_license
loisZ/miaomiaomiao
d45dc779355e2280fe6f505d959b5e5c475f9b9c
6236255e4062d1788d7a212fa49af1849965f22c
refs/heads/master
2021-08-24T09:22:41.648169
2017-12-09T00:56:41
2017-12-09T00:56:41
111,349,685
1
0
null
null
null
null
UTF-8
Java
false
false
322
java
package org.apache.spark.ml.param; // no position // not preceding public class DoubleParam$ implements scala.Serializable { /** * Static reference to the singleton instance of this Scala object. */ public static final DoubleParam$ MODULE$ = null; public DoubleParam$ () { throw new RuntimeException(); } }
271e7f843cdc71979930dd617f81281b24ee36b7
7998aad89ec510011c2938e668c4933b7f9b6043
/Java/Basic Programs/simpleInterest.java
c5309f105860929e3ffa223553f9f00f1c54b144
[]
no_license
sahilc07/DS-and-Algorithms
6cd6585d4624923f11168ea746bc10d224d60950
0f611beb26959b2da7e6d82fd8be8f6b108bfa5c
refs/heads/main
2023-02-28T01:18:50.815573
2021-02-09T07:01:02
2021-02-09T07:01:02
300,905,155
1
1
null
2020-10-17T12:09:25
2020-10-03T14:54:43
Java
UTF-8
Java
false
false
590
java
/** * simpleInterest */ import java.util.*; public class simpleInterest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Principle amount: "); int principle = sc.nextInt(); System.out.println("Enter rate: "); float rate = sc.nextFloat(); System.out.println("Enter Time: "); int time = sc.nextInt(); float simpleInterest = (principle * rate * time)/100; System.out.println("Simple Interest: "+ simpleInterest); sc.close(); } }
cc7fc19bd9059cae773326ca26cf1ac6701392a3
dab6ef514e1762e528953bbecc17f0a482e798c8
/src/Rectangle.java
3481886064a2bccc70fc41cb820fd40cbbef68bf
[]
no_license
nikkizip/project-pipeline
f441904806864c6b8952f18b6617b3a6629a83d7
4515cbc97939c4a00ca246f4a332465970698ba2
refs/heads/master
2020-04-13T11:04:24.307971
2018-12-26T10:44:59
2018-12-26T10:44:59
163,162,834
0
0
null
2018-12-26T09:37:32
2018-12-26T09:37:32
null
UTF-8
Java
false
false
273
java
public class Rectangle { public int length; public int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public int getArea() { return length * width; } public int getPerimeter() { return 2 * (length + width); } }
809d7f7d25b1aaee0521b902ac9c5007b7b2b6ef
3aa728bfeb6444777dd4bf36af27177b800e0321
/app/src/main/java/cl/ucn/disc/dsm/fsalinas/news/utils/Validation.java
05612d5dd1d5d11fefec09745d95fc47e866fc09
[]
no_license
pipesalinass/news
77e5eb74d9f2393d912786c9762fee5ca71959b4
ba3a8ffbe6236ac3f0c7e289c83769ce09868542
refs/heads/master
2023-02-11T08:04:39.422961
2021-01-06T17:46:45
2021-01-06T17:46:45
313,183,747
0
0
null
null
null
null
UTF-8
Java
false
false
2,015
java
/* * Copyright 2020 Felipe Salinas-Urra, [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package cl.ucn.disc.dsm.fsalinas.news.utils; /** * The Validations. * * @author Felipe Salinas-Urra. */ public final class Validation { /** * Check the size. * * @param value to check. * @param minSize to check. * @param message to throw in case of wrong size */ public static void minSize(String value, int minSize, String message) { // Nullity notNull(value, message); if (value.length() < minSize) { throw new IllegalArgumentException("Argument null or wrong size --> " + message); } } /** * Check nullity. * * @param value to check. * @param message to throw in case of nullity. */ public static void notNull(Object value, String message) { if (value == null) { throw new IllegalArgumentException("Argument was null --> " + message); } } }
ba76e8b33b86a5856167e671abf07d4b92ff7c89
63a97ed7965c442014081693f0e58a9b85b9dc99
/apl-ignite-demo/src/main/java/com/apl/ignite/demo/config/IgniteThinClient.java
e12b1af69f5522c01367a5ae44dd5ae9d5d4c5bb
[]
no_license
hujiren/test-database-demo-java
d4cd7b20290c868f7175f6352420a360cd5edd18
4b9ab248363c6be0638aca5b4e546cde8b01b9b2
refs/heads/master
2023-03-09T19:44:27.160738
2021-02-20T01:20:22
2021-02-20T01:20:22
340,530,795
0
0
null
null
null
null
UTF-8
Java
false
false
2,900
java
package com.apl.ignite.demo.config; import org.apache.ignite.Ignite; import org.apache.ignite.Ignition; import org.apache.ignite.client.IgniteClient; import org.apache.ignite.configuration.ClientConfiguration; import org.apache.ignite.configuration.ClientConnectorConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; /** * @author hjr start * @Classname IgniteThinClient * @Date 2020/12/10 9:45 */ @Configuration @Component public class IgniteThinClient { @Bean public IgniteClient thinClientBean(){ ClientConnectorConfiguration clientConnectorCfg = new ClientConnectorConfiguration(); //设置服务端地址 clientConnectorCfg.setHost("192.168.1.185:10800"); //设置要连接的端口 clientConnectorCfg.setPort(10800); //设置连接端口范围, 10800 - 10805 瘦客户端回尝试绑定从port开始到range结束的每个端口, 直到找到可用端口为止, 如果都不可用, 则瘦客户端无法启动 clientConnectorCfg.setPortRange(5); //启用/禁用 客户端接入 clientConnectorCfg.setThinClientEnabled(true); //启用/禁用 SSL加密传输 // clientConnectorCfg.setSslEnabled(true); IgniteConfiguration cfg = new IgniteConfiguration(); cfg.setClientConnectorConfiguration(clientConnectorCfg); //接入集群 如果地址都不通, 则抛出ClientConnectionException异常 ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setAddresses("192.168.1.185:10800").setUserName("ignite").setUserPassword("ignite").setPartitionAwarenessEnabled(true);//分区感知 IgniteClient igniteClient = Ignition.startClient(clientConfiguration);//igniteClient对象提供了访问数据的各种方法 // Ignite ignite = Ignition.start(cfg); return igniteClient; } } // 动态创建缓存 // ClientCacheConfiguration cacheCfg = new ClientCacheConfiguration().setName("References") // .setCacheMode(CacheMode.REPLICATED) // .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); // ClientCache<Integer, String> cache = client.getOrCreateCache(cacheCfg); // igniteClient和ignite会直接访问缓存, 如果缓存不存在, 则创建该缓存,且使用默认的配置 // igniteClient.cache(""); // 列出所有的缓存 // igniteClient.cacheNames(); // 使用ScanQuery<K, V>类当做条件可获得一组满足给定条件的条目,瘦客户端将查询操作发送到集群节点,在集群节点上将其作为普通扫描查询执行。
d085d5843e78dbcb061a4282198d3d5694f3492f
a1f170211f658be47ebef6d58686f9010959e877
/src/main/java/CF194B.java
cf2282f2593bcd835d1da51815d468fe98d8e89a
[]
no_license
tasyrkin/Codeforces
cdd1c2cbee8c43b03cff3205e46fccf76deb9977
58ef55a399d092cdb5a9328ff41c0bcd1363496c
refs/heads/master
2020-07-04T05:00:38.185228
2019-01-06T20:35:59
2019-01-06T20:36:18
33,376,443
0
0
null
null
null
null
UTF-8
Java
false
false
3,248
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class CF194B { private static class Pair { int x; int y; public Pair(final int x1, final int y1) { x = x1; y = y1; } @Override public boolean equals(final Object o) { if (o != null && o instanceof Pair) { Pair p = (Pair) o; return x == p.x && y == p.y; } return false; } @Override public int hashCode() { return Integer.valueOf(x).hashCode() + Integer.valueOf(y).hashCode(); } } public static void main(final String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Set<Pair> set = new HashSet<Pair>(); Pair[] pairs = new Pair[8]; int minX = Integer.MAX_VALUE; int minY = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; for (int i = 0; i < 8; i++) { String[] parts = br.readLine().split("\\s+"); pairs[i] = new Pair(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); set.add(pairs[i]); if (minX > pairs[i].x) { minX = pairs[i].x; } if (minY > pairs[i].y) { minY = pairs[i].y; } if (maxX < pairs[i].x) { maxX = pairs[i].x; } if (maxY < pairs[i].y) { maxY = pairs[i].y; } } if (set.size() != 8) { System.out.println("ugly"); return; } List<Pair> minxes = new ArrayList<Pair>(); List<Pair> minyes = new ArrayList<Pair>(); List<Pair> maxxes = new ArrayList<Pair>(); List<Pair> maxyes = new ArrayList<Pair>(); for (Pair p : pairs) { if (p.x == minX) { minxes.add(p); } if (p.y == minY) { minyes.add(p); } if (p.x == maxX) { maxxes.add(p); } if (p.y == maxY) { maxyes.add(p); } } if (minxes.size() != 3 || minyes.size() != 3 || maxxes.size() != 3 || maxyes.size() != 3) { System.out.println("ugly"); return; } for (Pair p : minxes) { int found = 0; for (Pair p1 : maxxes) { if (p.y == p1.y) { found++; } } if (found != 1) { System.out.println("ugly"); return; } } for (Pair p : minyes) { int found = 0; for (Pair p1 : maxyes) { if (p.x == p1.x) { found++; } } if (found != 1) { System.out.println("ugly"); return; } } System.out.println("respectable"); } }
baf410af6bc7c3699397003d233d724ca349c2e2
cea3fe1ae551bf2f81b431876d15563d6347119b
/case 3.6.5 sharding-jdbc/case Depots table/src/main/java/com/gang/shardingjdbc/demo/DemoApplication.java
f4c24ac0eb2c7401cfe762d274c3d8dd894dab15
[]
no_license
black-ant/case
2e33cbd74b559924d3a53092a8b070edea4d143d
589598bb41398b330bc29b2ca61757296b55b579
refs/heads/master
2023-07-31T23:22:51.168312
2022-07-24T06:15:53
2022-07-24T06:15:53
137,761,384
86
26
null
2023-07-17T01:03:21
2018-06-18T14:22:01
Java
UTF-8
Java
false
false
768
java
package com.gang.shardingjdbc.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @EnableTransactionManagement(proxyTargetClass = true) @EnableConfigurationProperties public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } /** * Sharding jdbc 操作记录 : * * */ }
112cfef913a9388ddab78c143a93d0e9c868f762
a86eda9fbfa8de51bf7e096fb6b982940e161fd8
/app/src/main/java/com/example/android/moviedb3/adapter/FragmentAdapter/YoursFragmentAdapter.java
0a26a572ceb407a8554065087eb9273c699abc36
[]
no_license
wisnunugroho21/MyWatchList
d89f036f9348c2a53ab189e37f6c9f8f69b456cb
29a94fb448a90c92e992f3b66fc956a4088f70a4
refs/heads/master
2021-01-20T23:51:58.542471
2017-09-24T12:36:55
2017-09-24T12:36:55
101,855,464
0
0
null
null
null
null
UTF-8
Java
false
false
2,456
java
package com.example.android.moviedb3.adapter.FragmentAdapter; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import com.example.android.moviedb3.R; import com.example.android.moviedb3.fragment.MovieListFragment; import com.example.android.moviedb3.localDatabase.FavoriteDataDB; import com.example.android.moviedb3.localDatabase.PlanToWatchDataDB; import com.example.android.moviedb3.localDatabase.WatchlistDataDB; import java.util.ArrayList; /** * Created by nugroho on 01/09/17. */ public class YoursFragmentAdapter extends FragmentStatePagerAdapter { Context context; ArrayList<MovieListFragment> movieListFragments; ArrayList<String> pageTitle; public YoursFragmentAdapter(FragmentManager fm, Context context, boolean isLinearList) { super(fm); this.context = context; movieListFragments = new ArrayList<>(); pageTitle = new ArrayList<>(); MovieListFragment favoriteMovieListFragment = new MovieListFragment(); favoriteMovieListFragment.setMovieListDB(new FavoriteDataDB(context)); favoriteMovieListFragment.setLinearList(isLinearList); MovieListFragment watchMovieListFragment = new MovieListFragment(); watchMovieListFragment.setMovieListDB(new WatchlistDataDB(context)); watchMovieListFragment.setLinearList(isLinearList); MovieListFragment planToWatchListFragment = new MovieListFragment(); planToWatchListFragment.setMovieListDB(new PlanToWatchDataDB(context)); planToWatchListFragment.setLinearList(isLinearList); movieListFragments.add(favoriteMovieListFragment); movieListFragments.add(watchMovieListFragment); movieListFragments.add(planToWatchListFragment); pageTitle.add(context.getString(R.string.favorite_label)); pageTitle.add(context.getString(R.string.watched_label)); pageTitle.add(context.getString(R.string.plan_to_watched_label)); } @Override public Fragment getItem(int position) { return movieListFragments.get(position); } @Override public int getCount() { return movieListFragments.size(); } @Override public CharSequence getPageTitle(int position) { return pageTitle.get(position); } }