blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2e8033a8646f1a787d8a384ae5084de531d9d4a
| 37,778,532,352,036 |
b3427e4b72a05f3b47e5e0a3ff754cd387ee8457
|
/src/main/java/commande/model/Produit.java
|
9e582d0f9df81791d4edc34e0bac512ae840cfe3
|
[] |
no_license
|
mariembenali/BoutiqueManagerServer
|
https://github.com/mariembenali/BoutiqueManagerServer
|
9942bc9f9b627e6391d60a954932eabc64623ce7
|
5a1e4b0639165857281e4250706a2e21e0405f8f
|
refs/heads/master
| 2023-02-19T08:58:03.352000 | 2021-01-26T20:31:27 | 2021-01-26T20:31:27 | 326,272,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package commande.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
@Entity
public class Produit implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 50, unique = true, nullable = false)
private String numSerie;
@Column(length = 100)
private String libelle;
private int prixUnitaire;
private int marge;
private int quantite;
private int seuil;
@Column(columnDefinition = "int default 0")
private int etat;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "categorie_id")
private Categorie categorie;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "marque_id")
private Marque marque;
@OneToMany(mappedBy = "produit")
private List<Detail> details;
@OneToMany(mappedBy = "produit")
private List<Stock> entrees;
public Produit() {
}
/**
* @return int return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return String return the libelle
*/
public String getLibelle() {
return libelle;
}
/**
* @param libelle the libelle to set
*/
public void setLibelle(String libelle) {
this.libelle = libelle;
}
/**
* @return float return the prixUnitaire
*/
public int getPrixUnitaire() {
return prixUnitaire;
}
/**
* @param prixUnitaire the prixUnitaire to set
*/
public void setPrixUnitaire(int prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
/**
* @return int return the quantite
*/
public int getQuantite() {
return quantite;
}
/**
* @param quantite the quantite to set
*/
public void setQuantite(int quantite) {
this.quantite = quantite;
}
/**
* @return int return the seuil
*/
public int getSeuil() {
return seuil;
}
/**
* @param seuil the seuil to set
*/
public void setSeuil(int seuil) {
this.seuil = seuil;
}
/**
* @return List<Detail> return the details
*/
public List<Detail> getDetails() {
return details;
}
/**
* @param details the details to set
*/
public void setDetails(List<Detail> details) {
this.details = details;
}
/**
* @return int return the marge
*/
public int getMarge() {
return marge;
}
/**
* @param marge the marge to set
*/
public void setMarge(int marge) {
this.marge = marge;
}
/**
* @return int return the etat
*/
public int getEtat() {
return etat;
}
/**
* @param etat the etat to set
*/
public void setEtat(int etat) {
this.etat = etat;
}
/**
* @return List<Stock> return the entrees
*/
public List<Stock> getEntrees() {
return entrees;
}
/**
* @param entrees the entrees to set
*/
public void setEntrees(List<Stock> entrees) {
this.entrees = entrees;
}
@Override
public String toString() {
return getLibelle();
}
/**
* @return Categorie return the categorie
*/
public Categorie getCategorie() {
return categorie;
}
/**
* @param categorie the categorie to set
*/
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
/**
* @return Marque return the marque
*/
public Marque getMarque() {
return marque;
}
/**
* @param marque the marque to set
*/
public void setMarque(Marque marque) {
this.marque = marque;
}
/**
* @return String return the numSerie
*/
public String getNumSerie() {
return numSerie;
}
/**
* @param numSerie the numSerie to set
*/
public void setNumSerie(String numSerie) {
this.numSerie = numSerie;
}
}
|
UTF-8
|
Java
| 4,227 |
java
|
Produit.java
|
Java
|
[] | null |
[] |
package commande.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
@Entity
public class Produit implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 50, unique = true, nullable = false)
private String numSerie;
@Column(length = 100)
private String libelle;
private int prixUnitaire;
private int marge;
private int quantite;
private int seuil;
@Column(columnDefinition = "int default 0")
private int etat;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "categorie_id")
private Categorie categorie;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "marque_id")
private Marque marque;
@OneToMany(mappedBy = "produit")
private List<Detail> details;
@OneToMany(mappedBy = "produit")
private List<Stock> entrees;
public Produit() {
}
/**
* @return int return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return String return the libelle
*/
public String getLibelle() {
return libelle;
}
/**
* @param libelle the libelle to set
*/
public void setLibelle(String libelle) {
this.libelle = libelle;
}
/**
* @return float return the prixUnitaire
*/
public int getPrixUnitaire() {
return prixUnitaire;
}
/**
* @param prixUnitaire the prixUnitaire to set
*/
public void setPrixUnitaire(int prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
/**
* @return int return the quantite
*/
public int getQuantite() {
return quantite;
}
/**
* @param quantite the quantite to set
*/
public void setQuantite(int quantite) {
this.quantite = quantite;
}
/**
* @return int return the seuil
*/
public int getSeuil() {
return seuil;
}
/**
* @param seuil the seuil to set
*/
public void setSeuil(int seuil) {
this.seuil = seuil;
}
/**
* @return List<Detail> return the details
*/
public List<Detail> getDetails() {
return details;
}
/**
* @param details the details to set
*/
public void setDetails(List<Detail> details) {
this.details = details;
}
/**
* @return int return the marge
*/
public int getMarge() {
return marge;
}
/**
* @param marge the marge to set
*/
public void setMarge(int marge) {
this.marge = marge;
}
/**
* @return int return the etat
*/
public int getEtat() {
return etat;
}
/**
* @param etat the etat to set
*/
public void setEtat(int etat) {
this.etat = etat;
}
/**
* @return List<Stock> return the entrees
*/
public List<Stock> getEntrees() {
return entrees;
}
/**
* @param entrees the entrees to set
*/
public void setEntrees(List<Stock> entrees) {
this.entrees = entrees;
}
@Override
public String toString() {
return getLibelle();
}
/**
* @return Categorie return the categorie
*/
public Categorie getCategorie() {
return categorie;
}
/**
* @param categorie the categorie to set
*/
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
/**
* @return Marque return the marque
*/
public Marque getMarque() {
return marque;
}
/**
* @param marque the marque to set
*/
public void setMarque(Marque marque) {
this.marque = marque;
}
/**
* @return String return the numSerie
*/
public String getNumSerie() {
return numSerie;
}
/**
* @param numSerie the numSerie to set
*/
public void setNumSerie(String numSerie) {
this.numSerie = numSerie;
}
}
| 4,227 | 0.560918 | 0.559262 | 234 | 17.064102 | 16.126375 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.188034 | false | false |
5
|
1d043e8f3500c39202efc5abe68b4a8aabbb6f7b
| 36,129,264,916,785 |
f9b254b3d57453bd6fc4e66dc082f3e92dce4179
|
/EHomeHDV5_1/eHomeHD/src/cc/wulian/app/model/device/impls/controlable/newthermostat/setting/differential/SendDifferentialItem.java
|
09f28fc85c3cd4cb23fb64fae208868459b54a27
|
[] |
no_license
|
zcz123/ehome
|
https://github.com/zcz123/ehome
|
a45255bb4ebbfeb7804f424b1be53cf531589bf6
|
5a2df0be832f542cab6b49e7a0e8071d4f101525
|
refs/heads/master
| 2021-01-19T21:47:57.674000 | 2017-04-19T04:13:16 | 2017-04-19T04:13:16 | 88,708,738 | 3 | 0 | null | true | 2017-04-19T06:24:17 | 2017-04-19T06:24:17 | 2017-04-19T06:23:25 | 2017-04-19T04:11:27 | 56,282 | 0 | 0 | 0 | null | null | null |
package cc.wulian.app.model.device.impls.controlable.newthermostat.setting.differential;
import android.content.Context;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import cc.wulian.smarthomev5.R;
import cc.wulian.smarthomev5.fragment.setting.AbstractSettingItem;
public class SendDifferentialItem extends AbstractSettingItem{
private Button sendBtn;
private SendClickListener sendClickListener;
public SendDifferentialItem(Context context) {
// super(context, R.drawable.icon_gateway_id, context.getResources().getString(R.string.set_account_manager_gw_ID));
super(context, R.drawable.icon_gateway_id, "sendDifferential");
}
@Override
public void initSystemState() {
super.initSystemState();
setSendEquipment();
}
public void setSendClickListener(SendClickListener sendClickListener) {
this.sendClickListener = sendClickListener;
}
public void setSendEquipment() {
view.setBackgroundColor(mContext.getResources().getColor(R.color.trant));
upLinearLayout.removeAllViews();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(0, 0,0, 0);
upLinearLayout.setLayoutParams(params);
LinearLayout.LayoutParams sendParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
sendParams.setMargins(0, 0,0, 0);
sendBtn = new Button(mContext);
sendBtn.setLayoutParams(sendParams);
sendBtn.setGravity(Gravity.CENTER);
sendBtn.setText("Send all differential settings to the thermostat?");
sendBtn.setTextSize(14);
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector);
upLinearLayout.addView(sendBtn);
sendBtn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector2);
return true;
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_UP:
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector);
sendClickListener.onSendClick();
return true;
}
return false;
}
});
}
public interface SendClickListener{
public void onSendClick();
}
@Override
public void doSomethingAboutSystem() {
}
}
|
UTF-8
|
Java
| 2,624 |
java
|
SendDifferentialItem.java
|
Java
|
[] | null |
[] |
package cc.wulian.app.model.device.impls.controlable.newthermostat.setting.differential;
import android.content.Context;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import cc.wulian.smarthomev5.R;
import cc.wulian.smarthomev5.fragment.setting.AbstractSettingItem;
public class SendDifferentialItem extends AbstractSettingItem{
private Button sendBtn;
private SendClickListener sendClickListener;
public SendDifferentialItem(Context context) {
// super(context, R.drawable.icon_gateway_id, context.getResources().getString(R.string.set_account_manager_gw_ID));
super(context, R.drawable.icon_gateway_id, "sendDifferential");
}
@Override
public void initSystemState() {
super.initSystemState();
setSendEquipment();
}
public void setSendClickListener(SendClickListener sendClickListener) {
this.sendClickListener = sendClickListener;
}
public void setSendEquipment() {
view.setBackgroundColor(mContext.getResources().getColor(R.color.trant));
upLinearLayout.removeAllViews();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(0, 0,0, 0);
upLinearLayout.setLayoutParams(params);
LinearLayout.LayoutParams sendParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
sendParams.setMargins(0, 0,0, 0);
sendBtn = new Button(mContext);
sendBtn.setLayoutParams(sendParams);
sendBtn.setGravity(Gravity.CENTER);
sendBtn.setText("Send all differential settings to the thermostat?");
sendBtn.setTextSize(14);
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector);
upLinearLayout.addView(sendBtn);
sendBtn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector2);
return true;
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_UP:
sendBtn.setBackgroundResource(R.drawable.thermost_setting_send_btn_selector);
sendClickListener.onSendClick();
return true;
}
return false;
}
});
}
public interface SendClickListener{
public void onSendClick();
}
@Override
public void doSomethingAboutSystem() {
}
}
| 2,624 | 0.782012 | 0.775915 | 78 | 32.641026 | 31.628441 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.384615 | false | false |
5
|
26ee81bcfa3164706b23c5ae6b05223f9c7f8602
| 15,522,011,871,729 |
5f407527d3ff1efc056c47bed61be1bdb4e9c80f
|
/src/br/com/senaimg/wms/dao/CatalogueDAO.java
|
9503838ef6f16f35e017b911a6631ca3107bd46b
|
[] |
no_license
|
nesag/PyxisWMS
|
https://github.com/nesag/PyxisWMS
|
28e7970ea7acfb02f83db7b458bb9ef6df812ea6
|
ec2104c9373b76dae8fdfde7aea9eadf5170ec7d
|
refs/heads/master
| 2021-01-21T13:29:35.437000 | 2017-08-19T00:48:53 | 2017-08-19T00:48:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.senaimg.wms.dao;
import br.com.senaimg.wms.hibernate.SessionHibernateUtil;
import br.com.senaimg.wms.language.Lang;
import br.com.senaimg.wms.model.warehouse.agent.Catalogue;
import br.com.senaimg.wms.model.warehouse.agent.Supplier;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author ÁlefeLucas
*/
public abstract class CatalogueDAO {
/**
*
* @param catalogue
*/
public static void insertCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
Lang.loadLanguage();
}
/**
* Updates a record in the catalogue table in database through Hibernate.
*
* @param catalogue
*/
public static void updateCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.update(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Deletes a record in the catalogue table in database through Hibernate.
*
* @param catalogue
*/
public static void deleteCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates or inserts if not exists a record in the catalogue table in
* database through Hibernate.
*
* @param catalogue
*/
public static void mergeCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.merge(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Inserts several new records into the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void insertCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.save(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates several records in the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void updateCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.update(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Deletes several records in the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void deleteCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.delete(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates or inserts if not exists several records in the catalogue table in
* database through Hibernate.
*
* @param catalogues
*/
public static void mergeCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.merge(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Lists all the records from the catalogue table in database through
* Hibernate.
*
* @return List < Catalogue>
*/
public static List<Catalogue> selectCatalogues() {
List<Catalogue> catalogues = new ArrayList<>();
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Catalogue.class);
catalogues = criteria.list();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
return catalogues;
}
public static List<Catalogue> selectCatalogues(Supplier supplier) {
List<Catalogue> catalogues = selectCatalogues();
ArrayList<Catalogue> selected = new ArrayList<>();
for(Catalogue catalogue : catalogues){
if(catalogue.getSupplier().equals(supplier)){
selected.add(catalogue);
}
}
return selected;
}
}
|
UTF-8
|
Java
| 6,790 |
java
|
CatalogueDAO.java
|
Java
|
[
{
"context": " org.hibernate.Transaction;\r\n\r\n/**\r\n *\r\n * @author ÁlefeLucas\r\n */\r\npublic abstract class CatalogueDAO {\r\n \r\n ",
"end": 630,
"score": 0.999692976474762,
"start": 620,
"tag": "NAME",
"value": "ÁlefeLucas"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.senaimg.wms.dao;
import br.com.senaimg.wms.hibernate.SessionHibernateUtil;
import br.com.senaimg.wms.language.Lang;
import br.com.senaimg.wms.model.warehouse.agent.Catalogue;
import br.com.senaimg.wms.model.warehouse.agent.Supplier;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author ÁlefeLucas
*/
public abstract class CatalogueDAO {
/**
*
* @param catalogue
*/
public static void insertCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
Lang.loadLanguage();
}
/**
* Updates a record in the catalogue table in database through Hibernate.
*
* @param catalogue
*/
public static void updateCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.update(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Deletes a record in the catalogue table in database through Hibernate.
*
* @param catalogue
*/
public static void deleteCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates or inserts if not exists a record in the catalogue table in
* database through Hibernate.
*
* @param catalogue
*/
public static void mergeCatalogue(Catalogue catalogue) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.merge(catalogue);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Inserts several new records into the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void insertCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.save(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates several records in the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void updateCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.update(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Deletes several records in the catalogue table in database through
* Hibernate.
*
* @param catalogues
*/
public static void deleteCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.delete(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Updates or inserts if not exists several records in the catalogue table in
* database through Hibernate.
*
* @param catalogues
*/
public static void mergeCatalogues(List<Catalogue> catalogues) {
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
catalogues.forEach(catalogue -> session.merge(catalogue));
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
/**
* Lists all the records from the catalogue table in database through
* Hibernate.
*
* @return List < Catalogue>
*/
public static List<Catalogue> selectCatalogues() {
List<Catalogue> catalogues = new ArrayList<>();
try {
Session session = SessionHibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Catalogue.class);
catalogues = criteria.list();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
return catalogues;
}
public static List<Catalogue> selectCatalogues(Supplier supplier) {
List<Catalogue> catalogues = selectCatalogues();
ArrayList<Catalogue> selected = new ArrayList<>();
for(Catalogue catalogue : catalogues){
if(catalogue.getSupplier().equals(supplier)){
selected.add(catalogue);
}
}
return selected;
}
}
| 6,790 | 0.572544 | 0.571218 | 244 | 25.823771 | 25.605089 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.336066 | false | false |
5
|
8514aa06be463c19f16a0120cd4b02b9b17dc5cc
| 15,522,011,873,442 |
0871d8606145cedaa6b677b41193c894c99b772a
|
/src/test/java/com/github/irgalin/reachablesettlements/SettlementsStorageTest.java
|
5b10949104962bbe7b211bdce835047cd57c23be
|
[] |
no_license
|
Irgalin/reachable-settlements-service
|
https://github.com/Irgalin/reachable-settlements-service
|
24cf3f432a96c4b51fd359c16b55dbbaa288cfd0
|
2b2c2ac3963976ef24f9601c3958dbda161b987b
|
refs/heads/master
| 2022-04-28T10:55:50.710000 | 2020-04-29T11:37:59 | 2020-04-29T11:37:59 | 247,795,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.irgalin.reachablesettlements;
import com.github.irgalin.reachablesettlements.entity.Settlement;
import com.github.irgalin.reachablesettlements.storage.SettlementsStorage;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.log4j.Level.ERROR;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
public class SettlementsStorageTest {
private final Appender mockAppender = mock(Appender.class);
@Test
public void testReadDataFromJsonFileWithCorrectData() {
SettlementsStorage correctDataStorage1 = new SettlementsStorage("classpath:correct-test-data-1.json");
assertThat(correctDataStorage1.hasData()).isTrue();
assertThat(correctDataStorage1.settlementsCount()).isEqualTo(3);
assertThat(correctDataStorage1.getSettlementByName("town3"))
.isNotNull()
.isInstanceOf(Settlement.class);
assertThat(correctDataStorage1.getSettlementByName("town3").getCommutes())
.isNotNull()
.hasSize(2);
SettlementsStorage correctDataStorage2 = new SettlementsStorage("classpath:correct-test-data-2.json");
assertThat(correctDataStorage2.hasData()).isTrue();
assertThat(correctDataStorage2.settlementsCount()).isEqualTo(2);
assertThat(correctDataStorage2.getSettlementByName("town1"))
.isNotNull()
.isInstanceOf(Settlement.class);
}
@Test
public void testReadDataFromJsonFileWithWrongData() {
Logger logger = Logger.getLogger(SettlementsStorage.class);
logger.addAppender(mockAppender);
SettlementsStorage wrongDataStorage1 = new SettlementsStorage("classpath:wrong-test-data-1.json");
assertThat(wrongDataStorage1.hasData()).isFalse();
SettlementsStorage wrongDataStorage2 = new SettlementsStorage("classpath:wrong-test-data-2.json");
assertThat(wrongDataStorage2.hasData()).isFalse();
ArgumentCaptor<LoggingEvent> eventArgumentCaptor = ArgumentCaptor.forClass(LoggingEvent.class);
verify(mockAppender, times(2)).doAppend(eventArgumentCaptor.capture());
LoggingEvent firstLoggingEvent = eventArgumentCaptor.getAllValues().get(0);
assertThat(firstLoggingEvent.getLevel()).isEqualTo(ERROR);
assertThat(firstLoggingEvent.getMessage().toString()
.contains("The data in JSON file doesn't match to the defined schema.")).isTrue();
LoggingEvent secondLoggingEvent = eventArgumentCaptor.getAllValues().get(0);
assertThat(secondLoggingEvent.getLevel()).isEqualTo(ERROR);
assertThat(secondLoggingEvent.getMessage().toString()
.contains("The data in JSON file doesn't match to the defined schema.")).isTrue();
}
}
|
UTF-8
|
Java
| 2,948 |
java
|
SettlementsStorageTest.java
|
Java
|
[
{
"context": "package com.github.irgalin.reachablesettlements;\n\nimport com.github.irgalin.",
"end": 26,
"score": 0.9790489077568054,
"start": 19,
"tag": "USERNAME",
"value": "irgalin"
},
{
"context": ".irgalin.reachablesettlements;\n\nimport com.github.irgalin.reachablesettlements.entity.Settlement;\nimport co",
"end": 75,
"score": 0.9887304306030273,
"start": 68,
"tag": "USERNAME",
"value": "irgalin"
},
{
"context": "esettlements.entity.Settlement;\nimport com.github.irgalin.reachablesettlements.storage.SettlementsStorage;\n",
"end": 141,
"score": 0.9876708388328552,
"start": 134,
"tag": "USERNAME",
"value": "irgalin"
}
] | null |
[] |
package com.github.irgalin.reachablesettlements;
import com.github.irgalin.reachablesettlements.entity.Settlement;
import com.github.irgalin.reachablesettlements.storage.SettlementsStorage;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.log4j.Level.ERROR;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
public class SettlementsStorageTest {
private final Appender mockAppender = mock(Appender.class);
@Test
public void testReadDataFromJsonFileWithCorrectData() {
SettlementsStorage correctDataStorage1 = new SettlementsStorage("classpath:correct-test-data-1.json");
assertThat(correctDataStorage1.hasData()).isTrue();
assertThat(correctDataStorage1.settlementsCount()).isEqualTo(3);
assertThat(correctDataStorage1.getSettlementByName("town3"))
.isNotNull()
.isInstanceOf(Settlement.class);
assertThat(correctDataStorage1.getSettlementByName("town3").getCommutes())
.isNotNull()
.hasSize(2);
SettlementsStorage correctDataStorage2 = new SettlementsStorage("classpath:correct-test-data-2.json");
assertThat(correctDataStorage2.hasData()).isTrue();
assertThat(correctDataStorage2.settlementsCount()).isEqualTo(2);
assertThat(correctDataStorage2.getSettlementByName("town1"))
.isNotNull()
.isInstanceOf(Settlement.class);
}
@Test
public void testReadDataFromJsonFileWithWrongData() {
Logger logger = Logger.getLogger(SettlementsStorage.class);
logger.addAppender(mockAppender);
SettlementsStorage wrongDataStorage1 = new SettlementsStorage("classpath:wrong-test-data-1.json");
assertThat(wrongDataStorage1.hasData()).isFalse();
SettlementsStorage wrongDataStorage2 = new SettlementsStorage("classpath:wrong-test-data-2.json");
assertThat(wrongDataStorage2.hasData()).isFalse();
ArgumentCaptor<LoggingEvent> eventArgumentCaptor = ArgumentCaptor.forClass(LoggingEvent.class);
verify(mockAppender, times(2)).doAppend(eventArgumentCaptor.capture());
LoggingEvent firstLoggingEvent = eventArgumentCaptor.getAllValues().get(0);
assertThat(firstLoggingEvent.getLevel()).isEqualTo(ERROR);
assertThat(firstLoggingEvent.getMessage().toString()
.contains("The data in JSON file doesn't match to the defined schema.")).isTrue();
LoggingEvent secondLoggingEvent = eventArgumentCaptor.getAllValues().get(0);
assertThat(secondLoggingEvent.getLevel()).isEqualTo(ERROR);
assertThat(secondLoggingEvent.getMessage().toString()
.contains("The data in JSON file doesn't match to the defined schema.")).isTrue();
}
}
| 2,948 | 0.729308 | 0.719132 | 64 | 45.0625 | 33.899612 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
5
|
8d6d60be4960d8d3860b09b8087c96403dbffc63
| 36,910,948,968,036 |
d2b125d5aed28c08fffe1302eff5317e4a189779
|
/src/com/company/LinkedListCompare.java
|
1f2399a6f19a4286639b838b4b62a7e1bb3f03a1
|
[] |
no_license
|
klakshmi75/ProblemSolving
|
https://github.com/klakshmi75/ProblemSolving
|
19716fa73e28967444b2076de4e88ba9e5247f09
|
cab629c8947d1c562ba69ba5de817b43509ef22c
|
refs/heads/master
| 2020-03-23T07:05:05.118000 | 2018-09-20T10:42:46 | 2018-09-20T10:42:46 | 141,247,409 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class LinkedListCompare {
static class SinglyLinkedListNode {
public int data;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(int nodeData) {
this.data = nodeData;
this.next = null;
}
}
static class SinglyLinkedList {
public SinglyLinkedListNode head;
public SinglyLinkedListNode tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
public void insertNode(int nodeData) {
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
}
public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException {
while (node != null) {
bufferedWriter.write(String.valueOf(node.data));
node = node.next;
if (node != null) {
bufferedWriter.write(sep);
}
}
}
// Complete the compareLists function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
while(head1 != null && head2 != null) {
if(head1.data != head2.data) {
break;
}
head1 = head1.next;
head2 = head2.next;
}
if(head1 != null || head2 != null) {
return false;
} else {
return true;
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
SinglyLinkedList list1 = createList(10);
SinglyLinkedList list2 = createList(10);
System.out.println("Lists are equal : " + compareLists(list1.head, list2.head));
SinglyLinkedList list3 = createList(10);
SinglyLinkedList list4 = createList(0);
System.out.println("Lists are equal : " + compareLists(list3.head, list4.head));
SinglyLinkedList list5 = createList(10);
SinglyLinkedList list6 = createList(20);
System.out.println("Lists are equal : " + compareLists(list5.head, list6.head));
}
public static SinglyLinkedList createList(int size) {
SinglyLinkedList list = new SinglyLinkedList();
for (int i = 0; i < size; i++) {
list.insertNode(i+10);
}
return list;
}
}
|
UTF-8
|
Java
| 2,877 |
java
|
LinkedListCompare.java
|
Java
|
[] | null |
[] |
package com.company;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class LinkedListCompare {
static class SinglyLinkedListNode {
public int data;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(int nodeData) {
this.data = nodeData;
this.next = null;
}
}
static class SinglyLinkedList {
public SinglyLinkedListNode head;
public SinglyLinkedListNode tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
public void insertNode(int nodeData) {
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
}
public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException {
while (node != null) {
bufferedWriter.write(String.valueOf(node.data));
node = node.next;
if (node != null) {
bufferedWriter.write(sep);
}
}
}
// Complete the compareLists function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
while(head1 != null && head2 != null) {
if(head1.data != head2.data) {
break;
}
head1 = head1.next;
head2 = head2.next;
}
if(head1 != null || head2 != null) {
return false;
} else {
return true;
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
SinglyLinkedList list1 = createList(10);
SinglyLinkedList list2 = createList(10);
System.out.println("Lists are equal : " + compareLists(list1.head, list2.head));
SinglyLinkedList list3 = createList(10);
SinglyLinkedList list4 = createList(0);
System.out.println("Lists are equal : " + compareLists(list3.head, list4.head));
SinglyLinkedList list5 = createList(10);
SinglyLinkedList list6 = createList(20);
System.out.println("Lists are equal : " + compareLists(list5.head, list6.head));
}
public static SinglyLinkedList createList(int size) {
SinglyLinkedList list = new SinglyLinkedList();
for (int i = 0; i < size; i++) {
list.insertNode(i+10);
}
return list;
}
}
| 2,877 | 0.57699 | 0.563782 | 102 | 27.196079 | 24.904146 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false |
5
|
3ce9afdb4db04c8e3ff54f2199b94f8c25323625
| 37,331,855,764,146 |
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/6/6_1a5403d76b8416e18f54588a8c420aff16716cbf/ITabsheet/6_1a5403d76b8416e18f54588a8c420aff16716cbf_ITabsheet_s.java
|
8dbe871d0a2598b272132fa05ec63c8001c25ea3
|
[] |
no_license
|
zhongxingyu/Seer
|
https://github.com/zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false |
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Iterator;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SourcesTabEvents;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabListener;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class ITabsheet extends FlowPanel implements Paintable,
ContainerResizedListener {
public static final String CLASSNAME = "i-tabsheet";
String id;
ApplicationConnection client;
ArrayList tabKeys = new ArrayList();
ArrayList captions = new ArrayList();
int activeTabIndex = 0;
private final TabBar tb;
private final ITabsheetPanel tp;
private final Element deco;
private final TabListener tl = new TabListener() {
public void onTabSelected(SourcesTabEvents sender, final int tabIndex) {
if (ITabsheet.this.client != null
&& ITabsheet.this.activeTabIndex != tabIndex) {
addStyleDependentName("loading");
ITabsheet.this.tp.clear();
DeferredCommand.addCommand(new Command() {
public void execute() {
ITabsheet.this.client.updateVariable(ITabsheet.this.id,
"selected", ""
+ ITabsheet.this.tabKeys.get(tabIndex),
true);
}
});
}
}
public boolean onBeforeTabSelected(SourcesTabEvents sender, int tabIndex) {
return true;
}
};
private String height;
public ITabsheet() {
setStyleName(CLASSNAME);
this.tb = new TabBar();
this.tp = new ITabsheetPanel();
this.deco = DOM.createDiv();
this.tp.setStyleName(CLASSNAME + "-content");
addStyleDependentName("loading"); // Indicate initial progress
this.tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(this.deco, "className", CLASSNAME + "-deco");
add(this.tb);
add(this.tp);
DOM.appendChild(getElement(), this.deco);
this.tb.addTabListener(this.tl);
clearTabs();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
this.id = uidl.getId();
if (client.updateComponent(this, uidl, false)) {
return;
}
// Add proper stylenames for all elements
if (uidl.hasAttribute("style")) {
String[] styles = uidl.getStringAttribute("style").split(" ");
String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
this.tb.addStyleDependentName(styles[i]);
this.tp.addStyleDependentName(styles[i]);
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(this.deco, "className", decoClass);
}
// Adjust width and height
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : null;
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : null;
setWidth(w != null ? w : "auto");
// Height calculations
if (h != null) {
setHeight(h);
} else {
this.height = null;
this.tp.setHeight("auto");
// We don't need overflow:auto when tabsheet height is not set
// TODO reconsider, we might sometimes have wide, non-breaking
// content
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "hidden");
}
// Render content
UIDL tabs = uidl.getChildUIDL(0);
boolean keepCurrentTabs = this.tabKeys.size() == tabs
.getNumberOfChildren();
for (int i = 0; keepCurrentTabs && i < this.tabKeys.size(); i++) {
keepCurrentTabs = this.tabKeys.get(i).equals(
tabs.getChildUIDL(i).getStringAttribute("key"))
&& this.captions.get(i).equals(
tabs.getChildUIDL(i).getStringAttribute("caption"));
}
if (keepCurrentTabs) {
int index = 0;
for (Iterator it = tabs.getChildIterator(); it.hasNext();) {
UIDL tab = (UIDL) it.next();
if (tab.getBooleanAttribute("selected")) {
this.activeTabIndex = index;
renderContent(tab.getChildUIDL(0));
}
index++;
}
} else {
this.tabKeys.clear();
this.captions.clear();
clearTabs();
int index = 0;
for (Iterator it = tabs.getChildIterator(); it.hasNext();) {
UIDL tab = (UIDL) it.next();
String key = tab.getStringAttribute("key");
String caption = tab.getStringAttribute("caption");
if (caption == null) {
caption = "";
}
this.captions.add(caption);
this.tabKeys.add(key);
// Add new tab (additional SPAN-element for loading indication)
this.tb.insertTab("<span>" + caption + "</span>", true, this.tb
.getTabCount());
// Add placeholder content
this.tp.add(new ILabel(""));
if (tab.getBooleanAttribute("selected")) {
this.activeTabIndex = index;
renderContent(tab.getChildUIDL(0));
}
index++;
}
}
// Open selected tab
this.tb.selectTab(this.activeTabIndex);
// tp.showWidget(activeTabIndex);
}
private void renderContent(final UIDL contentUIDL) {
DeferredCommand.addCommand(new Command() {
public void execute() {
// Loading done, start drawing
Widget content = ITabsheet.this.client.getWidget(contentUIDL);
ITabsheet.this.tp.remove(ITabsheet.this.activeTabIndex);
ITabsheet.this.tp
.insert(content, ITabsheet.this.activeTabIndex);
ITabsheet.this.tp.showWidget(ITabsheet.this.activeTabIndex);
((Paintable) content).updateFromUIDL(contentUIDL,
ITabsheet.this.client);
removeStyleDependentName("loading");
}
});
}
private void clearTabs() {
int i = this.tb.getTabCount();
while (i > 0) {
this.tb.removeTab(--i);
}
this.tp.clear();
// Get rid of unnecessary 100% cell heights in TabBar (really ugly hack)
Element tr = DOM.getChild(DOM.getChild(this.tb.getElement(), 0), 0);
Element rest = DOM.getChild(
DOM.getChild(tr, DOM.getChildCount(tr) - 1), 0);
DOM.removeElementAttribute(rest, "style");
}
public void setHeight(String height) {
this.height = height;
iLayout();
}
public void iLayout() {
if (this.height != null) {
// Make content zero height
this.tp.setHeight("0");
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "hidden");
// First, calculate needed pixel height
super.setHeight(this.height);
int neededHeight = getOffsetHeight();
super.setHeight("");
// Then calculate the size the content area needs to be
int pixelHeight = getOffsetHeight();
this.tp.setHeight(neededHeight - pixelHeight + "px");
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "");
}
Util.runAncestorsLayout(this);
}
}
|
UTF-8
|
Java
| 7,138 |
java
|
6_1a5403d76b8416e18f54588a8c420aff16716cbf_ITabsheet_s.java
|
Java
|
[] | null |
[] |
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Iterator;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SourcesTabEvents;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabListener;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class ITabsheet extends FlowPanel implements Paintable,
ContainerResizedListener {
public static final String CLASSNAME = "i-tabsheet";
String id;
ApplicationConnection client;
ArrayList tabKeys = new ArrayList();
ArrayList captions = new ArrayList();
int activeTabIndex = 0;
private final TabBar tb;
private final ITabsheetPanel tp;
private final Element deco;
private final TabListener tl = new TabListener() {
public void onTabSelected(SourcesTabEvents sender, final int tabIndex) {
if (ITabsheet.this.client != null
&& ITabsheet.this.activeTabIndex != tabIndex) {
addStyleDependentName("loading");
ITabsheet.this.tp.clear();
DeferredCommand.addCommand(new Command() {
public void execute() {
ITabsheet.this.client.updateVariable(ITabsheet.this.id,
"selected", ""
+ ITabsheet.this.tabKeys.get(tabIndex),
true);
}
});
}
}
public boolean onBeforeTabSelected(SourcesTabEvents sender, int tabIndex) {
return true;
}
};
private String height;
public ITabsheet() {
setStyleName(CLASSNAME);
this.tb = new TabBar();
this.tp = new ITabsheetPanel();
this.deco = DOM.createDiv();
this.tp.setStyleName(CLASSNAME + "-content");
addStyleDependentName("loading"); // Indicate initial progress
this.tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(this.deco, "className", CLASSNAME + "-deco");
add(this.tb);
add(this.tp);
DOM.appendChild(getElement(), this.deco);
this.tb.addTabListener(this.tl);
clearTabs();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
this.id = uidl.getId();
if (client.updateComponent(this, uidl, false)) {
return;
}
// Add proper stylenames for all elements
if (uidl.hasAttribute("style")) {
String[] styles = uidl.getStringAttribute("style").split(" ");
String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
this.tb.addStyleDependentName(styles[i]);
this.tp.addStyleDependentName(styles[i]);
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(this.deco, "className", decoClass);
}
// Adjust width and height
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : null;
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : null;
setWidth(w != null ? w : "auto");
// Height calculations
if (h != null) {
setHeight(h);
} else {
this.height = null;
this.tp.setHeight("auto");
// We don't need overflow:auto when tabsheet height is not set
// TODO reconsider, we might sometimes have wide, non-breaking
// content
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "hidden");
}
// Render content
UIDL tabs = uidl.getChildUIDL(0);
boolean keepCurrentTabs = this.tabKeys.size() == tabs
.getNumberOfChildren();
for (int i = 0; keepCurrentTabs && i < this.tabKeys.size(); i++) {
keepCurrentTabs = this.tabKeys.get(i).equals(
tabs.getChildUIDL(i).getStringAttribute("key"))
&& this.captions.get(i).equals(
tabs.getChildUIDL(i).getStringAttribute("caption"));
}
if (keepCurrentTabs) {
int index = 0;
for (Iterator it = tabs.getChildIterator(); it.hasNext();) {
UIDL tab = (UIDL) it.next();
if (tab.getBooleanAttribute("selected")) {
this.activeTabIndex = index;
renderContent(tab.getChildUIDL(0));
}
index++;
}
} else {
this.tabKeys.clear();
this.captions.clear();
clearTabs();
int index = 0;
for (Iterator it = tabs.getChildIterator(); it.hasNext();) {
UIDL tab = (UIDL) it.next();
String key = tab.getStringAttribute("key");
String caption = tab.getStringAttribute("caption");
if (caption == null) {
caption = "";
}
this.captions.add(caption);
this.tabKeys.add(key);
// Add new tab (additional SPAN-element for loading indication)
this.tb.insertTab("<span>" + caption + "</span>", true, this.tb
.getTabCount());
// Add placeholder content
this.tp.add(new ILabel(""));
if (tab.getBooleanAttribute("selected")) {
this.activeTabIndex = index;
renderContent(tab.getChildUIDL(0));
}
index++;
}
}
// Open selected tab
this.tb.selectTab(this.activeTabIndex);
// tp.showWidget(activeTabIndex);
}
private void renderContent(final UIDL contentUIDL) {
DeferredCommand.addCommand(new Command() {
public void execute() {
// Loading done, start drawing
Widget content = ITabsheet.this.client.getWidget(contentUIDL);
ITabsheet.this.tp.remove(ITabsheet.this.activeTabIndex);
ITabsheet.this.tp
.insert(content, ITabsheet.this.activeTabIndex);
ITabsheet.this.tp.showWidget(ITabsheet.this.activeTabIndex);
((Paintable) content).updateFromUIDL(contentUIDL,
ITabsheet.this.client);
removeStyleDependentName("loading");
}
});
}
private void clearTabs() {
int i = this.tb.getTabCount();
while (i > 0) {
this.tb.removeTab(--i);
}
this.tp.clear();
// Get rid of unnecessary 100% cell heights in TabBar (really ugly hack)
Element tr = DOM.getChild(DOM.getChild(this.tb.getElement(), 0), 0);
Element rest = DOM.getChild(
DOM.getChild(tr, DOM.getChildCount(tr) - 1), 0);
DOM.removeElementAttribute(rest, "style");
}
public void setHeight(String height) {
this.height = height;
iLayout();
}
public void iLayout() {
if (this.height != null) {
// Make content zero height
this.tp.setHeight("0");
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "hidden");
// First, calculate needed pixel height
super.setHeight(this.height);
int neededHeight = getOffsetHeight();
super.setHeight("");
// Then calculate the size the content area needs to be
int pixelHeight = getOffsetHeight();
this.tp.setHeight(neededHeight - pixelHeight + "px");
DOM.setStyleAttribute(this.tp.getElement(), "overflow", "");
}
Util.runAncestorsLayout(this);
}
}
| 7,138 | 0.666853 | 0.664472 | 238 | 28.987394 | 22.151974 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.810924 | false | false |
5
|
5dfbcf9aa977ee7979c435229c71c0de791f267a
| 37,331,855,764,748 |
2b1de73c2678c35a732bc6ba7cdb4b1a4a762da2
|
/src/main/java/com/oberasoftware/train/controllers/ecos/EcosTrainController.java
|
647360a53d314ce975e5eab07a507973c3303dc0
|
[] |
no_license
|
renarj/rc-train
|
https://github.com/renarj/rc-train
|
213dea4ef0dcfe2299b4bae48af5d1a9dd1672ab
|
4e23a316d520223ee138302e2ebbb13e38510fbe
|
refs/heads/master
| 2021-04-18T21:33:24.502000 | 2016-08-10T19:34:50 | 2016-08-10T19:34:50 | 63,798,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.oberasoftware.train.controllers.ecos;
import com.oberasoftware.home.api.converters.ConverterManager;
import com.oberasoftware.train.api.ConnectionException;
import com.oberasoftware.train.api.TrainCommand;
import com.oberasoftware.train.api.TrainController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.Socket;
@Component
public class EcosTrainController implements TrainController {
private static final Logger LOG = LoggerFactory.getLogger(EcosTrainController.class);
private Socket ecosSocket;
@Value("${ecos.host}")
private String hostName;
@Value("${ecos.port}")
private int portNumber;
@Value("${controllerId:ecos}")
private String controllerId;
@Autowired
private EcosProtocolReceiver protocolReceiver;
@Autowired
private EcosProtocolSender protocolSender;
@Autowired
private ConverterManager converterManager;
@Override
public String getControllerId() {
return controllerId;
}
@Override
public void connect() throws ConnectionException {
try {
ecosSocket = new Socket(hostName, portNumber);
protocolReceiver.start(ecosSocket);
protocolSender.start(ecosSocket);
//force it to enable the station
protocolSender.publish(EcosCommandBuilder.set(1).param("go").build());
} catch(IOException e) {
throw new ConnectionException("Unable to connect to Ecos Control center, due too IOException", e);
}
}
@Override
public void publish(TrainCommand command) {
LOG.info("Received train command: {}", command);
EcosCommand ecosCommand = converterManager.convert(command, EcosCommand.class);
if(ecosCommand != null) {
try {
LOG.debug("Sending ecos command: {}", ecosCommand);
protocolSender.publish(ecosCommand);
} catch (ConnectionException e) {
LOG.error("", e);
}
} else {
LOG.warn("Could not convert train command: {}", command);
}
}
@Override
public void disconnect() throws ConnectionException {
try {
this.protocolReceiver.stop();
this.protocolSender.stop();
this.ecosSocket.close();
} catch(IOException e) {
throw new ConnectionException("Unable to close connection to Ecos Controller", e);
}
}
}
|
UTF-8
|
Java
| 2,559 |
java
|
EcosTrainController.java
|
Java
|
[] | null |
[] |
package com.oberasoftware.train.controllers.ecos;
import com.oberasoftware.home.api.converters.ConverterManager;
import com.oberasoftware.train.api.ConnectionException;
import com.oberasoftware.train.api.TrainCommand;
import com.oberasoftware.train.api.TrainController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.Socket;
@Component
public class EcosTrainController implements TrainController {
private static final Logger LOG = LoggerFactory.getLogger(EcosTrainController.class);
private Socket ecosSocket;
@Value("${ecos.host}")
private String hostName;
@Value("${ecos.port}")
private int portNumber;
@Value("${controllerId:ecos}")
private String controllerId;
@Autowired
private EcosProtocolReceiver protocolReceiver;
@Autowired
private EcosProtocolSender protocolSender;
@Autowired
private ConverterManager converterManager;
@Override
public String getControllerId() {
return controllerId;
}
@Override
public void connect() throws ConnectionException {
try {
ecosSocket = new Socket(hostName, portNumber);
protocolReceiver.start(ecosSocket);
protocolSender.start(ecosSocket);
//force it to enable the station
protocolSender.publish(EcosCommandBuilder.set(1).param("go").build());
} catch(IOException e) {
throw new ConnectionException("Unable to connect to Ecos Control center, due too IOException", e);
}
}
@Override
public void publish(TrainCommand command) {
LOG.info("Received train command: {}", command);
EcosCommand ecosCommand = converterManager.convert(command, EcosCommand.class);
if(ecosCommand != null) {
try {
LOG.debug("Sending ecos command: {}", ecosCommand);
protocolSender.publish(ecosCommand);
} catch (ConnectionException e) {
LOG.error("", e);
}
} else {
LOG.warn("Could not convert train command: {}", command);
}
}
@Override
public void disconnect() throws ConnectionException {
try {
this.protocolReceiver.stop();
this.protocolSender.stop();
this.ecosSocket.close();
} catch(IOException e) {
throw new ConnectionException("Unable to close connection to Ecos Controller", e);
}
}
}
| 2,559 | 0.699883 | 0.69871 | 88 | 28.079546 | 25.391132 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.931818 | false | false |
5
|
8c8b1195b57537d165f154edb876b78e5e90fec9
| 35,570,919,179,433 |
2d4e4535f2019e717b4e069f879340834918d7d7
|
/desenvolvimento/src/java/PWebServ/src/br/jsan/org/app/domain/Tarefa.java
|
67bfc2a7467c1aa7782e23d294e62180743b9812
|
[] |
no_license
|
alessandrots/project-hera
|
https://github.com/alessandrots/project-hera
|
59d0f7d5787bc18f8f93b010e65a2ce1bdb10605
|
0ab35350a64a2774858b62413440d9da3f905275
|
refs/heads/master
| 2016-09-08T01:25:41.331000 | 2013-07-16T10:43:21 | 2013-07-16T10:43:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.jsan.org.app.domain;
import java.sql.Timestamp;
public class Tarefa implements Domain {
/**
*
*/
private static final long serialVersionUID = -5652715197735231887L;
private Integer codigo;
private String nome;
private Integer duracao;
private Timestamp dataInicio;
private Timestamp dataEntrega;
private Timestamp dataTermino;
/**
* @return the codigo
*/
public Integer getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the dataInicio
*/
public Timestamp getDataInicio() {
return dataInicio;
}
/**
* @param dataInicio the dataInicio to set
*/
public void setDataInicio(Timestamp dataInicio) {
this.dataInicio = dataInicio;
}
/**
* @return the dataFim
*/
public Timestamp getDataEntrega() {
return dataEntrega;
}
/**
* @param dataFim the dataFim to set
*/
public void setDataEntrega(Timestamp dataFim) {
this.dataEntrega = dataFim;
}
/**
* @return the dataTermino
*/
public Timestamp getDataTermino() {
return dataTermino;
}
/**
* @param dataTermino the dataTermino to set
*/
public void setDataTermino(Timestamp dataTermino) {
this.dataTermino = dataTermino;
}
/**
* @return the duracao
*/
public Integer getDuracao() {
return duracao;
}
/**
* @param duracao the duracao to set
*/
public void setDuracao(Integer duracao) {
this.duracao = duracao;
}
}
|
UTF-8
|
Java
| 1,658 |
java
|
Tarefa.java
|
Java
|
[] | null |
[] |
package br.jsan.org.app.domain;
import java.sql.Timestamp;
public class Tarefa implements Domain {
/**
*
*/
private static final long serialVersionUID = -5652715197735231887L;
private Integer codigo;
private String nome;
private Integer duracao;
private Timestamp dataInicio;
private Timestamp dataEntrega;
private Timestamp dataTermino;
/**
* @return the codigo
*/
public Integer getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the dataInicio
*/
public Timestamp getDataInicio() {
return dataInicio;
}
/**
* @param dataInicio the dataInicio to set
*/
public void setDataInicio(Timestamp dataInicio) {
this.dataInicio = dataInicio;
}
/**
* @return the dataFim
*/
public Timestamp getDataEntrega() {
return dataEntrega;
}
/**
* @param dataFim the dataFim to set
*/
public void setDataEntrega(Timestamp dataFim) {
this.dataEntrega = dataFim;
}
/**
* @return the dataTermino
*/
public Timestamp getDataTermino() {
return dataTermino;
}
/**
* @param dataTermino the dataTermino to set
*/
public void setDataTermino(Timestamp dataTermino) {
this.dataTermino = dataTermino;
}
/**
* @return the duracao
*/
public Integer getDuracao() {
return duracao;
}
/**
* @param duracao the duracao to set
*/
public void setDuracao(Integer duracao) {
this.duracao = duracao;
}
}
| 1,658 | 0.672497 | 0.661037 | 95 | 16.452631 | 15.870376 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.284211 | false | false |
5
|
9eabfd99f7610c6b5a6bd25e5b1133a425abfc9f
| 36,721,970,406,792 |
e827b9873580f3fc4ae51694504fe92e3b225f3f
|
/app/src/main/java/com/example/android/apis/graphics/spritetext/LabelMaker.java
|
0895c7a26db2d5f98335fa3307f83a4e59c3e0e3
|
[] |
no_license
|
vlad5ss/ApiDemos
|
https://github.com/vlad5ss/ApiDemos
|
d7b7aab4389b7c6d325474cc51af30ba85284d4f
|
ff0c40931245b7c02f4cc9fc9a39514ea0b9d65c
|
refs/heads/master
| 2020-12-23T03:43:31.639000 | 2020-01-29T13:46:27 | 2020-01-29T13:46:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.graphics.spritetext;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.opengl.GLUtils;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* An OpenGL text label maker.
* <p>
* OpenGL labels are implemented by creating a Bitmap, drawing all the labels
* into the Bitmap, converting the Bitmap into an Alpha texture, and drawing
* portions of the texture using glDrawTexiOES.
* <p>
* The benefits of this approach are that the labels are drawn using the high
* quality anti-aliased font rasterizer, full character set support, and all the
* text labels are stored on a single texture, which makes it faster to use.
* <p>
* The drawbacks are that you can only have as many labels as will fit onto one
* texture, and you have to recreate the whole texture if any label text
* changes.
*/
@SuppressWarnings({"WeakerAccess", "FieldCanBeLocal"})
public class LabelMaker {
/**
* Width of text, rounded up to power of 2, set to the {@code strikeWidth} parameter to our
* constructor.
*/
private int mStrikeWidth;
/**
* Height of text, rounded up to power of 2, set to the {@code strikeHeight} parameter to our
* constructor.
*/
private int mStrikeHeight;
/**
* true if we want a full color backing store (4444), otherwise we generate a grey L8 backing
* store. Set to the {@code boolean fullColor} parameter of our constructor, always true in our
* case.
*/
private boolean mFullColor;
/**
* {@code Bitmap} we create our labels in, and when done creating the labels we upload it as
* GL_TEXTURE_2D for drawing the labels (and then recycle it).
*/
private Bitmap mBitmap;
/**
* {@code Canvas} we use to draw into {@code Bitmap mBitmap}.
*/
private Canvas mCanvas;
/**
* We create this as a black paint, with a style of FILL but never actually use it.
*/
private Paint mClearPaint;
/**
* Texture name of our label texture.
*/
private int mTextureID;
@SuppressWarnings("unused")
private float mTexelWidth; // Convert texel to U
@SuppressWarnings("unused")
private float mTexelHeight; // Convert texel to V
/**
* {@code u} (x) coordinate to use when adding next label to our texture.
*/
private int mU;
/**
* {@code v} (y) coordinate to use when adding next label to our texture.
*/
private int mV;
/**
* Height of the current line of labels.
*/
private int mLineHeight;
/**
* List of the {@code Label} objects in our texture. A {@code Label} instance contains information
* about the location and size of the label's text in the texture, as well as the cropping
* parameters to use to draw only that {@code Label}.
*/
private ArrayList<Label> mLabels = new ArrayList<>();
/**
* Constant used to set our field {@code mState} to indicate that we are just starting the
* creation of our {@code Label} texture and there are no resources that need to be freed if
* our {@code GLSurface} is destroyed.
*/
private static final int STATE_NEW = 0;
/**
* Constant used to set our field {@code mState} to indicate that our {@code initialize} method
* has been called, and we are ready to begin adding labels. We have acquired a texture name
* for our field {@code mTextureID}, bound it to GL_TEXTURE_2D and configured it so there is
* a texture which needs to be freed if our {@code GLSurface} is destroyed.
*/
private static final int STATE_INITIALIZED = 1;
/**
* Constant used to set our field {@code mState} to indicate that our {@code beginAdding} method
* has been called, and we are ready to add a label (or an additional label). {@code initialize}
* was called before us, and we have allocated a {@code Bitmap} for our field {@code Bitmap mBitmap}
* so there is some needed if our {@code GLSurface} is destroyed.
*/
private static final int STATE_ADDING = 2;
/**
* Constant used to set our field {@code mState} to indicate that our {@code beginDrawing} method
* has been called and we are in the process of drawing the various {@code Label} objects located
* in our texture.
*/
private static final int STATE_DRAWING = 3;
/**
* State that our {@code LabelMaker} instance is in, one of the above constants. It is used by
* our method {@code checkState} to make sure that a state change is "legal", and also by our
* method {@code shutdown} to make sure that our texture is deleted when our surface has been
* destroyed (a texture will only have been allocated if {@code mState>STATE_NEW}).
*/
private int mState;
/**
* Create a label maker. For maximum compatibility with various OpenGL ES implementations, the
* strike width and height must be powers of two, We want the strike width to be at least as
* wide as the widest window. First we initialize our field {@code boolean mFullColor} to our
* parameter {@code boolean fullColor}, {@code int mStrikeWidth} to {@code int strikeWidth}, and
* {@code int mStrikeHeight} to {@code int strikeHeight}. We configure 3 fields which are never
* used: {@code mTexelWidth}. {@code mTexelHeight}, and {@code mPaint}. Finally we set our field
* {@code int mState} to STATE_NEW (in this state we do not yet have a texture that will need to
* be freed if our surface is destroyed, but we are ready to begin building our label texture).
*
* @param fullColor true if we want a full color backing store (4444),
* otherwise we generate a grey L8 backing store.
* @param strikeWidth width of strike
* @param strikeHeight height of strike
*/
public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) {
mFullColor = fullColor;
mStrikeWidth = strikeWidth;
mStrikeHeight = strikeHeight;
mTexelWidth = (float) (1.0 / mStrikeWidth); // UNUSED
mTexelHeight = (float) (1.0 / mStrikeHeight); // UNUSED
mClearPaint = new Paint();
mClearPaint.setARGB(0, 0, 0, 0);
mClearPaint.setStyle(Style.FILL);
mState = STATE_NEW;
}
/**
* Call to initialize the class. Call whenever the surface has been created. First we set our
* field {@code int mState} to STATE_INITIALIZED (in this state we have generated a texture name,
* bound that texture to GL_TEXTURE_2D and configured it to our liking, but no image data has
* been uploaded yet). Next we generate a texture name and save it in our field {@code int mTextureID}.
* <p>
* We bind the texture {@code mTextureID} to the target GL_TEXTURE_2D (GL_TEXTURE_2D becomes an
* alias for our texture), and set both the texture parameters GL_TEXTURE_MIN_FILTER and
* GL_TEXTURE_MAG_FILTER of GL_TEXTURE_2D to GL_NEAREST (uses the value of the texture element
* that is nearest (in Manhattan distance) to the center of the pixel being textured when the
* pixel being textured maps to an area greater than one texture element, as well as when the
* the pixel being textured maps to an area less than or equal to one texture element). We set
* the texture parameters GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T of GL_TEXTURE_2D both to
* GL_CLAMP_TO_EDGE (when the fragment being textured is larger than the texture, the texture
* elements at the edges will be used for the rest of the fragment).
* <p>
* Finally we set the texture environment parameter GL_TEXTURE_ENV_MODE of the texture environment
* GL_TEXTURE_ENV to GL_REPLACE (the texture will replace whatever was in the fragment).
*
* @param gl the gl interface
*/
public void initialize(GL10 gl) {
mState = STATE_INITIALIZED;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
// Use Nearest for performance.
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
}
/**
* Called when the surface we were labeling has been destroyed and a new surface is being created
* so that the the label texture used by this instance of {@code LabelMaker} can be deleted. To
* do this if we have already passed to a state where a texture name has been allocated by the
* hardware ({@code mState>STATE_NEW}) we must delete our texture {@code int mTextureID} and
* move our state field {@code int mState} to the state STATE_NEW (ready to start building a new
* label texture).
*
* @param gl the gl interface
*/
public void shutdown(GL10 gl) {
if (gl != null) {
if (mState > STATE_NEW) {
int[] textures = new int[1];
textures[0] = mTextureID;
gl.glDeleteTextures(1, textures, 0);
mState = STATE_NEW;
}
}
}
/**
* Call before adding labels, and after calling {@code initialize}. Clears out any existing labels.
* First we call {@code checkState} to make sure we are currently in STATE_INITIALIZED, and if so
* changing to state STATE_ADDING. Next we clear our current list of {@code Label} objects contained
* in {@code ArrayList<LabelMaker.Label> mLabels}. We reset the texture coordinates for our next
* label {@code int mU} and {@code int mV}, and set the height of the current line {@code int mLineHeight}
* to 0. We set {@code Bitmap.Config config} to ARGB_4444 if our field {@code boolean mFullColor}
* is true, or to ALPHA_8 if it is false. Then we initialize our field {@code Bitmap mBitmap} with
* a new instance of {@code Bitmap} using {@code config} which is {@code mStrikeWidth} pixels by
* {@code mStrikeHeight} pixels. We initialize {@code Canvas mCanvas} with a canvas which will use
* {@code mBitmap} to draw to, then set the entire {@code mBitmap} to black.
*
* @param gl the gl interface UNUSED
*/
@SuppressWarnings("UnusedParameters")
public void beginAdding(GL10 gl) {
checkState(STATE_INITIALIZED, STATE_ADDING);
mLabels.clear();
mU = 0;
mV = 0;
mLineHeight = 0;
Bitmap.Config config = mFullColor ?
Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8;
mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config);
mCanvas = new Canvas(mBitmap);
mBitmap.eraseColor(0);
}
/**
* Call to add a label, convenience function to call the full argument {@code add} with a null
* {@code Drawable background} and {@code winWidth} and {@code minHeight} both equal to 0. We
* simply supply a null for {@code Drawable background} and pass the call on.
*
* @param gl the gl interface
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, String text, Paint textPaint) {
return add(gl, null, text, textPaint);
}
/**
* Call to add a label, convenience function to call the full argument {@code add} with
* {@code winWidth} and {@code minHeight} both equal to 0. We simply supply 0 for both
* {@code int minWidth} and {@code int minHeight} and pass the call on.
*
* @param gl the gl interface
* @param background background {@code Drawable} to use
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, String text, Paint textPaint) {
return add(gl, background, text, textPaint, 0, 0);
}
/**
* Call to add a label UNUSED
*
* @param gl the gl interface
* @param background background {@code Drawable} to use
* @param minWidth minimum width of label
* @param minHeight minimum height of label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, int minWidth, int minHeight) {
return add(gl, background, null, null, minWidth, minHeight);
}
/**
* Call to add a label. First we call our method {@code checkState} to make sure we are in the
* state STATE_ADDING (our method {@code beginAdding} has been called). Next we determine if
* we have a {@code background} to draw {@code background != null}) saving the result to
* {@code boolean drawBackground}, and determine if we have text to draw ({@code text != null}
* and {@code textPaint != null}) saving the result to {@code boolean drawText}.
* <p>
* We allocate a new instance for {@code Rect padding} and if we have a background that needs to
* be drawn we fetch the padding insets for {@code background} to {@code padding}, set the input
* parameter {@code minWidth} to the max of {@code minWidth} and the minimum width of the drawable
* {@code background}, and set the input parameter {@code minHeight} to the max of {@code minHeight}
* and the minimum height of the drawable {@code background}.
* <p>
* Next we set {@code int ascent}, {@code int descent} and {@code int measuredTextWidth} all to
* 0, and if we have text that needs drawing we set {@code int ascent} to the ceiling value of
* the highest ascent above the baseline for the current typeface and text size of the parameter
* {@code Paint textPaint}, set {@code int descent} to the ceiling value of the lowest descent
* below the baseline for the current typeface and text size of the parameter {@code Paint textPaint},
* and set {@code {@code measuredTextWidth}} to the ceiling value of the length of {@code text}.
* <p>
* We now perform a bunch of boring calculations to determine where on the {@code Canvas mCanvas}
* we are to draw our background and/or text, and if we have a background we draw the background
* drawable at that position, and if we have text we draw the text at that position.
* <p>
* Having done so, we update our field {@code mU} to point to the next u (x) coordinate we can
* use, {@code mV} to point to the next v (y) coordinate we can use, and {@code mLineHeight} to
* the (possibly new) height of our current line.
* <p>
* Finally we add a new instance of {@code Label} to {@code ArrayList<Label> mLabels} with the
* information that will be needed to locate, crop and draw the label we just drew, and return
* the index of this {@code Label} object to the caller.
*
* @param gl the gl interface UNUSED
* @param background background {@code Drawable} to use
* @param text the text of the label
* @param textPaint the paint of the label
* @param minWidth minimum width of label
* @param minHeight minimum height of label
* @return index of the {@code Label} in {@code ArrayList<Label> mLabels}, the {@code Label}
* object will be used to locate, measure, crop and draw the label.
*/
@SuppressWarnings("UnusedParameters")
public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) {
checkState(STATE_ADDING, STATE_ADDING);
boolean drawBackground = background != null;
boolean drawText = (text != null) && (textPaint != null);
Rect padding = new Rect();
if (drawBackground) {
background.getPadding(padding);
minWidth = Math.max(minWidth, background.getMinimumWidth());
minHeight = Math.max(minHeight, background.getMinimumHeight());
}
int ascent = 0;
int descent = 0;
int measuredTextWidth = 0;
if (drawText) {
// Paint.ascent is negative, so negate it.
ascent = (int) Math.ceil(-textPaint.ascent());
descent = (int) Math.ceil(textPaint.descent());
measuredTextWidth = (int) Math.ceil(textPaint.measureText(text));
}
int textHeight = ascent + descent;
int textWidth = Math.min(mStrikeWidth, measuredTextWidth);
int padHeight = padding.top + padding.bottom;
int padWidth = padding.left + padding.right;
int height = Math.max(minHeight, textHeight + padHeight);
int width = Math.max(minWidth, textWidth + padWidth);
int effectiveTextHeight = height - padHeight;
int effectiveTextWidth = width - padWidth;
int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2;
int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2;
// Make changes to the local variables, only commit them
// to the member variables after we've decided not to throw
// any exceptions.
int u = mU;
int v = mV;
int lineHeight = mLineHeight;
if (width > mStrikeWidth) {
width = mStrikeWidth;
}
// Is there room for this string on the current line?
if (u + width > mStrikeWidth) {
// No room, go to the next line:
u = 0;
v += lineHeight;
lineHeight = 0;
}
lineHeight = Math.max(lineHeight, height);
if (v + lineHeight > mStrikeHeight) {
throw new IllegalArgumentException("Out of texture space.");
}
@SuppressWarnings("unused")
int u2 = u + width;
int vBase = v + ascent;
@SuppressWarnings("unused")
int v2 = v + height;
if (drawBackground) {
background.setBounds(u, v, u + width, v + height);
background.draw(mCanvas);
}
if (drawText) {
mCanvas.drawText(text,
u + padding.left + centerOffsetWidth,
vBase + padding.top + centerOffsetHeight,
textPaint);
}
// We know there's enough space, so update the member variables
mU = u + width;
mV = v;
mLineHeight = lineHeight;
mLabels.add(new Label(width, height, ascent, u, v + height, width, -height));
return mLabels.size() - 1;
}
/**
* Call to end adding labels. Must be called before drawing starts. First we call our method
* {@code checkState} to verify that we are in the STATE_ADDING state, and if so transition back
* to the STATE_INITIALIZED state. Next we bind our texture name {@code mTextureID} to the
* GL_TEXTURE_2D target, upload our {@code Bitmap mBitmap} to the GPU, recycle our {@code mBitmap}
* and null our both {@code mBitmap} and {@code mCanvas} so they can be garbage collected.
*
* @param gl the gl interface
*/
public void endAdding(GL10 gl) {
checkState(STATE_ADDING, STATE_INITIALIZED);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
// Reclaim storage used by bitmap and canvas.
mBitmap.recycle();
mBitmap = null;
mCanvas = null;
}
/**
* Get the width in pixels of a given label. Convenience getter for the {@code width} field of
* the {@code Label} at index value {@code labelID} in our {@code ArrayList<Label> mLabels}.
*
* @param labelID index of label
* @return the width in pixels
*/
public float getWidth(int labelID) {
return mLabels.get(labelID).width;
}
/**
* Get the height in pixels of a given label. Convenience getter for the {@code height} field of
* the {@code Label} at index value {@code labelID} in our {@code ArrayList<Label> mLabels}.
*
* @param labelID index of label
* @return the height in pixels
*/
public float getHeight(int labelID) {
return mLabels.get(labelID).height;
}
/**
* Get the baseline of a given label. That's how many pixels from the top of the label to the
* text baseline. (This is equivalent to the negative of the label's paint's ascent.) UNUSED
*
* @param labelID index of label
* @return the baseline in pixels.
*/
@SuppressWarnings("unused")
public float getBaseline(int labelID) {
return mLabels.get(labelID).baseline;
}
/**
* Begin drawing labels. Sets the OpenGL state for rapid drawing. First we call our method
* {@code checkState} to verify that we are in STATE_INITIALIZED state and if so to transition
* to STATE_DRAWING state. Next we bind our texture name {@code mTextureID} to the target
* GL_TEXTURE_2D, set the shade model to GL_FLAT and enable the server side capability GL_BLEND
* (blend the computed fragment color values with the values in the color buffers). We call the
* method {@code glBlendFunc} to set the source blending function to GL_SRC_ALPHA, and the
* destination blending function to GL_ONE_MINUS_SRC_ALPHA (modifies the incoming color by its
* associated alpha value and modifies the destination color by one minus the incoming alpha
* value. The sum of these two colors is then written back into the framebuffer.) We then call
* the method {@code glColor4x} to set the primitive’s opacity to 1.0 in GLfixed format.
* <p>
* We set the current matrix to the projection matrix GL_PROJECTION, push the current projection
* matrix to its stack, load GL_PROJECTION with the identity matrix, and multiply it with the
* orthographic matrix that has the left clipping plane at 0, the right clipping plane at
* {@code viewWidth}, the bottom clipping plane at 0, the top clipping plane at {@code viewHeight},
* the near clipping plane at 0.0, and the far clipping plane at 1.0
* <p>
* We then set the current matrix to the model view matrix GL_MODELVIEW, push the current model
* view matrix to its stack, load GL_MODELVIEW with the identity matrix, and multiply it by a
* translation matrix which moves both x and y coordinates by 0.375 in order to promote consistent
* rasterization.
*
* @param gl the gl interface
* @param viewWidth view width
* @param viewHeight view height
*/
public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
checkState(STATE_INITIALIZED, STATE_DRAWING);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPushMatrix();
gl.glLoadIdentity();
// Magic offsets to promote consistent rasterization.
gl.glTranslatef(0.375f, 0.375f, 0.0f);
}
/**
* Draw a given label at a given x,y position, expressed in pixels, with the lower-left-hand
* corner of the view being (0,0). First we call our method {@code checkState} to make sure we
* are in the STATE_DRAWING state. We fetch the {@code Label} object for the label we are to
* draw to {@code Label label}, enable the server side capability GL_TEXTURE_2D, and set the
* cropping rectangle of GL_TEXTURE_2D to the contents of the {@code label.mCrop} field. Then
* we call glDrawTexiOES to draw the cropped area of the texture at {@code (x,y,z)} using the
* width and height specified by the {@code label.width} field, and the {@code label.height}
* field.
*
* @param gl the gl interface
* @param x x coordinate to draw at
* @param y y coordinate to draw at
* @param labelID index of {@code Label} in the list {@code ArrayList<Label> mLabels} to draw
*/
public void draw(GL10 gl, float x, float y, int labelID) {
checkState(STATE_DRAWING, STATE_DRAWING);
Label label = mLabels.get(labelID);
gl.glEnable(GL10.GL_TEXTURE_2D);
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0);
((GL11Ext) gl).glDrawTexiOES((int) x, (int) y, 0, (int) label.width, (int) label.height);
}
/**
* Ends the drawing and restores the OpenGL state. First we call our method {@code checkState} to
* make sure we are in the STATE_DRAWING state and if so to transition to the STATE_INITIALIZED
* state. We disable the server side capability GL_BLEND, set the current matrix to the projection
* matrix GL_PROJECTION and pop the old matrix off of its stake, and then set the current matrix
* to the model view matrix GL_MODELVIEW and pop the old matrix off of its stake.
*
* @param gl the gl interface
*/
public void endDrawing(GL10 gl) {
checkState(STATE_DRAWING, STATE_INITIALIZED);
gl.glDisable(GL10.GL_BLEND);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPopMatrix();
}
/**
* Throws an IllegalArgumentException if we are not currently in the state {@code oldState}, and
* if we are in that state transitions to {@code newState}.
*
* @param oldState state we need to be in to use the method we are called from
* @param newState state to transition to iff we were in {@code oldState}
*/
private void checkState(int oldState, int newState) {
if (mState != oldState) {
throw new IllegalArgumentException("Can't call this method now.");
}
mState = newState;
}
/**
* Class that contains the information needed to crop and draw a label contained in the current
* GL_TEXTURE_2D label texture.
*/
private static class Label {
/**
* width of the label in pixels
*/
public float width;
/**
* height of the label in pixels
*/
public float height;
/**
* Unused, but set to the ascent value of the font and font size of the paint used to draw
*/
public float baseline;
/**
* Defines the location and size of the label in the texture, it is used to crop the texture
* so that only this label is used for drawing.
*/
public int[] mCrop;
/**
* Our constructor. We simply initialize our fields using our input parameters.
*
* @param width width of our label
* @param height height of our label
* @param baseLine baseline of our label
* @param cropU u coordinate of left side of label in texture
* @param cropV v coordinate of top of texture
* @param cropW width of label in texture
* @param cropH height of the crop region, the negative value in our case specifies that the
* region lies below the coordinate (u,v) in the texture image.
*/
public Label(float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) {
this.width = width;
this.height = height;
this.baseline = baseLine;
int[] crop = new int[4];
crop[0] = cropU;
crop[1] = cropV;
crop[2] = cropW;
crop[3] = cropH;
mCrop = crop;
}
}
}
|
UTF-8
|
Java
| 29,065 |
java
|
LabelMaker.java
|
Java
|
[] | null |
[] |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.graphics.spritetext;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.opengl.GLUtils;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* An OpenGL text label maker.
* <p>
* OpenGL labels are implemented by creating a Bitmap, drawing all the labels
* into the Bitmap, converting the Bitmap into an Alpha texture, and drawing
* portions of the texture using glDrawTexiOES.
* <p>
* The benefits of this approach are that the labels are drawn using the high
* quality anti-aliased font rasterizer, full character set support, and all the
* text labels are stored on a single texture, which makes it faster to use.
* <p>
* The drawbacks are that you can only have as many labels as will fit onto one
* texture, and you have to recreate the whole texture if any label text
* changes.
*/
@SuppressWarnings({"WeakerAccess", "FieldCanBeLocal"})
public class LabelMaker {
/**
* Width of text, rounded up to power of 2, set to the {@code strikeWidth} parameter to our
* constructor.
*/
private int mStrikeWidth;
/**
* Height of text, rounded up to power of 2, set to the {@code strikeHeight} parameter to our
* constructor.
*/
private int mStrikeHeight;
/**
* true if we want a full color backing store (4444), otherwise we generate a grey L8 backing
* store. Set to the {@code boolean fullColor} parameter of our constructor, always true in our
* case.
*/
private boolean mFullColor;
/**
* {@code Bitmap} we create our labels in, and when done creating the labels we upload it as
* GL_TEXTURE_2D for drawing the labels (and then recycle it).
*/
private Bitmap mBitmap;
/**
* {@code Canvas} we use to draw into {@code Bitmap mBitmap}.
*/
private Canvas mCanvas;
/**
* We create this as a black paint, with a style of FILL but never actually use it.
*/
private Paint mClearPaint;
/**
* Texture name of our label texture.
*/
private int mTextureID;
@SuppressWarnings("unused")
private float mTexelWidth; // Convert texel to U
@SuppressWarnings("unused")
private float mTexelHeight; // Convert texel to V
/**
* {@code u} (x) coordinate to use when adding next label to our texture.
*/
private int mU;
/**
* {@code v} (y) coordinate to use when adding next label to our texture.
*/
private int mV;
/**
* Height of the current line of labels.
*/
private int mLineHeight;
/**
* List of the {@code Label} objects in our texture. A {@code Label} instance contains information
* about the location and size of the label's text in the texture, as well as the cropping
* parameters to use to draw only that {@code Label}.
*/
private ArrayList<Label> mLabels = new ArrayList<>();
/**
* Constant used to set our field {@code mState} to indicate that we are just starting the
* creation of our {@code Label} texture and there are no resources that need to be freed if
* our {@code GLSurface} is destroyed.
*/
private static final int STATE_NEW = 0;
/**
* Constant used to set our field {@code mState} to indicate that our {@code initialize} method
* has been called, and we are ready to begin adding labels. We have acquired a texture name
* for our field {@code mTextureID}, bound it to GL_TEXTURE_2D and configured it so there is
* a texture which needs to be freed if our {@code GLSurface} is destroyed.
*/
private static final int STATE_INITIALIZED = 1;
/**
* Constant used to set our field {@code mState} to indicate that our {@code beginAdding} method
* has been called, and we are ready to add a label (or an additional label). {@code initialize}
* was called before us, and we have allocated a {@code Bitmap} for our field {@code Bitmap mBitmap}
* so there is some needed if our {@code GLSurface} is destroyed.
*/
private static final int STATE_ADDING = 2;
/**
* Constant used to set our field {@code mState} to indicate that our {@code beginDrawing} method
* has been called and we are in the process of drawing the various {@code Label} objects located
* in our texture.
*/
private static final int STATE_DRAWING = 3;
/**
* State that our {@code LabelMaker} instance is in, one of the above constants. It is used by
* our method {@code checkState} to make sure that a state change is "legal", and also by our
* method {@code shutdown} to make sure that our texture is deleted when our surface has been
* destroyed (a texture will only have been allocated if {@code mState>STATE_NEW}).
*/
private int mState;
/**
* Create a label maker. For maximum compatibility with various OpenGL ES implementations, the
* strike width and height must be powers of two, We want the strike width to be at least as
* wide as the widest window. First we initialize our field {@code boolean mFullColor} to our
* parameter {@code boolean fullColor}, {@code int mStrikeWidth} to {@code int strikeWidth}, and
* {@code int mStrikeHeight} to {@code int strikeHeight}. We configure 3 fields which are never
* used: {@code mTexelWidth}. {@code mTexelHeight}, and {@code mPaint}. Finally we set our field
* {@code int mState} to STATE_NEW (in this state we do not yet have a texture that will need to
* be freed if our surface is destroyed, but we are ready to begin building our label texture).
*
* @param fullColor true if we want a full color backing store (4444),
* otherwise we generate a grey L8 backing store.
* @param strikeWidth width of strike
* @param strikeHeight height of strike
*/
public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) {
mFullColor = fullColor;
mStrikeWidth = strikeWidth;
mStrikeHeight = strikeHeight;
mTexelWidth = (float) (1.0 / mStrikeWidth); // UNUSED
mTexelHeight = (float) (1.0 / mStrikeHeight); // UNUSED
mClearPaint = new Paint();
mClearPaint.setARGB(0, 0, 0, 0);
mClearPaint.setStyle(Style.FILL);
mState = STATE_NEW;
}
/**
* Call to initialize the class. Call whenever the surface has been created. First we set our
* field {@code int mState} to STATE_INITIALIZED (in this state we have generated a texture name,
* bound that texture to GL_TEXTURE_2D and configured it to our liking, but no image data has
* been uploaded yet). Next we generate a texture name and save it in our field {@code int mTextureID}.
* <p>
* We bind the texture {@code mTextureID} to the target GL_TEXTURE_2D (GL_TEXTURE_2D becomes an
* alias for our texture), and set both the texture parameters GL_TEXTURE_MIN_FILTER and
* GL_TEXTURE_MAG_FILTER of GL_TEXTURE_2D to GL_NEAREST (uses the value of the texture element
* that is nearest (in Manhattan distance) to the center of the pixel being textured when the
* pixel being textured maps to an area greater than one texture element, as well as when the
* the pixel being textured maps to an area less than or equal to one texture element). We set
* the texture parameters GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T of GL_TEXTURE_2D both to
* GL_CLAMP_TO_EDGE (when the fragment being textured is larger than the texture, the texture
* elements at the edges will be used for the rest of the fragment).
* <p>
* Finally we set the texture environment parameter GL_TEXTURE_ENV_MODE of the texture environment
* GL_TEXTURE_ENV to GL_REPLACE (the texture will replace whatever was in the fragment).
*
* @param gl the gl interface
*/
public void initialize(GL10 gl) {
mState = STATE_INITIALIZED;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
// Use Nearest for performance.
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
}
/**
* Called when the surface we were labeling has been destroyed and a new surface is being created
* so that the the label texture used by this instance of {@code LabelMaker} can be deleted. To
* do this if we have already passed to a state where a texture name has been allocated by the
* hardware ({@code mState>STATE_NEW}) we must delete our texture {@code int mTextureID} and
* move our state field {@code int mState} to the state STATE_NEW (ready to start building a new
* label texture).
*
* @param gl the gl interface
*/
public void shutdown(GL10 gl) {
if (gl != null) {
if (mState > STATE_NEW) {
int[] textures = new int[1];
textures[0] = mTextureID;
gl.glDeleteTextures(1, textures, 0);
mState = STATE_NEW;
}
}
}
/**
* Call before adding labels, and after calling {@code initialize}. Clears out any existing labels.
* First we call {@code checkState} to make sure we are currently in STATE_INITIALIZED, and if so
* changing to state STATE_ADDING. Next we clear our current list of {@code Label} objects contained
* in {@code ArrayList<LabelMaker.Label> mLabels}. We reset the texture coordinates for our next
* label {@code int mU} and {@code int mV}, and set the height of the current line {@code int mLineHeight}
* to 0. We set {@code Bitmap.Config config} to ARGB_4444 if our field {@code boolean mFullColor}
* is true, or to ALPHA_8 if it is false. Then we initialize our field {@code Bitmap mBitmap} with
* a new instance of {@code Bitmap} using {@code config} which is {@code mStrikeWidth} pixels by
* {@code mStrikeHeight} pixels. We initialize {@code Canvas mCanvas} with a canvas which will use
* {@code mBitmap} to draw to, then set the entire {@code mBitmap} to black.
*
* @param gl the gl interface UNUSED
*/
@SuppressWarnings("UnusedParameters")
public void beginAdding(GL10 gl) {
checkState(STATE_INITIALIZED, STATE_ADDING);
mLabels.clear();
mU = 0;
mV = 0;
mLineHeight = 0;
Bitmap.Config config = mFullColor ?
Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8;
mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config);
mCanvas = new Canvas(mBitmap);
mBitmap.eraseColor(0);
}
/**
* Call to add a label, convenience function to call the full argument {@code add} with a null
* {@code Drawable background} and {@code winWidth} and {@code minHeight} both equal to 0. We
* simply supply a null for {@code Drawable background} and pass the call on.
*
* @param gl the gl interface
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, String text, Paint textPaint) {
return add(gl, null, text, textPaint);
}
/**
* Call to add a label, convenience function to call the full argument {@code add} with
* {@code winWidth} and {@code minHeight} both equal to 0. We simply supply 0 for both
* {@code int minWidth} and {@code int minHeight} and pass the call on.
*
* @param gl the gl interface
* @param background background {@code Drawable} to use
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, String text, Paint textPaint) {
return add(gl, background, text, textPaint, 0, 0);
}
/**
* Call to add a label UNUSED
*
* @param gl the gl interface
* @param background background {@code Drawable} to use
* @param minWidth minimum width of label
* @param minHeight minimum height of label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, int minWidth, int minHeight) {
return add(gl, background, null, null, minWidth, minHeight);
}
/**
* Call to add a label. First we call our method {@code checkState} to make sure we are in the
* state STATE_ADDING (our method {@code beginAdding} has been called). Next we determine if
* we have a {@code background} to draw {@code background != null}) saving the result to
* {@code boolean drawBackground}, and determine if we have text to draw ({@code text != null}
* and {@code textPaint != null}) saving the result to {@code boolean drawText}.
* <p>
* We allocate a new instance for {@code Rect padding} and if we have a background that needs to
* be drawn we fetch the padding insets for {@code background} to {@code padding}, set the input
* parameter {@code minWidth} to the max of {@code minWidth} and the minimum width of the drawable
* {@code background}, and set the input parameter {@code minHeight} to the max of {@code minHeight}
* and the minimum height of the drawable {@code background}.
* <p>
* Next we set {@code int ascent}, {@code int descent} and {@code int measuredTextWidth} all to
* 0, and if we have text that needs drawing we set {@code int ascent} to the ceiling value of
* the highest ascent above the baseline for the current typeface and text size of the parameter
* {@code Paint textPaint}, set {@code int descent} to the ceiling value of the lowest descent
* below the baseline for the current typeface and text size of the parameter {@code Paint textPaint},
* and set {@code {@code measuredTextWidth}} to the ceiling value of the length of {@code text}.
* <p>
* We now perform a bunch of boring calculations to determine where on the {@code Canvas mCanvas}
* we are to draw our background and/or text, and if we have a background we draw the background
* drawable at that position, and if we have text we draw the text at that position.
* <p>
* Having done so, we update our field {@code mU} to point to the next u (x) coordinate we can
* use, {@code mV} to point to the next v (y) coordinate we can use, and {@code mLineHeight} to
* the (possibly new) height of our current line.
* <p>
* Finally we add a new instance of {@code Label} to {@code ArrayList<Label> mLabels} with the
* information that will be needed to locate, crop and draw the label we just drew, and return
* the index of this {@code Label} object to the caller.
*
* @param gl the gl interface UNUSED
* @param background background {@code Drawable} to use
* @param text the text of the label
* @param textPaint the paint of the label
* @param minWidth minimum width of label
* @param minHeight minimum height of label
* @return index of the {@code Label} in {@code ArrayList<Label> mLabels}, the {@code Label}
* object will be used to locate, measure, crop and draw the label.
*/
@SuppressWarnings("UnusedParameters")
public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) {
checkState(STATE_ADDING, STATE_ADDING);
boolean drawBackground = background != null;
boolean drawText = (text != null) && (textPaint != null);
Rect padding = new Rect();
if (drawBackground) {
background.getPadding(padding);
minWidth = Math.max(minWidth, background.getMinimumWidth());
minHeight = Math.max(minHeight, background.getMinimumHeight());
}
int ascent = 0;
int descent = 0;
int measuredTextWidth = 0;
if (drawText) {
// Paint.ascent is negative, so negate it.
ascent = (int) Math.ceil(-textPaint.ascent());
descent = (int) Math.ceil(textPaint.descent());
measuredTextWidth = (int) Math.ceil(textPaint.measureText(text));
}
int textHeight = ascent + descent;
int textWidth = Math.min(mStrikeWidth, measuredTextWidth);
int padHeight = padding.top + padding.bottom;
int padWidth = padding.left + padding.right;
int height = Math.max(minHeight, textHeight + padHeight);
int width = Math.max(minWidth, textWidth + padWidth);
int effectiveTextHeight = height - padHeight;
int effectiveTextWidth = width - padWidth;
int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2;
int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2;
// Make changes to the local variables, only commit them
// to the member variables after we've decided not to throw
// any exceptions.
int u = mU;
int v = mV;
int lineHeight = mLineHeight;
if (width > mStrikeWidth) {
width = mStrikeWidth;
}
// Is there room for this string on the current line?
if (u + width > mStrikeWidth) {
// No room, go to the next line:
u = 0;
v += lineHeight;
lineHeight = 0;
}
lineHeight = Math.max(lineHeight, height);
if (v + lineHeight > mStrikeHeight) {
throw new IllegalArgumentException("Out of texture space.");
}
@SuppressWarnings("unused")
int u2 = u + width;
int vBase = v + ascent;
@SuppressWarnings("unused")
int v2 = v + height;
if (drawBackground) {
background.setBounds(u, v, u + width, v + height);
background.draw(mCanvas);
}
if (drawText) {
mCanvas.drawText(text,
u + padding.left + centerOffsetWidth,
vBase + padding.top + centerOffsetHeight,
textPaint);
}
// We know there's enough space, so update the member variables
mU = u + width;
mV = v;
mLineHeight = lineHeight;
mLabels.add(new Label(width, height, ascent, u, v + height, width, -height));
return mLabels.size() - 1;
}
/**
* Call to end adding labels. Must be called before drawing starts. First we call our method
* {@code checkState} to verify that we are in the STATE_ADDING state, and if so transition back
* to the STATE_INITIALIZED state. Next we bind our texture name {@code mTextureID} to the
* GL_TEXTURE_2D target, upload our {@code Bitmap mBitmap} to the GPU, recycle our {@code mBitmap}
* and null our both {@code mBitmap} and {@code mCanvas} so they can be garbage collected.
*
* @param gl the gl interface
*/
public void endAdding(GL10 gl) {
checkState(STATE_ADDING, STATE_INITIALIZED);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
// Reclaim storage used by bitmap and canvas.
mBitmap.recycle();
mBitmap = null;
mCanvas = null;
}
/**
* Get the width in pixels of a given label. Convenience getter for the {@code width} field of
* the {@code Label} at index value {@code labelID} in our {@code ArrayList<Label> mLabels}.
*
* @param labelID index of label
* @return the width in pixels
*/
public float getWidth(int labelID) {
return mLabels.get(labelID).width;
}
/**
* Get the height in pixels of a given label. Convenience getter for the {@code height} field of
* the {@code Label} at index value {@code labelID} in our {@code ArrayList<Label> mLabels}.
*
* @param labelID index of label
* @return the height in pixels
*/
public float getHeight(int labelID) {
return mLabels.get(labelID).height;
}
/**
* Get the baseline of a given label. That's how many pixels from the top of the label to the
* text baseline. (This is equivalent to the negative of the label's paint's ascent.) UNUSED
*
* @param labelID index of label
* @return the baseline in pixels.
*/
@SuppressWarnings("unused")
public float getBaseline(int labelID) {
return mLabels.get(labelID).baseline;
}
/**
* Begin drawing labels. Sets the OpenGL state for rapid drawing. First we call our method
* {@code checkState} to verify that we are in STATE_INITIALIZED state and if so to transition
* to STATE_DRAWING state. Next we bind our texture name {@code mTextureID} to the target
* GL_TEXTURE_2D, set the shade model to GL_FLAT and enable the server side capability GL_BLEND
* (blend the computed fragment color values with the values in the color buffers). We call the
* method {@code glBlendFunc} to set the source blending function to GL_SRC_ALPHA, and the
* destination blending function to GL_ONE_MINUS_SRC_ALPHA (modifies the incoming color by its
* associated alpha value and modifies the destination color by one minus the incoming alpha
* value. The sum of these two colors is then written back into the framebuffer.) We then call
* the method {@code glColor4x} to set the primitive’s opacity to 1.0 in GLfixed format.
* <p>
* We set the current matrix to the projection matrix GL_PROJECTION, push the current projection
* matrix to its stack, load GL_PROJECTION with the identity matrix, and multiply it with the
* orthographic matrix that has the left clipping plane at 0, the right clipping plane at
* {@code viewWidth}, the bottom clipping plane at 0, the top clipping plane at {@code viewHeight},
* the near clipping plane at 0.0, and the far clipping plane at 1.0
* <p>
* We then set the current matrix to the model view matrix GL_MODELVIEW, push the current model
* view matrix to its stack, load GL_MODELVIEW with the identity matrix, and multiply it by a
* translation matrix which moves both x and y coordinates by 0.375 in order to promote consistent
* rasterization.
*
* @param gl the gl interface
* @param viewWidth view width
* @param viewHeight view height
*/
public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
checkState(STATE_INITIALIZED, STATE_DRAWING);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPushMatrix();
gl.glLoadIdentity();
// Magic offsets to promote consistent rasterization.
gl.glTranslatef(0.375f, 0.375f, 0.0f);
}
/**
* Draw a given label at a given x,y position, expressed in pixels, with the lower-left-hand
* corner of the view being (0,0). First we call our method {@code checkState} to make sure we
* are in the STATE_DRAWING state. We fetch the {@code Label} object for the label we are to
* draw to {@code Label label}, enable the server side capability GL_TEXTURE_2D, and set the
* cropping rectangle of GL_TEXTURE_2D to the contents of the {@code label.mCrop} field. Then
* we call glDrawTexiOES to draw the cropped area of the texture at {@code (x,y,z)} using the
* width and height specified by the {@code label.width} field, and the {@code label.height}
* field.
*
* @param gl the gl interface
* @param x x coordinate to draw at
* @param y y coordinate to draw at
* @param labelID index of {@code Label} in the list {@code ArrayList<Label> mLabels} to draw
*/
public void draw(GL10 gl, float x, float y, int labelID) {
checkState(STATE_DRAWING, STATE_DRAWING);
Label label = mLabels.get(labelID);
gl.glEnable(GL10.GL_TEXTURE_2D);
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0);
((GL11Ext) gl).glDrawTexiOES((int) x, (int) y, 0, (int) label.width, (int) label.height);
}
/**
* Ends the drawing and restores the OpenGL state. First we call our method {@code checkState} to
* make sure we are in the STATE_DRAWING state and if so to transition to the STATE_INITIALIZED
* state. We disable the server side capability GL_BLEND, set the current matrix to the projection
* matrix GL_PROJECTION and pop the old matrix off of its stake, and then set the current matrix
* to the model view matrix GL_MODELVIEW and pop the old matrix off of its stake.
*
* @param gl the gl interface
*/
public void endDrawing(GL10 gl) {
checkState(STATE_DRAWING, STATE_INITIALIZED);
gl.glDisable(GL10.GL_BLEND);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPopMatrix();
}
/**
* Throws an IllegalArgumentException if we are not currently in the state {@code oldState}, and
* if we are in that state transitions to {@code newState}.
*
* @param oldState state we need to be in to use the method we are called from
* @param newState state to transition to iff we were in {@code oldState}
*/
private void checkState(int oldState, int newState) {
if (mState != oldState) {
throw new IllegalArgumentException("Can't call this method now.");
}
mState = newState;
}
/**
* Class that contains the information needed to crop and draw a label contained in the current
* GL_TEXTURE_2D label texture.
*/
private static class Label {
/**
* width of the label in pixels
*/
public float width;
/**
* height of the label in pixels
*/
public float height;
/**
* Unused, but set to the ascent value of the font and font size of the paint used to draw
*/
public float baseline;
/**
* Defines the location and size of the label in the texture, it is used to crop the texture
* so that only this label is used for drawing.
*/
public int[] mCrop;
/**
* Our constructor. We simply initialize our fields using our input parameters.
*
* @param width width of our label
* @param height height of our label
* @param baseLine baseline of our label
* @param cropU u coordinate of left side of label in texture
* @param cropV v coordinate of top of texture
* @param cropW width of label in texture
* @param cropH height of the crop region, the negative value in our case specifies that the
* region lies below the coordinate (u,v) in the texture image.
*/
public Label(float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) {
this.width = width;
this.height = height;
this.baseline = baseLine;
int[] crop = new int[4];
crop[0] = cropU;
crop[1] = cropV;
crop[2] = cropW;
crop[3] = cropH;
mCrop = crop;
}
}
}
| 29,065 | 0.652514 | 0.643705 | 631 | 45.058636 | 35.318447 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581616 | false | false |
5
|
78b824cef9151a5bc1e0284dba33bf28566bb827
| 36,009,005,848,831 |
7245a0d76f44995a46134200ef27c4f89be903fd
|
/src/blogic/PersonDM.java
|
d706333384dca3973da75e5ef8e94f44d3d2fc86
|
[] |
no_license
|
AndreyOSGit/DBtable
|
https://github.com/AndreyOSGit/DBtable
|
107bd613ffa71d992c5da97235c73245764a6fb9
|
56121d6ca380a7e5b915c8d4f944c46ab81992fd
|
refs/heads/master
| 2020-04-04T18:39:45.164000 | 2018-11-11T20:02:34 | 2018-11-11T20:02:34 | 156,172,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package blogic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.activation.ActivationSystem;
import java.util.ArrayList;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.hibernate.mapping.Table;
import dal.PersonDaoH2;
import dal.iPersonDao;
import view.PPanel;
public class PersonDM extends AbstractTableModel {
private ArrayList<Person> pp;
iPersonDao dao;
PersonDaoH2 daoh2;
public PPanel panelBD;
public ActionCreate aCreate;
public ActionRead aRead;
public ActionDelete aDelete;
public ActionUpdate aUpdate;
public PersonDM() {
pp = new ArrayList<Person>();
}
public PersonDM(PPanel pPanel) {
pp = new ArrayList<Person>();
panelBD = pPanel;
aCreate = new ActionCreate();
aRead = new ActionRead();
aDelete = new ActionDelete();
aUpdate = new ActionUpdate();
}
// public static getPresonDM getInstance()
// {
// if (instance == null)
// {
// instance = new PCommand();
// }
//
// return instance;
// }
public ActionCreate getaCreate() {
return aCreate;
}
public void setaCreate(ActionCreate aCreate) {
this.aCreate = aCreate;
}
public ActionRead getaRead() {
return aRead;
}
public void setaRead(ActionRead aRead) {
this.aRead = aRead;
}
public ActionDelete getaDelete() {
return aDelete;
}
public void setaDelete(ActionDelete aDelete) {
this.aDelete = aDelete;
}
public ActionUpdate getaUpdate() {
return aUpdate;
}
public void setaUpdate(ActionUpdate aUpdate) {
this.aUpdate = aUpdate;
}
public String getColumnName(int index) {
String colName = "";
return colName;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object getValueAt(int row, int cal) {
// TODO Auto-generated method stub
return null;
}
public void setDataInTable(ArrayList<Person> pp) {
Object[] row = { pp.get(0).id
, pp.get(0).firstName
, pp.get(0).lastName
, pp.get(0).age };
DefaultTableModel model = (DefaultTableModel) panelBD.getDataTable().getModel();
model.addRow(row);
}
class ActionCreate implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
daoh2.create(p);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("create");
}
}
class ActionUpdate implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
daoh2.update(p);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("update");
}
}
class ActionRead implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
// pp = daoh2.read();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Person p1 = new Person(1,"Man","Good",33);
pp.set(0, p1);
setDataInTable(pp);
System.out.println("read");
}
}
class ActionDelete implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("delete");
Person p = getPersonaFromUI(panelBD);
try {
daoh2.delete(p);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void select(String cmd)
{
}
private Person getPersonaFromUI(PPanel panelBD)
{
Person p = new Person(
Integer.parseInt( panelBD.getFildeID().getText() ),
panelBD.fildeFirstName.getText(),
panelBD.fildeLastName.getText(),
Integer.parseInt( panelBD.fildeAge.getText() )
);
System.out.println(
Integer.parseInt( panelBD.fildeID.getText() )
+ "|" + panelBD.fildeFirstName.getText()
+ "|" + panelBD.fildeLastName.getText()
+ "|" + Integer.parseInt( panelBD.fildeAge.getText() )
);
return p;
}
//вложенных класса имплиментирующих action listners - слушатели для кнопок CRUD
//Вычитывает из полей данные - потом отправляет данные на запрос из базы
}
|
WINDOWS-1251
|
Java
| 4,497 |
java
|
PersonDM.java
|
Java
|
[
{
"context": "ntStackTrace();\n\t\t\t}\n\t\t\tPerson p1 = new Person(1,\"Man\",\"Good\",33);\n\t\t\tpp.set(0, p1);\n\t\t\tsetDataInTable(",
"end": 3240,
"score": 0.9983091354370117,
"start": 3237,
"tag": "NAME",
"value": "Man"
},
{
"context": "kTrace();\n\t\t\t}\n\t\t\tPerson p1 = new Person(1,\"Man\",\"Good\",33);\n\t\t\tpp.set(0, p1);\n\t\t\tsetDataInTable(pp);\n\t\t",
"end": 3247,
"score": 0.9975847005844116,
"start": 3243,
"tag": "NAME",
"value": "Good"
}
] | null |
[] |
package blogic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.activation.ActivationSystem;
import java.util.ArrayList;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.hibernate.mapping.Table;
import dal.PersonDaoH2;
import dal.iPersonDao;
import view.PPanel;
public class PersonDM extends AbstractTableModel {
private ArrayList<Person> pp;
iPersonDao dao;
PersonDaoH2 daoh2;
public PPanel panelBD;
public ActionCreate aCreate;
public ActionRead aRead;
public ActionDelete aDelete;
public ActionUpdate aUpdate;
public PersonDM() {
pp = new ArrayList<Person>();
}
public PersonDM(PPanel pPanel) {
pp = new ArrayList<Person>();
panelBD = pPanel;
aCreate = new ActionCreate();
aRead = new ActionRead();
aDelete = new ActionDelete();
aUpdate = new ActionUpdate();
}
// public static getPresonDM getInstance()
// {
// if (instance == null)
// {
// instance = new PCommand();
// }
//
// return instance;
// }
public ActionCreate getaCreate() {
return aCreate;
}
public void setaCreate(ActionCreate aCreate) {
this.aCreate = aCreate;
}
public ActionRead getaRead() {
return aRead;
}
public void setaRead(ActionRead aRead) {
this.aRead = aRead;
}
public ActionDelete getaDelete() {
return aDelete;
}
public void setaDelete(ActionDelete aDelete) {
this.aDelete = aDelete;
}
public ActionUpdate getaUpdate() {
return aUpdate;
}
public void setaUpdate(ActionUpdate aUpdate) {
this.aUpdate = aUpdate;
}
public String getColumnName(int index) {
String colName = "";
return colName;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object getValueAt(int row, int cal) {
// TODO Auto-generated method stub
return null;
}
public void setDataInTable(ArrayList<Person> pp) {
Object[] row = { pp.get(0).id
, pp.get(0).firstName
, pp.get(0).lastName
, pp.get(0).age };
DefaultTableModel model = (DefaultTableModel) panelBD.getDataTable().getModel();
model.addRow(row);
}
class ActionCreate implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
daoh2.create(p);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("create");
}
}
class ActionUpdate implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
daoh2.update(p);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("update");
}
}
class ActionRead implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Person p = getPersonaFromUI(panelBD);
try {
// pp = daoh2.read();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Person p1 = new Person(1,"Man","Good",33);
pp.set(0, p1);
setDataInTable(pp);
System.out.println("read");
}
}
class ActionDelete implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("delete");
Person p = getPersonaFromUI(panelBD);
try {
daoh2.delete(p);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void select(String cmd)
{
}
private Person getPersonaFromUI(PPanel panelBD)
{
Person p = new Person(
Integer.parseInt( panelBD.getFildeID().getText() ),
panelBD.fildeFirstName.getText(),
panelBD.fildeLastName.getText(),
Integer.parseInt( panelBD.fildeAge.getText() )
);
System.out.println(
Integer.parseInt( panelBD.fildeID.getText() )
+ "|" + panelBD.fildeFirstName.getText()
+ "|" + panelBD.fildeLastName.getText()
+ "|" + Integer.parseInt( panelBD.fildeAge.getText() )
);
return p;
}
//вложенных класса имплиментирующих action listners - слушатели для кнопок CRUD
//Вычитывает из полей данные - потом отправляет данные на запрос из базы
}
| 4,497 | 0.68041 | 0.67426 | 225 | 18.51111 | 18.009901 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.022222 | false | false |
5
|
ef15e94bd8ea1eb6de8d6148a9e85c69dac03182
| 13,022,340,844,709 |
cc9bc722ac13c50566ad27d2f8a0c97c7835af65
|
/src/com/guushamm/helloworld/HelloWorldActivity.java
|
4314cc3d67d4f380bad12ff462293b386422d16d
|
[] |
no_license
|
GuusHamm/helloWorld
|
https://github.com/GuusHamm/helloWorld
|
95d692c83191c8aac633a26e37e87b117eb87b27
|
f3a6a1cdb3fcf4095560faa5aef85077a3d450ba
|
refs/heads/master
| 2021-01-10T17:44:21.500000 | 2016-02-25T14:06:07 | 2016-02-25T14:06:07 | 52,509,495 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.guushamm.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class HelloWorldActivity extends Activity {
/**
* Called when the activity is first created.
*/
boolean rebelSwitchActivated = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Switch rebelSwitch = (Switch) findViewById(R.id.rebelSwitch);
rebelSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
rebelSwitchActivated = isChecked;
}
});
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!rebelSwitchActivated){
CharSequence text = "Hello World!";
Toast toast = Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG);
toast.show();
}
else {
CharSequence text = "You are such a rebel";
Toast toast = Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
|
UTF-8
|
Java
| 1,344 |
java
|
HelloWorldActivity.java
|
Java
|
[] | null |
[] |
package com.guushamm.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class HelloWorldActivity extends Activity {
/**
* Called when the activity is first created.
*/
boolean rebelSwitchActivated = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Switch rebelSwitch = (Switch) findViewById(R.id.rebelSwitch);
rebelSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
rebelSwitchActivated = isChecked;
}
});
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!rebelSwitchActivated){
CharSequence text = "Hello World!";
Toast toast = Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG);
toast.show();
}
else {
CharSequence text = "You are such a rebel";
Toast toast = Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
| 1,344 | 0.738095 | 0.738095 | 49 | 26.428572 | 25.020807 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.346939 | false | false |
5
|
46434b250ebe90f8d37ef73195e33f27203c5540
| 25,031,069,402,344 |
ed44e68a9efeeed455062ecaa57e25b3200ee5ed
|
/ltudjava_bt2/src/Main.java
|
152ef511c546d8ce4a0aa5226a493a4a5bf6569f
|
[] |
no_license
|
caophuccp/student-management
|
https://github.com/caophuccp/student-management
|
d37f4e386f5a6e469f376795fe378821e7b430fd
|
7cafd0fe0f75653bf2acf4515cea6416633f5d3a
|
refs/heads/master
| 2022-11-05T13:59:36.693000 | 2020-07-05T08:01:33 | 2020-07-05T08:01:33 | 273,207,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import hibernate.java.HibernateUtil;
import screens.Application;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
System.setProperty("apple.awt.application.name", "FAPP");
HibernateUtil.getSessionFactory();
Application app = new Application();
app.start();
}
}
|
UTF-8
|
Java
| 337 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import hibernate.java.HibernateUtil;
import screens.Application;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
System.setProperty("apple.awt.application.name", "FAPP");
HibernateUtil.getSessionFactory();
Application app = new Application();
app.start();
}
}
| 337 | 0.67359 | 0.67359 | 13 | 24.923077 | 19.687799 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false |
5
|
e891a741ee90fbae49aa81b3f7bed4d7dcfe5ec3
| 24,919,400,275,577 |
09447c7efba8ecd7ac854cc442d38f661b5abd78
|
/src/edu/pjwstk/demo/datastore/SBAStoreForJavaObjects.java
|
42c0312af1d0f793876f1b40678ecf2bebdda40c
|
[] |
no_license
|
mtomkowicz/JSP_1_AST
|
https://github.com/mtomkowicz/JSP_1_AST
|
acf86c5e8b3ef36f0aa28645afe0ee1ab7d76990
|
fd7e30ca09bedf5d94598d961f6dec9cba032092
|
refs/heads/master
| 2021-01-15T13:34:57.899000 | 2014-03-13T22:16:21 | 2014-03-13T22:16:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.pjwstk.demo.datastore;
import edu.pjwstk.demo.result.BagResult;
import edu.pjwstk.demo.result.ReferenceResult;
import edu.pjwstk.jps.datastore.IOID;
import edu.pjwstk.jps.datastore.ISBAObject;
import edu.pjwstk.jps.result.IBagResult;
import edu.pjwstk.jps.result.ISingleResult;
import java.util.ArrayList;
import java.util.Collection;
public class SBAStoreForJavaObjects extends SBAStore implements ISBAStoreJavaObjects {
@Override
public IOID getLastOID() {
return new OID(lastGeneratedId);
}
@Override
public IBagResult getBag(String name) {
Collection<ISingleResult> results = new ArrayList<>();
for (ISBAObject o : hash.values())
{
if (o.getName() == name){
results.add(new ReferenceResult(o.getOID()));
}
}
return new BagResult(results);
}
}
|
UTF-8
|
Java
| 877 |
java
|
SBAStoreForJavaObjects.java
|
Java
|
[] | null |
[] |
package edu.pjwstk.demo.datastore;
import edu.pjwstk.demo.result.BagResult;
import edu.pjwstk.demo.result.ReferenceResult;
import edu.pjwstk.jps.datastore.IOID;
import edu.pjwstk.jps.datastore.ISBAObject;
import edu.pjwstk.jps.result.IBagResult;
import edu.pjwstk.jps.result.ISingleResult;
import java.util.ArrayList;
import java.util.Collection;
public class SBAStoreForJavaObjects extends SBAStore implements ISBAStoreJavaObjects {
@Override
public IOID getLastOID() {
return new OID(lastGeneratedId);
}
@Override
public IBagResult getBag(String name) {
Collection<ISingleResult> results = new ArrayList<>();
for (ISBAObject o : hash.values())
{
if (o.getName() == name){
results.add(new ReferenceResult(o.getOID()));
}
}
return new BagResult(results);
}
}
| 877 | 0.686431 | 0.686431 | 32 | 26.40625 | 21.898714 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40625 | false | false |
5
|
62eff970e0245438a85486f7d33394f5f18ce1fb
| 28,784,870,821,139 |
8e798a941596d381f351b8e6691060c526e0ea15
|
/src/com/gy/DecoratorMode.java
|
bc14a34d55ffaec6fbe3310f864e3672e2e6a308
|
[] |
no_license
|
gy13477000/design_mode_test
|
https://github.com/gy13477000/design_mode_test
|
9c7a925b18eb8d928aed9d1604d2afa648615299
|
8323b2e06919ccf75ccba1db6cb83dce67f11b46
|
refs/heads/master
| 2022-11-17T00:16:43.797000 | 2020-07-08T07:32:34 | 2020-07-08T07:32:34 | 277,773,170 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gy;
// 装饰器模式:动态地将责任附加到对象上,若要扩展功能,装饰着提供了比继承更有弹性的替代方案。
// java中的io类大量使用此模式
public class DecoratorMode {
public static void main(String[] args) {
Drink blackCoffee = new BlackCoffee();
Drink suggerBlackCoffee = new SuggerBlackCoffee(blackCoffee);
Drink dubbleSuggerBlackCoffee = new SuggerBlackCoffee(suggerBlackCoffee);
System.out.println(blackCoffee.getName() + blackCoffee.cost());
System.out.println(suggerBlackCoffee.getName() + suggerBlackCoffee.cost());
System.out.println(dubbleSuggerBlackCoffee.getName() + dubbleSuggerBlackCoffee.cost());
}
}
class SuggerBlackCoffee implements Drink {
private Drink blackCoffee;
public SuggerBlackCoffee(Drink drink) {
this.blackCoffee = blackCoffee;
}
@Override
public String getName() {
return blackCoffee.getName() + ",加糖";
}
@Override
public double cost() {
return blackCoffee.cost() + 0.5;
}
}
interface Drink {
String getName();
double cost();
}
class BlackCoffee implements Drink {
@Override
public String getName() {
return "黑咖啡";
}
@Override
public double cost() {
return 8;
}
}
|
UTF-8
|
Java
| 1,336 |
java
|
DecoratorMode.java
|
Java
|
[] | null |
[] |
package com.gy;
// 装饰器模式:动态地将责任附加到对象上,若要扩展功能,装饰着提供了比继承更有弹性的替代方案。
// java中的io类大量使用此模式
public class DecoratorMode {
public static void main(String[] args) {
Drink blackCoffee = new BlackCoffee();
Drink suggerBlackCoffee = new SuggerBlackCoffee(blackCoffee);
Drink dubbleSuggerBlackCoffee = new SuggerBlackCoffee(suggerBlackCoffee);
System.out.println(blackCoffee.getName() + blackCoffee.cost());
System.out.println(suggerBlackCoffee.getName() + suggerBlackCoffee.cost());
System.out.println(dubbleSuggerBlackCoffee.getName() + dubbleSuggerBlackCoffee.cost());
}
}
class SuggerBlackCoffee implements Drink {
private Drink blackCoffee;
public SuggerBlackCoffee(Drink drink) {
this.blackCoffee = blackCoffee;
}
@Override
public String getName() {
return blackCoffee.getName() + ",加糖";
}
@Override
public double cost() {
return blackCoffee.cost() + 0.5;
}
}
interface Drink {
String getName();
double cost();
}
class BlackCoffee implements Drink {
@Override
public String getName() {
return "黑咖啡";
}
@Override
public double cost() {
return 8;
}
}
| 1,336 | 0.663383 | 0.66092 | 53 | 21.962265 | 24.201172 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.301887 | false | false |
5
|
75de980ac7349e551669ef68eae179c91c83d483
| 14,207,751,878,869 |
8c3285346cbfb70350b7542e5ec411bb6d0ed80d
|
/java/simulator/src/main/java/com/hazelcast/simulator/test/annotations/TimeStep.java
|
3cc89193a2cfacad5be4307baa6893bc77a1b53c
|
[
"Apache-2.0"
] |
permissive
|
hazelcast/hazelcast-simulator
|
https://github.com/hazelcast/hazelcast-simulator
|
5627d80c81e1f840127a1c41d290fb3538beb0e0
|
5d786228966d76863fe8accbdf222f7650364339
|
refs/heads/master
| 2023-08-25T10:46:18.508000 | 2023-08-11T13:38:39 | 2023-08-11T13:38:39 | 11,445,479 | 83 | 71 |
Apache-2.0
| false | 2023-09-14T10:10:00 | 2013-07-16T09:18:54 | 2023-08-16T15:57:09 | 2023-09-14T10:09:59 | 19,627 | 83 | 67 | 109 |
Java
| false | false |
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.simulator.test.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Needs to be placed on a load generating method of a test.
*
* A method should contain either:
* <ol>
* <li>{@link Run}</li>
* <li>{@link TimeStep}</li>
* </ol>
* The {@link TimeStep} is the one that should be picked by default. It is the most powerful and it relies on code generation
* to create a runner with the least amount of overhead. The {@link TimeStep} looks a lot like the @Benchmark from JMH.
*
* <h1>Probabilities</h1>
* THe simplest timestep test has a single timestep method, but in reality there is often some kind of ratio, e.g. 10% write
* and 90% read. This can be done configuring probability:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=0.10)
* public void write(){
*
* }
* }
* </pre>
* The sum of the probabilities needs to be 1.
*
* For backwards compatibility reasons one of the timestep methods can be the 'default' by assigning -1 to its probability.
* It means that whatever remains, will be given to that method. For example the above 90/10 could also be configured using:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=-1)
* public void write(){
*
* }
* }
* </pre>
*
* <h1>Thread state</h1>
* In a lot of cases a timestep thread needs to have some thread specific context e.g. counters. THe thread-state needs to be
* a public class with a public no arg constructor, or a constructor receiving the test instance.
*
* <pre>
* {@code
* @TimeStep
* public void timestep(ThreadState context){
* ...
* }
*
* public class ThreadContext{
* int counter;
* }
* }
* </pre>
* Each thread will get its own instance of the ThreadContext. In practice you probably want to extend from the
* {@link com.hazelcast.simulator.test.BaseThreadState} since it has convenience functions for randomization. The Thread state
* can be used on the TimeStep methods, but also in the {@link BeforeRun} and {@link AfterRun} methods where the {@link BeforeRun}
* can take of initialization, and the {@link AfterRun} can take care of some post processing. For a full example see the
* AtomicLongTest.
*
* <h1>Code generation</h1>
* The timestep based tests rely on code generation for the actual code to call the timestep methods. This prevents the need
* for reflection and and the motto is that you should not pay for a feature if it isn't used. For example where logging is not
* configured, no logging code is generated. If there is only a single timestep method, then there is no randomization. This way
* we can reduce the overhead by the benchmark framework to the bare minimum. The generated code of the TimeStepLoop can be
* found in the worker directory.
*
* <h1>Execution groups</h1>
* Normally all timestep methods from a test belong to the same execution group; meaning that there is a group of threads will
* will call each timestep method using some distribution. But in some cases this is unwanted, e.g. a typical producer/consumer
* test. In such cases one can make use of execution groups:
* <pre>
* {@code
* @TimeStep(executionGroup="producer")
* public void produce(){
* ...
* }
*
* @TimeStep(executionGroup="consumer")
* public void consume(){
* ...
* }
* }
* </pre>
* In this case there are 2 execution groups: producer and consumer and each will get their own threads where the producer
* timestep threads calls methods from the 'producer' execution group, and the consumer timestep threads, call methods from
* the 'consumer' execution-group.
*
* Most of the features are configured per timestep group and by default the group "" is used. So you can configure probabilities,
* metronomes, thread context etc per execution group.
*
* <h1>Threadcount</h1>
* A timestep test run multiple timestep threads in parallel. This can be configured using the threadCount property:
* <pre>
* {@code
* class=yourtest
* threadCount=1
* }
* </pre>
* Threadcount defaults to 10.
*
* If there are multiple execution groups, each group can be configured independently. Imagine there is some kind of producer
* consumer test, then each execution group is configured using:
* <pre>
* {@code
* class=yourtest
* producerThreadCount=2
* consumerThreadCount=4
* }
* </pre>
*
* <h1>Iterations</h1>
* TimeStep based tests have out of the box support for running a given number of iterations. This can be configured using
* <pre>
* {@code
* class=yourtest
* iterations=1000000
* }
* </pre>
* This will run 1M iterations per worker-thread.
*
* Each exception group can be configured independently. So imagine there is a producer and consumer execution group, then
* the producers can be configured using:
* <pre>
* {@code
* class=yourtest
* producerIterations=1000000
* }
* </pre>
* In this example the producer has a configured number of iterations for warmup and running, the consumer has no such limitation.
*
* <h1>Stopping a timestep thread</h1>
* A Timestep thread can also stop itself by throwing the {@link com.hazelcast.simulator.test.StopException}. This doesn't lead
* to an error, it is just a signal for the test that the thread is ready.
*
* <h1>Probes</h1>
* By default every timestep method will get its own probe. E.g.
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=0.10)
* public void write(){
* ...
* }
* }
* </pre>
* In this case 2 probes that keep track of writer or read. So by default tracking latency is taken care of by the timestep
* runner. In some cases, especially with async testing, the completion of the system being tested, doesn't align with the
* completion of the timestep method. So the latency can't be determined by the timestep runner. In such cases one can
* get access to the Probe and startTime like this:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void asyncCall(Probe probe, @StartNanos long startNanos){
* ...
* }
* }
* </pre>
* One can decide to e.g. make use of an completion listener to determine when the call completed and record the right latency
* on the probe.
*
* Keep in mind that the current iteration (and therefor numbers like throughput) are based on completion of the timestep method,
* but that doesn't need to mean completion of the async call.
*
* <h1>Logging</h1>
* By default a timestep based thread will not log anything during the run/warmup period. But sometimes some logging is required,
* e.g. when needing to do some debugging. There are 2 out of the box options for logging:
* <ol>
* <li>frequency based: e.g. every 1000th iteration</li>
* <li>time rate based: e.g. every 100ms</li>
* </ol>
*
* <h2>Frequency based logging</h2>
* With frequency based logging each timestep thread will add a log entry every so many calls. Frequency based logging can be
* configured using:
* <pre>
* {@code
* class=yourtest
* logFrequency=10000
* }
* </pre>
* Meaning that each timestep thread will log an entry every 10000th calls.
*
* Frequency based logging can be configured per execution group. If there is an execution group producer, then the logFrequency
* can be configured using:
* <pre>
* {@code
* class=yourtest
* producerLogFrequency=10000
* }
* </pre>
*
* <h2>Time rate based logging</h2>
* The time rate based logging allows for a log entry per timestep thread to be written at a maximum rate. E.g. if we want to see
* at most 1 time a second a log entry, we can configure the test:
* <pre>
* {@code
* class=yourtest
* logRateMs=1000
* }
* </pre>
* Time rate based logging is very useful to prevent overloading the system with log entries.
*
* Time rate based logging can be configured per execution group. If there is an execution group producer, then the logRate can
* be configured using:
* <pre>
* {@code
* class=yourtest
* producerRateMs=1000
* }
* </pre>
*
* <h1>Latency testing</h1>
* For Latency testing you normally want to rate the number of requests per second. This can be done by setting the interval
* property. This property configures the interval between requests and is independent of thread count. So if interval is set
* to 10ms, you get 100 operations/second. If there are 2 threads, each thread will do 1 request every 20ms. If there are
* 4 threads, each thread will do 1 request every 40ms.
*
* Example:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* threadCount=2
* }
* </pre>
* In this example there will be 2 threads, that together will make 1 request every 10ms (so after 1 second, 100 requests have
* been made). Interval can be configured with ns, us, ms, s, m, h. Keep in mind that the interval is per machine, so if the
* interval is 10ms and there are 2 machines, on average there is 1 request every 5ms.
*
* The interval can also be configured using the ratePerSecond property:
* <pre>
* {@code
* class=yourtest
* ratePerSecond=100
* threadCount=2
* }
* </pre>
* It is converted to interval under the hood, so there is no difference at runtime. ratePerSecond, just like interval, is
* independent of the number of threads. If you have 200 requests per second, and 2 threads, each thread is going to do
* 100 requests/second. With 4 threads, each thread is going to do 50 requests/second.
*
* If there are multiple execution groups, the interval can be configured using:
* <pre>
* {@code
* class=yourtest
* producerInterval=10ms
* producerThreadCount=2
* }
* </pre>
*
* <h1>Stress testing</h1>
* With stress testing you try to find the highest performance until you run into the breaking point of the system. In Simulator
* this is done by increasing the number of threads until the `threadCount` number of threads are all running. This can be done
* using the rampupSeconds:
* <pre>
* {@code
* class=yourtest
* threadCount=10
* rampupSeconds=60
* }
* </pre>
* In this case every 6 seconds a new thread is added to the test until the maximum number of 10 threads; so after 60 seconds
* all the threads are running.
*
* <h1>Measure latency</h1>
* In some cases measuring the latency can be very expensive due to contention on HDR or because reading out the clock
* can be expensive on certain environments (e.g. EC2 with XEN clock. By adding 'measureLatency=false' to the test,
* Simulator will not measure latency.
*
* <h2>Coordinated omission</h2>
* A lot of testing frameworks are suffering from a problem called coordinated omission:
* https://www.infoq.com/presentations/latency-pitfalls
* By default coordinated omission is prevented by determining the latency based on the expected start-time instead of the actual
* start time. This is all done under the hood and not something you need to worry about. In some cases you want to see the
* impact of coordinated omission and you can allow for it using:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* accountForCoordinatedOmission=false
* }
* </pre>
*
* <h2>Different flavors of metronomes</h2>
* Internally a {@link com.hazelcast.simulator.worker.metronome.Metronome} is used to control the rate of requests. There are
* currently 3 out of the box implementations:
* <ol>
* <li>{@link com.hazelcast.simulator.worker.metronome.SleepingMetronome}: which used LockSupport.park for waiting.
* This metronome is the default and useful if you don't want to consume a lot of CPU cycles.</li>
* <li>{@link com.hazelcast.simulator.worker.metronome.BusySpinningMetronome}: which used busy spinning for waiting.
* It will give you the best time, but it will totally consume a single core. You certainly don't want to use this
* metronome when having many load generating threads.
* </li>
* <li>{@link com.hazelcast.simulator.worker.metronome.ConstantCombinedRateMetronome} is special type of metronome. The
* first 2 metronomes have a rate per thread; if a thread gets blocked, a bubble of requests will build up that needs
* to get processed as soon as the thread unblocks. Even though coordinated omission by default is taken care of, the bubble
* might not what you want because it means that you will get a dip in system pressure and then a peek, which
* both can influence the benchmark. With the ConstantCombinedRateMetronome as long as their is a thread available, a
* requests will be made. THis prevents building up the bubble and will give a more stable request rate.
* </li>
* </ol>
*
* The metronome type can be configured using:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* metronomeClass=com.hazelcast.simulator.worker.metronome.ConstantCombinedRateMetronome
* }
* </pre>
*
* @see BeforeRun
* @see AfterRun
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeStep {
/**
* The probability of this method running. 0 means there is 0% chance, and 1 means there is 100% chance.
*
* The sum of probability of all timestep methods needs to be one.
*
* Compatibility mode:
* If the probability is -1, it will receive all remaining probability. E.g. if there is a put configured with probability
* 0.2, and get with -1 and put and get are the only 2 options, then the eventual probability for the get will be 1-0.2=0.8.
*
* The reason this is done is to provide compatibility with the old way of probability configuration where one operation
* received whatever remains.
*
* @return the probability.
*/
double prob() default 1;
/**
* Normally all timeStep methods will be executed by a single executionGroup of threads. But in some case you need to have
* some methods executed by one executionGroup of threads, and other methods by other groups threads. A good example would
* be a produce/consume example where the produce timeStep methods are called by different methods than consume timestep
* methods.
*
* Normally threadCount is configured using 'threadCount=5'. In case of 'foobar' executionGroup, the threadCount is
* configured using 'foobarThreadCount=5'.
*
* This setting is copied from JMH, see:
* http://javadox.com/org.openjdk.jmh/jmh-core/0.9/org/openjdk/jmh/annotations/Group.html
*
* @return the executionGroup.
*/
String executionGroup() default "";
}
|
UTF-8
|
Java
| 15,469 |
java
|
TimeStep.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.simulator.test.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Needs to be placed on a load generating method of a test.
*
* A method should contain either:
* <ol>
* <li>{@link Run}</li>
* <li>{@link TimeStep}</li>
* </ol>
* The {@link TimeStep} is the one that should be picked by default. It is the most powerful and it relies on code generation
* to create a runner with the least amount of overhead. The {@link TimeStep} looks a lot like the @Benchmark from JMH.
*
* <h1>Probabilities</h1>
* THe simplest timestep test has a single timestep method, but in reality there is often some kind of ratio, e.g. 10% write
* and 90% read. This can be done configuring probability:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=0.10)
* public void write(){
*
* }
* }
* </pre>
* The sum of the probabilities needs to be 1.
*
* For backwards compatibility reasons one of the timestep methods can be the 'default' by assigning -1 to its probability.
* It means that whatever remains, will be given to that method. For example the above 90/10 could also be configured using:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=-1)
* public void write(){
*
* }
* }
* </pre>
*
* <h1>Thread state</h1>
* In a lot of cases a timestep thread needs to have some thread specific context e.g. counters. THe thread-state needs to be
* a public class with a public no arg constructor, or a constructor receiving the test instance.
*
* <pre>
* {@code
* @TimeStep
* public void timestep(ThreadState context){
* ...
* }
*
* public class ThreadContext{
* int counter;
* }
* }
* </pre>
* Each thread will get its own instance of the ThreadContext. In practice you probably want to extend from the
* {@link com.hazelcast.simulator.test.BaseThreadState} since it has convenience functions for randomization. The Thread state
* can be used on the TimeStep methods, but also in the {@link BeforeRun} and {@link AfterRun} methods where the {@link BeforeRun}
* can take of initialization, and the {@link AfterRun} can take care of some post processing. For a full example see the
* AtomicLongTest.
*
* <h1>Code generation</h1>
* The timestep based tests rely on code generation for the actual code to call the timestep methods. This prevents the need
* for reflection and and the motto is that you should not pay for a feature if it isn't used. For example where logging is not
* configured, no logging code is generated. If there is only a single timestep method, then there is no randomization. This way
* we can reduce the overhead by the benchmark framework to the bare minimum. The generated code of the TimeStepLoop can be
* found in the worker directory.
*
* <h1>Execution groups</h1>
* Normally all timestep methods from a test belong to the same execution group; meaning that there is a group of threads will
* will call each timestep method using some distribution. But in some cases this is unwanted, e.g. a typical producer/consumer
* test. In such cases one can make use of execution groups:
* <pre>
* {@code
* @TimeStep(executionGroup="producer")
* public void produce(){
* ...
* }
*
* @TimeStep(executionGroup="consumer")
* public void consume(){
* ...
* }
* }
* </pre>
* In this case there are 2 execution groups: producer and consumer and each will get their own threads where the producer
* timestep threads calls methods from the 'producer' execution group, and the consumer timestep threads, call methods from
* the 'consumer' execution-group.
*
* Most of the features are configured per timestep group and by default the group "" is used. So you can configure probabilities,
* metronomes, thread context etc per execution group.
*
* <h1>Threadcount</h1>
* A timestep test run multiple timestep threads in parallel. This can be configured using the threadCount property:
* <pre>
* {@code
* class=yourtest
* threadCount=1
* }
* </pre>
* Threadcount defaults to 10.
*
* If there are multiple execution groups, each group can be configured independently. Imagine there is some kind of producer
* consumer test, then each execution group is configured using:
* <pre>
* {@code
* class=yourtest
* producerThreadCount=2
* consumerThreadCount=4
* }
* </pre>
*
* <h1>Iterations</h1>
* TimeStep based tests have out of the box support for running a given number of iterations. This can be configured using
* <pre>
* {@code
* class=yourtest
* iterations=1000000
* }
* </pre>
* This will run 1M iterations per worker-thread.
*
* Each exception group can be configured independently. So imagine there is a producer and consumer execution group, then
* the producers can be configured using:
* <pre>
* {@code
* class=yourtest
* producerIterations=1000000
* }
* </pre>
* In this example the producer has a configured number of iterations for warmup and running, the consumer has no such limitation.
*
* <h1>Stopping a timestep thread</h1>
* A Timestep thread can also stop itself by throwing the {@link com.hazelcast.simulator.test.StopException}. This doesn't lead
* to an error, it is just a signal for the test that the thread is ready.
*
* <h1>Probes</h1>
* By default every timestep method will get its own probe. E.g.
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void read(){
* ...
* }
*
* @TimeStep(prob=0.10)
* public void write(){
* ...
* }
* }
* </pre>
* In this case 2 probes that keep track of writer or read. So by default tracking latency is taken care of by the timestep
* runner. In some cases, especially with async testing, the completion of the system being tested, doesn't align with the
* completion of the timestep method. So the latency can't be determined by the timestep runner. In such cases one can
* get access to the Probe and startTime like this:
* <pre>
* {@code
* @TimeStep(prob=0.9)
* public void asyncCall(Probe probe, @StartNanos long startNanos){
* ...
* }
* }
* </pre>
* One can decide to e.g. make use of an completion listener to determine when the call completed and record the right latency
* on the probe.
*
* Keep in mind that the current iteration (and therefor numbers like throughput) are based on completion of the timestep method,
* but that doesn't need to mean completion of the async call.
*
* <h1>Logging</h1>
* By default a timestep based thread will not log anything during the run/warmup period. But sometimes some logging is required,
* e.g. when needing to do some debugging. There are 2 out of the box options for logging:
* <ol>
* <li>frequency based: e.g. every 1000th iteration</li>
* <li>time rate based: e.g. every 100ms</li>
* </ol>
*
* <h2>Frequency based logging</h2>
* With frequency based logging each timestep thread will add a log entry every so many calls. Frequency based logging can be
* configured using:
* <pre>
* {@code
* class=yourtest
* logFrequency=10000
* }
* </pre>
* Meaning that each timestep thread will log an entry every 10000th calls.
*
* Frequency based logging can be configured per execution group. If there is an execution group producer, then the logFrequency
* can be configured using:
* <pre>
* {@code
* class=yourtest
* producerLogFrequency=10000
* }
* </pre>
*
* <h2>Time rate based logging</h2>
* The time rate based logging allows for a log entry per timestep thread to be written at a maximum rate. E.g. if we want to see
* at most 1 time a second a log entry, we can configure the test:
* <pre>
* {@code
* class=yourtest
* logRateMs=1000
* }
* </pre>
* Time rate based logging is very useful to prevent overloading the system with log entries.
*
* Time rate based logging can be configured per execution group. If there is an execution group producer, then the logRate can
* be configured using:
* <pre>
* {@code
* class=yourtest
* producerRateMs=1000
* }
* </pre>
*
* <h1>Latency testing</h1>
* For Latency testing you normally want to rate the number of requests per second. This can be done by setting the interval
* property. This property configures the interval between requests and is independent of thread count. So if interval is set
* to 10ms, you get 100 operations/second. If there are 2 threads, each thread will do 1 request every 20ms. If there are
* 4 threads, each thread will do 1 request every 40ms.
*
* Example:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* threadCount=2
* }
* </pre>
* In this example there will be 2 threads, that together will make 1 request every 10ms (so after 1 second, 100 requests have
* been made). Interval can be configured with ns, us, ms, s, m, h. Keep in mind that the interval is per machine, so if the
* interval is 10ms and there are 2 machines, on average there is 1 request every 5ms.
*
* The interval can also be configured using the ratePerSecond property:
* <pre>
* {@code
* class=yourtest
* ratePerSecond=100
* threadCount=2
* }
* </pre>
* It is converted to interval under the hood, so there is no difference at runtime. ratePerSecond, just like interval, is
* independent of the number of threads. If you have 200 requests per second, and 2 threads, each thread is going to do
* 100 requests/second. With 4 threads, each thread is going to do 50 requests/second.
*
* If there are multiple execution groups, the interval can be configured using:
* <pre>
* {@code
* class=yourtest
* producerInterval=10ms
* producerThreadCount=2
* }
* </pre>
*
* <h1>Stress testing</h1>
* With stress testing you try to find the highest performance until you run into the breaking point of the system. In Simulator
* this is done by increasing the number of threads until the `threadCount` number of threads are all running. This can be done
* using the rampupSeconds:
* <pre>
* {@code
* class=yourtest
* threadCount=10
* rampupSeconds=60
* }
* </pre>
* In this case every 6 seconds a new thread is added to the test until the maximum number of 10 threads; so after 60 seconds
* all the threads are running.
*
* <h1>Measure latency</h1>
* In some cases measuring the latency can be very expensive due to contention on HDR or because reading out the clock
* can be expensive on certain environments (e.g. EC2 with XEN clock. By adding 'measureLatency=false' to the test,
* Simulator will not measure latency.
*
* <h2>Coordinated omission</h2>
* A lot of testing frameworks are suffering from a problem called coordinated omission:
* https://www.infoq.com/presentations/latency-pitfalls
* By default coordinated omission is prevented by determining the latency based on the expected start-time instead of the actual
* start time. This is all done under the hood and not something you need to worry about. In some cases you want to see the
* impact of coordinated omission and you can allow for it using:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* accountForCoordinatedOmission=false
* }
* </pre>
*
* <h2>Different flavors of metronomes</h2>
* Internally a {@link com.hazelcast.simulator.worker.metronome.Metronome} is used to control the rate of requests. There are
* currently 3 out of the box implementations:
* <ol>
* <li>{@link com.hazelcast.simulator.worker.metronome.SleepingMetronome}: which used LockSupport.park for waiting.
* This metronome is the default and useful if you don't want to consume a lot of CPU cycles.</li>
* <li>{@link com.hazelcast.simulator.worker.metronome.BusySpinningMetronome}: which used busy spinning for waiting.
* It will give you the best time, but it will totally consume a single core. You certainly don't want to use this
* metronome when having many load generating threads.
* </li>
* <li>{@link com.hazelcast.simulator.worker.metronome.ConstantCombinedRateMetronome} is special type of metronome. The
* first 2 metronomes have a rate per thread; if a thread gets blocked, a bubble of requests will build up that needs
* to get processed as soon as the thread unblocks. Even though coordinated omission by default is taken care of, the bubble
* might not what you want because it means that you will get a dip in system pressure and then a peek, which
* both can influence the benchmark. With the ConstantCombinedRateMetronome as long as their is a thread available, a
* requests will be made. THis prevents building up the bubble and will give a more stable request rate.
* </li>
* </ol>
*
* The metronome type can be configured using:
* <pre>
* {@code
* class=yourtest
* interval=10ms
* metronomeClass=com.hazelcast.simulator.worker.metronome.ConstantCombinedRateMetronome
* }
* </pre>
*
* @see BeforeRun
* @see AfterRun
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeStep {
/**
* The probability of this method running. 0 means there is 0% chance, and 1 means there is 100% chance.
*
* The sum of probability of all timestep methods needs to be one.
*
* Compatibility mode:
* If the probability is -1, it will receive all remaining probability. E.g. if there is a put configured with probability
* 0.2, and get with -1 and put and get are the only 2 options, then the eventual probability for the get will be 1-0.2=0.8.
*
* The reason this is done is to provide compatibility with the old way of probability configuration where one operation
* received whatever remains.
*
* @return the probability.
*/
double prob() default 1;
/**
* Normally all timeStep methods will be executed by a single executionGroup of threads. But in some case you need to have
* some methods executed by one executionGroup of threads, and other methods by other groups threads. A good example would
* be a produce/consume example where the produce timeStep methods are called by different methods than consume timestep
* methods.
*
* Normally threadCount is configured using 'threadCount=5'. In case of 'foobar' executionGroup, the threadCount is
* configured using 'foobarThreadCount=5'.
*
* This setting is copied from JMH, see:
* http://javadox.com/org.openjdk.jmh/jmh-core/0.9/org/openjdk/jmh/annotations/Group.html
*
* @return the executionGroup.
*/
String executionGroup() default "";
}
| 15,469 | 0.706445 | 0.693128 | 384 | 39.283855 | 43.288399 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.200521 | false | false |
5
|
53e4a4a8be4de4da0965a480f78b1b497400b2d1
| 16,535,624,128,517 |
f4df86ca1eda62cbba6b5706094c9fb505fa1913
|
/src/test/java/kr/enterkey/accounts/AccountTest.java
|
b0b68a0811720fb979450fc8b19aa63cda2af038
|
[
"MIT"
] |
permissive
|
EnterKey/mirror-test2
|
https://github.com/EnterKey/mirror-test2
|
bd3fc9c7bf9ecf2b513dae8b8f060ef8c8207796
|
31126348cb12c4cf4b0a6deafe898c1493d0ae67
|
refs/heads/master
| 2021-08-23T07:39:09.986000 | 2017-12-04T05:34:14 | 2017-12-04T05:34:14 | 112,998,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kr.enterkey.accounts;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by enterkey88 on 2016-10-11.
*/
public class AccountTest {
@Test
public void getterSetter() {
Account account = new Account();
account.setUsername("enterkey");
account.setPassword("entjd123");
assertThat(account.getUsername(), is("enterkey"));
}
}
|
UTF-8
|
Java
| 453 |
java
|
AccountTest.java
|
Java
|
[
{
"context": "c org.junit.Assert.assertThat;\n\n\n/**\n * Created by enterkey88 on 2016-10-11.\n */\npublic class AccountTest {\n\n ",
"end": 172,
"score": 0.9996278285980225,
"start": 162,
"tag": "USERNAME",
"value": "enterkey88"
},
{
"context": "unt = new Account();\n account.setUsername(\"enterkey\");\n account.setPassword(\"entjd123\");\n ",
"end": 341,
"score": 0.999431848526001,
"start": 333,
"tag": "USERNAME",
"value": "enterkey"
},
{
"context": "sername(\"enterkey\");\n account.setPassword(\"entjd123\");\n assertThat(account.getUsername(), is(\"",
"end": 382,
"score": 0.9994050860404968,
"start": 374,
"tag": "PASSWORD",
"value": "entjd123"
},
{
"context": "\");\n assertThat(account.getUsername(), is(\"enterkey\"));\n }\n}\n",
"end": 440,
"score": 0.9990721940994263,
"start": 432,
"tag": "USERNAME",
"value": "enterkey"
}
] | null |
[] |
package kr.enterkey.accounts;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by enterkey88 on 2016-10-11.
*/
public class AccountTest {
@Test
public void getterSetter() {
Account account = new Account();
account.setUsername("enterkey");
account.setPassword("<PASSWORD>");
assertThat(account.getUsername(), is("enterkey"));
}
}
| 455 | 0.677704 | 0.649007 | 21 | 20.571428 | 18.9751 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
12
|
3a2274a2bb7ad175cdc27a5e7e47a0d874cf1842
| 16,346,645,535,417 |
d5b1baa3ca23334e398eff3dc8882164385b7c4b
|
/src/main/java/segmenter/Dictionary.java
|
e4a6c7abb58a8831721fdcdc4ab722ae7c6337ad
|
[] |
no_license
|
yangxy1998/homework_5
|
https://github.com/yangxy1998/homework_5
|
c8cca6ce5c7c801aaa603cccb62768537666e2dd
|
54a0588928df996dcc167d2eeac5115cad95a7a2
|
refs/heads/master
| 2021-09-03T04:10:51.145000 | 2018-01-05T13:33:15 | 2018-01-05T13:33:15 | 115,389,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package segmenter;
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
/**
*
* 每个项目自己的字典
* 一个项目对应一个字典
* totalDictionary是词库,包含所有词的内容和含该词的项目数量
* SumOfPrograms存储项目总量
*
*/
public class Dictionary {
//词库,装载了出现该单词的项目数
private static List<Pair<String,Integer>> totalDictionary=new ArrayList<>();
//项目当中包含词的总量
private int SumOfWords;
//总项目数
private static int SumOfPrograms;
//字典
private List<Word> vocabularies;
public Dictionary(){
vocabularies=new ArrayList<>();
SumOfPrograms=1;
SumOfWords=1;
}
public List<Word> getVocabularies() {
return vocabularies;
}
public void setVocabularies(List<Word> vocabularies) {
this.vocabularies = vocabularies;
}
//通过字符给字典添加词
public void addVocabulary(String vocabulary){
Word word=new Word(vocabulary);
word.setSumOfWords(SumOfWords);
word.setSumOfPrograms(SumOfPrograms);
vocabularies.add(word);
}
//通过其他字典已有的词给字典添加词
public void addVocabulary(Word vocabulary){
Word word=new Word(vocabulary.getName());
word.setSumOfWords(SumOfWords);
word.setSumOfPrograms(SumOfPrograms);
word.setCountOfWords(vocabulary.getCountOfWords());
for(Pair<String,Integer> p:totalDictionary){
if(p.getKey().equals(word.getName())){
word.setCountOfPrograms(p.getValue().intValue());
}
}
vocabularies.add(word);
}
public void setSumOfWords(int sumOfWords) {
SumOfWords = sumOfWords;
}
public int getSumOfWords() {
return SumOfWords;
}
public static int getSumOfPrograms() {
return SumOfPrograms;
}
//获取词库
public static List<Pair<String, Integer>> getTotalDictionary() {
return totalDictionary;
}
public static void setSumOfPrograms(int sumOfPrograms) {
SumOfPrograms = sumOfPrograms;
}
//在字典当中通过字符串查词
public Word Find(String string){
for(Word word : vocabularies){
if(string.equals(word.getName()))
return word;
}
return null;
}
//通过其他字典的词查词
public Word Find(Word word){
return Find(word.getName());
}
}
|
UTF-8
|
Java
| 2,537 |
java
|
Dictionary.java
|
Java
|
[] | null |
[] |
package segmenter;
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
/**
*
* 每个项目自己的字典
* 一个项目对应一个字典
* totalDictionary是词库,包含所有词的内容和含该词的项目数量
* SumOfPrograms存储项目总量
*
*/
public class Dictionary {
//词库,装载了出现该单词的项目数
private static List<Pair<String,Integer>> totalDictionary=new ArrayList<>();
//项目当中包含词的总量
private int SumOfWords;
//总项目数
private static int SumOfPrograms;
//字典
private List<Word> vocabularies;
public Dictionary(){
vocabularies=new ArrayList<>();
SumOfPrograms=1;
SumOfWords=1;
}
public List<Word> getVocabularies() {
return vocabularies;
}
public void setVocabularies(List<Word> vocabularies) {
this.vocabularies = vocabularies;
}
//通过字符给字典添加词
public void addVocabulary(String vocabulary){
Word word=new Word(vocabulary);
word.setSumOfWords(SumOfWords);
word.setSumOfPrograms(SumOfPrograms);
vocabularies.add(word);
}
//通过其他字典已有的词给字典添加词
public void addVocabulary(Word vocabulary){
Word word=new Word(vocabulary.getName());
word.setSumOfWords(SumOfWords);
word.setSumOfPrograms(SumOfPrograms);
word.setCountOfWords(vocabulary.getCountOfWords());
for(Pair<String,Integer> p:totalDictionary){
if(p.getKey().equals(word.getName())){
word.setCountOfPrograms(p.getValue().intValue());
}
}
vocabularies.add(word);
}
public void setSumOfWords(int sumOfWords) {
SumOfWords = sumOfWords;
}
public int getSumOfWords() {
return SumOfWords;
}
public static int getSumOfPrograms() {
return SumOfPrograms;
}
//获取词库
public static List<Pair<String, Integer>> getTotalDictionary() {
return totalDictionary;
}
public static void setSumOfPrograms(int sumOfPrograms) {
SumOfPrograms = sumOfPrograms;
}
//在字典当中通过字符串查词
public Word Find(String string){
for(Word word : vocabularies){
if(string.equals(word.getName()))
return word;
}
return null;
}
//通过其他字典的词查词
public Word Find(Word word){
return Find(word.getName());
}
}
| 2,537 | 0.630979 | 0.630101 | 102 | 21.343138 | 19.513945 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
12
|
ac2e5a6857bb18554db45dc4898347f2c62a0625
| 7,507,602,885,366 |
d41b52fa61132a6aac4169baeda706db53fbe805
|
/RoosterPGPlus/src/main/java/com/thomasdh/roosterpgplus/Settings/Constants.java
|
8b12e991ea935bbf4e692cd96b80f68391e8b27e
|
[] |
no_license
|
FWest98/Discipul-Android
|
https://github.com/FWest98/Discipul-Android
|
f6fc56adc1c44e51a9b3fb04e2a5b695a1010b5f
|
837312c2144de418ee3f9f04dc9442733fc00d16
|
refs/heads/development
| 2022-07-05T21:53:21.172000 | 2022-06-24T23:20:17 | 2022-06-24T23:20:17 | 14,755,508 | 2 | 1 | null | false | 2015-02-13T18:57:22 | 2013-11-27T18:33:50 | 2015-02-13T11:39:49 | 2015-02-13T18:57:22 | 4,556 | 3 | 1 | 6 |
Java
| null | null |
package com.thomasdh.roosterpgplus.Settings;
@SuppressWarnings("UnusedDeclaration")
public class Constants {
public static final String HTTP_BASE = "https://api.roosterpgplus.nl/";
public static final int WEEKS_IN_SPINNER = 10;
public static final String API_VERSION = "2";
public static final int TIMEOUT_MILLIS = 5000;
public static final String PLAY_SERVICES_APP_VERSION = "VERSION_1.0";
public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String PLAY_SERVICES_SENDER_ID = "878528381124";
public static final String ANALYTICS_CATEGORIES_ROOSTER = "Rooster";
public static final String ANALYTICS_CATEGORIES_SETTINGS = "Instellingen";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_LOAD = "Laad (ander) rooster";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_REFRESH = "Refresh rooster";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_CHANGE_WEEK = "Weekwijziging";
public static final String ANALYTICS_ACTION_LOGIN = "Login";
public static final String ANALYTICS_ACTION_REGISTER = "Registreer";
public static final String ANALYTICS_ACTION_EXTEND = "Uitbreidscherm";
public static final String ANALYTICS_ACTION_CHANGEUSERNAME = "Gebruikersnaam wijzigen";
public static final String ANALYTICS_ACTION_CHANGEPASS = "Wachtwoord wijzigen";
public static final String ANALYTICS_FRAGMENT_PERSROOSTER = "Persoonlijk rooster";
public static final String ANALYTICS_FRAGMENT_DOCROOSTER = "Lerarenrooster";
public static final String ANALYTICS_FRAGMENT_KLASROOSTER = "Klassenrooster";
public static final String ANALYTICS_FRAGMENT_LOKROOSTER = "Lokalenrooster";
public static final String ANALYTICS_FRAGMENT_LERROOSTER = "Leerlingenrooster";
public static final String ANALYTICS_FRAGMENT_SEARCHROOSTER = "Ander rooster";
public static final String ANALYTICS_FRAGMENT_PGTVROOSTER = "PG-TV Roosterwijzigingen";
public static final String ANALYTICS_FRAGMENT_PGTVALGEM = "PG-TV Algemene Mededelingen";
public static final String ANALYTICS_FRAGMENT_SETTINGS_MAIN = "Instellingen hoofdscherm";
public static final String ANALYTICS_FRAGMENT_SETTINGS_USER = "Instellingen gebruiker";
public static final String ANALYTICS_FRAGMENT_SETTINGS_NOTIFICATIES = "Instellingen notificaties";
public static final String ANALYTICS_FRAGMENT_SETTINGS_OVERIG = "Instellingen overig";
public static final String ANALYTICS_FRAGMENT_SETTINGS_INFO = "Instellingen info";
public static final String ANALYTICS_FRAGMENT_LOGIN = "Inlogscherm";
public static final String ANALYTICS_FRAGMENT_REGISTER = "Registreerscherm";
public static final String ANALYTICS_FRAGMENT_EXTEND = "Uitbreidscherm";
public static final String ANALYTICS_FRAGMENT_CHANGEUSERNAME = "Gebruikersnaamwijzigscherm";
public static final String ANALYTICS_FRAGMENT_CHANGEPASSWORD = "Wachtwoordwijzigscherm";
}
|
UTF-8
|
Java
| 2,961 |
java
|
Constants.java
|
Java
|
[
{
"context": "final String ANALYTICS_FRAGMENT_CHANGEUSERNAME = \"Gebruikersnaamwijzigscherm\";\n public static final String ANALYTICS_FRAGME",
"end": 2863,
"score": 0.9996223449707031,
"start": 2837,
"tag": "USERNAME",
"value": "Gebruikersnaamwijzigscherm"
},
{
"context": "final String ANALYTICS_FRAGMENT_CHANGEPASSWORD = \"Wachtwoordwijzigscherm\";\n}\n",
"end": 2956,
"score": 0.9985557198524475,
"start": 2934,
"tag": "PASSWORD",
"value": "Wachtwoordwijzigscherm"
}
] | null |
[] |
package com.thomasdh.roosterpgplus.Settings;
@SuppressWarnings("UnusedDeclaration")
public class Constants {
public static final String HTTP_BASE = "https://api.roosterpgplus.nl/";
public static final int WEEKS_IN_SPINNER = 10;
public static final String API_VERSION = "2";
public static final int TIMEOUT_MILLIS = 5000;
public static final String PLAY_SERVICES_APP_VERSION = "VERSION_1.0";
public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String PLAY_SERVICES_SENDER_ID = "878528381124";
public static final String ANALYTICS_CATEGORIES_ROOSTER = "Rooster";
public static final String ANALYTICS_CATEGORIES_SETTINGS = "Instellingen";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_LOAD = "Laad (ander) rooster";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_REFRESH = "Refresh rooster";
public static final String ANALYTICS_ACTIVITY_ROOSTER_ACTION_CHANGE_WEEK = "Weekwijziging";
public static final String ANALYTICS_ACTION_LOGIN = "Login";
public static final String ANALYTICS_ACTION_REGISTER = "Registreer";
public static final String ANALYTICS_ACTION_EXTEND = "Uitbreidscherm";
public static final String ANALYTICS_ACTION_CHANGEUSERNAME = "Gebruikersnaam wijzigen";
public static final String ANALYTICS_ACTION_CHANGEPASS = "Wachtwoord wijzigen";
public static final String ANALYTICS_FRAGMENT_PERSROOSTER = "Persoonlijk rooster";
public static final String ANALYTICS_FRAGMENT_DOCROOSTER = "Lerarenrooster";
public static final String ANALYTICS_FRAGMENT_KLASROOSTER = "Klassenrooster";
public static final String ANALYTICS_FRAGMENT_LOKROOSTER = "Lokalenrooster";
public static final String ANALYTICS_FRAGMENT_LERROOSTER = "Leerlingenrooster";
public static final String ANALYTICS_FRAGMENT_SEARCHROOSTER = "Ander rooster";
public static final String ANALYTICS_FRAGMENT_PGTVROOSTER = "PG-TV Roosterwijzigingen";
public static final String ANALYTICS_FRAGMENT_PGTVALGEM = "PG-TV Algemene Mededelingen";
public static final String ANALYTICS_FRAGMENT_SETTINGS_MAIN = "Instellingen hoofdscherm";
public static final String ANALYTICS_FRAGMENT_SETTINGS_USER = "Instellingen gebruiker";
public static final String ANALYTICS_FRAGMENT_SETTINGS_NOTIFICATIES = "Instellingen notificaties";
public static final String ANALYTICS_FRAGMENT_SETTINGS_OVERIG = "Instellingen overig";
public static final String ANALYTICS_FRAGMENT_SETTINGS_INFO = "Instellingen info";
public static final String ANALYTICS_FRAGMENT_LOGIN = "Inlogscherm";
public static final String ANALYTICS_FRAGMENT_REGISTER = "Registreerscherm";
public static final String ANALYTICS_FRAGMENT_EXTEND = "Uitbreidscherm";
public static final String ANALYTICS_FRAGMENT_CHANGEUSERNAME = "Gebruikersnaamwijzigscherm";
public static final String ANALYTICS_FRAGMENT_CHANGEPASSWORD = "<PASSWORD>";
}
| 2,949 | 0.778791 | 0.770348 | 47 | 62 | 33.999374 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.765957 | false | false |
12
|
cafe53e2471b7479453ea08a51d0e71813886a68
| 28,896,540,033,410 |
ee6ed7c92476cbb3cd72d702eb432dfd4f514329
|
/src/forecrecursion/example09.java
|
498713f9d172075abde758023362a098ca2be50b
|
[] |
no_license
|
yangxcc/Algorithm
|
https://github.com/yangxcc/Algorithm
|
739911bae63b6cc71c5d7a124212fa85cf34fdb0
|
9b9f9eea14561c2f127e15e5f4f4a8c08b9ab4f0
|
refs/heads/master
| 2022-05-21T01:36:08.349000 | 2022-03-28T03:07:27 | 2022-03-28T03:07:27 | 410,236,950 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package forecrecursion;
/**
* 对 n皇后问题进行优化
* n 皇后问题的时间复杂度是 O(N^N),下面的方式知识加速运算,减少常数时间
* 时间复杂度虽然还是这个指标,但是速度还是提升了不少
*
* */
public class example09 {
public static int queen(int n) {
if (n < 1 || n > 32) {
return -1;
}
// 如果是8皇后问题,那么后8位都是1,前24位都是0
// 如果是9皇后问题,那么后9位都是1,前23位都是0
int limit = n == 32 ? -1 : (1 << n) - 1;
return process(limit, 0, 0 , 0);
}
/**
* columnLimit 表示的是列限制,如果是8皇后问题,那么columnLimit最开始就是 00000000,
* leftLimit 表示的是左斜线限制,如果是8皇后问题,那么leftLimit最开始就是 00000000
* rightLimit 表示的是右斜线限制,如果是8皇后问题,那么rightLimit最开始就是 00000000
*
* 比如说,我把第一个皇后放在了第2列(编号从0开始)
* 那么columnLimit就变成了 00100000,
* leftLimit 变成了 01000000,
* rightLimit 变成了 00010000
* 所以,上面三个limit的并集就是第二个皇后不能在的位置
*
* */
public static int process(int limit, int columnLimit, int leftLimit, int rightLim) {
if (limit == columnLimit) {
return 1;
}
int pos = limit & (~(columnLimit | leftLimit | rightLim)); // 这个式子能够得到下一个皇后还能再的位置
int res = 0;
while (pos != 0) {
int mostRightOne = pos & (~pos + 1); // 取到最右侧的1,把皇后放在这个位置
pos = pos - mostRightOne;
res += process(limit, columnLimit | mostRightOne,
(leftLimit | mostRightOne) << 1, (rightLim | mostRightOne) >>> 1);
}
/**
* 在这里我要解释一下为什么 left | mostright之后要左移一位
*
* 0 1 2 3 4 5 6 7
* 0 * 假设第一个皇后放到了2位置
* 1 # # # * 那么123这三个位置都不能够在放皇后了,假如第二个皇后被放到了6位置
* 2 # # # # # 那么567位置不能够在放皇后了 ,此外,0和4位置同样也不能够放皇后,因为
* 3 他们是在左右斜线上的点,如果第三个皇后放在了0位置,那么他就会和第一个皇后
* 4 共斜线!!,所以左斜线再 | mostRightOne之后,需要整体左移一位
* 5 同理,右斜线限制再 | mostRightOne之后,需要整体右移一位
* 6
* 7
* */
return res;
}
public static void main(String[] args) {
System.out.println(queen(8));
}
}
|
UTF-8
|
Java
| 2,951 |
java
|
example09.java
|
Java
|
[] | null |
[] |
package forecrecursion;
/**
* 对 n皇后问题进行优化
* n 皇后问题的时间复杂度是 O(N^N),下面的方式知识加速运算,减少常数时间
* 时间复杂度虽然还是这个指标,但是速度还是提升了不少
*
* */
public class example09 {
public static int queen(int n) {
if (n < 1 || n > 32) {
return -1;
}
// 如果是8皇后问题,那么后8位都是1,前24位都是0
// 如果是9皇后问题,那么后9位都是1,前23位都是0
int limit = n == 32 ? -1 : (1 << n) - 1;
return process(limit, 0, 0 , 0);
}
/**
* columnLimit 表示的是列限制,如果是8皇后问题,那么columnLimit最开始就是 00000000,
* leftLimit 表示的是左斜线限制,如果是8皇后问题,那么leftLimit最开始就是 00000000
* rightLimit 表示的是右斜线限制,如果是8皇后问题,那么rightLimit最开始就是 00000000
*
* 比如说,我把第一个皇后放在了第2列(编号从0开始)
* 那么columnLimit就变成了 00100000,
* leftLimit 变成了 01000000,
* rightLimit 变成了 00010000
* 所以,上面三个limit的并集就是第二个皇后不能在的位置
*
* */
public static int process(int limit, int columnLimit, int leftLimit, int rightLim) {
if (limit == columnLimit) {
return 1;
}
int pos = limit & (~(columnLimit | leftLimit | rightLim)); // 这个式子能够得到下一个皇后还能再的位置
int res = 0;
while (pos != 0) {
int mostRightOne = pos & (~pos + 1); // 取到最右侧的1,把皇后放在这个位置
pos = pos - mostRightOne;
res += process(limit, columnLimit | mostRightOne,
(leftLimit | mostRightOne) << 1, (rightLim | mostRightOne) >>> 1);
}
/**
* 在这里我要解释一下为什么 left | mostright之后要左移一位
*
* 0 1 2 3 4 5 6 7
* 0 * 假设第一个皇后放到了2位置
* 1 # # # * 那么123这三个位置都不能够在放皇后了,假如第二个皇后被放到了6位置
* 2 # # # # # 那么567位置不能够在放皇后了 ,此外,0和4位置同样也不能够放皇后,因为
* 3 他们是在左右斜线上的点,如果第三个皇后放在了0位置,那么他就会和第一个皇后
* 4 共斜线!!,所以左斜线再 | mostRightOne之后,需要整体左移一位
* 5 同理,右斜线限制再 | mostRightOne之后,需要整体右移一位
* 6
* 7
* */
return res;
}
public static void main(String[] args) {
System.out.println(queen(8));
}
}
| 2,951 | 0.522936 | 0.46789 | 64 | 31.359375 | 25.479383 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484375 | false | false |
12
|
58f0ec6ef1af78ed2b561ff31c1339694698d9b0
| 25,443,386,299,249 |
3a21e95d1387b4390494855baea82ce05496853c
|
/src/main/java/io/github/encryptorcode/permissions/abstracts/Pipeline.java
|
cdeabd91b65d276dc6f9624f23ba9617b33d0e4f
|
[
"MIT"
] |
permissive
|
encryptorcode/spring-permissions
|
https://github.com/encryptorcode/spring-permissions
|
fdd72f7f00a9aa89252fd735e6ee5e292e04208b
|
248ae6d3055300e60f48624f8c0c72a2aa07da43
|
refs/heads/master
| 2023-06-15T23:19:00.578000 | 2021-05-29T16:53:12 | 2021-05-29T16:53:12 | 277,316,022 | 1 | 1 |
MIT
| false | 2021-07-15T06:04:43 | 2020-07-05T14:15:47 | 2021-05-29T16:53:15 | 2021-07-15T06:04:39 | 45 | 1 | 0 | 3 |
Java
| false | false |
package io.github.encryptorcode.permissions.abstracts;
public interface Pipeline<T> {
T pipe();
}
|
UTF-8
|
Java
| 103 |
java
|
Pipeline.java
|
Java
|
[] | null |
[] |
package io.github.encryptorcode.permissions.abstracts;
public interface Pipeline<T> {
T pipe();
}
| 103 | 0.747573 | 0.747573 | 5 | 19.6 | 20.323385 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
1efd406a0dfdaa7ca516183f074f4e3ef803528a
| 15,444,702,436,414 |
4f9e893cedd8f25557239f939edee6bcb1246715
|
/jinghua/dmm_teaching/src/main/java/cn/gilight/dmm/teaching/controller/StudentsQualityCtol.java
|
cac9099253464b0e98f7dc104bb3301ecc278870
|
[] |
no_license
|
yangtie34/projects
|
https://github.com/yangtie34/projects
|
cc9ba22c1fd235dadfe18509bc6951e21e9d3be4
|
5a3a86116e385db1086f8f6e9eb07198432fec27
|
refs/heads/master
| 2020-06-29T11:04:26.615000 | 2017-07-25T03:28:15 | 2017-07-25T03:28:15 | 74,436,105 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.gilight.dmm.teaching.controller;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.gilight.dmm.business.util.PageUtils;
import cn.gilight.dmm.teaching.service.StudentsQualityService;
import cn.gilight.framework.uitl.common.ExcelUtils;
import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping("studentsQuality")
public class StudentsQualityCtol {
@Resource
private StudentsQualityService studentsQualityService;
@RequestMapping()
public String init(){
return "studentsQuality";
}
/**
*
* @Description: 页面查询
* @return: Map<String,Object>
* @return
*/
@RequestMapping("querySelectType")
@ResponseBody
public Map<String, Object> querySelectType(){
return studentsQualityService.querySelectType();
}
/**
*
* @Description: 查询本科生各项数据
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudents")
@ResponseBody
public Map<String, Object> queryStudents(String year) {
return studentsQualityService.queryStudents(year);
}
/**
*
* @Description: 查询表中所有科类
* @return: List<Map<String,Object>>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryAllSub")
@ResponseBody
public List<Map<String, Object>> queryAllSub(String year){
return studentsQualityService.queryAllSub(year);
}
/**
*
* @Description: 选择某科类时,查询科类对应数据 sub:科类ID
* @return: List<Map<String,Object>>
* @param year 查询的年份
* @param sub 科类ID
* @return
*/
@RequestMapping("queryStudentsSub")
@ResponseBody
public List<Map<String, Object>> queryStudentsSub(String year, @RequestParam("sub[]") List<String> sub) {
return studentsQualityService.queryStudentsSub(year, sub);
}
/**
*
* @Description: 查询超出分数线20分的专业 及其各项数据
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param point 筛选条件
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsScore")
@ResponseBody
public Map<String, Object> queryStudentsScore(String page,String year,String point,String flag) {
return studentsQualityService.queryStudentsScore(PageUtils.converPage(page),year,point,flag);
}
/**
*
* @Description: 调剂率
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsAdjust")
@ResponseBody
public Map<String, Object> queryStudentsAdjust(String page,String year,String flag) {
return studentsQualityService.queryStudentsAdjust(PageUtils.converPage(page),year,flag);
}
/**
*
* @Description: 自主招生录取率
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsEnroll")
@ResponseBody
public Map<String, Object> queryStudentsEnroll(String page,String year,String flag) {
return studentsQualityService.queryStudentsEnroll(PageUtils.converPage(page),year,flag);
}
/**
*
* @Description: 未报到人数
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudentsNotReport")
@ResponseBody
public Map<String, Object> queryStudentsNotReport(String year) {
return studentsQualityService.queryStudentsNotReport(year);
}
/**
*
* @Description: 学生未报到地理分布
* @return: Map<String,Object>
* @param year 查询的年份
* @param xzqh 节点代码
* @param updown Boolean值,用于判断向上或者向下取节点
* @return
*/
@RequestMapping("queryStudentsNotReportByLocal")
@ResponseBody
public Map<String, Object> queryStudentsNotReportByLocal(String year,String xzqh,Boolean updown) {
return studentsQualityService.queryStudentsNotReportByLocal(year,xzqh,updown);
}
/**
*
* @Description: 未报到原因分布
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudentsNotReportReason")
@ResponseBody
public Map<String, Object> queryStudentsNotReportReason(String year) {
return studentsQualityService.queryStudentsNotReportReason(year);
}
/**
*
* @Description: 各省分数线详情
* @return: Map<String,Object>
* @param page 分页参数
* @param flag 样式改变 标志参数
* @param year 查询的年份
* @param majorId 专业ID
* @return
*/
@RequestMapping("queryScoreLineByPro")
@ResponseBody
public Map<String, Object> queryScoreLineByPro(String page,String flag,String year, String majorId){
return studentsQualityService.queryScoreLineByPro(PageUtils.converPage(page),flag,year, majorId);
}
/**
*
* @Description: 未报到学生详情
* @return: Map<String,Object>
* @param page 分页参数
* @param pid 父节点代码
* @param year 查询的年份
* @param fields 需获取字段的代码
* @return
*/
@RequestMapping("queryWbdDetail")
@ResponseBody
public Map<String, Object> queryWbdDetail(String page, String pid, String year,String fields){
return studentsQualityService.queryWbdDetail(PageUtils.converPage(page), pid, year, JSONObject.parseArray(fields, String.class));
}
/**
*
* @Description: 获取学生未报到原因
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param values 未报到原因ID
* @param fields 需获取字段的代码
* @return
*/
@RequestMapping("getNotReportReason")
@ResponseBody
public Map<String, Object> getNotReportReason(String page,String year,String values,String fields){
return studentsQualityService.getNotReportReason(PageUtils.converPage(page), year, values, JSONObject.parseArray(fields, String.class));
}
/**
* @Description: 下载
* @return: void
* @param page 分页参数
* @param pid 父节点代码
* @param year 查询的年份
* @param values 未报到原因ID
* @param fields 需获取的字段代码
* @param flag 样式改变标志代码
* @param point 分数值代码
* @param majorId 专业ID
* @param headers
* @param fileName
* @param request
* @param response
*/
@SuppressWarnings("unchecked")
@RequestMapping("down")
public void down(String page,String pid,String year,String values, String fields,String headers,
String fileName,String flag,String point,String majorId, HttpServletRequest request, HttpServletResponse response){
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("utf-8");
if(fileName == null) fileName = "下载文件";
try {
response.setHeader("Content-Disposition", "attachment;fileName=" +new String((fileName+".xls").getBytes(),"iso-8859-1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
List<String> fields2 = JSONObject.parseArray(fields, String.class),
headers2 = JSONObject.parseArray(headers, String.class);
Map<String, Object> map = new HashMap<String, Object>();
if(flag.equals("1")){
map = studentsQualityService.queryScoreLineByPro(PageUtils.converPage(page), flag, year, majorId);
}
if(flag.equals("2")){
map = studentsQualityService.queryStudentsScore(PageUtils.converPage(page), year, point, flag);
}
if(flag.equals("3")){
map = studentsQualityService.queryStudentsAdjust(PageUtils.converPage(page), year, flag);
}
if(flag.equals("4")){
map = studentsQualityService.queryStudentsEnroll(PageUtils.converPage(page), year, flag);
}
if(flag.equals("5")){
map = studentsQualityService.queryWbdDetail(PageUtils.converPage(page), pid, year, fields2);
}
if(flag.equals("6")){
map = studentsQualityService.getNotReportReason(PageUtils.converPage(page), year, values, fields2);
}
List<Map<String,Object>> list = (List<Map<String, Object>>) map.get("rows");
HSSFWorkbook workBook = ExcelUtils.createExcel(list, fields2, headers2, fileName);
try {
OutputStream os = response.getOutputStream();
workBook.write(os);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 8,718 |
java
|
StudentsQualityCtol.java
|
Java
|
[] | null |
[] |
package cn.gilight.dmm.teaching.controller;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.gilight.dmm.business.util.PageUtils;
import cn.gilight.dmm.teaching.service.StudentsQualityService;
import cn.gilight.framework.uitl.common.ExcelUtils;
import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping("studentsQuality")
public class StudentsQualityCtol {
@Resource
private StudentsQualityService studentsQualityService;
@RequestMapping()
public String init(){
return "studentsQuality";
}
/**
*
* @Description: 页面查询
* @return: Map<String,Object>
* @return
*/
@RequestMapping("querySelectType")
@ResponseBody
public Map<String, Object> querySelectType(){
return studentsQualityService.querySelectType();
}
/**
*
* @Description: 查询本科生各项数据
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudents")
@ResponseBody
public Map<String, Object> queryStudents(String year) {
return studentsQualityService.queryStudents(year);
}
/**
*
* @Description: 查询表中所有科类
* @return: List<Map<String,Object>>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryAllSub")
@ResponseBody
public List<Map<String, Object>> queryAllSub(String year){
return studentsQualityService.queryAllSub(year);
}
/**
*
* @Description: 选择某科类时,查询科类对应数据 sub:科类ID
* @return: List<Map<String,Object>>
* @param year 查询的年份
* @param sub 科类ID
* @return
*/
@RequestMapping("queryStudentsSub")
@ResponseBody
public List<Map<String, Object>> queryStudentsSub(String year, @RequestParam("sub[]") List<String> sub) {
return studentsQualityService.queryStudentsSub(year, sub);
}
/**
*
* @Description: 查询超出分数线20分的专业 及其各项数据
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param point 筛选条件
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsScore")
@ResponseBody
public Map<String, Object> queryStudentsScore(String page,String year,String point,String flag) {
return studentsQualityService.queryStudentsScore(PageUtils.converPage(page),year,point,flag);
}
/**
*
* @Description: 调剂率
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsAdjust")
@ResponseBody
public Map<String, Object> queryStudentsAdjust(String page,String year,String flag) {
return studentsQualityService.queryStudentsAdjust(PageUtils.converPage(page),year,flag);
}
/**
*
* @Description: 自主招生录取率
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param flag 样式变化标志参数
* @return
*/
@RequestMapping("queryStudentsEnroll")
@ResponseBody
public Map<String, Object> queryStudentsEnroll(String page,String year,String flag) {
return studentsQualityService.queryStudentsEnroll(PageUtils.converPage(page),year,flag);
}
/**
*
* @Description: 未报到人数
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudentsNotReport")
@ResponseBody
public Map<String, Object> queryStudentsNotReport(String year) {
return studentsQualityService.queryStudentsNotReport(year);
}
/**
*
* @Description: 学生未报到地理分布
* @return: Map<String,Object>
* @param year 查询的年份
* @param xzqh 节点代码
* @param updown Boolean值,用于判断向上或者向下取节点
* @return
*/
@RequestMapping("queryStudentsNotReportByLocal")
@ResponseBody
public Map<String, Object> queryStudentsNotReportByLocal(String year,String xzqh,Boolean updown) {
return studentsQualityService.queryStudentsNotReportByLocal(year,xzqh,updown);
}
/**
*
* @Description: 未报到原因分布
* @return: Map<String,Object>
* @param year 查询的年份
* @return
*/
@RequestMapping("queryStudentsNotReportReason")
@ResponseBody
public Map<String, Object> queryStudentsNotReportReason(String year) {
return studentsQualityService.queryStudentsNotReportReason(year);
}
/**
*
* @Description: 各省分数线详情
* @return: Map<String,Object>
* @param page 分页参数
* @param flag 样式改变 标志参数
* @param year 查询的年份
* @param majorId 专业ID
* @return
*/
@RequestMapping("queryScoreLineByPro")
@ResponseBody
public Map<String, Object> queryScoreLineByPro(String page,String flag,String year, String majorId){
return studentsQualityService.queryScoreLineByPro(PageUtils.converPage(page),flag,year, majorId);
}
/**
*
* @Description: 未报到学生详情
* @return: Map<String,Object>
* @param page 分页参数
* @param pid 父节点代码
* @param year 查询的年份
* @param fields 需获取字段的代码
* @return
*/
@RequestMapping("queryWbdDetail")
@ResponseBody
public Map<String, Object> queryWbdDetail(String page, String pid, String year,String fields){
return studentsQualityService.queryWbdDetail(PageUtils.converPage(page), pid, year, JSONObject.parseArray(fields, String.class));
}
/**
*
* @Description: 获取学生未报到原因
* @return: Map<String,Object>
* @param page 分页参数
* @param year 查询的年份
* @param values 未报到原因ID
* @param fields 需获取字段的代码
* @return
*/
@RequestMapping("getNotReportReason")
@ResponseBody
public Map<String, Object> getNotReportReason(String page,String year,String values,String fields){
return studentsQualityService.getNotReportReason(PageUtils.converPage(page), year, values, JSONObject.parseArray(fields, String.class));
}
/**
* @Description: 下载
* @return: void
* @param page 分页参数
* @param pid 父节点代码
* @param year 查询的年份
* @param values 未报到原因ID
* @param fields 需获取的字段代码
* @param flag 样式改变标志代码
* @param point 分数值代码
* @param majorId 专业ID
* @param headers
* @param fileName
* @param request
* @param response
*/
@SuppressWarnings("unchecked")
@RequestMapping("down")
public void down(String page,String pid,String year,String values, String fields,String headers,
String fileName,String flag,String point,String majorId, HttpServletRequest request, HttpServletResponse response){
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("utf-8");
if(fileName == null) fileName = "下载文件";
try {
response.setHeader("Content-Disposition", "attachment;fileName=" +new String((fileName+".xls").getBytes(),"iso-8859-1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
List<String> fields2 = JSONObject.parseArray(fields, String.class),
headers2 = JSONObject.parseArray(headers, String.class);
Map<String, Object> map = new HashMap<String, Object>();
if(flag.equals("1")){
map = studentsQualityService.queryScoreLineByPro(PageUtils.converPage(page), flag, year, majorId);
}
if(flag.equals("2")){
map = studentsQualityService.queryStudentsScore(PageUtils.converPage(page), year, point, flag);
}
if(flag.equals("3")){
map = studentsQualityService.queryStudentsAdjust(PageUtils.converPage(page), year, flag);
}
if(flag.equals("4")){
map = studentsQualityService.queryStudentsEnroll(PageUtils.converPage(page), year, flag);
}
if(flag.equals("5")){
map = studentsQualityService.queryWbdDetail(PageUtils.converPage(page), pid, year, fields2);
}
if(flag.equals("6")){
map = studentsQualityService.getNotReportReason(PageUtils.converPage(page), year, values, fields2);
}
List<Map<String,Object>> list = (List<Map<String, Object>>) map.get("rows");
HSSFWorkbook workBook = ExcelUtils.createExcel(list, fields2, headers2, fileName);
try {
OutputStream os = response.getOutputStream();
workBook.write(os);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 8,718 | 0.742131 | 0.739281 | 272 | 28.669117 | 28.501692 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.753676 | false | false |
12
|
5f2e63d189e909179878b1b116a0afb4a9fe6bee
| 8,022,998,929,786 |
dd07d7521c40c0602cbcd4342986636b3ade7229
|
/user-service/user-service-provider/src/main/java/github/com/suitelhy/dingding/user/service/provider/domain/event/api/write/idempotence/UserIdempotentWriteEventImpl.java
|
aaa73c01da68bf13a725933fc877a14dec6f8bb3
|
[] |
no_license
|
bellmit/DingDing
|
https://github.com/bellmit/DingDing
|
7d1454a0ae6825b9b58ec1e4a0a13e10816f27cd
|
8a090e70966741713ec2ddc2b4d2261cf3b08695
|
refs/heads/master
| 2023-07-05T09:54:19.583000 | 2021-05-14T12:06:05 | 2021-05-14T12:06:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package github.com.suitelhy.dingding.user.service.provider.domain.event.api.write.idempotence;
import github.com.suitelhy.dingding.core.infrastructure.exception.BusinessAtomicException;
import github.com.suitelhy.dingding.security.service.api.domain.entity.User;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityRole;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityUser;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityUserRole;
import github.com.suitelhy.dingding.security.service.api.domain.vo.Security;
import github.com.suitelhy.dingding.user.service.api.domain.entity.UserAccountOperationInfo;
import github.com.suitelhy.dingding.user.service.api.domain.entity.UserPersonInfo;
import github.com.suitelhy.dingding.user.service.api.domain.event.write.idempotence.UserIdempotentWriteEvent;
import github.com.suitelhy.dingding.user.service.provider.domain.event.UserEvent;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.constraints.NotNull;
import java.util.Set;
/**
* 用户 - 复杂业务接口
*
* @Design
* · 写入操作
* · 幂等性
*
* @see User
* @see UserAccountOperationInfo
* @see UserPersonInfo
* @see github.com.suitelhy.dingding.core.infrastructure.config.dubbo.vo.Dubbo.Strategy.ClusterVo#FORKING
*/
@Service(cluster = "forking")
public class UserIdempotentWriteEventImpl
implements UserIdempotentWriteEvent {
@Autowired
private UserEvent userEvent;
/**
* 新增一个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param userRole {@linkplain SecurityUserRole [(安全认证)用户 ←→ 角色]}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在相同的有效数据}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUserRole userRole, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(userRole, operator);
}
/**
* 新增多个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param user {@linkplain SecurityUser [(安全认证)用户]}
* @param roles {@linkplain SecurityRole [(安全认证)角色]}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在完全相同的有效数据集合}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUser user, @NotNull Set<SecurityRole> roles, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(user, roles, operator);
}
/**
* 新增一个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param user {@linkplain SecurityUser [(安全认证)用户]}
* @param roleVo {@linkplain Security.RoleVo [(安全) 用户 -> 角色]}, 仅需保证合法性, 不需要保证持久化.
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在相同的有效数据}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUser user, Security.@NotNull RoleVo roleVo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(user, roleVo, operator);
}
/**
* 更新指定的用户 -> 基础信息
*
* @Description 完整的业务流程.
*
* @param user {@linkplain User 被修改的用户 -> 基础信息}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUser(@NotNull User user, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUser(user, operator);
}
/**
* 更新指定的用户 -> 账户操作基础记录
*
* @Description 完整的业务流程.
*
* @param userAccountOperationInfo {@linkplain UserAccountOperationInfo 被修改的用户 -> 账户操作基础记录}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUserAccountOperationInfo(@NotNull UserAccountOperationInfo userAccountOperationInfo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUserAccountOperationInfo(userAccountOperationInfo, operator);
}
/**
* 更新指定的用户 -> 个人信息
*
* @Description 完整的业务流程.
*
* @param userPersonInfo {@linkplain UserPersonInfo 被修改的用户 -> 个人信息}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUserPersonInfo(@NotNull UserPersonInfo userPersonInfo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUserPersonInfo(userPersonInfo, operator);
}
}
|
UTF-8
|
Java
| 5,816 |
java
|
UserIdempotentWriteEventImpl.java
|
Java
|
[
{
"context": "package github.com.suitelhy.dingding.user.service.provider.domain.event.api.w",
"end": 27,
"score": 0.6867735981941223,
"start": 23,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "ent.api.write.idempotence;\n\nimport github.com.suitelhy.dingding.core.infrastructure.exception.BusinessAt",
"end": 122,
"score": 0.720327615737915,
"start": 118,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "on.BusinessAtomicException;\nimport github.com.suitelhy.dingding.security.service.api.domain.entity.User;",
"end": 213,
"score": 0.778939962387085,
"start": 209,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "ice.api.domain.entity.User;\nimport github.com.suitelhy.dingding.security.service.api.domain.entity.secur",
"end": 290,
"score": 0.794194221496582,
"start": 286,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "tity.security.SecurityRole;\nimport github.com.suitelhy.dingding.security.service.api.domain.entity.secur",
"end": 384,
"score": 0.901799738407135,
"start": 380,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "tity.security.SecurityUser;\nimport github.com.suitelhy.dingding.security.service.api.domain.entity.secur",
"end": 478,
"score": 0.6955046653747559,
"start": 474,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": ".security.SecurityUserRole;\nimport github.com.suitelhy.dingding.security.service.api.domain.vo.Security;",
"end": 576,
"score": 0.7705237865447998,
"start": 572,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "ice.api.domain.vo.Security;\nimport github.com.suitelhy.dingding.user.service.api.domain.entity.UserAccou",
"end": 653,
"score": 0.838190495967865,
"start": 649,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "y.UserAccountOperationInfo;\nimport github.com.suitelhy.dingding.user.service.api.domain.entity.UserPerso",
"end": 746,
"score": 0.8416818380355835,
"start": 742,
"tag": "USERNAME",
"value": "elhy"
},
{
"context": "in.entity.UserPersonInfo;\nimport github.com.suitelhy.dingding.user.service.api.domain.event.write.idem",
"end": 829,
"score": 0.6848254203796387,
"start": 827,
"tag": "USERNAME",
"value": "hy"
},
{
"context": "e.UserIdempotentWriteEvent;\nimport github.com.suitelhy.dingding.user.service.provider.domain.event.UserE",
"end": 939,
"score": 0.8296166658401489,
"start": 935,
"tag": "USERNAME",
"value": "elhy"
}
] | null |
[] |
package github.com.suitelhy.dingding.user.service.provider.domain.event.api.write.idempotence;
import github.com.suitelhy.dingding.core.infrastructure.exception.BusinessAtomicException;
import github.com.suitelhy.dingding.security.service.api.domain.entity.User;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityRole;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityUser;
import github.com.suitelhy.dingding.security.service.api.domain.entity.security.SecurityUserRole;
import github.com.suitelhy.dingding.security.service.api.domain.vo.Security;
import github.com.suitelhy.dingding.user.service.api.domain.entity.UserAccountOperationInfo;
import github.com.suitelhy.dingding.user.service.api.domain.entity.UserPersonInfo;
import github.com.suitelhy.dingding.user.service.api.domain.event.write.idempotence.UserIdempotentWriteEvent;
import github.com.suitelhy.dingding.user.service.provider.domain.event.UserEvent;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.constraints.NotNull;
import java.util.Set;
/**
* 用户 - 复杂业务接口
*
* @Design
* · 写入操作
* · 幂等性
*
* @see User
* @see UserAccountOperationInfo
* @see UserPersonInfo
* @see github.com.suitelhy.dingding.core.infrastructure.config.dubbo.vo.Dubbo.Strategy.ClusterVo#FORKING
*/
@Service(cluster = "forking")
public class UserIdempotentWriteEventImpl
implements UserIdempotentWriteEvent {
@Autowired
private UserEvent userEvent;
/**
* 新增一个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param userRole {@linkplain SecurityUserRole [(安全认证)用户 ←→ 角色]}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在相同的有效数据}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUserRole userRole, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(userRole, operator);
}
/**
* 新增多个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param user {@linkplain SecurityUser [(安全认证)用户]}
* @param roles {@linkplain SecurityRole [(安全认证)角色]}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在完全相同的有效数据集合}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUser user, @NotNull Set<SecurityRole> roles, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(user, roles, operator);
}
/**
* 新增一个[(安全认证)用户 ←→ 角色]关联关系
*
* @Description 完整的业务流程.
*
* @param user {@linkplain SecurityUser [(安全认证)用户]}
* @param roleVo {@linkplain Security.RoleVo [(安全) 用户 -> 角色]}, 仅需保证合法性, 不需要保证持久化.
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功 / 是否已存在相同的有效数据}
*/
@Override
public boolean insertUserRoleRelationship(@NotNull SecurityUser user, Security.@NotNull RoleVo roleVo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.insertUserRoleRelationship(user, roleVo, operator);
}
/**
* 更新指定的用户 -> 基础信息
*
* @Description 完整的业务流程.
*
* @param user {@linkplain User 被修改的用户 -> 基础信息}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUser(@NotNull User user, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUser(user, operator);
}
/**
* 更新指定的用户 -> 账户操作基础记录
*
* @Description 完整的业务流程.
*
* @param userAccountOperationInfo {@linkplain UserAccountOperationInfo 被修改的用户 -> 账户操作基础记录}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUserAccountOperationInfo(@NotNull UserAccountOperationInfo userAccountOperationInfo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUserAccountOperationInfo(userAccountOperationInfo, operator);
}
/**
* 更新指定的用户 -> 个人信息
*
* @Description 完整的业务流程.
*
* @param userPersonInfo {@linkplain UserPersonInfo 被修改的用户 -> 个人信息}
* @param operator {@linkplain SecurityUser 操作者}
*
* @return {@linkplain Boolean#TYPE 操作是否成功}
*/
@Override
public boolean updateUserPersonInfo(@NotNull UserPersonInfo userPersonInfo, @NotNull SecurityUser operator)
throws IllegalArgumentException, BusinessAtomicException
{
return userEvent.updateUserPersonInfo(userPersonInfo, operator);
}
}
| 5,816 | 0.708917 | 0.708917 | 142 | 35.169014 | 35.655033 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323944 | false | false |
12
|
9d755c439fa7b87f66907c90eb7497aab446dcd5
| 10,866,267,323,824 |
12dff6f7d7d02102eb34769b82fe2ce8b5c3e2cc
|
/new1/l_12yaoqingxuesheng.java
|
5fec6be4215f72ded1fad8e951c154ffb89ffab9
|
[] |
no_license
|
Gry1005/projectHelper
|
https://github.com/Gry1005/projectHelper
|
feb7a2304909b2dc86daa8554b4cc40c0e145026
|
b991e38917e4aafd696ecc22290afd55607d4453
|
refs/heads/master
| 2020-03-29T13:26:24.285000 | 2018-09-23T07:58:14 | 2018-09-23T07:58:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bianlaoshi.new1;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by frank on 2017/11/27.
*/
public class l_12yaoqingxuesheng extends AppCompatActivity {
public static student s;
public static user u1;
private Handler handler=new Handler();
private List<studentcomment> scList=new ArrayList<studentcomment>();
private List<studentreview> srList=new ArrayList<studentreview>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_12yaoqingxuesheng);
ImageButton invite=(ImageButton) findViewById(R.id.imageButtonyaoqingx);
ImageButton jubao=(ImageButton) findViewById(R.id.imageButtonjubaox);
this.u1=l_1shouye.u1;
RecyclerView r1=(RecyclerView)findViewById(R.id.r1);
r1.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
r1.setAdapter(new MemberAdapter(this));
String url="http://112.74.176.171:8080/xmb/servlet/l_12Servlet?sid="+s.getSid();
l_12yaoqingxueshengThread thread=new l_12yaoqingxueshengThread(url,this,handler,scList);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
String url1="http://112.74.176.171:8080/xmb/servlet/returnReviewServlet?sid="+s.getSid();
studentReviewThread srt=new studentReviewThread(url1,this,srList);
srt.start();
try {
srt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
invite.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setTitle("确认")
.setMessage("确定邀请该名学生吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chooseStudentActivity.s1=s;
chooseStudentActivity.u1=u1;
Intent intent=new Intent(l_12yaoqingxuesheng.this,chooseStudentActivity.class);
l_12yaoqingxuesheng.this.startActivity(intent);
}
})
.setNegativeButton("取消",null)
.show();
}
});
jubao.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setTitle("确认")
.setMessage("确定举报该名学生吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String url="http://112.74.176.171:8080/xmb/servlet/jubaoServlet?order=0&uid="+s.getSid();
//order: 0 user 1 project
new jubaoThread(url).start();
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setMessage("举报成功")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(l_12yaoqingxuesheng.this,L_Discovery.class);
startActivity(intent);
}
})
.show();
}
})
.setNegativeButton("取消",null)
.show();
}
});
}
private class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder>{
private LayoutInflater layoutInflater;
private Context context;
public MemberAdapter(Context context)
{
this.context=context;
this.layoutInflater=LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==0)
{
View itemView = layoutInflater.inflate(R.layout.header, parent, false);
return new ViewHolder(itemView);
}
else if(viewType==1)
{
View itemView = layoutInflater.inflate(R.layout.l_12item, parent, false);
return new SecondViewHolder(itemView);
}
else if(viewType==2)
{
View itemView = layoutInflater.inflate(R.layout.l_12item, parent, false);
return new ThirdViewHolder(itemView);
}
else if(viewType==3)
{
View itemView = layoutInflater.inflate(R.layout.divider1, parent, false);
return new FourthViewHolder(itemView);
}
else if(viewType==5)
{
View itemView = layoutInflater.inflate(R.layout.divider3, parent, false);
return new FourthViewHolder(itemView);
}
else if(viewType==6)
{
View itemView = layoutInflater.inflate(R.layout.divider4, parent, false);
return new FourthViewHolder(itemView);
}
else
{
View itemView = layoutInflater.inflate(R.layout.divider, parent, false);
return new FourthViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
switch (getItemViewType(position))
{
case 0: //姓名学校特长等
ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.mname.setText(s.getSname());
viewHolder.school.setText(s.getSschool());
viewHolder.strong.setText(s.getSadvantage());
viewHolder.else1.setText(s.getSintroduction());
break;
case 1: //老师评价
SecondViewHolder secondViewHolder = (SecondViewHolder) holder;
secondViewHolder.mname.setText(scList.get(position-2).getPname());
secondViewHolder.zhize.setText(scList.get(position-2).getSctag());
secondViewHolder.pingjia.setText(scList.get(position-2).getSccomment());
break;
case 2: //自我评价
ThirdViewHolder holder2 = (ThirdViewHolder) holder;
holder2.mname.setText(srList.get(position-scList.size()-3).getSrpname());
holder2.zhize.setText(srList.get(position-scList.size()-3).getSrjob());
holder2.pingjia.setText(srList.get(position-scList.size()-3).getSrreview());
break;
case 3: //老师评价分割线
break;
case 4: //自我评价分割线
break;
case 5: //老师评价暂无分割线
break;
case 6:
break;
}
}
@Override
public int getItemCount() {
return scList.size()+srList.size()+3;
}
public int getItemViewType(int position)
{
if(position==0)//姓名学校特长等
{
return 0;
}
else if(position==1&&scList.size()!=0) //老师评价分割线
{
return 3;
}
else if(position==1&&scList.size()==0) //老师评价分割线
{
return 5;
}
else if(position<=scList.size()+1&&position>1)//老师评价
{
return 1;
}
else if(position==scList.size()+2&&srList.size()!=0)//自我评价分割线
{
return 4;
}
else if(position==scList.size()+2&&srList.size()==0)//自我评价暂无分割线
{
return 6;
}
else //自我评价
{
return 2;
}
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView mname;
private TextView school;
private TextView strong;
private TextView else1;
public ViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView11);
school=(TextView)itemView.findViewById(R.id.textView12);
strong=(TextView)itemView.findViewById(R.id.textView58);
else1=(TextView)itemView.findViewById(R.id.textView13);
}
}
private class SecondViewHolder extends ViewHolder {
private TextView mname;
private TextView zhize;
private TextView pingjia;
public SecondViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView141);
zhize=(TextView)itemView.findViewById(R.id.textView161);
pingjia=(TextView)itemView.findViewById(R.id.textView181);
}
}
private class ThirdViewHolder extends ViewHolder {
private TextView mname;
private TextView zhize;
private TextView pingjia;
public ThirdViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView141);
zhize=(TextView)itemView.findViewById(R.id.textView161);
pingjia=(TextView)itemView.findViewById(R.id.textView181);
}
}
private class FourthViewHolder extends ViewHolder {
private Button b1;
public FourthViewHolder(View itemView){
super(itemView);
b1= (Button) findViewById(R.id.button8);
}
}
/* private class FifthViewHolder extends ViewHolder {
private Button b2;
public FifthViewHolder(View itemView){
super(itemView);
b2= (Button) findViewById(R.id.button8);
}
}*/
}
}
|
UTF-8
|
Java
| 11,642 |
java
|
l_12yaoqingxuesheng.java
|
Java
|
[
{
"context": "ayList;\nimport java.util.List;\n\n\n/**\n * Created by frank on 2017/11/27.\n */\n\npublic class l_12yaoqingxuesh",
"end": 653,
"score": 0.9988222122192383,
"start": 648,
"tag": "USERNAME",
"value": "frank"
},
{
"context": "emberAdapter(this));\n\n\n String url=\"http://112.74.176.171:8080/xmb/servlet/l_12Servlet?sid=\"+s.getSid();\n ",
"end": 1580,
"score": 0.9997261762619019,
"start": 1566,
"tag": "IP_ADDRESS",
"value": "112.74.176.171"
},
{
"context": "ackTrace();\n }\n String url1=\"http://112.74.176.171:8080/xmb/servlet/returnReviewServlet?sid=\"+s.getS",
"end": 1918,
"score": 0.9996119141578674,
"start": 1904,
"tag": "IP_ADDRESS",
"value": "112.74.176.171"
},
{
"context": " String url=\"http://112.74.176.171:8080/xmb/servlet/jubaoServlet?order=0&uid=\"+s.get",
"end": 3734,
"score": 0.9996967911720276,
"start": 3720,
"tag": "IP_ADDRESS",
"value": "112.74.176.171"
}
] | null |
[] |
package com.bianlaoshi.new1;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by frank on 2017/11/27.
*/
public class l_12yaoqingxuesheng extends AppCompatActivity {
public static student s;
public static user u1;
private Handler handler=new Handler();
private List<studentcomment> scList=new ArrayList<studentcomment>();
private List<studentreview> srList=new ArrayList<studentreview>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_12yaoqingxuesheng);
ImageButton invite=(ImageButton) findViewById(R.id.imageButtonyaoqingx);
ImageButton jubao=(ImageButton) findViewById(R.id.imageButtonjubaox);
this.u1=l_1shouye.u1;
RecyclerView r1=(RecyclerView)findViewById(R.id.r1);
r1.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
r1.setAdapter(new MemberAdapter(this));
String url="http://172.16.31.10:8080/xmb/servlet/l_12Servlet?sid="+s.getSid();
l_12yaoqingxueshengThread thread=new l_12yaoqingxueshengThread(url,this,handler,scList);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
String url1="http://172.16.31.10:8080/xmb/servlet/returnReviewServlet?sid="+s.getSid();
studentReviewThread srt=new studentReviewThread(url1,this,srList);
srt.start();
try {
srt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
invite.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setTitle("确认")
.setMessage("确定邀请该名学生吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chooseStudentActivity.s1=s;
chooseStudentActivity.u1=u1;
Intent intent=new Intent(l_12yaoqingxuesheng.this,chooseStudentActivity.class);
l_12yaoqingxuesheng.this.startActivity(intent);
}
})
.setNegativeButton("取消",null)
.show();
}
});
jubao.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setTitle("确认")
.setMessage("确定举报该名学生吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String url="http://172.16.31.10:8080/xmb/servlet/jubaoServlet?order=0&uid="+s.getSid();
//order: 0 user 1 project
new jubaoThread(url).start();
new AlertDialog.Builder(l_12yaoqingxuesheng.this)
.setMessage("举报成功")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(l_12yaoqingxuesheng.this,L_Discovery.class);
startActivity(intent);
}
})
.show();
}
})
.setNegativeButton("取消",null)
.show();
}
});
}
private class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder>{
private LayoutInflater layoutInflater;
private Context context;
public MemberAdapter(Context context)
{
this.context=context;
this.layoutInflater=LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==0)
{
View itemView = layoutInflater.inflate(R.layout.header, parent, false);
return new ViewHolder(itemView);
}
else if(viewType==1)
{
View itemView = layoutInflater.inflate(R.layout.l_12item, parent, false);
return new SecondViewHolder(itemView);
}
else if(viewType==2)
{
View itemView = layoutInflater.inflate(R.layout.l_12item, parent, false);
return new ThirdViewHolder(itemView);
}
else if(viewType==3)
{
View itemView = layoutInflater.inflate(R.layout.divider1, parent, false);
return new FourthViewHolder(itemView);
}
else if(viewType==5)
{
View itemView = layoutInflater.inflate(R.layout.divider3, parent, false);
return new FourthViewHolder(itemView);
}
else if(viewType==6)
{
View itemView = layoutInflater.inflate(R.layout.divider4, parent, false);
return new FourthViewHolder(itemView);
}
else
{
View itemView = layoutInflater.inflate(R.layout.divider, parent, false);
return new FourthViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
switch (getItemViewType(position))
{
case 0: //姓名学校特长等
ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.mname.setText(s.getSname());
viewHolder.school.setText(s.getSschool());
viewHolder.strong.setText(s.getSadvantage());
viewHolder.else1.setText(s.getSintroduction());
break;
case 1: //老师评价
SecondViewHolder secondViewHolder = (SecondViewHolder) holder;
secondViewHolder.mname.setText(scList.get(position-2).getPname());
secondViewHolder.zhize.setText(scList.get(position-2).getSctag());
secondViewHolder.pingjia.setText(scList.get(position-2).getSccomment());
break;
case 2: //自我评价
ThirdViewHolder holder2 = (ThirdViewHolder) holder;
holder2.mname.setText(srList.get(position-scList.size()-3).getSrpname());
holder2.zhize.setText(srList.get(position-scList.size()-3).getSrjob());
holder2.pingjia.setText(srList.get(position-scList.size()-3).getSrreview());
break;
case 3: //老师评价分割线
break;
case 4: //自我评价分割线
break;
case 5: //老师评价暂无分割线
break;
case 6:
break;
}
}
@Override
public int getItemCount() {
return scList.size()+srList.size()+3;
}
public int getItemViewType(int position)
{
if(position==0)//姓名学校特长等
{
return 0;
}
else if(position==1&&scList.size()!=0) //老师评价分割线
{
return 3;
}
else if(position==1&&scList.size()==0) //老师评价分割线
{
return 5;
}
else if(position<=scList.size()+1&&position>1)//老师评价
{
return 1;
}
else if(position==scList.size()+2&&srList.size()!=0)//自我评价分割线
{
return 4;
}
else if(position==scList.size()+2&&srList.size()==0)//自我评价暂无分割线
{
return 6;
}
else //自我评价
{
return 2;
}
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView mname;
private TextView school;
private TextView strong;
private TextView else1;
public ViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView11);
school=(TextView)itemView.findViewById(R.id.textView12);
strong=(TextView)itemView.findViewById(R.id.textView58);
else1=(TextView)itemView.findViewById(R.id.textView13);
}
}
private class SecondViewHolder extends ViewHolder {
private TextView mname;
private TextView zhize;
private TextView pingjia;
public SecondViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView141);
zhize=(TextView)itemView.findViewById(R.id.textView161);
pingjia=(TextView)itemView.findViewById(R.id.textView181);
}
}
private class ThirdViewHolder extends ViewHolder {
private TextView mname;
private TextView zhize;
private TextView pingjia;
public ThirdViewHolder(View itemView){
super(itemView);
mname=(TextView)itemView.findViewById(R.id.textView141);
zhize=(TextView)itemView.findViewById(R.id.textView161);
pingjia=(TextView)itemView.findViewById(R.id.textView181);
}
}
private class FourthViewHolder extends ViewHolder {
private Button b1;
public FourthViewHolder(View itemView){
super(itemView);
b1= (Button) findViewById(R.id.button8);
}
}
/* private class FifthViewHolder extends ViewHolder {
private Button b2;
public FifthViewHolder(View itemView){
super(itemView);
b2= (Button) findViewById(R.id.button8);
}
}*/
}
}
| 11,636 | 0.531491 | 0.515614 | 308 | 36.012985 | 28.503586 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522727 | false | false |
12
|
3d8a21993358110fe37e48cf915f8112b842ace1
| 35,244,501,683,893 |
725638b5f628de74dce207f926a458b2052d3358
|
/ydhy-service/src/main/java/com/example/ydhy/dto/UserInfo.java
|
b897df565b7befc4678bccc95917b98f4dd728d1
|
[] |
no_license
|
waveFuzf/ydhy
|
https://github.com/waveFuzf/ydhy
|
c2d4eae2a0da1bbf87047427e2d2832db9b77ede
|
b39ce1611eb8128257098f7ce4b052dec335d96d
|
refs/heads/master
| 2020-04-05T03:31:14.154000 | 2019-02-15T09:29:42 | 2019-02-15T09:29:42 | 156,475,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ydhy.dto;
import lombok.Data;
@Data
public class UserInfo {
private Integer id;
private String realName;
private String phone;
private String email;
private Integer deptId;
private String vchatNum;
}
|
UTF-8
|
Java
| 251 |
java
|
UserInfo.java
|
Java
|
[] | null |
[] |
package com.example.ydhy.dto;
import lombok.Data;
@Data
public class UserInfo {
private Integer id;
private String realName;
private String phone;
private String email;
private Integer deptId;
private String vchatNum;
}
| 251 | 0.705179 | 0.705179 | 18 | 12.944445 | 12.509872 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
12
|
0ee82e68fefa6a0a079f18acc65cd40b2b6c4508
| 36,704,790,546,153 |
3703f77103bf3a5acf0ac139ede2a1b151b83b56
|
/actions/pageObjectPayment/WithdrawPageObject.java
|
75a7753673a62ed00e6836c60f11de1fad8c7a5c
|
[] |
no_license
|
ngongoctram/POM_BANKGURU_11_TRAMNTN
|
https://github.com/ngongoctram/POM_BANKGURU_11_TRAMNTN
|
40a8e32a4779344b159743c3799fef500b63aa6c
|
9c1036a51c78701a3b2a50ce5a1fc0a92dcd777a
|
refs/heads/master
| 2022-04-03T00:10:35.124000 | 2019-12-01T17:36:31 | 2019-12-01T17:36:31 | 207,830,687 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pageObjectPayment;
import org.openqa.selenium.WebDriver;
import commons.AbstractPages;
import pageUIForPayment.WithdrawPageUI;
public class WithdrawPageObject extends AbstractPages {
private WebDriver driver;
public WithdrawPageObject(WebDriver driver) {
this.driver = driver;
}
public boolean isDisplayedMsgSuccess() {
waitToElementVisible(driver, WithdrawPageUI.TRANS_WITHDRAWAL_MSG);
return isElementDisplayed(driver, WithdrawPageUI.TRANS_WITHDRAWAL_MSG);
}
public String getCurrentAmount() {
waitToElementVisible(driver, WithdrawPageUI.CRRENT_BALANCE);
return getText(driver, WithdrawPageUI.CRRENT_BALANCE);
}
}
|
UTF-8
|
Java
| 673 |
java
|
WithdrawPageObject.java
|
Java
|
[] | null |
[] |
package pageObjectPayment;
import org.openqa.selenium.WebDriver;
import commons.AbstractPages;
import pageUIForPayment.WithdrawPageUI;
public class WithdrawPageObject extends AbstractPages {
private WebDriver driver;
public WithdrawPageObject(WebDriver driver) {
this.driver = driver;
}
public boolean isDisplayedMsgSuccess() {
waitToElementVisible(driver, WithdrawPageUI.TRANS_WITHDRAWAL_MSG);
return isElementDisplayed(driver, WithdrawPageUI.TRANS_WITHDRAWAL_MSG);
}
public String getCurrentAmount() {
waitToElementVisible(driver, WithdrawPageUI.CRRENT_BALANCE);
return getText(driver, WithdrawPageUI.CRRENT_BALANCE);
}
}
| 673 | 0.780089 | 0.780089 | 25 | 24.92 | 24.559999 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.24 | false | false |
12
|
05c10e041f2cc12f1c12d4bdc1c6da0cd45c363a
| 36,575,941,531,475 |
70ec881c4e14021b9e2f7569fcc194f37c341761
|
/src/liuxiaochun/L_Test.java
|
bed871719d2edb18c56ad0464098012aa6d077cd
|
[] |
no_license
|
Lxc123151321/Git_Test
|
https://github.com/Lxc123151321/Git_Test
|
2030a12cdeefae77ec6b5d218986c187af0866bb
|
0157ea28dd7fe9f11f4b77c22e31b929f91b533d
|
refs/heads/master
| 2020-07-09T02:03:07.978000 | 2019-08-23T02:19:13 | 2019-08-23T02:19:13 | 203,844,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package liuxiaochun;
public class L_Test {
public static void main(String[] args) {
System.out.println("H1ello wo11rld!");
}
}
|
UTF-8
|
Java
| 139 |
java
|
L_Test.java
|
Java
|
[] | null |
[] |
package liuxiaochun;
public class L_Test {
public static void main(String[] args) {
System.out.println("H1ello wo11rld!");
}
}
| 139 | 0.669065 | 0.647482 | 7 | 17.857143 | 16.452778 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false |
12
|
bd5c1025aa884cc6d82afff3f1632bc5ead1f37f
| 3,745,211,549,307 |
91976fd1f8fd6f459f44ca5dbe36d32470287c78
|
/src/main/java/com/biu/generate/mapper/NoticeMapper.java
|
25aa95eca0ccd278f9d723905252c3039711621d
|
[
"Apache-2.0"
] |
permissive
|
lihongwu19921215/FastDev
|
https://github.com/lihongwu19921215/FastDev
|
010e08f977b4e9e23d03b77da6a2b276f37a5349
|
359727a786c3be24f418c0fcf2c3c3ecae925d0c
|
refs/heads/master
| 2021-01-19T16:09:40.767000 | 2017-03-07T10:26:29 | 2017-03-07T10:26:29 | 88,251,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.biu.generate.mapper;
import com.biu.common.persistence.annotation.MyBatisRepository;
import com.biu.generate.model.Notice;
import com.biu.system.util.MapperUtils;
/**
* Created by Biu.
* 2017-03-07 15:42:08
*/
@MyBatisRepository
public interface NoticeMapper extends MapperUtils<Notice> {
}
|
UTF-8
|
Java
| 312 |
java
|
NoticeMapper.java
|
Java
|
[] | null |
[] |
package com.biu.generate.mapper;
import com.biu.common.persistence.annotation.MyBatisRepository;
import com.biu.generate.model.Notice;
import com.biu.system.util.MapperUtils;
/**
* Created by Biu.
* 2017-03-07 15:42:08
*/
@MyBatisRepository
public interface NoticeMapper extends MapperUtils<Notice> {
}
| 312 | 0.772436 | 0.727564 | 15 | 19.799999 | 21.251511 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false |
12
|
63992d19b029745d08564ea7fa8f48efe7b37767
| 38,628,935,887,583 |
9958af291a59a57ee6db4ed5f320e0276d24cbea
|
/app/src/main/java/com/viettel/bss/viettelpos/v4/connecttionMobile/beans/ProductOfferCharacterClone.java
|
e1d9ef804f7690e25d51eb789ba21cf234d68105
|
[] |
no_license
|
mincasoft/mBCCS_VTT_real_22022016
|
https://github.com/mincasoft/mBCCS_VTT_real_22022016
|
32ace9ec32b0476959726f91bbb1853b56c78631
|
0434b4bf83d021f58ec557552ac0fb913a88db96
|
refs/heads/master
| 2020-05-16T12:51:00.358000 | 2018-01-02T07:49:09 | 2018-01-02T07:49:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.viettel.bss.viettelpos.v4.connecttionMobile.beans;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import java.io.Serializable;
/**
* Created by thinhhq1 on 8/12/2017.
*/
@Root(name = "productOfferCharacterClone", strict = false)
public class ProductOfferCharacterClone implements Serializable{
@Element(name = "listingPrice", required = false)
private String listingPrice;
@Element(name = "upLoadSpeed", required = false)
private String upLoadSpeed;
@Element(name = "downLoadSpeed", required = false)
private String downLoadSpeed;
public ProductOfferCharacterClone() {
}
public String getListingPrice() {
return listingPrice;
}
public void setListingPrice(String listingPrice) {
this.listingPrice = listingPrice;
}
public String getUpLoadSpeed() {
return upLoadSpeed;
}
public ProductOfferCharacterClone(String listingPrice, String upLoadSpeed, String downLoadSpeed) {
this.listingPrice = listingPrice;
this.upLoadSpeed = upLoadSpeed;
this.downLoadSpeed = downLoadSpeed;
}
public void setUpLoadSpeed(String upLoadSpeed) {
this.upLoadSpeed = upLoadSpeed;
}
public String getDownLoadSpeed() {
return downLoadSpeed;
}
public void setDownLoadSpeed(String downLoadSpeed) {
this.downLoadSpeed = downLoadSpeed;
}
}
|
UTF-8
|
Java
| 1,424 |
java
|
ProductOfferCharacterClone.java
|
Java
|
[
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by thinhhq1 on 8/12/2017.\n */\n@Root(name = \"productOfferChara",
"end": 198,
"score": 0.9995570778846741,
"start": 190,
"tag": "USERNAME",
"value": "thinhhq1"
}
] | null |
[] |
package com.viettel.bss.viettelpos.v4.connecttionMobile.beans;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import java.io.Serializable;
/**
* Created by thinhhq1 on 8/12/2017.
*/
@Root(name = "productOfferCharacterClone", strict = false)
public class ProductOfferCharacterClone implements Serializable{
@Element(name = "listingPrice", required = false)
private String listingPrice;
@Element(name = "upLoadSpeed", required = false)
private String upLoadSpeed;
@Element(name = "downLoadSpeed", required = false)
private String downLoadSpeed;
public ProductOfferCharacterClone() {
}
public String getListingPrice() {
return listingPrice;
}
public void setListingPrice(String listingPrice) {
this.listingPrice = listingPrice;
}
public String getUpLoadSpeed() {
return upLoadSpeed;
}
public ProductOfferCharacterClone(String listingPrice, String upLoadSpeed, String downLoadSpeed) {
this.listingPrice = listingPrice;
this.upLoadSpeed = upLoadSpeed;
this.downLoadSpeed = downLoadSpeed;
}
public void setUpLoadSpeed(String upLoadSpeed) {
this.upLoadSpeed = upLoadSpeed;
}
public String getDownLoadSpeed() {
return downLoadSpeed;
}
public void setDownLoadSpeed(String downLoadSpeed) {
this.downLoadSpeed = downLoadSpeed;
}
}
| 1,424 | 0.706461 | 0.70014 | 53 | 25.867924 | 23.737589 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415094 | false | false |
12
|
1fa4489a404c3fd26f5c738d7d0599007c460e74
| 36,618,891,208,258 |
7989fc5119dfc0fe211578be475c677a97cba07e
|
/app/src/main/java/com/sakeenahstudios/roomwordsample/Word.java
|
835a86c4790ff52f0d25bf17337b8d4ba8727b70
|
[] |
no_license
|
theSalafee/AndroidRoomWithAView
|
https://github.com/theSalafee/AndroidRoomWithAView
|
e239aa89446eb9f24d84b3aaa18f9eeaae51bcf6
|
3d2b216b392671bfa7bbc8b5dcb8e0542c72dfe4
|
refs/heads/master
| 2022-11-23T06:27:19.928000 | 2020-08-01T18:46:51 | 2020-08-01T18:46:51 | 282,369,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sakeenahstudios.roomwordsample;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/*
db tables are called Entities which equate to SQLite tables. Each property represents
a column in the table
*/
// @Entity annotation to declare the tableName
@Entity(tableName = "word_table")
public class Word {
// Annotations to set PrimaryKey, Constraints, column name
// word = NonNull
// word = Primary Key
// autogenerate option
/* @PrimaryKey(autoGenerate = true)
private int id;
*/
@PrimaryKey
@NonNull
@ColumnInfo(name = "word")
private String mWord;
// Class constructor
public Word(@NonNull String word) {this.mWord = word;}
// get word
public String getWord () {
return this.mWord;
}
}
|
UTF-8
|
Java
| 863 |
java
|
Word.java
|
Java
|
[] | null |
[] |
package com.sakeenahstudios.roomwordsample;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/*
db tables are called Entities which equate to SQLite tables. Each property represents
a column in the table
*/
// @Entity annotation to declare the tableName
@Entity(tableName = "word_table")
public class Word {
// Annotations to set PrimaryKey, Constraints, column name
// word = NonNull
// word = Primary Key
// autogenerate option
/* @PrimaryKey(autoGenerate = true)
private int id;
*/
@PrimaryKey
@NonNull
@ColumnInfo(name = "word")
private String mWord;
// Class constructor
public Word(@NonNull String word) {this.mWord = word;}
// get word
public String getWord () {
return this.mWord;
}
}
| 863 | 0.687138 | 0.687138 | 38 | 21.710526 | 19.734964 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.289474 | false | false |
12
|
e5ef6e76e993ede9faaab47b472974f2c55cc367
| 39,127,152,088,758 |
eb1bbe97f34817e1c261fb5f4dd3e9bea39d28fd
|
/src/com/scurab/web/drifmaps/client/validation/NotZeroValidation.java
|
b49482de78dd2868b91835422f6265a0dabeb210
|
[] |
no_license
|
jbruchanov/MyPlaces.Server
|
https://github.com/jbruchanov/MyPlaces.Server
|
1cf5dda13ad2fd041bbc0900bfbba36163504c4b
|
e799c58d6d16edafc9424c7dfb8bcdad72471ecb
|
refs/heads/master
| 2016-09-02T03:23:57.857000 | 2012-09-09T11:33:27 | 2012-09-09T11:33:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.scurab.web.drifmaps.client.validation;
import com.pietschy.gwt.pectin.client.form.validation.ValidationResultCollector;
import com.pietschy.gwt.pectin.client.form.validation.Validator;
import com.pietschy.gwt.pectin.client.form.validation.message.ErrorMessage;
public class NotZeroValidation implements Validator<Double>
{
private String message;
private String infoMessage;
public NotZeroValidation(String message)
{
this(message, null);
}
public NotZeroValidation(String message, String infoMessage)
{
this.message = message;
this.infoMessage = infoMessage;
}
@Override
public void validate(Double value, ValidationResultCollector results)
{
if (value == 0)
results.add(new ErrorMessage(message, infoMessage));
}
}
|
UTF-8
|
Java
| 760 |
java
|
NotZeroValidation.java
|
Java
|
[] | null |
[] |
package com.scurab.web.drifmaps.client.validation;
import com.pietschy.gwt.pectin.client.form.validation.ValidationResultCollector;
import com.pietschy.gwt.pectin.client.form.validation.Validator;
import com.pietschy.gwt.pectin.client.form.validation.message.ErrorMessage;
public class NotZeroValidation implements Validator<Double>
{
private String message;
private String infoMessage;
public NotZeroValidation(String message)
{
this(message, null);
}
public NotZeroValidation(String message, String infoMessage)
{
this.message = message;
this.infoMessage = infoMessage;
}
@Override
public void validate(Double value, ValidationResultCollector results)
{
if (value == 0)
results.add(new ErrorMessage(message, infoMessage));
}
}
| 760 | 0.788158 | 0.786842 | 30 | 24.333334 | 26.858063 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false |
12
|
3e542760cea6327962e1ce9038cd12835568d382
| 24,266,565,284,194 |
921f0a61a015dd44bd88f2a8e5247ca1f70f3fab
|
/src/thinkingJavaWeekend_09/interfaceCollisions/I1.java
|
bf0460d49529d3d4829d24bc2390d7f8f09bbfa7
|
[] |
no_license
|
Ckattik/bookBruceEckelThinkingInJava
|
https://github.com/Ckattik/bookBruceEckelThinkingInJava
|
823c92da857f57305657711d9f7c6ba72b19060b
|
6d64f0f0261fd29a48ad7c01bb6913e987822cad
|
refs/heads/master
| 2020-09-02T16:17:28.150000 | 2019-12-03T05:33:00 | 2019-12-03T05:33:00 | 219,256,734 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package thinkingJavaWeekend_09.interfaceCollisions;
public interface I1 {
void f();
}
|
UTF-8
|
Java
| 98 |
java
|
I1.java
|
Java
|
[] | null |
[] |
package thinkingJavaWeekend_09.interfaceCollisions;
public interface I1 {
void f();
}
| 98 | 0.704082 | 0.673469 | 7 | 12 | 17.468338 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
12
|
a442df467ab706cc5b363bedc4fd590a008e4262
| 12,936,441,528,990 |
31b1ec6e628e86fc8b8887b431b99a382bced1bd
|
/pzy-domain/src/main/java/org/pzy/opensource/domain/enums/LocalDateTimePatternEnum.java
|
f5e8c2d77cc5b904bcf9eb46e51a1e542491dec6
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-mulanpsl-1.0-en",
"MulanPSL-1.0"
] |
permissive
|
free-pan/pzy-opensource
|
https://github.com/free-pan/pzy-opensource
|
211e78a7a697bf2f5b277efaae72a12f3cd35bd3
|
1b7a0121111bb422d5eaec4fcaa1de5a7a872119
|
refs/heads/master
| 2022-12-25T08:58:01.802000 | 2021-01-23T04:49:28 | 2021-01-23T04:49:28 | 248,950,490 | 0 | 0 |
NOASSERTION
| false | 2022-12-14T20:43:42 | 2020-03-21T10:11:07 | 2021-10-29T13:04:18 | 2022-12-14T20:43:42 | 14,152 | 1 | 0 | 7 |
Java
| false | false |
package org.pzy.opensource.domain.enums;
import org.pzy.opensource.domain.GlobalConstant;
import org.pzy.opensource.domain.entity.BaseEnum;
/**
* 日期格式字符串枚举
*
* @author pan
* @date 2020/4/5 16:55
*/
public enum LocalDateTimePatternEnum implements BaseEnum<String> {
/**
* 日期模式字符串: yyyy-MM-dd
*/
DATE_PATTERN(GlobalConstant.DATE_PATTERN),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:ss
*/
DATE_TIME_PATTERN(GlobalConstant.DATE_TIME_PATTERN),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm
*/
DATE_TIME_PATTERN_B(GlobalConstant.DATE_TIME_PATTERN_B),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:00
*/
DATE_TIME_PATTERN_C(GlobalConstant.DATE_TIME_PATTERN_C),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:59
*/
DATE_TIME_PATTERN_D(GlobalConstant.DATE_TIME_PATTERN_D),
/**
* 日期时间字符串: yyyy-MM-dd 00:00:00
*/
DATE_TIME_PATTERN_E(GlobalConstant.DATE_TIME_PATTERN_E),
/**
* 日期时间字符串: yyyy-MM-dd 23:59:59
*/
DATE_TIME_PATTERN_F(GlobalConstant.DATE_TIME_PATTERN_F),
/**
* 日期时间字符串: yyyy-MM-dd 00:00
*/
DATE_TIME_PATTERN_G(GlobalConstant.DATE_TIME_PATTERN_G),
/**
* 日期时间字符串: yyyy-MM-dd 23:59
*/
DATE_TIME_PATTERN_H(GlobalConstant.DATE_TIME_PATTERN_H);
/**
* 日期格式
*/
private String code;
LocalDateTimePatternEnum(String code) {
this.code = code;
}
@Override
public String getCode() {
return code;
}
@Override
public void setCode(String code) {
this.code = code;
}
}
|
UTF-8
|
Java
| 1,697 |
java
|
LocalDateTimePatternEnum.java
|
Java
|
[
{
"context": "n.entity.BaseEnum;\n\n/**\n * 日期格式字符串枚举\n *\n * @author pan\n * @date 2020/4/5 16:55\n */\npublic enum LocalDate",
"end": 176,
"score": 0.9922633171081543,
"start": 173,
"tag": "USERNAME",
"value": "pan"
}
] | null |
[] |
package org.pzy.opensource.domain.enums;
import org.pzy.opensource.domain.GlobalConstant;
import org.pzy.opensource.domain.entity.BaseEnum;
/**
* 日期格式字符串枚举
*
* @author pan
* @date 2020/4/5 16:55
*/
public enum LocalDateTimePatternEnum implements BaseEnum<String> {
/**
* 日期模式字符串: yyyy-MM-dd
*/
DATE_PATTERN(GlobalConstant.DATE_PATTERN),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:ss
*/
DATE_TIME_PATTERN(GlobalConstant.DATE_TIME_PATTERN),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm
*/
DATE_TIME_PATTERN_B(GlobalConstant.DATE_TIME_PATTERN_B),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:00
*/
DATE_TIME_PATTERN_C(GlobalConstant.DATE_TIME_PATTERN_C),
/**
* 日期时间字符串: yyyy-MM-dd HH:mm:59
*/
DATE_TIME_PATTERN_D(GlobalConstant.DATE_TIME_PATTERN_D),
/**
* 日期时间字符串: yyyy-MM-dd 00:00:00
*/
DATE_TIME_PATTERN_E(GlobalConstant.DATE_TIME_PATTERN_E),
/**
* 日期时间字符串: yyyy-MM-dd 23:59:59
*/
DATE_TIME_PATTERN_F(GlobalConstant.DATE_TIME_PATTERN_F),
/**
* 日期时间字符串: yyyy-MM-dd 00:00
*/
DATE_TIME_PATTERN_G(GlobalConstant.DATE_TIME_PATTERN_G),
/**
* 日期时间字符串: yyyy-MM-dd 23:59
*/
DATE_TIME_PATTERN_H(GlobalConstant.DATE_TIME_PATTERN_H);
/**
* 日期格式
*/
private String code;
LocalDateTimePatternEnum(String code) {
this.code = code;
}
@Override
public String getCode() {
return code;
}
@Override
public void setCode(String code) {
this.code = code;
}
}
| 1,697 | 0.60712 | 0.585113 | 69 | 21.391304 | 20.20849 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.231884 | false | false |
12
|
8b0d450f652b79aeac9055b6d94eb65587f25f38
| 14,362,370,701,395 |
9de95e5c649a0177a34765b75fc23dfbb22feaf5
|
/src/simpledb/index/hash/ExtensibleHashIndex.java
|
96b53301ed34d1a90396167835410d82f0c00a9f
|
[] |
no_license
|
SIZMW/cs4432-proj2
|
https://github.com/SIZMW/cs4432-proj2
|
43c537fffd684e16509ce91e90e860499981ac02
|
3109d1c9d5eeef13ce3bb38e17920041f33278a4
|
refs/heads/master
| 2021-01-10T15:34:51.595000 | 2015-10-17T01:34:51 | 2015-10-17T01:34:51 | 43,500,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package simpledb.index.hash;
import java.util.ArrayList;
import java.util.List;
import simpledb.index.Index;
import simpledb.query.Constant;
import simpledb.query.TableScan;
import simpledb.record.RID;
import simpledb.record.Schema;
import simpledb.record.TableInfo;
import simpledb.tx.Transaction;
/**
* CS 4432 Project 2
*
* This class is the extensible hash index implementation.
*
* @author Aditya Nivarthi
*/
public class ExtensibleHashIndex implements Index {
// Current values
protected int currentBucketCount = 0;
protected int currentBucketNumber = 0;
protected int currentBitCount = 1;
// Extensible hash index information
protected String idxname;
protected Schema sch;
protected Transaction tx;
protected Constant searchkey = null;
protected TableScan ts = null;
// Index file name
protected final String INDEX_FILENAME = "ehindexfile";
protected final String GLOBAL_FILENAME = "ehglbl";
// Global field names
protected final String GLOBAL_FIELD = "global";
// Index field names
protected final String BUCKET_NUM = "bucketnum";
protected final String BUCKET_BITS = "buckebitse";
protected final String BUCKET_TUPLES = "buckettuples";
protected final String BUCKET_FILE_NAME = "indexfilename";
// Maximum number of tuples in an index bucket
protected final int NUM_BUCKET_TUPLES = 100;
// Global information
protected Schema globalSchema;
protected TableInfo globalInfo;
protected TableScan globalScan;
// Index information
protected Schema indexBucketSchema;
protected TableInfo indexBucketTableInfo;
protected TableScan indexBucketTableScan;
// Hash value for modulo
protected static final int HASH_MOD_VAL = 1610612741;
/**
* Opens an extensible hash index for the specified index.
*
* @param idxname
* the name of the index
* @param sch
* the schema of the index records
* @param tx
* the calling transaction
*/
public ExtensibleHashIndex(String idxname, Schema sch, Transaction tx) {
this.idxname = idxname;
this.sch = sch;
this.tx = tx;
globalSchema = new Schema();
globalSchema.addIntField(GLOBAL_FIELD);
globalInfo = new TableInfo(GLOBAL_FILENAME, globalSchema);
globalScan = new TableScan(globalInfo, tx);
globalScan.beforeFirst();
globalScan.next();
try {
currentBitCount = globalScan.getInt(GLOBAL_FIELD);
} catch (Exception e) {
currentBitCount = 0;
System.out.println("No global bit count on disk.");
}
// Set up the bucket table schema
indexBucketSchema = new Schema();
indexBucketSchema.addIntField(BUCKET_NUM);
indexBucketSchema.addIntField(BUCKET_BITS);
indexBucketSchema.addIntField(BUCKET_TUPLES);
indexBucketSchema.addStringField(BUCKET_FILE_NAME, 10);
indexBucketTableInfo = new TableInfo(INDEX_FILENAME, indexBucketSchema);
indexBucketTableScan = new TableScan(indexBucketTableInfo, tx);
indexBucketTableScan.beforeFirst();
}
/**
* Writes the global bit count to the global index file.
*/
public void setGlobalBits() {
globalScan.beforeFirst();
while (globalScan.next()) {
globalScan.delete();
globalScan.beforeFirst();
}
globalScan.insert();
globalScan.setInt(GLOBAL_FIELD, currentBitCount);
}
/**
* This method closes the previous table scans if any and resets the current
* bucket number being evaluated to the new search key.
*
* (non-Javadoc)
*
* @see simpledb.index.Index#beforeFirst(simpledb.query.Constant)
*/
@Override
public void beforeFirst(Constant searchkey) {
close();
this.searchkey = searchkey;
currentBucketNumber = searchkey.hashCode() % HASH_MOD_VAL;
}
@Override
public boolean next() {
while (ts.next()) {
if (ts.getVal("dataval").equals(searchkey)) {
return true;
}
}
return false;
}
/**
* Retrieves the dataRID from the current record in the table scan for the
* bucket.
*
* @see simpledb.index.Index#getDataRid()
*/
@Override
public RID getDataRid() {
int blknum = ts.getInt("block");
int id = ts.getInt("id");
return new RID(blknum, id);
}
/**
* Returns a mask for the number of bits to leave unmasked starting from 2^0
* and moving up.
*
* @param bits
* The number of bits to leave unmasked from the rightmost bit.
* @return an integer
*/
protected int getMask(int bits) {
int sum = 0;
for (int i = bits - 1; i >= 0; i--) {
sum = sum | (int) Math.pow(2, i);
}
return sum;
}
/**
* CS 4432 Project 2
*
* Inserts a new record into the table scan for the bucket.
*
* @see simpledb.index.Index#insert(simpledb.query.Constant,
* simpledb.record.RID)
*/
@Override
public void insert(Constant val, RID rid) {
beforeFirst(val);
indexBucketTableScan.beforeFirst();
// Check if there is an existing bucket where the record can be placed
while (indexBucketTableScan.next()) {
// Get both the current hash value masked and the bucket value
// masked at the bucket's bit number
int bucketNumberMask = indexBucketTableScan.getInt(BUCKET_NUM)
& getMask(indexBucketTableScan.getInt(BUCKET_BITS));
int currentBucketNumberMask = currentBucketNumber & getMask(indexBucketTableScan.getInt(BUCKET_BITS));
// Check if both masked values are equal
if (bucketNumberMask == currentBucketNumberMask) {
// If the bucket is full or is about to be full
if (indexBucketTableScan.getInt(BUCKET_TUPLES) >= NUM_BUCKET_TUPLES) {
reorganizeBucketRecords(val, rid);
return;
} else {
insertExistingIndexBucket(val, rid);
// printExtensibleHashIndexInformation();
return;
}
}
}
// Insert a new bucket for the new value at the global number of bits
insertNewIndexBucket(val, rid, currentBucketNumber & getMask(currentBitCount), currentBitCount);
// printExtensibleHashIndexInformation();
}
/**
* CS 4432 Project 2
*
* Reorganizes the bucket values in order to expand the directory size and
* resort the values at the new bit values.
*
* @param val
* The value to be inserted.
* @param rid
* The RID of the value to be inserted.
*/
protected void reorganizeBucketRecords(Constant val, RID rid) {
int prevBucketBits = indexBucketTableScan.getInt(BUCKET_BITS);
indexBucketTableScan.setInt(BUCKET_BITS, indexBucketTableScan.getInt(BUCKET_BITS) + 1);
// Check if global index needs to be incremented
if (indexBucketTableScan.getInt(BUCKET_BITS) > currentBitCount) {
currentBitCount++;
setGlobalBits();
}
// Open the file for the current bucket that is full
String fileName = indexBucketTableScan.getString(BUCKET_FILE_NAME);
TableScan tblsn = getTableByFileName(fileName);
tblsn.beforeFirst();
List<Constant> resortList = new ArrayList<Constant>();
// Check each record in the bucket file
while (tblsn.next()) {
Constant key = tblsn.getVal("dataval");
int bucket = key.hashCode() % HASH_MOD_VAL;
// Get the masked values for the record and the bucket's new bit
// value
int checkBucketNumMask = indexBucketTableScan.getInt(BUCKET_NUM)
& getMask(indexBucketTableScan.getInt(BUCKET_BITS));
int bucketNumMask = bucket & getMask(indexBucketTableScan.getInt(BUCKET_BITS));
// If the record does not hash here after the bit value increment,
// mark it for removal and resorting
if (bucketNumMask != checkBucketNumMask) {
resortList.add(key);
indexBucketTableScan.setInt(BUCKET_TUPLES, indexBucketTableScan.getInt(BUCKET_TUPLES) - 1);
tblsn.delete();
}
}
int b = prevBucketBits;
int n = indexBucketTableScan.getInt(BUCKET_NUM);
int newN = (int) (n + Math.pow(2, b));
// Add the new bucket for the splitting of the full bucket
indexBucketTableScan.beforeFirst();
indexBucketTableScan.insert();
indexBucketTableScan.setInt(BUCKET_NUM, newN);
indexBucketTableScan.setInt(BUCKET_BITS, currentBitCount);
indexBucketTableScan.setInt(BUCKET_TUPLES, 0);
indexBucketTableScan.setString(BUCKET_FILE_NAME, idxname + newN);
indexBucketTableScan.beforeFirst();
// printExtensibleHashIndexInformation();
// Reinsert the records that were marked for removal
for (Constant k : resortList) {
insert(k, rid);
}
// Insert the new value
insert(val, rid);
tblsn.close();
}
/**
* CS 4432 Project 2
*
* Inserts the value into an existing bucket, and increments the number of
* tuples in that bucket.
*
* @param val
* The value to insert.
* @param rid
* The RID of the value to insert.
*/
protected void insertExistingIndexBucket(Constant val, RID rid) {
indexBucketTableScan.setInt(BUCKET_TUPLES, indexBucketTableScan.getInt(BUCKET_TUPLES) + 1);
TableScan tblsn = getTableByFileName(indexBucketTableScan.getString(BUCKET_FILE_NAME));
// Insert the new value
tblsn.beforeFirst();
tblsn.insert();
tblsn.setInt("block", rid.blockNumber());
tblsn.setInt("id", rid.id());
tblsn.setVal("dataval", val);
tblsn.close();
}
/**
* CS 4432 Project 2
*
* Inserts the new value into a new bucket.
*
* @param val
* The value to insert.
* @param rid
* The RID of the value to insert.
* @param maskedBucketNumber
* The bucket number for the new bucket.
* @param bits
* The number of bits to use for comparison of this bucket.
*/
protected void insertNewIndexBucket(Constant val, RID rid, int maskedBucketNumber, int bits) {
// Insert the new bucket
indexBucketTableScan.insert();
indexBucketTableScan.setInt(BUCKET_NUM, maskedBucketNumber);
indexBucketTableScan.setInt(BUCKET_BITS, bits);
indexBucketTableScan.setInt(BUCKET_TUPLES, 1);
indexBucketTableScan.setString(BUCKET_FILE_NAME, idxname + maskedBucketNumber);
// Check if the number of global bits needs to be incremented
if (bits > currentBitCount) {
currentBitCount++;
setGlobalBits();
}
TableScan tblsn = getTableByFileName(indexBucketTableScan.getString(BUCKET_FILE_NAME));
// Insert the record
tblsn.beforeFirst();
tblsn.insert();
tblsn.setInt("block", rid.blockNumber());
tblsn.setInt("id", rid.id());
tblsn.setVal("dataval", val);
tblsn.close();
// Increment the number of global bits
currentBucketCount++;
}
/**
* CS 4432 Project 2
*
* This method returns the TableScan for the specified table file name.
*
* @param fileName
* The file name of the table to read from disk.
* @return a TableScan
*/
protected TableScan getTableByFileName(String fileName) {
TableInfo tableInfo = new TableInfo(fileName, sch);
return new TableScan(tableInfo, tx);
}
/**
* Deletes the specified record from the table scan for the bucket. The
* method starts at the beginning of the scan, and loops through the records
* until the specified record is found.
*
* @see simpledb.index.Index#delete(simpledb.query.Constant,
* simpledb.record.RID)
*/
@Override
public void delete(Constant val, RID rid) {
beforeFirst(val);
while (next()) {
if (getDataRid().equals(rid)) {
ts.delete();
return;
}
}
}
/**
* Closes the index by closing the current table scan.
*
* @see simpledb.index.Index#close()
*/
@Override
public void close() {
if (ts != null) {
ts.close();
}
}
/**
* CS 4432 Project 2
*
* Prints the index bucket values on call.
*/
protected void printIndexBucketValues() {
indexBucketTableScan.beforeFirst();
System.out.println("\nINDEX BUCKET VALUE LISTING:\n------------------");
while (indexBucketTableScan.next()) {
System.out.println("NUM: " + indexBucketTableScan.getInt(BUCKET_NUM));
System.out.println("BIT: " + indexBucketTableScan.getInt(BUCKET_BITS));
System.out.println("CNT: " + indexBucketTableScan.getInt(BUCKET_TUPLES));
System.out.println("FLN: " + indexBucketTableScan.getString(BUCKET_FILE_NAME));
System.out.println("------------------");
}
System.out.println();
}
/**
* CS 4432 Project 2
*
* Prints the extensible hash index information on call.
*/
protected void printExtensibleHashIndexInformation() {
System.out.println("\n----------------------------------");
System.out.println("EXTENSIBLE HASH INDEX INFORMATION:");
System.out.println("----------------------------------");
System.out.println("Current bit count: " + currentBitCount);
System.out.println("Current bucket count: " + currentBucketCount);
System.out.println("Current bucket number: " + currentBucketNumber);
System.out.println("Hash modulo value: " + HASH_MOD_VAL);
System.out.println("----------------------------------\n");
printIndexBucketValues();
}
/**
* Returns the cost of searching an index file having the specified number
* of blocks. The method assumes that all buckets are about the same size,
* and so the cost is simply the size of the bucket.
*
* @param numblocks
* the number of blocks of index records
* @param rpb
* the number of records per block (not used here)
* @return the cost of traversing the index
*/
public int searchCost(int numblocks, int rpb) {
return numblocks / currentBucketCount;
}
}
|
UTF-8
|
Java
| 15,011 |
java
|
ExtensibleHashIndex.java
|
Java
|
[
{
"context": "xtensible hash index implementation.\n *\n * @author Aditya Nivarthi\n */\npublic class ExtensibleHashIndex implements I",
"end": 418,
"score": 0.9998569488525391,
"start": 403,
"tag": "NAME",
"value": "Aditya Nivarthi"
}
] | null |
[] |
package simpledb.index.hash;
import java.util.ArrayList;
import java.util.List;
import simpledb.index.Index;
import simpledb.query.Constant;
import simpledb.query.TableScan;
import simpledb.record.RID;
import simpledb.record.Schema;
import simpledb.record.TableInfo;
import simpledb.tx.Transaction;
/**
* CS 4432 Project 2
*
* This class is the extensible hash index implementation.
*
* @author <NAME>
*/
public class ExtensibleHashIndex implements Index {
// Current values
protected int currentBucketCount = 0;
protected int currentBucketNumber = 0;
protected int currentBitCount = 1;
// Extensible hash index information
protected String idxname;
protected Schema sch;
protected Transaction tx;
protected Constant searchkey = null;
protected TableScan ts = null;
// Index file name
protected final String INDEX_FILENAME = "ehindexfile";
protected final String GLOBAL_FILENAME = "ehglbl";
// Global field names
protected final String GLOBAL_FIELD = "global";
// Index field names
protected final String BUCKET_NUM = "bucketnum";
protected final String BUCKET_BITS = "buckebitse";
protected final String BUCKET_TUPLES = "buckettuples";
protected final String BUCKET_FILE_NAME = "indexfilename";
// Maximum number of tuples in an index bucket
protected final int NUM_BUCKET_TUPLES = 100;
// Global information
protected Schema globalSchema;
protected TableInfo globalInfo;
protected TableScan globalScan;
// Index information
protected Schema indexBucketSchema;
protected TableInfo indexBucketTableInfo;
protected TableScan indexBucketTableScan;
// Hash value for modulo
protected static final int HASH_MOD_VAL = 1610612741;
/**
* Opens an extensible hash index for the specified index.
*
* @param idxname
* the name of the index
* @param sch
* the schema of the index records
* @param tx
* the calling transaction
*/
public ExtensibleHashIndex(String idxname, Schema sch, Transaction tx) {
this.idxname = idxname;
this.sch = sch;
this.tx = tx;
globalSchema = new Schema();
globalSchema.addIntField(GLOBAL_FIELD);
globalInfo = new TableInfo(GLOBAL_FILENAME, globalSchema);
globalScan = new TableScan(globalInfo, tx);
globalScan.beforeFirst();
globalScan.next();
try {
currentBitCount = globalScan.getInt(GLOBAL_FIELD);
} catch (Exception e) {
currentBitCount = 0;
System.out.println("No global bit count on disk.");
}
// Set up the bucket table schema
indexBucketSchema = new Schema();
indexBucketSchema.addIntField(BUCKET_NUM);
indexBucketSchema.addIntField(BUCKET_BITS);
indexBucketSchema.addIntField(BUCKET_TUPLES);
indexBucketSchema.addStringField(BUCKET_FILE_NAME, 10);
indexBucketTableInfo = new TableInfo(INDEX_FILENAME, indexBucketSchema);
indexBucketTableScan = new TableScan(indexBucketTableInfo, tx);
indexBucketTableScan.beforeFirst();
}
/**
* Writes the global bit count to the global index file.
*/
public void setGlobalBits() {
globalScan.beforeFirst();
while (globalScan.next()) {
globalScan.delete();
globalScan.beforeFirst();
}
globalScan.insert();
globalScan.setInt(GLOBAL_FIELD, currentBitCount);
}
/**
* This method closes the previous table scans if any and resets the current
* bucket number being evaluated to the new search key.
*
* (non-Javadoc)
*
* @see simpledb.index.Index#beforeFirst(simpledb.query.Constant)
*/
@Override
public void beforeFirst(Constant searchkey) {
close();
this.searchkey = searchkey;
currentBucketNumber = searchkey.hashCode() % HASH_MOD_VAL;
}
@Override
public boolean next() {
while (ts.next()) {
if (ts.getVal("dataval").equals(searchkey)) {
return true;
}
}
return false;
}
/**
* Retrieves the dataRID from the current record in the table scan for the
* bucket.
*
* @see simpledb.index.Index#getDataRid()
*/
@Override
public RID getDataRid() {
int blknum = ts.getInt("block");
int id = ts.getInt("id");
return new RID(blknum, id);
}
/**
* Returns a mask for the number of bits to leave unmasked starting from 2^0
* and moving up.
*
* @param bits
* The number of bits to leave unmasked from the rightmost bit.
* @return an integer
*/
protected int getMask(int bits) {
int sum = 0;
for (int i = bits - 1; i >= 0; i--) {
sum = sum | (int) Math.pow(2, i);
}
return sum;
}
/**
* CS 4432 Project 2
*
* Inserts a new record into the table scan for the bucket.
*
* @see simpledb.index.Index#insert(simpledb.query.Constant,
* simpledb.record.RID)
*/
@Override
public void insert(Constant val, RID rid) {
beforeFirst(val);
indexBucketTableScan.beforeFirst();
// Check if there is an existing bucket where the record can be placed
while (indexBucketTableScan.next()) {
// Get both the current hash value masked and the bucket value
// masked at the bucket's bit number
int bucketNumberMask = indexBucketTableScan.getInt(BUCKET_NUM)
& getMask(indexBucketTableScan.getInt(BUCKET_BITS));
int currentBucketNumberMask = currentBucketNumber & getMask(indexBucketTableScan.getInt(BUCKET_BITS));
// Check if both masked values are equal
if (bucketNumberMask == currentBucketNumberMask) {
// If the bucket is full or is about to be full
if (indexBucketTableScan.getInt(BUCKET_TUPLES) >= NUM_BUCKET_TUPLES) {
reorganizeBucketRecords(val, rid);
return;
} else {
insertExistingIndexBucket(val, rid);
// printExtensibleHashIndexInformation();
return;
}
}
}
// Insert a new bucket for the new value at the global number of bits
insertNewIndexBucket(val, rid, currentBucketNumber & getMask(currentBitCount), currentBitCount);
// printExtensibleHashIndexInformation();
}
/**
* CS 4432 Project 2
*
* Reorganizes the bucket values in order to expand the directory size and
* resort the values at the new bit values.
*
* @param val
* The value to be inserted.
* @param rid
* The RID of the value to be inserted.
*/
protected void reorganizeBucketRecords(Constant val, RID rid) {
int prevBucketBits = indexBucketTableScan.getInt(BUCKET_BITS);
indexBucketTableScan.setInt(BUCKET_BITS, indexBucketTableScan.getInt(BUCKET_BITS) + 1);
// Check if global index needs to be incremented
if (indexBucketTableScan.getInt(BUCKET_BITS) > currentBitCount) {
currentBitCount++;
setGlobalBits();
}
// Open the file for the current bucket that is full
String fileName = indexBucketTableScan.getString(BUCKET_FILE_NAME);
TableScan tblsn = getTableByFileName(fileName);
tblsn.beforeFirst();
List<Constant> resortList = new ArrayList<Constant>();
// Check each record in the bucket file
while (tblsn.next()) {
Constant key = tblsn.getVal("dataval");
int bucket = key.hashCode() % HASH_MOD_VAL;
// Get the masked values for the record and the bucket's new bit
// value
int checkBucketNumMask = indexBucketTableScan.getInt(BUCKET_NUM)
& getMask(indexBucketTableScan.getInt(BUCKET_BITS));
int bucketNumMask = bucket & getMask(indexBucketTableScan.getInt(BUCKET_BITS));
// If the record does not hash here after the bit value increment,
// mark it for removal and resorting
if (bucketNumMask != checkBucketNumMask) {
resortList.add(key);
indexBucketTableScan.setInt(BUCKET_TUPLES, indexBucketTableScan.getInt(BUCKET_TUPLES) - 1);
tblsn.delete();
}
}
int b = prevBucketBits;
int n = indexBucketTableScan.getInt(BUCKET_NUM);
int newN = (int) (n + Math.pow(2, b));
// Add the new bucket for the splitting of the full bucket
indexBucketTableScan.beforeFirst();
indexBucketTableScan.insert();
indexBucketTableScan.setInt(BUCKET_NUM, newN);
indexBucketTableScan.setInt(BUCKET_BITS, currentBitCount);
indexBucketTableScan.setInt(BUCKET_TUPLES, 0);
indexBucketTableScan.setString(BUCKET_FILE_NAME, idxname + newN);
indexBucketTableScan.beforeFirst();
// printExtensibleHashIndexInformation();
// Reinsert the records that were marked for removal
for (Constant k : resortList) {
insert(k, rid);
}
// Insert the new value
insert(val, rid);
tblsn.close();
}
/**
* CS 4432 Project 2
*
* Inserts the value into an existing bucket, and increments the number of
* tuples in that bucket.
*
* @param val
* The value to insert.
* @param rid
* The RID of the value to insert.
*/
protected void insertExistingIndexBucket(Constant val, RID rid) {
indexBucketTableScan.setInt(BUCKET_TUPLES, indexBucketTableScan.getInt(BUCKET_TUPLES) + 1);
TableScan tblsn = getTableByFileName(indexBucketTableScan.getString(BUCKET_FILE_NAME));
// Insert the new value
tblsn.beforeFirst();
tblsn.insert();
tblsn.setInt("block", rid.blockNumber());
tblsn.setInt("id", rid.id());
tblsn.setVal("dataval", val);
tblsn.close();
}
/**
* CS 4432 Project 2
*
* Inserts the new value into a new bucket.
*
* @param val
* The value to insert.
* @param rid
* The RID of the value to insert.
* @param maskedBucketNumber
* The bucket number for the new bucket.
* @param bits
* The number of bits to use for comparison of this bucket.
*/
protected void insertNewIndexBucket(Constant val, RID rid, int maskedBucketNumber, int bits) {
// Insert the new bucket
indexBucketTableScan.insert();
indexBucketTableScan.setInt(BUCKET_NUM, maskedBucketNumber);
indexBucketTableScan.setInt(BUCKET_BITS, bits);
indexBucketTableScan.setInt(BUCKET_TUPLES, 1);
indexBucketTableScan.setString(BUCKET_FILE_NAME, idxname + maskedBucketNumber);
// Check if the number of global bits needs to be incremented
if (bits > currentBitCount) {
currentBitCount++;
setGlobalBits();
}
TableScan tblsn = getTableByFileName(indexBucketTableScan.getString(BUCKET_FILE_NAME));
// Insert the record
tblsn.beforeFirst();
tblsn.insert();
tblsn.setInt("block", rid.blockNumber());
tblsn.setInt("id", rid.id());
tblsn.setVal("dataval", val);
tblsn.close();
// Increment the number of global bits
currentBucketCount++;
}
/**
* CS 4432 Project 2
*
* This method returns the TableScan for the specified table file name.
*
* @param fileName
* The file name of the table to read from disk.
* @return a TableScan
*/
protected TableScan getTableByFileName(String fileName) {
TableInfo tableInfo = new TableInfo(fileName, sch);
return new TableScan(tableInfo, tx);
}
/**
* Deletes the specified record from the table scan for the bucket. The
* method starts at the beginning of the scan, and loops through the records
* until the specified record is found.
*
* @see simpledb.index.Index#delete(simpledb.query.Constant,
* simpledb.record.RID)
*/
@Override
public void delete(Constant val, RID rid) {
beforeFirst(val);
while (next()) {
if (getDataRid().equals(rid)) {
ts.delete();
return;
}
}
}
/**
* Closes the index by closing the current table scan.
*
* @see simpledb.index.Index#close()
*/
@Override
public void close() {
if (ts != null) {
ts.close();
}
}
/**
* CS 4432 Project 2
*
* Prints the index bucket values on call.
*/
protected void printIndexBucketValues() {
indexBucketTableScan.beforeFirst();
System.out.println("\nINDEX BUCKET VALUE LISTING:\n------------------");
while (indexBucketTableScan.next()) {
System.out.println("NUM: " + indexBucketTableScan.getInt(BUCKET_NUM));
System.out.println("BIT: " + indexBucketTableScan.getInt(BUCKET_BITS));
System.out.println("CNT: " + indexBucketTableScan.getInt(BUCKET_TUPLES));
System.out.println("FLN: " + indexBucketTableScan.getString(BUCKET_FILE_NAME));
System.out.println("------------------");
}
System.out.println();
}
/**
* CS 4432 Project 2
*
* Prints the extensible hash index information on call.
*/
protected void printExtensibleHashIndexInformation() {
System.out.println("\n----------------------------------");
System.out.println("EXTENSIBLE HASH INDEX INFORMATION:");
System.out.println("----------------------------------");
System.out.println("Current bit count: " + currentBitCount);
System.out.println("Current bucket count: " + currentBucketCount);
System.out.println("Current bucket number: " + currentBucketNumber);
System.out.println("Hash modulo value: " + HASH_MOD_VAL);
System.out.println("----------------------------------\n");
printIndexBucketValues();
}
/**
* Returns the cost of searching an index file having the specified number
* of blocks. The method assumes that all buckets are about the same size,
* and so the cost is simply the size of the bucket.
*
* @param numblocks
* the number of blocks of index records
* @param rpb
* the number of records per block (not used here)
* @return the cost of traversing the index
*/
public int searchCost(int numblocks, int rpb) {
return numblocks / currentBucketCount;
}
}
| 15,002 | 0.608487 | 0.603757 | 452 | 32.210178 | 26.172972 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464602 | false | false |
12
|
57362fd0ba0073ea0ba88873ba5644d54f672e25
| 12,773,232,767,252 |
64de275ceb39f60c7309e2ce65400d1d260906d5
|
/src/main/java/wlw/zc/demo/utils/EmojiFilterUtil.java
|
f1371b52fe7d639ec65a7c9117ca4cb1ef013a57
|
[] |
no_license
|
wlwNb/springboot-customer
|
https://github.com/wlwNb/springboot-customer
|
585e3f30fa1be9fbe41cb01d9a47fa2e9afebf94
|
d31009aa586085db812d10e596ce20eeb313a6cb
|
refs/heads/master
| 2023-04-16T10:09:37.895000 | 2021-04-29T08:41:16 | 2021-04-29T08:41:16 | 362,734,185 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package wlw.zc.demo.utils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by huyan on 2019/3/23 15:07
*/
public class EmojiFilterUtil {
/**
* 检测是否有emoji字符
*
* @param source
* @return 一旦含有就抛出
*/
public static boolean containsEmoji(String source) {
if (StringUtils.isBlank(source)) {
return false;
}
Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]");
Matcher matcher = pattern.matcher(source);
if(matcher .find()){
return true;
}
return false;
}
}
|
UTF-8
|
Java
| 746 |
java
|
EmojiFilterUtil.java
|
Java
|
[
{
"context": "mport java.util.regex.Pattern;\n\n\n/**\n * Created by huyan on 2019/3/23 15:07\n */\npublic class EmojiFilterUt",
"end": 176,
"score": 0.9996711611747742,
"start": 171,
"tag": "USERNAME",
"value": "huyan"
}
] | null |
[] |
package wlw.zc.demo.utils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by huyan on 2019/3/23 15:07
*/
public class EmojiFilterUtil {
/**
* 检测是否有emoji字符
*
* @param source
* @return 一旦含有就抛出
*/
public static boolean containsEmoji(String source) {
if (StringUtils.isBlank(source)) {
return false;
}
Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]");
Matcher matcher = pattern.matcher(source);
if(matcher .find()){
return true;
}
return false;
}
}
| 746 | 0.611421 | 0.571031 | 32 | 21.46875 | 24.071487 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34375 | false | false |
12
|
92ae8c8baaa11bb0aa57c2d74fc3fe9bbd1a3e87
| 21,388,937,189,842 |
e8d5dc8b6f28f83ae2ee67be4b2f7dbfeaf82440
|
/src/main/java/com/sapient/weatherprediction/web/WeatherController.java
|
405edef6ef9691020253a354fa1bdc2c6642f515
|
[] |
no_license
|
PSEH-8/weather-prediction
|
https://github.com/PSEH-8/weather-prediction
|
910e4e84db68418decaf42e8260f01a6d43a27ec
|
6b7921a22ce34ff63ad52b3bbf8dd1d537928fa7
|
refs/heads/master
| 2020-05-19T05:43:02.939000 | 2019-05-04T08:35:13 | 2019-05-04T08:35:13 | 184,855,103 | 0 | 0 | null | false | 2019-05-04T08:35:14 | 2019-05-04T05:15:23 | 2019-05-04T08:15:31 | 2019-05-04T08:35:14 | 7 | 0 | 0 | 0 |
Java
| false | false |
package com.sapient.weatherprediction.web;
import com.sapient.weatherprediction.services.Forecast;
import com.sapient.weatherprediction.services.WeatherService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/weather")
public class WeatherController {
private final WeatherService weatherService;
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@RequestMapping("/forecast/{country}/{city}")
public List<Forecast> getWeather(@PathVariable String country, @PathVariable String city){
return this.weatherService.getWeatherForecast(country, city);
}
}
|
UTF-8
|
Java
| 848 |
java
|
WeatherController.java
|
Java
|
[] | null |
[] |
package com.sapient.weatherprediction.web;
import com.sapient.weatherprediction.services.Forecast;
import com.sapient.weatherprediction.services.WeatherService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/weather")
public class WeatherController {
private final WeatherService weatherService;
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@RequestMapping("/forecast/{country}/{city}")
public List<Forecast> getWeather(@PathVariable String country, @PathVariable String city){
return this.weatherService.getWeatherForecast(country, city);
}
}
| 848 | 0.792453 | 0.792453 | 29 | 28.241379 | 28.443113 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413793 | false | false |
12
|
9f78878fcd2f5fb1181dc4889cda05d8b18a4f92
| 26,422,638,849,997 |
829ab3744db9bf024cbd57c08f5d129880b59f8a
|
/Java/Gra/Game.java
|
473fb6da031309d2e1edca363cbde242421f98a7
|
[] |
no_license
|
pawel2004/First-steps-in-programming
|
https://github.com/pawel2004/First-steps-in-programming
|
574665f01fb79009df18e855ec629387500a048d
|
00dee7c5856574de6c272a0e3873c95062cc2ce4
|
refs/heads/master
| 2020-04-05T04:54:20.945000 | 2019-06-02T19:35:28 | 2019-06-02T19:35:28 | 156,572,105 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
import java.util.Random;
public class Game {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Random random = new Random();
Player player = new Player();
Spider spider = new Spider();
Zombie zombie = new Zombie();
Rat rat = new Rat();
System.out.println("Witaj w Lochu!!!");
int n = 1;
int i = 1;
while (n==1)
{
System.out.println("Graj(1)");
System.out.println("Wyjdź(2)");
int score = 0;
int k = 0;
int user_input = scanner.nextInt();
if (user_input == 1)
{
System.out.println("Podaj mi swoje imię: ");
String user_name = scanner.next();
player.setName(user_name);
System.out.println("Jaki jest twój bohater? ");
System.out.println("Silny(1), przeciętny(2), czy słaby(3)?");
int user_body = scanner.nextInt();
if (user_body == 1)
{
player.setHp(40);
}
else if (user_body == 2)
{
player.setHp(20);
}
else if (user_body == 3)
{
player.setHp(10);
}
else
{
player.setHp(5);
}
System.out.println("Wybierz broń.");
System.out.println("Miecz(1), łuk(2), czy buława(3)?");
int user_weapon = scanner.nextInt();
if (user_weapon == 1)
{
player.setMin_damage(5);
player.setMax_damage(10);
}
else if (user_weapon == 2)
{
player.setMin_damage(4);
player.setMax_damage(8);
}
else if (user_weapon == 3)
{
player.setMin_damage(0);
player.setMax_damage(12);
}
else
{
player.setMin_damage(0);
player.setMax_damage(2);
}
System.out.println("Podaj ilość mikstur: ");
int user_potions = scanner.nextInt();
player.setPotions(user_potions);
while (i == 1)
{
if (k == 0) {
String name = player.getName();
int player_hp = player.getHp();
int potions = player.getPotions();
int player_min_damage = player.getMin_damage();
int player_max_damage = player.getMax_damage();
spider.setHp(20);
zombie.setHp(30);
rat.setHp(10);
System.out.println("Witaj w lochu, " + name);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Idziesz do przodu(1)");
System.out.println("Wychodzisz(2)");
int user_choice = scanner.nextInt();
if (user_choice == 1) {
int enemy = random.nextInt(3) + 1;
if (enemy == 1) {
System.out.println("Spotykasz pająka!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = spider.getHp();
int enemy_min_damage = spider.getMin_damage();
int enemy_max_damage = spider.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
spider.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if (potions > 0) {
player.setPotions(potions - 1);
player.setHp(player_hp + 5);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
}
else if (enemy == 2) {
System.out.println("Spotykasz zombie!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = zombie.getHp();
int enemy_min_damage = zombie.getMin_damage();
int enemy_max_damage = zombie.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
zombie.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if (potions > 0) {
player.setHp(player_hp + 5);
player.setPotions(potions - 1);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
} else if (enemy == 3) {
System.out.println("Spotykasz szczura!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = rat.getHp();
int enemy_min_damage = rat.getMin_damage();
int enemy_max_damage = rat.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
rat.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if(potions > 0) {
player.setHp(player_hp + 5);
player.setPotions(potions - 1);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
}
} else if (user_choice == 2) {
System.out.println("Zabite potwory: " + score);
break;
} else {
System.out.println("Nie ma takiej opcji!!!");
}
}
else
{
break;
}
}
}
else if (user_input == 2)
{
break;
}
else
{
System.out.println("Nie ma takiej opcji!!!");
}
}
}
}
|
UTF-8
|
Java
| 19,045 |
java
|
Game.java
|
Java
|
[
{
"context": "ater? \");\r\n System.out.println(\"Silny(1), przeciętny(2), czy słaby(3)?\");\r\n ",
"end": 995,
"score": 0.5295513272285461,
"start": 993,
"tag": "NAME",
"value": "ny"
}
] | null |
[] |
import java.util.Scanner;
import java.util.Random;
public class Game {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Random random = new Random();
Player player = new Player();
Spider spider = new Spider();
Zombie zombie = new Zombie();
Rat rat = new Rat();
System.out.println("Witaj w Lochu!!!");
int n = 1;
int i = 1;
while (n==1)
{
System.out.println("Graj(1)");
System.out.println("Wyjdź(2)");
int score = 0;
int k = 0;
int user_input = scanner.nextInt();
if (user_input == 1)
{
System.out.println("Podaj mi swoje imię: ");
String user_name = scanner.next();
player.setName(user_name);
System.out.println("Jaki jest twój bohater? ");
System.out.println("Silny(1), przeciętny(2), czy słaby(3)?");
int user_body = scanner.nextInt();
if (user_body == 1)
{
player.setHp(40);
}
else if (user_body == 2)
{
player.setHp(20);
}
else if (user_body == 3)
{
player.setHp(10);
}
else
{
player.setHp(5);
}
System.out.println("Wybierz broń.");
System.out.println("Miecz(1), łuk(2), czy buława(3)?");
int user_weapon = scanner.nextInt();
if (user_weapon == 1)
{
player.setMin_damage(5);
player.setMax_damage(10);
}
else if (user_weapon == 2)
{
player.setMin_damage(4);
player.setMax_damage(8);
}
else if (user_weapon == 3)
{
player.setMin_damage(0);
player.setMax_damage(12);
}
else
{
player.setMin_damage(0);
player.setMax_damage(2);
}
System.out.println("Podaj ilość mikstur: ");
int user_potions = scanner.nextInt();
player.setPotions(user_potions);
while (i == 1)
{
if (k == 0) {
String name = player.getName();
int player_hp = player.getHp();
int potions = player.getPotions();
int player_min_damage = player.getMin_damage();
int player_max_damage = player.getMax_damage();
spider.setHp(20);
zombie.setHp(30);
rat.setHp(10);
System.out.println("Witaj w lochu, " + name);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Idziesz do przodu(1)");
System.out.println("Wychodzisz(2)");
int user_choice = scanner.nextInt();
if (user_choice == 1) {
int enemy = random.nextInt(3) + 1;
if (enemy == 1) {
System.out.println("Spotykasz pająka!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = spider.getHp();
int enemy_min_damage = spider.getMin_damage();
int enemy_max_damage = spider.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
spider.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if (potions > 0) {
player.setPotions(potions - 1);
player.setHp(player_hp + 5);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
}
else if (enemy == 2) {
System.out.println("Spotykasz zombie!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = zombie.getHp();
int enemy_min_damage = zombie.getMin_damage();
int enemy_max_damage = zombie.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
zombie.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if (potions > 0) {
player.setHp(player_hp + 5);
player.setPotions(potions - 1);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
} else if (enemy == 3) {
System.out.println("Spotykasz szczura!!!");
int a = 1;
while (a == 1) {
player_hp = player.getHp();
potions = player.getPotions();
int enemy_hp = rat.getHp();
int enemy_min_damage = rat.getMin_damage();
int enemy_max_damage = rat.getMax_damage();
if (player_hp > 0) {
if (enemy_hp > 0) {
System.out.println("Hp wroga: " + enemy_hp);
System.out.println("Twoje hp: " + player_hp);
System.out.println("Twoje mikstury: " + potions);
System.out.println("Uderz(1)");
System.out.println("Użyj mikstury(2)");
System.out.println("Ucieknij(3)");
int user_turn = scanner.nextInt();
if (user_turn == 1) {
int player_hit = random.nextInt(2);
if (player_hit == 1) {
int player_deal = random.nextInt(player_max_damage - player_min_damage + 1) + player_min_damage;
System.out.println("Zadajesz " + player_deal + " obrażeń.");
rat.setHp(enemy_hp - player_deal);
} else {
System.out.println("Pudło!!!");
}
int enemy_hit = random.nextInt(2);
if (enemy_hit == 1) {
int enemy_deal = random.nextInt(enemy_max_damage - enemy_min_damage + 1) + enemy_min_damage;
System.out.println("Przeciwnik zadaje " + enemy_deal + " obrażeń.");
player.setHp(player_hp - enemy_deal);
} else {
System.out.println("Przeciwnik pudłuje!!!");
}
} else if (user_turn == 2) {
if(potions > 0) {
player.setHp(player_hp + 5);
player.setPotions(potions - 1);
}
else
{
System.out.println("Nie masz już mikstur!!!");
}
} else if (user_turn == 3) {
int escape = random.nextInt(2);
if (escape == 1) {
System.out.println("Uciekasz!!!");
break;
} else {
System.out.println("Nie udaje Ci się uciec!!!");
}
} else {
System.out.println("Nie ma takiej opcji!!!");
}
} else {
System.out.println("Przeciwnik ginie!!!");
score++;
break;
}
} else {
System.out.println("Koniec gry!!!");
k = 1;
System.out.println("Zabite potwory: " + score);
break;
}
}
}
} else if (user_choice == 2) {
System.out.println("Zabite potwory: " + score);
break;
} else {
System.out.println("Nie ma takiej opcji!!!");
}
}
else
{
break;
}
}
}
else if (user_input == 2)
{
break;
}
else
{
System.out.println("Nie ma takiej opcji!!!");
}
}
}
}
| 19,045 | 0.27332 | 0.266954 | 352 | 51.997158 | 31.218393 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519886 | false | false |
12
|
ecafd4d9afc61fde4e8f68d313637286b0248710
| 26,422,638,851,469 |
6b81fc4223abebcf57155a910494a3f6f9f79e5f
|
/src/main/java/com/eazytec/model/ListViewButtons.java
|
ab0a77633f8438e4345e8b58674a793a009370dc
|
[] |
no_license
|
Ramkavanan/easybpm
|
https://github.com/Ramkavanan/easybpm
|
20f691bf69d5f7aea8825da265738e929405de63
|
6f9ef2e26e9566e1255c3708ddd6cef29d3a19cd
|
refs/heads/master
| 2020-12-28T22:33:52.638000 | 2016-09-17T16:22:09 | 2016-09-17T16:22:09 | 68,453,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.eazytec.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.Indexed;
@Entity
@Table(name = "RE_LIST_VIEW_BUTTONS")
public class ListViewButtons {
private static final long serialVersionUID = 3644859655330969141L;
private String id;
private String displayName;
private String buttonMethod;
private int orderBy = 0;
private ListView listView;
private String iconPath;
private int version;
private boolean active;
private String tableName;
private String columnName;
private String redirectValue;
private String listViewButtonRoles;
private String listViewButtonUsers;
private String listViewButtonUsersFullName;
private String listViewButtonDeps;
private String listViewButtonGroups;
/**
* Default constructor - creates a new instance with no values set.
*/
public ListViewButtons() {
}
public ListViewButtons(List<Object> listViewButtons){
this.displayName=(String)listViewButtons.get(0);
this.buttonMethod=(String)listViewButtons.get(1);
if(listViewButtons.get(2)!="" && listViewButtons.get(2)!=null){
this.orderBy=Integer.parseInt(listViewButtons.get(2).toString());
}
}
@Id
@Column(name = "ID")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "DISPLAY_NAME",length = 255)
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Column(name = "BUTTON_METHOD", columnDefinition = "longtext")
public String getButtonMethod() {
return buttonMethod;
}
public void setButtonMethod(String buttonMethod) {
this.buttonMethod = buttonMethod;
}
@Column(name = "ORDER_BY",length = 10)
public int getOrderBy() {
return orderBy;
}
public void setOrderBy(int orderBy) {
this.orderBy = orderBy;
}
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "LIST_VIEW_ID", nullable = false)
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
@Column(name = "ICON_PATH")
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
@Column(name = "VERSION", columnDefinition = "int default 1")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public void setActive(boolean active) {
this.active = active;
}
@Column(name = "IS_ACTIVE", columnDefinition="boolean default false")
public boolean isActive() {
return active;
}
@Column(name = "TABLE_NAME")
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Column(name = "COLUMN_NAME")
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
@Column(name = "REDIRECT_VALUE")
public String getRedirectValue() {
return redirectValue;
}
public void setRedirectValue(String redirectValue) {
this.redirectValue = redirectValue;
}
@Column(name = "LIST_VIEW_ROLES")
public String getListViewButtonRoles() {
return listViewButtonRoles;
}
public void setListViewButtonRoles(String listViewButtonRoles) {
this.listViewButtonRoles = listViewButtonRoles;
}
@Column(name = "LIST_VIEW_USERS")
public String getListViewButtonUsers() {
return listViewButtonUsers;
}
public void setListViewButtonUsers(String listViewButtonUsers) {
this.listViewButtonUsers = listViewButtonUsers;
}
@Column(name = "LIST_VIEW_USERS_NAME")
public String getListViewButtonUsersFullName() {
return listViewButtonUsersFullName;
}
public void setListViewButtonUsersFullName(String listViewButtonUsersFullName) {
this.listViewButtonUsersFullName = listViewButtonUsersFullName;
}
@Column(name = "LIST_VIEW_DEPARTMENTS")
public String getListViewButtonDeps() {
return listViewButtonDeps;
}
public void setListViewButtonDeps(String listViewButtonDeps) {
this.listViewButtonDeps = listViewButtonDeps;
}
@Column(name = "LIST_VIEW_GROUPS")
public String getListViewButtonGroups() {
return listViewButtonGroups;
}
public void setListViewButtonGroups(String listViewButtonGroups) {
this.listViewButtonGroups = listViewButtonGroups;
}
}
|
UTF-8
|
Java
| 4,879 |
java
|
ListViewButtons.java
|
Java
|
[] | null |
[] |
package com.eazytec.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.Indexed;
@Entity
@Table(name = "RE_LIST_VIEW_BUTTONS")
public class ListViewButtons {
private static final long serialVersionUID = 3644859655330969141L;
private String id;
private String displayName;
private String buttonMethod;
private int orderBy = 0;
private ListView listView;
private String iconPath;
private int version;
private boolean active;
private String tableName;
private String columnName;
private String redirectValue;
private String listViewButtonRoles;
private String listViewButtonUsers;
private String listViewButtonUsersFullName;
private String listViewButtonDeps;
private String listViewButtonGroups;
/**
* Default constructor - creates a new instance with no values set.
*/
public ListViewButtons() {
}
public ListViewButtons(List<Object> listViewButtons){
this.displayName=(String)listViewButtons.get(0);
this.buttonMethod=(String)listViewButtons.get(1);
if(listViewButtons.get(2)!="" && listViewButtons.get(2)!=null){
this.orderBy=Integer.parseInt(listViewButtons.get(2).toString());
}
}
@Id
@Column(name = "ID")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "DISPLAY_NAME",length = 255)
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Column(name = "BUTTON_METHOD", columnDefinition = "longtext")
public String getButtonMethod() {
return buttonMethod;
}
public void setButtonMethod(String buttonMethod) {
this.buttonMethod = buttonMethod;
}
@Column(name = "ORDER_BY",length = 10)
public int getOrderBy() {
return orderBy;
}
public void setOrderBy(int orderBy) {
this.orderBy = orderBy;
}
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "LIST_VIEW_ID", nullable = false)
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
@Column(name = "ICON_PATH")
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
@Column(name = "VERSION", columnDefinition = "int default 1")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public void setActive(boolean active) {
this.active = active;
}
@Column(name = "IS_ACTIVE", columnDefinition="boolean default false")
public boolean isActive() {
return active;
}
@Column(name = "TABLE_NAME")
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Column(name = "COLUMN_NAME")
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
@Column(name = "REDIRECT_VALUE")
public String getRedirectValue() {
return redirectValue;
}
public void setRedirectValue(String redirectValue) {
this.redirectValue = redirectValue;
}
@Column(name = "LIST_VIEW_ROLES")
public String getListViewButtonRoles() {
return listViewButtonRoles;
}
public void setListViewButtonRoles(String listViewButtonRoles) {
this.listViewButtonRoles = listViewButtonRoles;
}
@Column(name = "LIST_VIEW_USERS")
public String getListViewButtonUsers() {
return listViewButtonUsers;
}
public void setListViewButtonUsers(String listViewButtonUsers) {
this.listViewButtonUsers = listViewButtonUsers;
}
@Column(name = "LIST_VIEW_USERS_NAME")
public String getListViewButtonUsersFullName() {
return listViewButtonUsersFullName;
}
public void setListViewButtonUsersFullName(String listViewButtonUsersFullName) {
this.listViewButtonUsersFullName = listViewButtonUsersFullName;
}
@Column(name = "LIST_VIEW_DEPARTMENTS")
public String getListViewButtonDeps() {
return listViewButtonDeps;
}
public void setListViewButtonDeps(String listViewButtonDeps) {
this.listViewButtonDeps = listViewButtonDeps;
}
@Column(name = "LIST_VIEW_GROUPS")
public String getListViewButtonGroups() {
return listViewButtonGroups;
}
public void setListViewButtonGroups(String listViewButtonGroups) {
this.listViewButtonGroups = listViewButtonGroups;
}
}
| 4,879 | 0.739906 | 0.733552 | 198 | 23.641415 | 20.600523 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.212121 | false | false |
12
|
b36693e1321e6b35403c38c245d40267963395dc
| 25,142,738,605,418 |
b5efdb0f2216ef94b814d27d4b3f3bf804b84c73
|
/src/com/example/flashbuddy/FlashBuddyEditDeckActivity.java
|
50bb1dd2b3adb7e0e071aad5a2a0e78368141a72
|
[] |
no_license
|
Zfalgout/FlashBuddy
|
https://github.com/Zfalgout/FlashBuddy
|
a06a3fe7097affc73cdece44d3fd683834ae7004
|
f4e9ca47367ed927f65fef4fd1f3ae97cdffd58d
|
refs/heads/master
| 2020-03-26T04:24:30.310000 | 2015-07-09T22:25:13 | 2015-07-09T22:25:13 | 38,848,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* FlashBuddy Edit Deck Activity
*
* FlashBuddy Edit Deck Activity Class
*
* @author John Leidel
* @author Zack Falgout
* @author Chase Baker
* @version 1.0
*
*/
package com.example.flashbuddy;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FlashBuddyEditDeckActivity extends Activity {
private String FileName;
private List<FlashBuddyCard> cards;
private FlashBuddyCard currentCard;
private FlashBuddyDeck editDeck = null;
private int currentCardIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_buddy_edit_deck);
/*
* Grab the Intent
*/
Intent intent = getIntent();
FileName = intent.getStringExtra( FlashBuddyModifyDecksActivity.FILE_MESSAGE );
/*
* read the deck into our editDeck object
*/
editDeck = new FlashBuddyDeck();
try {
InputStream in = null;
try {
in = openFileInput(FileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* read the deck into the object
*/
editDeck.readDeck(in);
try {
if( in != null ){
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* get the card data
*/
cards = editDeck.getCards();
currentCard = cards.get(0);
currentCardIndex = 1;
/*
* Update the text fields with the current data
*/
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
TextView cardDesignator = (TextView) findViewById(R.id.cardDesignator);
questionTextView.setText(currentCard.getQuestion());
answerTextView.setText(currentCard.getAnswer());
timerTextView.setText(Integer.toString(currentCard.getTimer()));
cardDesignator.setText("Card 1 of "+Integer.toString(editDeck.getNumCards()));
Button NextButton = (Button)findViewById(R.id.nextButton);
NextButton.scheduleDrawable(NextButton.getBackground(), checkInfo, 1000);
}
final Runnable checkInfo = new Runnable()
{
public void run()
{
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
String localTimer = timerTextView.getText().toString();
Button NextButton = (Button)findViewById(R.id.nextButton);
if (localQuestion.equals("") || localAnswer.equals("") || localTimer.equals(""))
{
NextButton.setBackgroundColor(Color.parseColor("#7b93af"));
}
else
{
NextButton.setBackgroundColor(Color.parseColor("#4FA044"));
}
NextButton.scheduleDrawable(NextButton.getBackground(), checkInfo, 1000);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.flash_buddy_edit_deck, menu);
return true;
}
/**
* onClickNextCard : flips the editing session to the next card
* @param view
*/
public void onClickNextCard( View view ){
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
TextView cardDesignator = (TextView) findViewById(R.id.cardDesignator);
/*
* grab the input values
*/
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
int localTimer = Integer.parseInt(timerTextView.getText().toString());
/*
* record them to the card object
*/
this.currentCard.setAnswer(localAnswer);
this.currentCard.setQuestion(localQuestion);
this.currentCard.setTimer(localTimer);
if( (this.currentCardIndex+1) > this.editDeck.getNumCards() ) {
/*
* cycle back to the first card
*/
this.currentCardIndex = 1;
this.cards = this.editDeck.getCards();
this.currentCard = this.cards.get(0);
/*
* set the data in the text views
*/
answerTextView.setText(this.currentCard.getAnswer());
questionTextView.setText(this.currentCard.getQuestion());
timerTextView.setText(Integer.toString(this.currentCard.getTimer()));
}else{
/*
* bump the data to the next card
*/
this.currentCardIndex++;
this.cards = this.editDeck.getCards();
this.currentCard = this.cards.get(this.currentCardIndex-1);
/*
* set the data in the text views
*/
answerTextView.setText(this.currentCard.getAnswer());
questionTextView.setText(this.currentCard.getQuestion());
timerTextView.setText(Integer.toString(this.currentCard.getTimer()));
}
cardDesignator.setText("Card " + Integer.toString(this.currentCardIndex)
+ " of " + Integer.toString(this.editDeck.getNumCards()));
}
/**
* onClickWriteCard : writes the card to disk
* @param view
*/
public void onClickWriteCard( View view ){
if( this.FileName.length() == 0){
/**
* DO NOTHING! The user hasn't entered anything
*/
return ;
}
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
/*
* grab the input values
*/
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
int localTimer = Integer.parseInt(timerTextView.getText().toString());
/*
* write the data into the object
*/
this.currentCard = this.cards.get(this.currentCardIndex-1);
this.currentCard.setAnswer(localAnswer);
this.currentCard.setQuestion(localQuestion);
this.currentCard.setTimer(localTimer);
/*
* deletes the target file name
*/
deleteFile(this.FileName);
/*
* write out the file
*/
try {
FileOutputStream of = openFileOutput(this.editDeck.getTitle() + ".xml", Context.MODE_PRIVATE);
this.editDeck.writeDeck(of);
/*
* close the file
*/
try {
of.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* done writing changes; return to ModifyDeckActivity
*/
Intent returnUserIntent = new Intent( this, FlashBuddyModifyDecksActivity.class );
Intent intent = getIntent();
String username = intent.getStringExtra(FlashBuddy.USERNAME_MESSAGE);
returnUserIntent.putExtra( FlashBuddy.USERNAME_MESSAGE, username );
startActivity(returnUserIntent);
}
}
|
UTF-8
|
Java
| 7,932 |
java
|
FlashBuddyEditDeckActivity.java
|
Java
|
[
{
"context": "lashBuddy Edit Deck Activity Class \n * \n * @author John Leidel\n * @author Zack Falgout\n * @author Chase Baker \n ",
"end": 107,
"score": 0.9998731017112732,
"start": 96,
"tag": "NAME",
"value": "John Leidel"
},
{
"context": "ivity Class \n * \n * @author John Leidel\n * @author Zack Falgout\n * @author Chase Baker \n * @version 1.0\n * \n */\n\n",
"end": 131,
"score": 0.9998775720596313,
"start": 119,
"tag": "NAME",
"value": "Zack Falgout"
},
{
"context": "hor John Leidel\n * @author Zack Falgout\n * @author Chase Baker \n * @version 1.0\n * \n */\n\npackage com.example.fla",
"end": 154,
"score": 0.9998774528503418,
"start": 143,
"tag": "NAME",
"value": "Chase Baker"
}
] | null |
[] |
/**
* FlashBuddy Edit Deck Activity
*
* FlashBuddy Edit Deck Activity Class
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @version 1.0
*
*/
package com.example.flashbuddy;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FlashBuddyEditDeckActivity extends Activity {
private String FileName;
private List<FlashBuddyCard> cards;
private FlashBuddyCard currentCard;
private FlashBuddyDeck editDeck = null;
private int currentCardIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_buddy_edit_deck);
/*
* Grab the Intent
*/
Intent intent = getIntent();
FileName = intent.getStringExtra( FlashBuddyModifyDecksActivity.FILE_MESSAGE );
/*
* read the deck into our editDeck object
*/
editDeck = new FlashBuddyDeck();
try {
InputStream in = null;
try {
in = openFileInput(FileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* read the deck into the object
*/
editDeck.readDeck(in);
try {
if( in != null ){
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* get the card data
*/
cards = editDeck.getCards();
currentCard = cards.get(0);
currentCardIndex = 1;
/*
* Update the text fields with the current data
*/
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
TextView cardDesignator = (TextView) findViewById(R.id.cardDesignator);
questionTextView.setText(currentCard.getQuestion());
answerTextView.setText(currentCard.getAnswer());
timerTextView.setText(Integer.toString(currentCard.getTimer()));
cardDesignator.setText("Card 1 of "+Integer.toString(editDeck.getNumCards()));
Button NextButton = (Button)findViewById(R.id.nextButton);
NextButton.scheduleDrawable(NextButton.getBackground(), checkInfo, 1000);
}
final Runnable checkInfo = new Runnable()
{
public void run()
{
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
String localTimer = timerTextView.getText().toString();
Button NextButton = (Button)findViewById(R.id.nextButton);
if (localQuestion.equals("") || localAnswer.equals("") || localTimer.equals(""))
{
NextButton.setBackgroundColor(Color.parseColor("#7b93af"));
}
else
{
NextButton.setBackgroundColor(Color.parseColor("#4FA044"));
}
NextButton.scheduleDrawable(NextButton.getBackground(), checkInfo, 1000);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.flash_buddy_edit_deck, menu);
return true;
}
/**
* onClickNextCard : flips the editing session to the next card
* @param view
*/
public void onClickNextCard( View view ){
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
TextView cardDesignator = (TextView) findViewById(R.id.cardDesignator);
/*
* grab the input values
*/
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
int localTimer = Integer.parseInt(timerTextView.getText().toString());
/*
* record them to the card object
*/
this.currentCard.setAnswer(localAnswer);
this.currentCard.setQuestion(localQuestion);
this.currentCard.setTimer(localTimer);
if( (this.currentCardIndex+1) > this.editDeck.getNumCards() ) {
/*
* cycle back to the first card
*/
this.currentCardIndex = 1;
this.cards = this.editDeck.getCards();
this.currentCard = this.cards.get(0);
/*
* set the data in the text views
*/
answerTextView.setText(this.currentCard.getAnswer());
questionTextView.setText(this.currentCard.getQuestion());
timerTextView.setText(Integer.toString(this.currentCard.getTimer()));
}else{
/*
* bump the data to the next card
*/
this.currentCardIndex++;
this.cards = this.editDeck.getCards();
this.currentCard = this.cards.get(this.currentCardIndex-1);
/*
* set the data in the text views
*/
answerTextView.setText(this.currentCard.getAnswer());
questionTextView.setText(this.currentCard.getQuestion());
timerTextView.setText(Integer.toString(this.currentCard.getTimer()));
}
cardDesignator.setText("Card " + Integer.toString(this.currentCardIndex)
+ " of " + Integer.toString(this.editDeck.getNumCards()));
}
/**
* onClickWriteCard : writes the card to disk
* @param view
*/
public void onClickWriteCard( View view ){
if( this.FileName.length() == 0){
/**
* DO NOTHING! The user hasn't entered anything
*/
return ;
}
TextView questionTextView = (TextView) findViewById(R.id.questionEntry);
TextView answerTextView = (TextView) findViewById(R.id.answerEntry);
TextView timerTextView = (TextView) findViewById(R.id.timerEntry);
/*
* grab the input values
*/
String localQuestion = questionTextView.getText().toString();
String localAnswer = answerTextView.getText().toString();
int localTimer = Integer.parseInt(timerTextView.getText().toString());
/*
* write the data into the object
*/
this.currentCard = this.cards.get(this.currentCardIndex-1);
this.currentCard.setAnswer(localAnswer);
this.currentCard.setQuestion(localQuestion);
this.currentCard.setTimer(localTimer);
/*
* deletes the target file name
*/
deleteFile(this.FileName);
/*
* write out the file
*/
try {
FileOutputStream of = openFileOutput(this.editDeck.getTitle() + ".xml", Context.MODE_PRIVATE);
this.editDeck.writeDeck(of);
/*
* close the file
*/
try {
of.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* done writing changes; return to ModifyDeckActivity
*/
Intent returnUserIntent = new Intent( this, FlashBuddyModifyDecksActivity.class );
Intent intent = getIntent();
String username = intent.getStringExtra(FlashBuddy.USERNAME_MESSAGE);
returnUserIntent.putExtra( FlashBuddy.USERNAME_MESSAGE, username );
startActivity(returnUserIntent);
}
}
| 7,916 | 0.686334 | 0.68293 | 286 | 26.734266 | 24.921963 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.185315 | false | false |
12
|
aceb082836feb531e602d4d253b66e869e36e974
| 10,496,900,101,865 |
621b7e0cc50033184ac13030de5e1911d8fd781e
|
/src/Servlet/AdManageuServlet.java
|
d8abde92511d7feece22844fdfa1f4a5acc0e1ba
|
[] |
no_license
|
Gin96/Awork
|
https://github.com/Gin96/Awork
|
3d6a747d690cfc15228f169cc256551edd1fcaa3
|
7fd5784c7f92b3603fbd1a5b35fc0695cc97fc37
|
refs/heads/master
| 2021-01-01T16:12:21.464000 | 2017-07-20T03:40:07 | 2017-07-20T03:40:07 | 97,787,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Bll.AdminBll;
import Model.Admin;
import Model.Page;
public class AdManageuServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Admin admin=(Admin)request.getSession().getAttribute("admin");
if(admin!=null){
int currentPage=1;
int pageCount=8;
if(request.getParameter("currentPage")!=null){
currentPage=Integer.valueOf(request.getParameter("currentPage").toString());
}
Page userPage=new AdminBll().getPageUser(currentPage, pageCount);
request.setAttribute("userPage",userPage);
request.getRequestDispatcher("adminmanageuser.jsp").forward(request, response);
}else{
request.setAttribute("error", "ÇëÏȵǼ");
request.getRequestDispatcher("adminlogin.jsp").forward(request, response);
}
}
}
|
WINDOWS-1252
|
Java
| 1,326 |
java
|
AdManageuServlet.java
|
Java
|
[] | null |
[] |
package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Bll.AdminBll;
import Model.Admin;
import Model.Page;
public class AdManageuServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Admin admin=(Admin)request.getSession().getAttribute("admin");
if(admin!=null){
int currentPage=1;
int pageCount=8;
if(request.getParameter("currentPage")!=null){
currentPage=Integer.valueOf(request.getParameter("currentPage").toString());
}
Page userPage=new AdminBll().getPageUser(currentPage, pageCount);
request.setAttribute("userPage",userPage);
request.getRequestDispatcher("adminmanageuser.jsp").forward(request, response);
}else{
request.setAttribute("error", "ÇëÏȵǼ");
request.getRequestDispatcher("adminlogin.jsp").forward(request, response);
}
}
}
| 1,326 | 0.754932 | 0.751897 | 41 | 30.146341 | 26.164173 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.04878 | false | false |
12
|
3ccc61b728dddcc74f8944e559f56b8987f41835
| 3,461,743,641,699 |
8909c8082cf003bd0dc5ea99f7866039be6ec64f
|
/src/reusing/Component2.java
|
0e0ab1da1e99ef843007b240cf0a684083c956f4
|
[] |
no_license
|
kscsq/Eckel
|
https://github.com/kscsq/Eckel
|
62c83a443eecf7bcf67265c4862dfe0a78b71833
|
60f5463a3240d5f3efd30f4821975dc40442c4f1
|
refs/heads/master
| 2021-01-20T15:09:59.958000 | 2017-05-09T18:14:54 | 2017-05-09T18:14:54 | 90,709,878 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package reusing;
/**
* Created by kscsq on 04.05.2017.
*/
public class Component2 {
public Component2(){
System.out.println("Comp2 const");
}
}
|
UTF-8
|
Java
| 163 |
java
|
Component2.java
|
Java
|
[
{
"context": "package reusing;\n\n/**\n * Created by kscsq on 04.05.2017.\n */\npublic class Component2 {\n ",
"end": 41,
"score": 0.9996357560157776,
"start": 36,
"tag": "USERNAME",
"value": "kscsq"
}
] | null |
[] |
package reusing;
/**
* Created by kscsq on 04.05.2017.
*/
public class Component2 {
public Component2(){
System.out.println("Comp2 const");
}
}
| 163 | 0.619632 | 0.552147 | 10 | 15.3 | 14.422552 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
7d00a675b5ec9e33eec0a4719fdf31bf2d11199b
| 6,605,659,746,786 |
1cc488a327c2677a777084bc128425fec6da409a
|
/spring_project/SinchonBeer3-shop&cart/src/main/java/com/bitcamp/sc/cart/service/CartService.java
|
2a4e82efdf1d23124846c2e6a9e21c9310fc192f
|
[] |
no_license
|
seongdeokjo/JAVA_Practice
|
https://github.com/seongdeokjo/JAVA_Practice
|
8e54be671875b94a65d5ec19dee2118388cbd539
|
3e6046756b2c1b02753c7b5e9f8322f976e4c1a6
|
refs/heads/master
| 2023-08-23T21:51:21.513000 | 2021-10-23T06:39:11 | 2021-10-23T06:39:11 | 363,949,184 | 0 | 0 | null | false | 2021-06-29T07:14:07 | 2021-05-03T14:03:10 | 2021-06-29T07:01:56 | 2021-06-29T07:13:32 | 7,857 | 0 | 0 | 0 |
Java
| false | false |
package com.bitcamp.sc.cart.service;
public interface CartService {
// 구매 상품 인터페이스 만들것
}
|
UTF-8
|
Java
| 118 |
java
|
CartService.java
|
Java
|
[] | null |
[] |
package com.bitcamp.sc.cart.service;
public interface CartService {
// 구매 상품 인터페이스 만들것
}
| 118 | 0.723404 | 0.723404 | 7 | 12.428572 | 14.529351 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
12
|
bcf70210c27508645c30959d369f3c7fcdee5041
| 21,311,627,743,291 |
0133d1fe8b0c6548fba9bcc0f06e35fb851c6d24
|
/doc/main/java/com/hpe/cmca/pojo/DataCompare.java
|
db020a640bfc157129c4d81c6f35e9f3420e60af
|
[] |
no_license
|
libing070/vj
|
https://github.com/libing070/vj
|
60d91d64624760775dfe6c68f539abb7c5c30151
|
4762d000fda7f10cb8a215d888d4f9b317eb4070
|
refs/heads/master
| 2022-08-24T01:53:38.841000 | 2020-01-17T12:05:42 | 2020-01-17T12:05:42 | 162,565,378 | 2 | 0 | null | false | 2022-08-05T05:00:58 | 2018-12-20T10:41:26 | 2020-01-17T12:06:14 | 2022-08-05T05:00:58 | 125,271 | 0 | 0 | 7 |
Vue
| false | false |
package com.hpe.cmca.pojo;
import java.util.Date;
public class DataCompare {
private Integer id;
private Integer orderNum;
private String fieldName;
private String wordValue;
private String wordName;
private String excelName;
private String excelValue;
private String compareResult;
private String operPerson;
private Date createDatetime;
private Integer isdel;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getWordValue() {
return wordValue;
}
public void setWordValue(String wordValue) {
this.wordValue = wordValue;
}
public String getExcelName() {
return excelName;
}
public void setExcelName(String excelName) {
this.excelName = excelName;
}
public String getCompareResult() {
return compareResult;
}
public void setCompareResult(String compareResult) {
this.compareResult = compareResult;
}
public String getOperPerson() {
return operPerson;
}
public void setOperPerson(String operPerson) {
this.operPerson = operPerson;
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public String getExcelValue() {
return excelValue;
}
public void setExcelValue(String excelValue) {
this.excelValue = excelValue;
}
public String getWordName() {
return wordName;
}
public void setWordName(String wordName) {
this.wordName = wordName;
}
public Integer getIsdel() {
return isdel;
}
public void setIsdel(Integer isdel) {
this.isdel = isdel;
}
}
|
UTF-8
|
Java
| 1,844 |
java
|
DataCompare.java
|
Java
|
[] | null |
[] |
package com.hpe.cmca.pojo;
import java.util.Date;
public class DataCompare {
private Integer id;
private Integer orderNum;
private String fieldName;
private String wordValue;
private String wordName;
private String excelName;
private String excelValue;
private String compareResult;
private String operPerson;
private Date createDatetime;
private Integer isdel;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getWordValue() {
return wordValue;
}
public void setWordValue(String wordValue) {
this.wordValue = wordValue;
}
public String getExcelName() {
return excelName;
}
public void setExcelName(String excelName) {
this.excelName = excelName;
}
public String getCompareResult() {
return compareResult;
}
public void setCompareResult(String compareResult) {
this.compareResult = compareResult;
}
public String getOperPerson() {
return operPerson;
}
public void setOperPerson(String operPerson) {
this.operPerson = operPerson;
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public String getExcelValue() {
return excelValue;
}
public void setExcelValue(String excelValue) {
this.excelValue = excelValue;
}
public String getWordName() {
return wordName;
}
public void setWordName(String wordName) {
this.wordName = wordName;
}
public Integer getIsdel() {
return isdel;
}
public void setIsdel(Integer isdel) {
this.isdel = isdel;
}
}
| 1,844 | 0.74295 | 0.74295 | 85 | 20.694118 | 15.104362 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.588235 | false | false |
12
|
5f909c8894465fe86bb1cd4300265e835381f986
| 24,472,723,658,389 |
c0505e10f531dfe0f707de06858cba848012684a
|
/src/test/java/com/treino/libreria/configuration/RestTemplateTestConfiguration.java
|
329ae805c9d81597a6f66d12f49eab99115c6a70
|
[] |
no_license
|
caique/libreria
|
https://github.com/caique/libreria
|
f7654b0c5cf46173b17aeb527aa71f0a22b0d959
|
5bba931a2820f7db839d5722f665e9d82b37c815
|
refs/heads/master
| 2020-06-03T14:51:27.962000 | 2019-05-31T18:52:31 | 2019-05-31T18:52:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.treino.libreria.configuration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import static org.mockito.Mockito.mock;
@Configuration
public class RestTemplateTestConfiguration {
@Bean
@Primary
public RestTemplate restTemplateBuilderMethod() {
return mock(RestTemplate.class);
}
}
|
UTF-8
|
Java
| 565 |
java
|
RestTemplateTestConfiguration.java
|
Java
|
[] | null |
[] |
package com.treino.libreria.configuration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import static org.mockito.Mockito.mock;
@Configuration
public class RestTemplateTestConfiguration {
@Bean
@Primary
public RestTemplate restTemplateBuilderMethod() {
return mock(RestTemplate.class);
}
}
| 565 | 0.814159 | 0.814159 | 20 | 27.25 | 24.334904 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
ad90d334174e403718cdb8dad42ce04544d8b6ea
| 23,845,658,445,601 |
45961c4ff7ecc966aac1ed53d945946fa2683583
|
/src/main/java/echopointng/AbleProperties.java
|
f8e0fe8102f46191c5c3fd211816128b72a186f7
|
[] |
no_license
|
ibissource/ibis-echo2
|
https://github.com/ibissource/ibis-echo2
|
6ac8c33c7c8196068d23910ff8acd0aa654a1262
|
a72a36e186fd45de3acb092339ded8be64a6eac4
|
refs/heads/master
| 2023-03-10T13:48:07.645000 | 2022-08-29T09:59:07 | 2022-08-29T09:59:07 | 141,299,432 | 2 | 1 | null | false | 2023-02-22T08:10:17 | 2018-07-17T14:14:39 | 2022-08-25T08:10:45 | 2023-02-22T08:10:16 | 1,515 | 2 | 0 | 1 |
Java
| false | false |
/*
* This file is part of the Echo Point Project. This project is a collection
* of Components that have extended the Echo Web Application Framework.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package echopointng;
import java.io.Serializable;
import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.Component;
import nextapp.echo2.app.FillImage;
import echopointng.able.Alignable;
import echopointng.able.BackgroundImageable;
/**
* <code>AbleProperties</code> is a collection of UI properties that are related to the
* various *.able interfaces. This allows you to specify many individual
* properties in one object.
* <p>
* This class is really design to be used NOT as a fully fledged component in its own right
* but rather as a holder of specific properties. Being derived from <code>Component</code> allows
* it to re-use much of the Style/Property/Rendering code infrastructure of Echo2.
* <p>
* Because <code>AbleProperties</code> is ultimately derived from
* <code>Component</code>, then you can set properties in here via
* <code>Style</code> objects. However to get full <code>StyleSheet</code> support,
* the <code>AbleProperties</code> must be part of the Echo2 component
* hiearchy.
*/
public class AbleProperties extends AbleComponent implements Serializable, Alignable, BackgroundImageable {
/**
* Constructs a <code>AbleProperties</code>
*/
public AbleProperties() {
super();
}
/**
* We dont allow anu children to be added to the component.
*
* @see nextapp.echo2.app.Component#isValidChild(nextapp.echo2.app.Component)
*/
public boolean isValidChild(Component child) {
return false;
}
/**
* @see echopointng.able.Alignable#getAlignment()
*/
public Alignment getAlignment() {
return (Alignment) getProperty(Alignable.PROPERTY_ALIGNMENT);
}
/**
* @see echopointng.able.Alignable#setAlignment(nextapp.echo2.app.Alignment)
*/
public void setAlignment(Alignment newValue) {
setProperty(Alignable.PROPERTY_ALIGNMENT, newValue);
}
/**
* @see echopointng.able.BackgroundImageable#getBackgroundImage()
*/
public FillImage getBackgroundImage() {
return (FillImage) getProperty(BackgroundImageable.PROPERTY_BACKGROUND_IMAGE);
}
/**
* @see echopointng.able.BackgroundImageable#setBackgroundImage(nextapp.echo2.app.FillImage)
*/
public void setBackgroundImage(FillImage newValue) {
setProperty(BackgroundImageable.PROPERTY_BACKGROUND_IMAGE, newValue);
}
}
|
UTF-8
|
Java
| 3,867 |
java
|
AbleProperties.java
|
Java
|
[] | null |
[] |
/*
* This file is part of the Echo Point Project. This project is a collection
* of Components that have extended the Echo Web Application Framework.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package echopointng;
import java.io.Serializable;
import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.Component;
import nextapp.echo2.app.FillImage;
import echopointng.able.Alignable;
import echopointng.able.BackgroundImageable;
/**
* <code>AbleProperties</code> is a collection of UI properties that are related to the
* various *.able interfaces. This allows you to specify many individual
* properties in one object.
* <p>
* This class is really design to be used NOT as a fully fledged component in its own right
* but rather as a holder of specific properties. Being derived from <code>Component</code> allows
* it to re-use much of the Style/Property/Rendering code infrastructure of Echo2.
* <p>
* Because <code>AbleProperties</code> is ultimately derived from
* <code>Component</code>, then you can set properties in here via
* <code>Style</code> objects. However to get full <code>StyleSheet</code> support,
* the <code>AbleProperties</code> must be part of the Echo2 component
* hiearchy.
*/
public class AbleProperties extends AbleComponent implements Serializable, Alignable, BackgroundImageable {
/**
* Constructs a <code>AbleProperties</code>
*/
public AbleProperties() {
super();
}
/**
* We dont allow anu children to be added to the component.
*
* @see nextapp.echo2.app.Component#isValidChild(nextapp.echo2.app.Component)
*/
public boolean isValidChild(Component child) {
return false;
}
/**
* @see echopointng.able.Alignable#getAlignment()
*/
public Alignment getAlignment() {
return (Alignment) getProperty(Alignable.PROPERTY_ALIGNMENT);
}
/**
* @see echopointng.able.Alignable#setAlignment(nextapp.echo2.app.Alignment)
*/
public void setAlignment(Alignment newValue) {
setProperty(Alignable.PROPERTY_ALIGNMENT, newValue);
}
/**
* @see echopointng.able.BackgroundImageable#getBackgroundImage()
*/
public FillImage getBackgroundImage() {
return (FillImage) getProperty(BackgroundImageable.PROPERTY_BACKGROUND_IMAGE);
}
/**
* @see echopointng.able.BackgroundImageable#setBackgroundImage(nextapp.echo2.app.FillImage)
*/
public void setBackgroundImage(FillImage newValue) {
setProperty(BackgroundImageable.PROPERTY_BACKGROUND_IMAGE, newValue);
}
}
| 3,867 | 0.731575 | 0.726403 | 99 | 37.060608 | 33.367504 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747475 | false | false |
12
|
1befac3990eab1c14168241d8b54a05a758281eb
| 30,425,548,344,859 |
cc953f667e11f32d4119ac827d9378ed477b7706
|
/backend-exts/store-ext/src/main/java/com/stosz/store/ext/model/Invoicing.java
|
cb1f5a6c6006c18e3c92190bbaf61526322af1b5
|
[] |
no_license
|
ttggaa/erp
|
https://github.com/ttggaa/erp
|
e20ed03ecf6965da95c9fc472d505ae8ef4f3902
|
167f5d60d085d016b08452083f172df654a7c5c5
|
refs/heads/master
| 2020-04-22T12:03:43.913000 | 2018-12-05T16:16:11 | 2018-12-05T16:16:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.stosz.store.ext.model;
import com.stosz.plat.model.AbstractParamEntity;
import com.stosz.plat.model.DBColumn;
import com.stosz.plat.model.ITable;
import com.stosz.store.ext.enums.InvoicingTypeEnum;
import com.stosz.store.ext.enums.StockStateEnum;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* @Author:yangqinghui
* @Description:Invoicing
* @Created Time:2017/11/22 18:16
* @Update Time:
*/
public class Invoicing extends AbstractParamEntity implements ITable, Serializable {
@DBColumn
private Integer id;
@DBColumn
private Integer wmsId;
@DBColumn
private Integer deptId;
@DBColumn
private String deptNo;
@DBColumn
private String deptName;
@DBColumn
private String spu;
@DBColumn
private String sku;
@DBColumn
private String voucherNo;
@DBColumn
private Integer quantity;
@DBColumn
private BigDecimal cost;
@DBColumn
private Integer state;
@DBColumn
private BigDecimal amount;
@DBColumn
private Integer type;
@DBColumn
private Integer stockDate;
@DBColumn
private Integer planId;
@DBColumn
private LocalDateTime changeAt;
@DBColumn
private LocalDateTime createAt;
@DBColumn
private LocalDateTime updateAt;
@DBColumn
private String creator;
@DBColumn
private Integer creatorId;
/**
* 仓库名
*/
private transient String wmsName;
/**
* 月份
*/
private transient String planMonth;
/**
* 单据类型
*/
private transient InvoicingTypeEnum invoicingTypeEnum;
/**
* 0:进仓 1:出仓
*/
private transient StockStateEnum stockStateEnum;
public Invoicing() {
}
public Invoicing(Integer wmsId, Integer deptId, String sku) {
this.wmsId = wmsId;
this.deptId = deptId;
this.sku = sku;
}
public String getPlanMonth() {
return planMonth;
}
public void setPlanMonth(String planMonth) {
this.planMonth = planMonth;
}
public InvoicingTypeEnum getInvoicingTypeEnum() {
return type == null ? null : InvoicingTypeEnum.fromId(type);
}
public void setInvoicingTypeEnum(InvoicingTypeEnum invoicingTypeEnum) {
this.invoicingTypeEnum = invoicingTypeEnum;
}
public StockStateEnum getStockStateEnum() {
return state == null ? null : StockStateEnum.fromId(state);
}
public void setStockStateEnum(StockStateEnum stockStateEnum) {
this.stockStateEnum = stockStateEnum;
}
public String getWmsName() {
return wmsName;
}
public void setWmsName(String wmsName) {
this.wmsName = wmsName;
}
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public Integer getWmsId() {
return wmsId;
}
public void setWmsId(Integer wmsId) {
this.wmsId = wmsId;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptNo() {
return deptNo;
}
public void setDeptNo(String deptNo) {
this.deptNo = deptNo;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getSpu() {
return spu;
}
public void setSpu(String spu) {
this.spu = spu;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getVoucherNo() {
return voucherNo;
}
public void setVoucherNo(String voucherNo) {
this.voucherNo = voucherNo;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStockDate() {
return stockDate;
}
public void setStockDate(Integer stockDate) {
this.stockDate = stockDate;
}
public Integer getPlanId() {
return planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public LocalDateTime getChangeAt() {
return changeAt;
}
public void setChangeAt(LocalDateTime changeAt) {
this.changeAt = changeAt;
}
public LocalDateTime getCreateAt() {
return createAt;
}
public void setCreateAt(LocalDateTime createAt) {
this.createAt = createAt;
}
public LocalDateTime getUpdateAt() {
return updateAt;
}
public void setUpdateAt(LocalDateTime updateAt) {
this.updateAt = updateAt;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
@Override
public Integer getCreatorId() {
return creatorId;
}
@Override
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
@Override
public String getTable() {
return "invoicing";
}
}
|
UTF-8
|
Java
| 5,823 |
java
|
Invoicing.java
|
Java
|
[
{
"context": ";\nimport java.time.LocalDateTime;\n\n/**\n * @Author:yangqinghui\n * @Description:Invoicing\n * @Created Time:2017/1",
"end": 378,
"score": 0.9992489814758301,
"start": 367,
"tag": "USERNAME",
"value": "yangqinghui"
}
] | null |
[] |
package com.stosz.store.ext.model;
import com.stosz.plat.model.AbstractParamEntity;
import com.stosz.plat.model.DBColumn;
import com.stosz.plat.model.ITable;
import com.stosz.store.ext.enums.InvoicingTypeEnum;
import com.stosz.store.ext.enums.StockStateEnum;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* @Author:yangqinghui
* @Description:Invoicing
* @Created Time:2017/11/22 18:16
* @Update Time:
*/
public class Invoicing extends AbstractParamEntity implements ITable, Serializable {
@DBColumn
private Integer id;
@DBColumn
private Integer wmsId;
@DBColumn
private Integer deptId;
@DBColumn
private String deptNo;
@DBColumn
private String deptName;
@DBColumn
private String spu;
@DBColumn
private String sku;
@DBColumn
private String voucherNo;
@DBColumn
private Integer quantity;
@DBColumn
private BigDecimal cost;
@DBColumn
private Integer state;
@DBColumn
private BigDecimal amount;
@DBColumn
private Integer type;
@DBColumn
private Integer stockDate;
@DBColumn
private Integer planId;
@DBColumn
private LocalDateTime changeAt;
@DBColumn
private LocalDateTime createAt;
@DBColumn
private LocalDateTime updateAt;
@DBColumn
private String creator;
@DBColumn
private Integer creatorId;
/**
* 仓库名
*/
private transient String wmsName;
/**
* 月份
*/
private transient String planMonth;
/**
* 单据类型
*/
private transient InvoicingTypeEnum invoicingTypeEnum;
/**
* 0:进仓 1:出仓
*/
private transient StockStateEnum stockStateEnum;
public Invoicing() {
}
public Invoicing(Integer wmsId, Integer deptId, String sku) {
this.wmsId = wmsId;
this.deptId = deptId;
this.sku = sku;
}
public String getPlanMonth() {
return planMonth;
}
public void setPlanMonth(String planMonth) {
this.planMonth = planMonth;
}
public InvoicingTypeEnum getInvoicingTypeEnum() {
return type == null ? null : InvoicingTypeEnum.fromId(type);
}
public void setInvoicingTypeEnum(InvoicingTypeEnum invoicingTypeEnum) {
this.invoicingTypeEnum = invoicingTypeEnum;
}
public StockStateEnum getStockStateEnum() {
return state == null ? null : StockStateEnum.fromId(state);
}
public void setStockStateEnum(StockStateEnum stockStateEnum) {
this.stockStateEnum = stockStateEnum;
}
public String getWmsName() {
return wmsName;
}
public void setWmsName(String wmsName) {
this.wmsName = wmsName;
}
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public Integer getWmsId() {
return wmsId;
}
public void setWmsId(Integer wmsId) {
this.wmsId = wmsId;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptNo() {
return deptNo;
}
public void setDeptNo(String deptNo) {
this.deptNo = deptNo;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getSpu() {
return spu;
}
public void setSpu(String spu) {
this.spu = spu;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getVoucherNo() {
return voucherNo;
}
public void setVoucherNo(String voucherNo) {
this.voucherNo = voucherNo;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStockDate() {
return stockDate;
}
public void setStockDate(Integer stockDate) {
this.stockDate = stockDate;
}
public Integer getPlanId() {
return planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public LocalDateTime getChangeAt() {
return changeAt;
}
public void setChangeAt(LocalDateTime changeAt) {
this.changeAt = changeAt;
}
public LocalDateTime getCreateAt() {
return createAt;
}
public void setCreateAt(LocalDateTime createAt) {
this.createAt = createAt;
}
public LocalDateTime getUpdateAt() {
return updateAt;
}
public void setUpdateAt(LocalDateTime updateAt) {
this.updateAt = updateAt;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
@Override
public Integer getCreatorId() {
return creatorId;
}
@Override
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
@Override
public String getTable() {
return "invoicing";
}
}
| 5,823 | 0.622046 | 0.619631 | 291 | 18.924398 | 17.293737 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302406 | false | false |
12
|
a398eecd9d20625218b6f24196c4e27e236a382e
| 2,147,483,703,882 |
4a22f9b02de0162aded549367abbfc6100963f69
|
/YAPCAsiaViewer/src/main/java/com/github/takuji31/yapcasiaviewer/YAVListFragment.java
|
481017d92bd82602e52782a1fb54e476d4c29d1c
|
[
"Apache-2.0"
] |
permissive
|
takuji31/YAPCAsiaViewer
|
https://github.com/takuji31/YAPCAsiaViewer
|
c77bf3641f4f8e542a84221e83b6c2ad4c190207
|
e773740eddb79d3d52fb305a6f7a7c13a2d8193c
|
HEAD
| 2016-09-06T21:40:02.914000 | 2015-07-10T00:18:15 | 2015-07-10T00:18:15 | 5,510,648 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.takuji31.yapcasiaviewer;
import com.github.takuji31.appbase.app.BaseListFragment;
public class YAVListFragment extends BaseListFragment<YapcAsiaViewer, YAVActivity> {
}
|
UTF-8
|
Java
| 191 |
java
|
YAVListFragment.java
|
Java
|
[
{
"context": "package com.github.takuji31.yapcasiaviewer;\n\nimport com.github.takuji31.appba",
"end": 27,
"score": 0.99885094165802,
"start": 19,
"tag": "USERNAME",
"value": "takuji31"
},
{
"context": "ithub.takuji31.yapcasiaviewer;\n\nimport com.github.takuji31.appbase.app.BaseListFragment;\n\npublic class YAVLi",
"end": 71,
"score": 0.9989715814590454,
"start": 63,
"tag": "USERNAME",
"value": "takuji31"
}
] | null |
[] |
package com.github.takuji31.yapcasiaviewer;
import com.github.takuji31.appbase.app.BaseListFragment;
public class YAVListFragment extends BaseListFragment<YapcAsiaViewer, YAVActivity> {
}
| 191 | 0.842932 | 0.82199 | 7 | 26.285715 | 32.083439 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
12
|
ee5f0933588bbb39ed4edb3b96732d139e719ab4
| 1,236,950,609,998 |
42b5c17d0eea72ded9b5b27e1aaad3a35efbc6b8
|
/dp/1048. Longest String Chain.java
|
6c9ebc55e6a2929740de3158bfb36f9a2cc06bb8
|
[] |
no_license
|
ankurraj511/leetcode
|
https://github.com/ankurraj511/leetcode
|
ecc7cf26d933c0f5f381d0f104c6ab0e0c0a1c45
|
0a9e5894bf03f8d3bc48cec2cc80203ceddf803a
|
refs/heads/main
| 2023-04-23T11:46:13.328000 | 2021-05-16T23:56:38 | 2021-05-16T23:56:38 | 359,750,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Pair {
String str;
int len;
Pair(String s , int l) {
str = s;
len = l;
}
}
class Solution {
ArrayList<ArrayList<Pair>> ls;
boolean isChain(String s1 , String s2) {
for (int i = 0 ; i < s2.length() ; i++) {
int j = 0 , k = 0;
while (j < s1.length()) {
if (k == i)
k += 1;
if (s1.charAt(j) != s2.charAt(k))
break;
j += 1;
k += 1;
}
if (j == s1.length())
return true;
}
return false;
}
int dfs(int len, int pos) {
if (len == 15)
return 1;
String curr = ls.get(len).get(pos).str;
int curr_len = ls.get(len).get(pos).len;
if (curr_len != 0)
return curr_len;
for (int i = 0 ; i < ls.get(len + 1).size() ; i++) {
String next = ls.get(len + 1).get(i).str;
if (isChain(curr , next)) {
curr_len = Math.max(curr_len , dfs(len + 1 , i));
}
}
curr_len += 1;
return ls.get(len).get(pos).len = curr_len;
}
public int longestStrChain(String[] words) {
int n = words.length;
ls = new ArrayList();
for (int i = 0 ; i < 16 ; i++)
ls.add(new ArrayList());
for (int i = 0 ; i < n ; i++)
ls.get(words[i].length() - 1).add(new Pair(words[i] , 0));
int res = 0;
for (int i = 0 ; i < 16 ; i++)
for (int j = 0 ; j < ls.get(i).size() ; j++)
res = Math.max(res , dfs(i , j));
return res;
}
}
|
UTF-8
|
Java
| 1,674 |
java
|
1048. Longest String Chain.java
|
Java
|
[] | null |
[] |
class Pair {
String str;
int len;
Pair(String s , int l) {
str = s;
len = l;
}
}
class Solution {
ArrayList<ArrayList<Pair>> ls;
boolean isChain(String s1 , String s2) {
for (int i = 0 ; i < s2.length() ; i++) {
int j = 0 , k = 0;
while (j < s1.length()) {
if (k == i)
k += 1;
if (s1.charAt(j) != s2.charAt(k))
break;
j += 1;
k += 1;
}
if (j == s1.length())
return true;
}
return false;
}
int dfs(int len, int pos) {
if (len == 15)
return 1;
String curr = ls.get(len).get(pos).str;
int curr_len = ls.get(len).get(pos).len;
if (curr_len != 0)
return curr_len;
for (int i = 0 ; i < ls.get(len + 1).size() ; i++) {
String next = ls.get(len + 1).get(i).str;
if (isChain(curr , next)) {
curr_len = Math.max(curr_len , dfs(len + 1 , i));
}
}
curr_len += 1;
return ls.get(len).get(pos).len = curr_len;
}
public int longestStrChain(String[] words) {
int n = words.length;
ls = new ArrayList();
for (int i = 0 ; i < 16 ; i++)
ls.add(new ArrayList());
for (int i = 0 ; i < n ; i++)
ls.get(words[i].length() - 1).add(new Pair(words[i] , 0));
int res = 0;
for (int i = 0 ; i < 16 ; i++)
for (int j = 0 ; j < ls.get(i).size() ; j++)
res = Math.max(res , dfs(i , j));
return res;
}
}
| 1,674 | 0.398447 | 0.378734 | 56 | 28.892857 | 16.766973 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false |
12
|
9eb85b8f2077ebdc43a3b0e32d9b8f191f69bcf6
| 7,017,976,567,399 |
dd36289ccebd3b4c4c5981538467ce1f9932eeee
|
/AndroidStudioProjects/AndroidTutorial-master/examples/0501/MyAndroidTutorial/app/src/main/java/net/macdidi/myandroidtutorial/PlayActivity.java
|
5cfb523c3381a0210552fc3f4c0666b6c0b2e5f0
|
[] |
no_license
|
skyforcetw/skygoodjob
|
https://github.com/skyforcetw/skygoodjob
|
110a37c62f7564a85e31cdfb1f36da27788dac31
|
2edaa07caf81b21b404539ec333bf60d390bc7d4
|
refs/heads/master
| 2018-10-20T03:34:11.714000 | 2018-10-08T11:13:42 | 2018-10-08T11:13:42 | 32,726,734 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.macdidi.myandroidtutorial;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class PlayActivity extends Activity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
Intent intent = getIntent();
String fileName = intent.getStringExtra("fileName");
// 建立指定資源的MediaPlayer物件
Uri uri = Uri.parse(fileName);
mediaPlayer = MediaPlayer.create(this, uri);
}
@Override
protected void onStop() {
if (mediaPlayer.isPlaying()) {
// 停止播放
mediaPlayer.stop();
}
// 清除MediaPlayer物件
mediaPlayer.release();
super.onStop();
}
public void onSubmit(View view) {
// 結束Activity元件
finish();
}
public void clickPlay(View view) {
// 開始播放
mediaPlayer.start();
}
public void clickPause(View view) {
// 暫停播放
mediaPlayer.pause();
}
public void clickStop(View view) {
// 停止播放
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
// 回到開始的位置
mediaPlayer.seekTo(0);
}
}
|
UTF-8
|
Java
| 1,469 |
java
|
PlayActivity.java
|
Java
|
[] | null |
[] |
package net.macdidi.myandroidtutorial;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class PlayActivity extends Activity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
Intent intent = getIntent();
String fileName = intent.getStringExtra("fileName");
// 建立指定資源的MediaPlayer物件
Uri uri = Uri.parse(fileName);
mediaPlayer = MediaPlayer.create(this, uri);
}
@Override
protected void onStop() {
if (mediaPlayer.isPlaying()) {
// 停止播放
mediaPlayer.stop();
}
// 清除MediaPlayer物件
mediaPlayer.release();
super.onStop();
}
public void onSubmit(View view) {
// 結束Activity元件
finish();
}
public void clickPlay(View view) {
// 開始播放
mediaPlayer.start();
}
public void clickPause(View view) {
// 暫停播放
mediaPlayer.pause();
}
public void clickStop(View view) {
// 停止播放
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
// 回到開始的位置
mediaPlayer.seekTo(0);
}
}
| 1,469 | 0.606192 | 0.605472 | 64 | 20.71875 | 16.670023 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359375 | false | false |
12
|
e90ead1d0182985ad79a79b2f7c04ca879fe92e0
| 3,917,010,240,838 |
4fc3360e558d6b8d76a7b752c1528429391d4a6e
|
/ALDA/src/alda/linear/CAKLinkedList.java
|
76d9348a1be08032f05db983605749cad5580448
|
[] |
no_license
|
chanpa/ALDA
|
https://github.com/chanpa/ALDA
|
cb229b724b8264669dff65511cf680af4c36d738
|
6b4a406d5c632837856e151015707840610d64b7
|
refs/heads/master
| 2020-12-24T14:19:01.892000 | 2014-03-12T16:33:28 | 2014-03-12T16:33:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package alda.linear;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CAKLinkedList<E> implements ALDAList<E> {
private int modCount = 0;
private int numberOfElements;
private Node<E> head;
private Node<E> tail;
public CAKLinkedList(){
clear();
}
public void add(E data){
add(size(), data);
}
public void add(int index, E data){
Node<E>[] arr = getNodes(index);
Node<E> prev = arr[0];
Node<E> current = arr[1];
Node<E> newNode = new Node<E>(data, current);
prev.next = newNode;
numberOfElements++;
}
public boolean remove(E element){
int index = indexOf(element);
// That element does not exist
if (index == -1)
return false;
remove(index);
return true;
}
public E remove(int index){
if (index >= size())
throw new IndexOutOfBoundsException();
Node<E>[] arr = getNodes(index);
Node<E> prev = arr[0];
Node<E> current = arr[1];
prev.next = current.next;
numberOfElements--;
return current.data;
}
public E remove(Node<E> prev, Node<E> current){
prev.next = current.next;
numberOfElements--;
return current.data;
}
public E get(int index){
if (size() == 0)
throw new IndexOutOfBoundsException();
if (index >= size())
throw new IndexOutOfBoundsException();
Node<E> node = getNodes(index)[1];
return node.data;
}
public boolean contains(E element){
return indexOf(element) != -1;
}
public int indexOf(E element){
Node<E> current = head.next;
for (int i = 0; i < size(); i++){
if (current.data.equals(element))
return i;
current = current.next;
}
return -1;
}
public void clear(){
tail = new Node<E>(null, null);
head = new Node<E>(null, tail);
numberOfElements = 0;
modCount++;
}
public int size(){
return numberOfElements;
}
public Iterator<E> iterator(){
return new CAKLinkedListIterator();
}
private Node<E>[] getNodes(int index){
if (index > size() || index < 0)
throw new IndexOutOfBoundsException();
Node<E> prev = head;
Node<E> current = prev.next;
for (int i = 0; i < index; i++){
prev = current;
current = current.next;
}
Node<E>[] arr = new Node[2];
arr[0] = prev;
arr[1] = current;
return arr;
}
public String toString(){
String str = "[";
Node<E> current = head.next;
for (int i = 0; i < size(); i++){
str += current.data + ", ";
current = current.next;
}
if (str.length() > 1){
str = str.substring(0, str.length()-2);
}
return str + "]";
}
private static class Node<E>{
Node<E> next;
E data;
Node(E data, Node<E> next){
this.next = next;
this.data = data;
}
}
private class CAKLinkedListIterator implements java.util.Iterator<E>{
private Node<E> prev = null;
private Node<E> current = head;
private Node<E> next = current.next;
private int expectedModCount = modCount;
private boolean removeAllowed = false;
private int i = 0;
public boolean hasNext(){
// System.out.println(tail+"\n"+current.next+"\n");
return next != tail;
}
public E next(){
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!hasNext())
throw new java.util.NoSuchElementException();
E nextItem = next.data;
prev = current;
current = next;
next = next.next;
removeAllowed = true;
i++;
return nextItem;
}
public void remove(){
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!removeAllowed)
throw new IllegalStateException();
CAKLinkedList.this.remove(prev, current);
removeAllowed = false;
}
}
}
|
UTF-8
|
Java
| 3,892 |
java
|
CAKLinkedList.java
|
Java
|
[] | null |
[] |
package alda.linear;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CAKLinkedList<E> implements ALDAList<E> {
private int modCount = 0;
private int numberOfElements;
private Node<E> head;
private Node<E> tail;
public CAKLinkedList(){
clear();
}
public void add(E data){
add(size(), data);
}
public void add(int index, E data){
Node<E>[] arr = getNodes(index);
Node<E> prev = arr[0];
Node<E> current = arr[1];
Node<E> newNode = new Node<E>(data, current);
prev.next = newNode;
numberOfElements++;
}
public boolean remove(E element){
int index = indexOf(element);
// That element does not exist
if (index == -1)
return false;
remove(index);
return true;
}
public E remove(int index){
if (index >= size())
throw new IndexOutOfBoundsException();
Node<E>[] arr = getNodes(index);
Node<E> prev = arr[0];
Node<E> current = arr[1];
prev.next = current.next;
numberOfElements--;
return current.data;
}
public E remove(Node<E> prev, Node<E> current){
prev.next = current.next;
numberOfElements--;
return current.data;
}
public E get(int index){
if (size() == 0)
throw new IndexOutOfBoundsException();
if (index >= size())
throw new IndexOutOfBoundsException();
Node<E> node = getNodes(index)[1];
return node.data;
}
public boolean contains(E element){
return indexOf(element) != -1;
}
public int indexOf(E element){
Node<E> current = head.next;
for (int i = 0; i < size(); i++){
if (current.data.equals(element))
return i;
current = current.next;
}
return -1;
}
public void clear(){
tail = new Node<E>(null, null);
head = new Node<E>(null, tail);
numberOfElements = 0;
modCount++;
}
public int size(){
return numberOfElements;
}
public Iterator<E> iterator(){
return new CAKLinkedListIterator();
}
private Node<E>[] getNodes(int index){
if (index > size() || index < 0)
throw new IndexOutOfBoundsException();
Node<E> prev = head;
Node<E> current = prev.next;
for (int i = 0; i < index; i++){
prev = current;
current = current.next;
}
Node<E>[] arr = new Node[2];
arr[0] = prev;
arr[1] = current;
return arr;
}
public String toString(){
String str = "[";
Node<E> current = head.next;
for (int i = 0; i < size(); i++){
str += current.data + ", ";
current = current.next;
}
if (str.length() > 1){
str = str.substring(0, str.length()-2);
}
return str + "]";
}
private static class Node<E>{
Node<E> next;
E data;
Node(E data, Node<E> next){
this.next = next;
this.data = data;
}
}
private class CAKLinkedListIterator implements java.util.Iterator<E>{
private Node<E> prev = null;
private Node<E> current = head;
private Node<E> next = current.next;
private int expectedModCount = modCount;
private boolean removeAllowed = false;
private int i = 0;
public boolean hasNext(){
// System.out.println(tail+"\n"+current.next+"\n");
return next != tail;
}
public E next(){
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!hasNext())
throw new java.util.NoSuchElementException();
E nextItem = next.data;
prev = current;
current = next;
next = next.next;
removeAllowed = true;
i++;
return nextItem;
}
public void remove(){
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!removeAllowed)
throw new IllegalStateException();
CAKLinkedList.this.remove(prev, current);
removeAllowed = false;
}
}
}
| 3,892 | 0.595838 | 0.590185 | 195 | 17.958975 | 15.429853 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.34359 | false | false |
12
|
b994e1d634dbaf32aeaffb34d856cc99fa75a467
| 19,602,230,747,582 |
7495df42f81cca8db2cddc19ea06abb2f4d702f6
|
/src/main/java/cn/vfire/common/utils/enums/ClzTypeEnum.java
|
3e5cd9cf84396c5e7a29a07b732ac1b4dcdb062e
|
[] |
no_license
|
zgbn/WebCollector
|
https://github.com/zgbn/WebCollector
|
5f76b3291f6bd7a33a3b702ef5d89655015500c5
|
e643823dccd6a810ecc8fc04750995c4e56f608e
|
refs/heads/master
| 2021-01-21T04:55:26.685000 | 2016-06-11T08:54:09 | 2016-06-11T08:54:09 | 53,814,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.vfire.common.utils.enums;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public enum ClzTypeEnum {
NULL, BYTE, BYTE_ARRAY, CHAR, CHAR_ARRAY, SHORT, SHORT_ARRAY, INT, INT_ARRAY, LONG, LONG_ARRAY, FLOAT, FLOAT_ARRAY, DOUBLE, DOUBLE_ARRAY, BOOLEAN, BOOLEAN_ARRAY, STRING, STRING_ARRAY, OBJECT, OBJECT_ARRAY, LIST, SET, COLLECTION, MAP;
public static ClzTypeEnum parseClzTypeEnum(Class<?> clz) {
if (clz == byte.class || clz == Byte.class) {
return BYTE;
} else if (clz == byte[].class || clz == Byte[].class) {
return BYTE_ARRAY;
} else if (clz == char.class || clz == Character.class) {
return CHAR;
} else if (clz == char[].class || clz == Character[].class) {
return CHAR_ARRAY;
} else if (clz == short.class || clz == Short.class) {
return SHORT;
} else if (clz == short[].class || clz == Short[].class) {
return SHORT_ARRAY;
} else if (clz == int.class || clz == Integer.class) {
return INT;
} else if (clz == int[].class || clz == Integer[].class) {
return INT_ARRAY;
} else if (clz == long.class || clz == Long.class) {
return LONG;
} else if (clz == long[].class || clz == Long[].class) {
return LONG_ARRAY;
} else if (clz == float.class || clz == Float.class) {
return FLOAT;
} else if (clz == float[].class || clz == Float[].class) {
return FLOAT_ARRAY;
} else if (clz == double.class || clz == Double.class) {
return DOUBLE;
} else if (clz == double[].class || clz == Double[].class) {
return DOUBLE_ARRAY;
} else if (clz == boolean.class || clz == Boolean.class) {
return BOOLEAN;
} else if (clz == boolean[].class || clz == Boolean[].class) {
return BOOLEAN_ARRAY;
} else if (clz == String.class) {
return STRING;
} else if (clz == String[].class) {
return STRING_ARRAY;
} else if (clz == Object.class) {
return OBJECT;
} else if (clz == Object[].class) {
return OBJECT_ARRAY;
} else if (clz == List.class || List.class.isAssignableFrom(clz)) {
return LIST;
} else if (clz == Set.class || Set.class.isAssignableFrom(clz)) {
return SET;
} else if (clz == Collection.class || Collection.class.isAssignableFrom(clz)) {
return COLLECTION;
} else if (clz == Map.class || Map.class.isAssignableFrom(clz)) {
return MAP;
}
return NULL;
}
}
|
UTF-8
|
Java
| 2,403 |
java
|
ClzTypeEnum.java
|
Java
|
[] | null |
[] |
package cn.vfire.common.utils.enums;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public enum ClzTypeEnum {
NULL, BYTE, BYTE_ARRAY, CHAR, CHAR_ARRAY, SHORT, SHORT_ARRAY, INT, INT_ARRAY, LONG, LONG_ARRAY, FLOAT, FLOAT_ARRAY, DOUBLE, DOUBLE_ARRAY, BOOLEAN, BOOLEAN_ARRAY, STRING, STRING_ARRAY, OBJECT, OBJECT_ARRAY, LIST, SET, COLLECTION, MAP;
public static ClzTypeEnum parseClzTypeEnum(Class<?> clz) {
if (clz == byte.class || clz == Byte.class) {
return BYTE;
} else if (clz == byte[].class || clz == Byte[].class) {
return BYTE_ARRAY;
} else if (clz == char.class || clz == Character.class) {
return CHAR;
} else if (clz == char[].class || clz == Character[].class) {
return CHAR_ARRAY;
} else if (clz == short.class || clz == Short.class) {
return SHORT;
} else if (clz == short[].class || clz == Short[].class) {
return SHORT_ARRAY;
} else if (clz == int.class || clz == Integer.class) {
return INT;
} else if (clz == int[].class || clz == Integer[].class) {
return INT_ARRAY;
} else if (clz == long.class || clz == Long.class) {
return LONG;
} else if (clz == long[].class || clz == Long[].class) {
return LONG_ARRAY;
} else if (clz == float.class || clz == Float.class) {
return FLOAT;
} else if (clz == float[].class || clz == Float[].class) {
return FLOAT_ARRAY;
} else if (clz == double.class || clz == Double.class) {
return DOUBLE;
} else if (clz == double[].class || clz == Double[].class) {
return DOUBLE_ARRAY;
} else if (clz == boolean.class || clz == Boolean.class) {
return BOOLEAN;
} else if (clz == boolean[].class || clz == Boolean[].class) {
return BOOLEAN_ARRAY;
} else if (clz == String.class) {
return STRING;
} else if (clz == String[].class) {
return STRING_ARRAY;
} else if (clz == Object.class) {
return OBJECT;
} else if (clz == Object[].class) {
return OBJECT_ARRAY;
} else if (clz == List.class || List.class.isAssignableFrom(clz)) {
return LIST;
} else if (clz == Set.class || Set.class.isAssignableFrom(clz)) {
return SET;
} else if (clz == Collection.class || Collection.class.isAssignableFrom(clz)) {
return COLLECTION;
} else if (clz == Map.class || Map.class.isAssignableFrom(clz)) {
return MAP;
}
return NULL;
}
}
| 2,403 | 0.608406 | 0.608406 | 67 | 33.865673 | 33.248451 | 234 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.313433 | false | false |
12
|
f13e1f4e956ba4ccee233e0e4e92bccb04286e4b
| 26,525,718,086,085 |
c18c3f3bdc51f048f662344d032f9388dfecbd9d
|
/ddf-parent/ddf-service-rent/src/main/java/com/ddf/rent/service/simple/ApartmentService.java
|
e9b162901e5f165e7adcd33419bd6abe99b65113
|
[] |
no_license
|
soldiers1989/my_dev
|
https://github.com/soldiers1989/my_dev
|
88d62e4f182ac68db26be3d5d3ddc8a68e36c852
|
4250267f6d6d1660178518e71b1f588b4f3926f7
|
refs/heads/master
| 2020-03-27T19:39:28.191000 | 2018-02-12T02:29:51 | 2018-02-12T02:29:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ddf.rent.service.simple;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ddf.component.mybatis.api.impl.CrudServiceImpl;
import com.ddf.entity.base.dto.Page;
import com.ddf.entity.db.eo.TableName;
import com.ddf.entity.rent.dto.Apartment;
import com.ddf.entity.rent.eo.ApartmentDepositStatus;
import com.ddf.entity.rent.eo.ApartmentMatchStatus;
import com.ddf.entity.rent.eo.ApartmentStatus;
import com.ddf.entity.rent.query.ApartmentQuery;
import com.ddf.entity.rent.vo.ApartmentVo;
import com.ddf.reference.common.DateReference;
import com.ddf.reference.common.IdReference;
import com.ddf.rent.dao.ApartmentDao;
/**
* apartment Service
*
* @author robot
* @version 2018-02-02
*/
@Service
public class ApartmentService extends CrudServiceImpl<Apartment, ApartmentVo, ApartmentQuery> {
@Autowired
private ApartmentDao apartmentDao;
@Autowired
private IdReference idReference;
@Autowired
private DateReference dateReference;
public Page<ApartmentVo> query4page(ApartmentQuery apartmentQuery, int pageNum, int pageSize) {
apartmentQuery.buildPageSql(pageNum, pageSize);
List<ApartmentVo> list = this.findList(apartmentQuery);
long totalCount = this.findCount(apartmentQuery);
Page<ApartmentVo> page = new Page<ApartmentVo>(pageNum, pageSize, totalCount, list);
return page;
}
/**
* 创建整租房源
*/
public boolean createApartment(Apartment apartment) {
// 设置默认参数
apartment.setId(idReference.createId(TableName.apartment).getData());
apartment.setMatchStatus(ApartmentMatchStatus.open);
apartment.setDepositStatus(ApartmentDepositStatus.close);
apartment.setStatus(ApartmentStatus.wait_review);
apartment.setHideFlag(false);
Date tempDate = dateReference.queryCurrentDate().getData();
apartment.setCreateDate(tempDate);
apartment.setUpdateDate(tempDate);
return apartmentDao.create(apartment);
}
/**
* 修改房源
*/
public boolean modifyApartment(Apartment apartment) {
// 设置默认参数
apartment.setStatus(ApartmentStatus.wait_review);
apartment.setUpdateDate(dateReference.queryCurrentDate().getData());
Apartment apartmentTemp = apartmentDao.query4id(apartment.getId());
apartment.setUserId(apartmentTemp.getUserId());
apartment.setAssistantId(apartmentTemp.getAssistantId());
apartment.setMatchStatus(apartmentTemp.getMatchStatus());
apartment.setDepositStatus(apartmentTemp.getDepositStatus());
apartment.setHideFlag(apartmentTemp.getHideFlag());
apartment.setCreateDate(apartmentTemp.getCreateDate());
return apartmentDao.modify(apartment);
}
/**
* 伪删除
*/
public boolean remove4id(String id) {
return apartmentDao.remove4id(id) > 0 ? true : false;
}
/**
* 审核
* @return
*/
public Boolean review(String id, ApartmentStatus status) {
Apartment apartment = apartmentDao.query4id(id);
apartment.setStatus(status);
apartment.setReviewSuccessDate(dateReference.queryCurrentDate().getData());
return this.apartmentDao.modify(apartment);
}
/**
* 停租、招租
* @return
*/
public Boolean matchStatus(String id, ApartmentMatchStatus apartmentMatchStatus) {
Apartment apartment = apartmentDao.query4id(id);
apartment.setMatchStatus(apartmentMatchStatus);
return this.apartmentDao.modify(apartment);
}
/**
* 房源列表
* @return
*/
public Page<ApartmentVo> list(ApartmentQuery apartmentQuery) {
int pageNum = apartmentQuery.getPageNum();
int pageSize = apartmentQuery.getPageSize();
apartmentQuery.buildSortSql("order by a.create_date desc");
return this.query4page(apartmentQuery, pageNum, pageSize);
}
/**
* 我的房源
* @return
*/
public Page<ApartmentVo> pagequery4my(ApartmentQuery apartmentQuery) {
int pageNum = apartmentQuery.getPageNum();
int pageSize = apartmentQuery.getPageSize();
apartmentQuery.getApartment().setHideFlag(false);
apartmentQuery.buildSortSql("order by a.create_date desc");
return this.query4page(apartmentQuery, pageNum, pageSize);
}
}
|
UTF-8
|
Java
| 4,096 |
java
|
ApartmentService.java
|
Java
|
[
{
"context": "tmentDao;\n\n/**\n * apartment Service\n * \n * @author robot\n * @version 2018-02-02\n */\n@Service\npublic class ",
"end": 794,
"score": 0.9989169836044312,
"start": 789,
"tag": "USERNAME",
"value": "robot"
}
] | null |
[] |
package com.ddf.rent.service.simple;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ddf.component.mybatis.api.impl.CrudServiceImpl;
import com.ddf.entity.base.dto.Page;
import com.ddf.entity.db.eo.TableName;
import com.ddf.entity.rent.dto.Apartment;
import com.ddf.entity.rent.eo.ApartmentDepositStatus;
import com.ddf.entity.rent.eo.ApartmentMatchStatus;
import com.ddf.entity.rent.eo.ApartmentStatus;
import com.ddf.entity.rent.query.ApartmentQuery;
import com.ddf.entity.rent.vo.ApartmentVo;
import com.ddf.reference.common.DateReference;
import com.ddf.reference.common.IdReference;
import com.ddf.rent.dao.ApartmentDao;
/**
* apartment Service
*
* @author robot
* @version 2018-02-02
*/
@Service
public class ApartmentService extends CrudServiceImpl<Apartment, ApartmentVo, ApartmentQuery> {
@Autowired
private ApartmentDao apartmentDao;
@Autowired
private IdReference idReference;
@Autowired
private DateReference dateReference;
public Page<ApartmentVo> query4page(ApartmentQuery apartmentQuery, int pageNum, int pageSize) {
apartmentQuery.buildPageSql(pageNum, pageSize);
List<ApartmentVo> list = this.findList(apartmentQuery);
long totalCount = this.findCount(apartmentQuery);
Page<ApartmentVo> page = new Page<ApartmentVo>(pageNum, pageSize, totalCount, list);
return page;
}
/**
* 创建整租房源
*/
public boolean createApartment(Apartment apartment) {
// 设置默认参数
apartment.setId(idReference.createId(TableName.apartment).getData());
apartment.setMatchStatus(ApartmentMatchStatus.open);
apartment.setDepositStatus(ApartmentDepositStatus.close);
apartment.setStatus(ApartmentStatus.wait_review);
apartment.setHideFlag(false);
Date tempDate = dateReference.queryCurrentDate().getData();
apartment.setCreateDate(tempDate);
apartment.setUpdateDate(tempDate);
return apartmentDao.create(apartment);
}
/**
* 修改房源
*/
public boolean modifyApartment(Apartment apartment) {
// 设置默认参数
apartment.setStatus(ApartmentStatus.wait_review);
apartment.setUpdateDate(dateReference.queryCurrentDate().getData());
Apartment apartmentTemp = apartmentDao.query4id(apartment.getId());
apartment.setUserId(apartmentTemp.getUserId());
apartment.setAssistantId(apartmentTemp.getAssistantId());
apartment.setMatchStatus(apartmentTemp.getMatchStatus());
apartment.setDepositStatus(apartmentTemp.getDepositStatus());
apartment.setHideFlag(apartmentTemp.getHideFlag());
apartment.setCreateDate(apartmentTemp.getCreateDate());
return apartmentDao.modify(apartment);
}
/**
* 伪删除
*/
public boolean remove4id(String id) {
return apartmentDao.remove4id(id) > 0 ? true : false;
}
/**
* 审核
* @return
*/
public Boolean review(String id, ApartmentStatus status) {
Apartment apartment = apartmentDao.query4id(id);
apartment.setStatus(status);
apartment.setReviewSuccessDate(dateReference.queryCurrentDate().getData());
return this.apartmentDao.modify(apartment);
}
/**
* 停租、招租
* @return
*/
public Boolean matchStatus(String id, ApartmentMatchStatus apartmentMatchStatus) {
Apartment apartment = apartmentDao.query4id(id);
apartment.setMatchStatus(apartmentMatchStatus);
return this.apartmentDao.modify(apartment);
}
/**
* 房源列表
* @return
*/
public Page<ApartmentVo> list(ApartmentQuery apartmentQuery) {
int pageNum = apartmentQuery.getPageNum();
int pageSize = apartmentQuery.getPageSize();
apartmentQuery.buildSortSql("order by a.create_date desc");
return this.query4page(apartmentQuery, pageNum, pageSize);
}
/**
* 我的房源
* @return
*/
public Page<ApartmentVo> pagequery4my(ApartmentQuery apartmentQuery) {
int pageNum = apartmentQuery.getPageNum();
int pageSize = apartmentQuery.getPageSize();
apartmentQuery.getApartment().setHideFlag(false);
apartmentQuery.buildSortSql("order by a.create_date desc");
return this.query4page(apartmentQuery, pageNum, pageSize);
}
}
| 4,096 | 0.776145 | 0.771663 | 128 | 30.382813 | 25.790661 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.625 | false | false |
12
|
12b0ddc6d40dedb08e588da1546b6d7da68bc28d
| 27,401,891,418,915 |
dd7f294e62844fd24c8ee2a47219e1b30fe81aa7
|
/SoapServer/src/main/java/com/soapworkshop/ws/client/XmlRequest.java
|
f8fcb370acadc515e75edbcb1985476d24db7491
|
[] |
no_license
|
coremedy/SoapServer
|
https://github.com/coremedy/SoapServer
|
ef2ed34799217680fb8e7446a281fe4170f377dc
|
dff8c1eb1ca83db02ac5f82b856847dee2055f17
|
refs/heads/master
| 2021-01-19T10:49:12.449000 | 2015-04-10T07:27:51 | 2015-04-10T07:33:30 | 33,711,464 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.soapworkshop.ws.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>xmlRequest complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="xmlRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="doubleMember" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="intMember" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="strMember" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "xmlRequest", propOrder = {
"doubleMember",
"intMember",
"strMember"
})
public class XmlRequest {
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected Double doubleMember;
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected Integer intMember;
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected String strMember;
/**
* 获取doubleMember属性的值。
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getDoubleMember() {
return doubleMember;
}
/**
* 设置doubleMember属性的值。
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setDoubleMember(Double value) {
this.doubleMember = value;
}
/**
* 获取intMember属性的值。
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getIntMember() {
return intMember;
}
/**
* 设置intMember属性的值。
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setIntMember(Integer value) {
this.intMember = value;
}
/**
* 获取strMember属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getStrMember() {
return strMember;
}
/**
* 设置strMember属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStrMember(String value) {
this.strMember = value;
}
}
|
GB18030
|
Java
| 2,867 |
java
|
XmlRequest.java
|
Java
|
[] | null |
[] |
package com.soapworkshop.ws.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>xmlRequest complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="xmlRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="doubleMember" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="intMember" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="strMember" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "xmlRequest", propOrder = {
"doubleMember",
"intMember",
"strMember"
})
public class XmlRequest {
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected Double doubleMember;
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected Integer intMember;
@XmlElement(namespace="http://ws.soapworkshop.com/")
protected String strMember;
/**
* 获取doubleMember属性的值。
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getDoubleMember() {
return doubleMember;
}
/**
* 设置doubleMember属性的值。
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setDoubleMember(Double value) {
this.doubleMember = value;
}
/**
* 获取intMember属性的值。
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getIntMember() {
return intMember;
}
/**
* 设置intMember属性的值。
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setIntMember(Integer value) {
this.intMember = value;
}
/**
* 获取strMember属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getStrMember() {
return strMember;
}
/**
* 设置strMember属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStrMember(String value) {
this.strMember = value;
}
}
| 2,867 | 0.544026 | 0.535623 | 119 | 20.983192 | 20.12356 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277311 | false | false |
12
|
8a7a36b0d98067418027192c376f083cb151b61c
| 26,439,818,700,377 |
0622765cbcb197d80206467542f84a4c44a03907
|
/app/cms/cms/src/main/java/com/ace/app/cms/drug/action/DepartmentJobAction.java
|
75194445877a85712507ee70b544ddcbabc0f887
|
[] |
no_license
|
naruto890809/ace-parent
|
https://github.com/naruto890809/ace-parent
|
3a99b6b249e26c0653677f68de3bdd64970dbd25
|
d0f8f23079a89dd8dcb61eeed18b8416e08db5b9
|
refs/heads/master
| 2022-12-26T18:45:45.512000 | 2019-07-03T06:58:10 | 2019-07-03T06:58:10 | 194,997,363 | 0 | 0 | null | false | 2022-12-16T02:45:30 | 2019-07-03T06:57:36 | 2019-07-03T07:00:10 | 2022-12-16T02:45:25 | 8,763 | 0 | 0 | 31 |
JavaScript
| false | false |
package com.ace.app.cms.drug.action;
import com.ace.app.cms.drug.domain.DepartmentJob;
import com.ace.app.cms.drug.domain.Drug;
import com.ace.app.cms.drug.model.DepartmentJobModel;
import com.ace.app.cms.drug.service.DepartmentJobService;
import com.ace.app.cms.drug.service.DepartmentService;
import com.ace.app.cms.drug.service.DrugService;
import com.ace.framework.base.BaseAction;
import com.ace.framework.base.JsonResultUtil;
import com.ace.framework.base.Page;
import com.ace.framework.util.ExecutionContext;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import com.ace.app.cms.CmsConstant;
import java.util.Arrays;
import com.ace.app.cms.account.AccountService;
/**
* 任务管理
* WuZhiWei v1.0
* @author 代码生成器 v1.0
* @since 2018-10-18 21:27:37
*/
@Scope("prototype")
public class DepartmentJobAction extends BaseAction<DepartmentJobModel> {
@Resource
private DepartmentJobService departmentJobService;
@Resource
private AccountService accountService;
@Resource
private DrugService drugService;
public String index() {
setModel();
super.setTarget("index");
return COMMON;
}
private void setModel() {
Drug entity = new Drug();
entity.setApprove(CmsConstant.PASSED);
List<Drug> drugs = drugService.findList(entity);
model.setDrugs(drugs);
}
public String addOrEditIndex(){
String id = model.getId();
DepartmentJob departmentJob = null;
if (StringUtils.isBlank(id)){
departmentJob = new DepartmentJob();
}else {
departmentJob = departmentJobService.getById(id);
}
model.setDepartmentJob(departmentJob);
setModel();
super.setTarget("addOrEdit");
return COMMON;
}
public String addOrEdit(){
DepartmentJob departmentJob = model.getDepartmentJob();
if (StringUtils.isBlank(departmentJob.getId())){
departmentJob.setId(null);
departmentJobService.save(departmentJob);
}else {
departmentJobService.update(departmentJob);
}
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
public String search() {
DepartmentJob departmentJob = model.getDepartmentJob();
if(departmentJob==null){
departmentJob=new DepartmentJob();
}
departmentJob.setCorpCode(ExecutionContext.getCorpCode());
Page<DepartmentJob> page = model.getPage();
page = departmentJobService.search(departmentJob, page);
List<DepartmentJob> rows = page.getRows();
if (CollectionUtils.isEmpty(rows)){
return renderJson(page);
}
Map<String,String> aidNameMap = accountService.getAidNameMap();
Map<String, String> drugIdNameMap = drugService.getDrugIdNameMap();
for (DepartmentJob row : rows) {
row.setCreateByName(aidNameMap.get(row.getCreateBy()));
row.setDrugName(drugIdNameMap.get(row.getDrugId()));
}
return renderJson(page);
}
/**
* 删除
* @return
*/
public String remove() {
departmentJobService.deleteById(model.getId());
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
/**
* 审批
* @return
*/
public String approve() {
String idsStr = model.getIdsStr();
if (StringUtils.isEmpty(idsStr)){
return renderJson(JsonResultUtil.err("请选择操作的列"));
}
List<String> ids = Arrays.asList(idsStr.split(","));
DepartmentJob departmentJob = new DepartmentJob();
departmentJob.setIds(ids);
departmentJobService.update(departmentJob);
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
}
|
UTF-8
|
Java
| 4,053 |
java
|
DepartmentJobAction.java
|
Java
|
[] | null |
[] |
package com.ace.app.cms.drug.action;
import com.ace.app.cms.drug.domain.DepartmentJob;
import com.ace.app.cms.drug.domain.Drug;
import com.ace.app.cms.drug.model.DepartmentJobModel;
import com.ace.app.cms.drug.service.DepartmentJobService;
import com.ace.app.cms.drug.service.DepartmentService;
import com.ace.app.cms.drug.service.DrugService;
import com.ace.framework.base.BaseAction;
import com.ace.framework.base.JsonResultUtil;
import com.ace.framework.base.Page;
import com.ace.framework.util.ExecutionContext;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import com.ace.app.cms.CmsConstant;
import java.util.Arrays;
import com.ace.app.cms.account.AccountService;
/**
* 任务管理
* WuZhiWei v1.0
* @author 代码生成器 v1.0
* @since 2018-10-18 21:27:37
*/
@Scope("prototype")
public class DepartmentJobAction extends BaseAction<DepartmentJobModel> {
@Resource
private DepartmentJobService departmentJobService;
@Resource
private AccountService accountService;
@Resource
private DrugService drugService;
public String index() {
setModel();
super.setTarget("index");
return COMMON;
}
private void setModel() {
Drug entity = new Drug();
entity.setApprove(CmsConstant.PASSED);
List<Drug> drugs = drugService.findList(entity);
model.setDrugs(drugs);
}
public String addOrEditIndex(){
String id = model.getId();
DepartmentJob departmentJob = null;
if (StringUtils.isBlank(id)){
departmentJob = new DepartmentJob();
}else {
departmentJob = departmentJobService.getById(id);
}
model.setDepartmentJob(departmentJob);
setModel();
super.setTarget("addOrEdit");
return COMMON;
}
public String addOrEdit(){
DepartmentJob departmentJob = model.getDepartmentJob();
if (StringUtils.isBlank(departmentJob.getId())){
departmentJob.setId(null);
departmentJobService.save(departmentJob);
}else {
departmentJobService.update(departmentJob);
}
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
public String search() {
DepartmentJob departmentJob = model.getDepartmentJob();
if(departmentJob==null){
departmentJob=new DepartmentJob();
}
departmentJob.setCorpCode(ExecutionContext.getCorpCode());
Page<DepartmentJob> page = model.getPage();
page = departmentJobService.search(departmentJob, page);
List<DepartmentJob> rows = page.getRows();
if (CollectionUtils.isEmpty(rows)){
return renderJson(page);
}
Map<String,String> aidNameMap = accountService.getAidNameMap();
Map<String, String> drugIdNameMap = drugService.getDrugIdNameMap();
for (DepartmentJob row : rows) {
row.setCreateByName(aidNameMap.get(row.getCreateBy()));
row.setDrugName(drugIdNameMap.get(row.getDrugId()));
}
return renderJson(page);
}
/**
* 删除
* @return
*/
public String remove() {
departmentJobService.deleteById(model.getId());
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
/**
* 审批
* @return
*/
public String approve() {
String idsStr = model.getIdsStr();
if (StringUtils.isEmpty(idsStr)){
return renderJson(JsonResultUtil.err("请选择操作的列"));
}
List<String> ids = Arrays.asList(idsStr.split(","));
DepartmentJob departmentJob = new DepartmentJob();
departmentJob.setIds(ids);
departmentJobService.update(departmentJob);
return renderJson(JsonResultUtil.location("departmentJob.index.do"));
}
}
| 4,053 | 0.670321 | 0.665836 | 133 | 29.172932 | 22.795433 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518797 | false | false |
12
|
56ca3dea82ff9a4bcd656cd69213284354063f5c
| 128,849,044,062 |
5ae4a19a3aecb7d0a43c2f601d690b3dc0c4bb4d
|
/src/math/Algo.java
|
5bde79b1656af6cb0b04b492c6f25a099b55a39d
|
[] |
no_license
|
VivienGaluchot/primes
|
https://github.com/VivienGaluchot/primes
|
bde5a199997914ed6f1399c0e45cf9ef6590dc36
|
518bd0e82521fe11c34838e44dab0e12b1c9fbf7
|
refs/heads/master
| 2021-01-23T12:38:38.277000 | 2017-06-08T19:00:41 | 2017-06-08T19:00:41 | 93,185,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package math;
public class Algo {
static public int pow(int x, int n) {
if (n < 0)
throw new IllegalArgumentException("power can't be negative");
int r = 1;
while (n > 0) {
r *= x;
n--;
}
return r;
}
public static void main(String[] args) {
PrimeCache cache = new PrimeCache(100000);
for (int i = 1; i < 1000; i++) {
System.out.println(PrimeArray.create(i, cache));
}
}
}
|
UTF-8
|
Java
| 407 |
java
|
Algo.java
|
Java
|
[] | null |
[] |
package math;
public class Algo {
static public int pow(int x, int n) {
if (n < 0)
throw new IllegalArgumentException("power can't be negative");
int r = 1;
while (n > 0) {
r *= x;
n--;
}
return r;
}
public static void main(String[] args) {
PrimeCache cache = new PrimeCache(100000);
for (int i = 1; i < 1000; i++) {
System.out.println(PrimeArray.create(i, cache));
}
}
}
| 407 | 0.601966 | 0.567568 | 21 | 18.333334 | 18.757433 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.095238 | false | false |
12
|
2f26938316c9dee947ca9fe25d428ca1c28b9014
| 12,790,412,631,991 |
d9eab55de57772151b6e498bbf2f36e303c09542
|
/app/src/main/java/com/iet/abhinay/pravah/Sponcers.java
|
8bf8d8b4e256d7f6aba357452207296e21f72e33
|
[] |
no_license
|
devabhi36/Pravah18
|
https://github.com/devabhi36/Pravah18
|
fa178adb908ba135149c5cf180c823a04f008b18
|
89084c9f395e8ba3b50ae25c067a046d0f2adbe9
|
refs/heads/master
| 2021-04-27T17:36:26.751000 | 2018-03-28T12:56:10 | 2018-03-28T12:56:10 | 122,324,060 | 0 | 0 | null | false | 2018-03-04T07:37:34 | 2018-02-21T10:49:39 | 2018-02-21T11:03:47 | 2018-03-04T07:37:34 | 13,136 | 0 | 0 | 0 |
Java
| false | null |
package com.iet.abhinay.pravah;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
public class Sponcers extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sponcers);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void sp1(View s1){
String url = "http://www.uptourism.gov.in/";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp2(View s2){
String url = "http://swachhbharaturban.gov.in/ihhl/";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp3(View s3){
String url = "https://www.indiamart.com/proddetail/lucknow-central-gomti-nagar-6771064612.html";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp4(View s4){
String url = "http://blueworld.co.in/packages.php";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
}
|
UTF-8
|
Java
| 1,442 |
java
|
Sponcers.java
|
Java
|
[] | null |
[] |
package com.iet.abhinay.pravah;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
public class Sponcers extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sponcers);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void sp1(View s1){
String url = "http://www.uptourism.gov.in/";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp2(View s2){
String url = "http://swachhbharaturban.gov.in/ihhl/";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp3(View s3){
String url = "https://www.indiamart.com/proddetail/lucknow-central-gomti-nagar-6771064612.html";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
public void sp4(View s4){
String url = "http://blueworld.co.in/packages.php";
WebView webView = new WebView(getApplicationContext());
webView.loadUrl(url);
}
}
| 1,442 | 0.695562 | 0.681692 | 40 | 35.049999 | 23.654757 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
12
|
6d771f2c55cf4f3103ef54b60a0a87b560d48b86
| 30,322,469,135,438 |
cebf08841064bb3423df06527181eb6782d39b18
|
/Electricity Bill Calculation/src/com/wipro/eb/service/ConnectionServiceTest1.java
|
c3cb0e3bcfcf5523257082bf98489d8d7ca5d3b1
|
[] |
no_license
|
TABSHEERA-NASREEN/Electicity_bill_calculation_wtn
|
https://github.com/TABSHEERA-NASREEN/Electicity_bill_calculation_wtn
|
acfdbeee7feccc761f8e3d64be060b524d9e8546
|
b7daee8eb1e18897d2f0700682079c73225101d0
|
refs/heads/master
| 2022-11-20T15:47:11.714000 | 2020-07-22T11:00:56 | 2020-07-22T11:00:56 | 281,652,653 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wipro.eb.service;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.wipro.eb.entity.Commercial;
import com.wipro.eb.entity.Domestic;
import com.wipro.eb.exception.InvalidConnectionException;
import com.wipro.eb.exception.InvalidReadingException;
public class ConnectionServiceTest1 {
ConnectionService cs;
Domestic d;
Commercial c;
@Before
public void setup()
{
cs=new ConnectionService();
}
@Test
public void testValidate() throws InvalidReadingException, InvalidConnectionException {
//fail("Not yet implemented");
assertEquals(true,cs.validate(120, 0,"domestic"));
assertEquals(true,cs.validate(120,30,"commercial"));
try {
assertEquals("Incorrect Reading",cs.validate(-9, 120,"domestic"));
} catch (InvalidReadingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assertEquals("Invalid Connection Type",cs.validate(120,0,"comm"));
}
catch (InvalidReadingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testCalculateBillAmt() {
//fail("Not yet implemented");
assertEquals(435.0,cs.calculateBillAmt(240,120,"domestic"),0.0);
assertEquals(781.3200073242188,cs.calculateBillAmt(120,0,"commercial"),0.0);
assertEquals(-1.0,cs.calculateBillAmt(0,120,"domestic"),0.0);
assertEquals(-2.0,cs.calculateBillAmt(2000,120,"dome"),0.0);
}
@Test
public void testGenerateBill() {
//fail("Not yet implemented");
assertEquals("Amount to be paid is:435.0",cs.generateBill(120,0,"domestic"));
assertEquals("Amount to be paid is:781.32",cs.generateBill(240,120,"commercial"));
assertEquals("Incorrect Reading",cs.generateBill(0,12,"domestic"));
assertEquals("Invalid Connection Type",cs.generateBill(20,12,"dom"));
}
}
|
UTF-8
|
Java
| 2,072 |
java
|
ConnectionServiceTest1.java
|
Java
|
[] | null |
[] |
package com.wipro.eb.service;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.wipro.eb.entity.Commercial;
import com.wipro.eb.entity.Domestic;
import com.wipro.eb.exception.InvalidConnectionException;
import com.wipro.eb.exception.InvalidReadingException;
public class ConnectionServiceTest1 {
ConnectionService cs;
Domestic d;
Commercial c;
@Before
public void setup()
{
cs=new ConnectionService();
}
@Test
public void testValidate() throws InvalidReadingException, InvalidConnectionException {
//fail("Not yet implemented");
assertEquals(true,cs.validate(120, 0,"domestic"));
assertEquals(true,cs.validate(120,30,"commercial"));
try {
assertEquals("Incorrect Reading",cs.validate(-9, 120,"domestic"));
} catch (InvalidReadingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assertEquals("Invalid Connection Type",cs.validate(120,0,"comm"));
}
catch (InvalidReadingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testCalculateBillAmt() {
//fail("Not yet implemented");
assertEquals(435.0,cs.calculateBillAmt(240,120,"domestic"),0.0);
assertEquals(781.3200073242188,cs.calculateBillAmt(120,0,"commercial"),0.0);
assertEquals(-1.0,cs.calculateBillAmt(0,120,"domestic"),0.0);
assertEquals(-2.0,cs.calculateBillAmt(2000,120,"dome"),0.0);
}
@Test
public void testGenerateBill() {
//fail("Not yet implemented");
assertEquals("Amount to be paid is:435.0",cs.generateBill(120,0,"domestic"));
assertEquals("Amount to be paid is:781.32",cs.generateBill(240,120,"commercial"));
assertEquals("Incorrect Reading",cs.generateBill(0,12,"domestic"));
assertEquals("Invalid Connection Type",cs.generateBill(20,12,"dom"));
}
}
| 2,072 | 0.715734 | 0.668919 | 72 | 27.777779 | 25.578976 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.513889 | false | false |
12
|
b3e9a9f0886533d6a003a08d7a4f639fafba43b2
| 22,574,348,139,439 |
5ac2fb4db63c9383abad7931025d5ac9bc7259d3
|
/Tama_app/src/main/java/com/tama/chat/ui/adapters/mapBlink/MapBlinkElementAdapter.java
|
e5cea3b139285f51cc6ba80e773ecfe725693778
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
Testtaccount/TamaAndroid
|
https://github.com/Testtaccount/TamaAndroid
|
097f48f913c23449c983fa1260a1696b06742cc8
|
82912bd3cb80c9fc274c0c23adc005bba85b7fb7
|
refs/heads/master
| 2021-09-19T08:26:09.108000 | 2018-07-25T12:33:20 | 2018-07-25T12:35:42 | 139,688,915 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tama.chat.ui.adapters.mapBlink;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.tama.chat.BuildConfig;
import com.tama.chat.R;
import com.tama.chat.ui.activities.base.BaseActivity;
import com.tama.chat.ui.adapters.base.BaseClickListenerViewHolder;
import com.tama.chat.ui.adapters.base.BaseFilterAdapter;
import com.tama.chat.ui.adapters.base.BaseViewHolder;
import com.tama.chat.utils.helpers.TextViewHelper;
import com.tama.chat.gcm.MapBlinkElement;
import java.util.List;
import butterknife.Bind;
//chka
public class MapBlinkElementAdapter extends BaseFilterAdapter<MapBlinkElement, BaseClickListenerViewHolder<MapBlinkElement>> {
public MapBlinkElementAdapter(BaseActivity baseActivity, List<MapBlinkElement> usersList) {
super(baseActivity, usersList);
}
@Override
protected boolean isMatch(MapBlinkElement item, String query) {
return item.getName() != null && item.getName().toLowerCase().contains(query);
}
@Override
public BaseClickListenerViewHolder<MapBlinkElement> onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(this, layoutInflater.inflate(R.layout.item_map_blink_element, parent, false));
}
@Override
public void onBindViewHolder(BaseClickListenerViewHolder<MapBlinkElement> baseClickListenerViewHolder, final int position) {
MapBlinkElement mapElement = getItem(position);
ViewHolder viewHolder = (ViewHolder) baseClickListenerViewHolder;
initViewElement(viewHolder, mapElement);
if (!TextUtils.isEmpty(query)) {
TextViewHelper.changeTextColorView(baseActivity, viewHolder.nameTextView, query);
}
}
private void initViewElement(ViewHolder viewHolder, MapBlinkElement mapElement){
viewHolder.nameTextView.setText(mapElement.getName());
if(mapElement.getImageResId()!=0){
viewHolder.mapBlinkImageView.setImageResource(mapElement.getImageResId());
}else{
if(mapElement.getPhotosRefList()!=null&&!mapElement.getPhotosRefList().isEmpty()){
displayAvatarImage(mapElement.getPhotoUrl(BuildConfig.GOOGLE_API_KEY,0,400), viewHolder.mapBlinkImageView);
}else{
viewHolder.mapBlinkImageView.setImageResource(R.drawable.quantum_ic_art_track_grey600_48);
}
viewHolder.mapBlink.setVisibility(View.VISIBLE);
if(mapElement.getRating()>0){
viewHolder.mapBlinkRatingText.setVisibility(View.VISIBLE);
viewHolder.mapBlinkRatingBar.setVisibility(View.VISIBLE);
viewHolder.mapBlinkRatingBar.setRating(mapElement.getRating());
}else{
viewHolder.mapBlinkRatingText.setVisibility(View.GONE);
viewHolder.mapBlinkRatingBar.setVisibility(View.GONE);
}
if(mapElement.getDescription()!=null&&!mapElement.getDescription().equals("")){
viewHolder.mapBlinkDescription.setVisibility(View.VISIBLE);
viewHolder.mapBlinkDescription.setText(mapElement.getDescription());
}else{
viewHolder.mapBlinkDescription.setVisibility(View.GONE);
}
if(mapElement.getOpenNow()!=null){
viewHolder.mapBlinkIsOpen.setVisibility(View.VISIBLE);
if(mapElement.getOpenNow()){
viewHolder.mapBlinkIsOpen.setText("Now open");
viewHolder.mapBlinkIsOpen.setTextColor(Color.GREEN);
}else{
viewHolder.mapBlinkIsOpen.setText("Close");
viewHolder.mapBlinkIsOpen.setTextColor(Color.RED);
}
}else{
viewHolder.mapBlinkIsOpen.setVisibility(View.GONE);
}
}
}
protected static class ViewHolder extends BaseViewHolder<MapBlinkElement> {
@Bind(R.id.map_blink_image_view)
ImageView mapBlinkImageView;
@Bind(R.id.map_blink_name_text_view)
TextView nameTextView;
@Bind(R.id.map_blink_rating_text)
TextView mapBlinkRatingText;
@Bind(R.id.map_blink_description)
TextView mapBlinkDescription;
@Bind(R.id.map_blink_is_open)
TextView mapBlinkIsOpen;
@Bind(R.id.map_blink)
TextView mapBlink;
@Bind(R.id.map_blink_rating_bar)
RatingBar mapBlinkRatingBar;
public ViewHolder(MapBlinkElementAdapter adapter, View view) {
super(adapter, view);
}
}
}
|
UTF-8
|
Java
| 4,713 |
java
|
MapBlinkElementAdapter.java
|
Java
|
[] | null |
[] |
package com.tama.chat.ui.adapters.mapBlink;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.tama.chat.BuildConfig;
import com.tama.chat.R;
import com.tama.chat.ui.activities.base.BaseActivity;
import com.tama.chat.ui.adapters.base.BaseClickListenerViewHolder;
import com.tama.chat.ui.adapters.base.BaseFilterAdapter;
import com.tama.chat.ui.adapters.base.BaseViewHolder;
import com.tama.chat.utils.helpers.TextViewHelper;
import com.tama.chat.gcm.MapBlinkElement;
import java.util.List;
import butterknife.Bind;
//chka
public class MapBlinkElementAdapter extends BaseFilterAdapter<MapBlinkElement, BaseClickListenerViewHolder<MapBlinkElement>> {
public MapBlinkElementAdapter(BaseActivity baseActivity, List<MapBlinkElement> usersList) {
super(baseActivity, usersList);
}
@Override
protected boolean isMatch(MapBlinkElement item, String query) {
return item.getName() != null && item.getName().toLowerCase().contains(query);
}
@Override
public BaseClickListenerViewHolder<MapBlinkElement> onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(this, layoutInflater.inflate(R.layout.item_map_blink_element, parent, false));
}
@Override
public void onBindViewHolder(BaseClickListenerViewHolder<MapBlinkElement> baseClickListenerViewHolder, final int position) {
MapBlinkElement mapElement = getItem(position);
ViewHolder viewHolder = (ViewHolder) baseClickListenerViewHolder;
initViewElement(viewHolder, mapElement);
if (!TextUtils.isEmpty(query)) {
TextViewHelper.changeTextColorView(baseActivity, viewHolder.nameTextView, query);
}
}
private void initViewElement(ViewHolder viewHolder, MapBlinkElement mapElement){
viewHolder.nameTextView.setText(mapElement.getName());
if(mapElement.getImageResId()!=0){
viewHolder.mapBlinkImageView.setImageResource(mapElement.getImageResId());
}else{
if(mapElement.getPhotosRefList()!=null&&!mapElement.getPhotosRefList().isEmpty()){
displayAvatarImage(mapElement.getPhotoUrl(BuildConfig.GOOGLE_API_KEY,0,400), viewHolder.mapBlinkImageView);
}else{
viewHolder.mapBlinkImageView.setImageResource(R.drawable.quantum_ic_art_track_grey600_48);
}
viewHolder.mapBlink.setVisibility(View.VISIBLE);
if(mapElement.getRating()>0){
viewHolder.mapBlinkRatingText.setVisibility(View.VISIBLE);
viewHolder.mapBlinkRatingBar.setVisibility(View.VISIBLE);
viewHolder.mapBlinkRatingBar.setRating(mapElement.getRating());
}else{
viewHolder.mapBlinkRatingText.setVisibility(View.GONE);
viewHolder.mapBlinkRatingBar.setVisibility(View.GONE);
}
if(mapElement.getDescription()!=null&&!mapElement.getDescription().equals("")){
viewHolder.mapBlinkDescription.setVisibility(View.VISIBLE);
viewHolder.mapBlinkDescription.setText(mapElement.getDescription());
}else{
viewHolder.mapBlinkDescription.setVisibility(View.GONE);
}
if(mapElement.getOpenNow()!=null){
viewHolder.mapBlinkIsOpen.setVisibility(View.VISIBLE);
if(mapElement.getOpenNow()){
viewHolder.mapBlinkIsOpen.setText("Now open");
viewHolder.mapBlinkIsOpen.setTextColor(Color.GREEN);
}else{
viewHolder.mapBlinkIsOpen.setText("Close");
viewHolder.mapBlinkIsOpen.setTextColor(Color.RED);
}
}else{
viewHolder.mapBlinkIsOpen.setVisibility(View.GONE);
}
}
}
protected static class ViewHolder extends BaseViewHolder<MapBlinkElement> {
@Bind(R.id.map_blink_image_view)
ImageView mapBlinkImageView;
@Bind(R.id.map_blink_name_text_view)
TextView nameTextView;
@Bind(R.id.map_blink_rating_text)
TextView mapBlinkRatingText;
@Bind(R.id.map_blink_description)
TextView mapBlinkDescription;
@Bind(R.id.map_blink_is_open)
TextView mapBlinkIsOpen;
@Bind(R.id.map_blink)
TextView mapBlink;
@Bind(R.id.map_blink_rating_bar)
RatingBar mapBlinkRatingBar;
public ViewHolder(MapBlinkElementAdapter adapter, View view) {
super(adapter, view);
}
}
}
| 4,713 | 0.683429 | 0.681095 | 122 | 37.639343 | 33.195415 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57377 | false | false |
12
|
10589f2063e1bcc0dd22c3d00b9b6e7d9a022055
| 29,326,036,716,147 |
41683150335e770e46bcb2863f751aff20385765
|
/src/main/java/app/model/Users.java
|
94fe140fe77fc2f3055a3a7c2c70673164f3fb2f
|
[] |
no_license
|
hipacy/ticket-projetct
|
https://github.com/hipacy/ticket-projetct
|
64e2d780177d28afa70bdd63af9e4a186accc564
|
ae9f086fe7a1b7615dcdc35f9d9fa965a459911f
|
refs/heads/master
| 2020-09-14T02:58:38.827000 | 2020-01-05T16:23:20 | 2020-01-05T16:23:20 | 221,514,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package app.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@ToString
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "Users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UserId")
private Integer userId;
@Column(name = "Password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
private String password;
@Column(name = "FirstName")
@NotEmpty(message = "*Please provide your first name")
private String firstName;
@Column(name = "LastName")
@NotEmpty(message = "*Please provide your last name")
private String lastName;
@BatchSize(size = 10)
@ManyToMany
@Fetch(value = FetchMode.SUBSELECT)
@JoinTable(name = "Users_Team",
joinColumns = @JoinColumn(name = "Users_TeamId", referencedColumnName = "UserId"),
inverseJoinColumns = @JoinColumn(name = "Team_TeamId", referencedColumnName = "TeamId"))
private List<Team> teams;
@Column(name = "Email")
@Email(message = "*Please provide a valid Email")
@NotEmpty(message = "*Please provide an email")
private String email;
@Column(name = "JobTitle")
private String jobTitle;
@Column(name = "IsActive")
private Integer isActive;
@Column(name = "Image")
private String imageLink;
@BatchSize(size = 5)
@ManyToMany
@Fetch(value = FetchMode.SUBSELECT)
@JoinTable(name = "Users_UserType",
joinColumns = @JoinColumn(name = "UserId"),
inverseJoinColumns = @JoinColumn(name = "UserTypeId"))
@NotEmpty(message = "*Please choose at least one role!")
private List<UserType> roles;
}
|
UTF-8
|
Java
| 2,149 |
java
|
Users.java
|
Java
|
[] | null |
[] |
package app.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@ToString
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "Users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UserId")
private Integer userId;
@Column(name = "Password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
private String password;
@Column(name = "FirstName")
@NotEmpty(message = "*Please provide your first name")
private String firstName;
@Column(name = "LastName")
@NotEmpty(message = "*Please provide your last name")
private String lastName;
@BatchSize(size = 10)
@ManyToMany
@Fetch(value = FetchMode.SUBSELECT)
@JoinTable(name = "Users_Team",
joinColumns = @JoinColumn(name = "Users_TeamId", referencedColumnName = "UserId"),
inverseJoinColumns = @JoinColumn(name = "Team_TeamId", referencedColumnName = "TeamId"))
private List<Team> teams;
@Column(name = "Email")
@Email(message = "*Please provide a valid Email")
@NotEmpty(message = "*Please provide an email")
private String email;
@Column(name = "JobTitle")
private String jobTitle;
@Column(name = "IsActive")
private Integer isActive;
@Column(name = "Image")
private String imageLink;
@BatchSize(size = 5)
@ManyToMany
@Fetch(value = FetchMode.SUBSELECT)
@JoinTable(name = "Users_UserType",
joinColumns = @JoinColumn(name = "UserId"),
inverseJoinColumns = @JoinColumn(name = "UserTypeId"))
@NotEmpty(message = "*Please choose at least one role!")
private List<UserType> roles;
}
| 2,149 | 0.697068 | 0.694742 | 75 | 27.653334 | 22.165134 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
f0c2e486970fc495be818ba12b2201dd1c9b5b0b
| 22,101,901,733,256 |
2ff16e40cacbbf46949a8ba860ffda5320e125ab
|
/src/main/java/org/fanjun/controller/StudentController.java
|
920c08c5be41ffa4937d1a8c7d00b1b8e910536e
|
[] |
no_license
|
fanjun-wu/school
|
https://github.com/fanjun-wu/school
|
be03c5e8116cf971d8424f358bdeb23f7af7878d
|
59fd5813fd90f03f804bc87182369061d9f14983
|
refs/heads/master
| 2016-09-06T10:06:35.040000 | 2014-02-21T11:31:11 | 2014-02-21T11:31:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.fanjun.controller;
import java.util.Map;
import javax.annotation.Resource;
import org.fanjun.model.College;
import org.fanjun.model.Student;
import org.fanjun.service.CollegeService;
import org.fanjun.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private CollegeService collegeService;
public StudentService getStudentService() {
return studentService;
}
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
public CollegeService getCollegeService() {
return collegeService;
}
public void setCollegeService(CollegeService collegeService) {
this.collegeService = collegeService;
}
@RequestMapping("/index")
public String setupForm(Map<String, Object> map){
Student student = new Student();
map.put("student", student);
map.put("studentList", studentService.getAllStudent());
return "student";
}
@RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(@ModelAttribute Student student, BindingResult result, @RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
switch(action.toLowerCase()){
case "add":
System.out.println("Add");
studentService.add(student);
studentResult = student;
break;
case "edit":
studentService.edit(student);
studentResult = student;
break;
case "delete":
studentService.delete(student.getStudentId());
studentResult = new Student();
break;
case "search":
Student searchedStudent = studentService.getStudent(student.getStudentId());
studentResult = searchedStudent!=null ? searchedStudent : new Student();
break;
case "join":
System.out.println("Join");
break;
}
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
@RequestMapping(value = "/join", method = RequestMethod.GET)
public String getJoin(@RequestParam("id") Integer studentId,Map<String, Object> map) {
//Student student =new Student();
College college = new College();
//student.setStudentId(studentId);
//map.put("student", student);
map.put("college", college);
map.put("collegeList", collegeService.getAllCollege());
System.out.println("Student ID= "+studentId);
return "ListofCollege";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String postAdd(@RequestParam("id") Integer studentId,
@RequestParam("c_id") Integer college_id) {
// Delegate to service
//College c=collegeService.getCollege(college_id);
studentService.addStudenttoCollege(studentId, college_id);
// System.out.println("Student ID= "+ studentService.getStudent(studentId).getfirstname() +" College ID "+studentService.getStudent(studentId).getCollege().getCollegeName());
// Redirect to url
return "redirect:index";
}
}
|
UTF-8
|
Java
| 3,577 |
java
|
StudentController.java
|
Java
|
[] | null |
[] |
package org.fanjun.controller;
import java.util.Map;
import javax.annotation.Resource;
import org.fanjun.model.College;
import org.fanjun.model.Student;
import org.fanjun.service.CollegeService;
import org.fanjun.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private CollegeService collegeService;
public StudentService getStudentService() {
return studentService;
}
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
public CollegeService getCollegeService() {
return collegeService;
}
public void setCollegeService(CollegeService collegeService) {
this.collegeService = collegeService;
}
@RequestMapping("/index")
public String setupForm(Map<String, Object> map){
Student student = new Student();
map.put("student", student);
map.put("studentList", studentService.getAllStudent());
return "student";
}
@RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(@ModelAttribute Student student, BindingResult result, @RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
switch(action.toLowerCase()){
case "add":
System.out.println("Add");
studentService.add(student);
studentResult = student;
break;
case "edit":
studentService.edit(student);
studentResult = student;
break;
case "delete":
studentService.delete(student.getStudentId());
studentResult = new Student();
break;
case "search":
Student searchedStudent = studentService.getStudent(student.getStudentId());
studentResult = searchedStudent!=null ? searchedStudent : new Student();
break;
case "join":
System.out.println("Join");
break;
}
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
@RequestMapping(value = "/join", method = RequestMethod.GET)
public String getJoin(@RequestParam("id") Integer studentId,Map<String, Object> map) {
//Student student =new Student();
College college = new College();
//student.setStudentId(studentId);
//map.put("student", student);
map.put("college", college);
map.put("collegeList", collegeService.getAllCollege());
System.out.println("Student ID= "+studentId);
return "ListofCollege";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String postAdd(@RequestParam("id") Integer studentId,
@RequestParam("c_id") Integer college_id) {
// Delegate to service
//College c=collegeService.getCollege(college_id);
studentService.addStudenttoCollege(studentId, college_id);
// System.out.println("Student ID= "+ studentService.getStudent(studentId).getfirstname() +" College ID "+studentService.getStudent(studentId).getCollege().getCollegeName());
// Redirect to url
return "redirect:index";
}
}
| 3,577 | 0.71792 | 0.71792 | 112 | 29.9375 | 28.143852 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.116071 | false | false |
12
|
9673431585374454c55f0b383d4e8782be8317a7
| 601,295,457,279 |
ee32e9115dc8d0187bb5c212832644ab9c35ab46
|
/test/MPQSimulatorTests/AbilityTests.java
|
92f4bb89ba155f8e36d073e9d9e93e6b1e311643
|
[] |
no_license
|
NorthernPolarity/MPQSimulator
|
https://github.com/NorthernPolarity/MPQSimulator
|
1bb3fdbe6f7967f95bf01b34f750a40d0e01f5f1
|
5abba02a7a894884f47160156d4768facd48d0f6
|
refs/heads/master
| 2021-01-22T10:02:26.018000 | 2015-01-28T20:57:27 | 2015-01-28T20:57:27 | 20,146,354 | 0 | 0 | null | false | 2014-12-01T22:30:27 | 2014-05-25T04:15:24 | 2014-11-25T01:37:02 | 2014-12-01T22:30:26 | 2,359 | 0 | 2 | 2 |
Java
| null | null |
package MPQSimulatorTests;
import static org.junit.Assert.*;
import org.junit.Test;
import MPQSimulator.Abilities.AbilityImpl;
import MPQSimulator.Abilities.AbilityComponent;
import MPQSimulator.Abilities.SwapTileAbilityComponent;
import MPQSimulator.Core.GameEngineImpl;
import MPQSimulator.Core.Tile.TileColor;
public class AbilityTests {
@Test
public void testComponentStacking() {
AbilityComponent black =
new SwapTileAbilityComponent(0, 0, TileColor.BLACK);
AbilityComponent red =
new SwapTileAbilityComponent(1, 0, TileColor.RED);
AbilityComponent green =
new SwapTileAbilityComponent(2, 0, TileColor.GREEN);
AbilityComponent yellow =
new SwapTileAbilityComponent(0, 0, TileColor.YELLOW);
AbilityComponent purple =
new SwapTileAbilityComponent(1, 0, TileColor.PURPLE);
AbilityComponent blue =
new SwapTileAbilityComponent(2, 0, TileColor.BLUE);
AbilityImpl level1 = new AbilityImpl();
level1.addComponent(black);
assertEquals(level1.getComponents().get(0), black);
AbilityImpl level2 = new AbilityImpl(level1);
level2.addComponent(red);
assertEquals(level2.getComponents().get(0), black);
assertEquals(level2.getComponents().get(1), red);
AbilityImpl level3 = new AbilityImpl(level2);
level3.addComponent(green);
assertEquals(level3.getComponents().get(0), black);
assertEquals(level3.getComponents().get(1), red);
assertEquals(level3.getComponents().get(2), green);
AbilityImpl level4 = new AbilityImpl(level3);
level4.addComponent(yellow);
assertEquals(level4.getComponents().get(0), black);
assertEquals(level4.getComponents().get(1), red);
assertEquals(level4.getComponents().get(2), green);
assertEquals(level4.getComponents().get(3), yellow);
AbilityImpl level5 = new AbilityImpl(level4);
level5.addComponent(purple);
level5.addComponent(blue);
assertEquals(level5.getComponents().get(0), black);
assertEquals(level5.getComponents().get(1), red);
assertEquals(level5.getComponents().get(2), green);
assertEquals(level5.getComponents().get(3), yellow);
assertEquals(level5.getComponents().get(4), purple);
assertEquals(level5.getComponents().get(5), blue);
}
}
|
UTF-8
|
Java
| 2,195 |
java
|
AbilityTests.java
|
Java
|
[] | null |
[] |
package MPQSimulatorTests;
import static org.junit.Assert.*;
import org.junit.Test;
import MPQSimulator.Abilities.AbilityImpl;
import MPQSimulator.Abilities.AbilityComponent;
import MPQSimulator.Abilities.SwapTileAbilityComponent;
import MPQSimulator.Core.GameEngineImpl;
import MPQSimulator.Core.Tile.TileColor;
public class AbilityTests {
@Test
public void testComponentStacking() {
AbilityComponent black =
new SwapTileAbilityComponent(0, 0, TileColor.BLACK);
AbilityComponent red =
new SwapTileAbilityComponent(1, 0, TileColor.RED);
AbilityComponent green =
new SwapTileAbilityComponent(2, 0, TileColor.GREEN);
AbilityComponent yellow =
new SwapTileAbilityComponent(0, 0, TileColor.YELLOW);
AbilityComponent purple =
new SwapTileAbilityComponent(1, 0, TileColor.PURPLE);
AbilityComponent blue =
new SwapTileAbilityComponent(2, 0, TileColor.BLUE);
AbilityImpl level1 = new AbilityImpl();
level1.addComponent(black);
assertEquals(level1.getComponents().get(0), black);
AbilityImpl level2 = new AbilityImpl(level1);
level2.addComponent(red);
assertEquals(level2.getComponents().get(0), black);
assertEquals(level2.getComponents().get(1), red);
AbilityImpl level3 = new AbilityImpl(level2);
level3.addComponent(green);
assertEquals(level3.getComponents().get(0), black);
assertEquals(level3.getComponents().get(1), red);
assertEquals(level3.getComponents().get(2), green);
AbilityImpl level4 = new AbilityImpl(level3);
level4.addComponent(yellow);
assertEquals(level4.getComponents().get(0), black);
assertEquals(level4.getComponents().get(1), red);
assertEquals(level4.getComponents().get(2), green);
assertEquals(level4.getComponents().get(3), yellow);
AbilityImpl level5 = new AbilityImpl(level4);
level5.addComponent(purple);
level5.addComponent(blue);
assertEquals(level5.getComponents().get(0), black);
assertEquals(level5.getComponents().get(1), red);
assertEquals(level5.getComponents().get(2), green);
assertEquals(level5.getComponents().get(3), yellow);
assertEquals(level5.getComponents().get(4), purple);
assertEquals(level5.getComponents().get(5), blue);
}
}
| 2,195 | 0.75672 | 0.729841 | 68 | 31.279411 | 21.359558 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.5 | false | false |
12
|
c175fd0c6351cbb4fbe8851b20820cf25804ffde
| 14,654,428,450,787 |
c5cad04270aac1d218decebb69ecb78c797d1671
|
/src/Queue/Main.java
|
91c1831417017a4cafd2ec331547abe9db2082e6
|
[] |
no_license
|
Abrar051/LinkedList
|
https://github.com/Abrar051/LinkedList
|
643223f059ce6e704d844baec3c57219110aaa5e
|
e15455e9306a7b2e635b104a17255034cfd63c06
|
refs/heads/master
| 2023-03-27T12:15:19.979000 | 2021-03-24T12:02:26 | 2021-03-24T12:02:26 | 344,027,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Queue;
import java.util.*;
public class Main {
public static void main(String[] args) {
QueueFunctions obj = new QueueFunctions();
Scanner input = new Scanner(System.in);
for (int i=0;i<10;i++)
{
obj.push(i);
}
obj.display();
obj.popPrint();
obj.display();
obj.popPrint();
obj.display();
obj.popPrint();
obj.display();
System.out.println("Number of members in queue is "+obj.queueMemberNumber());
}
}
|
UTF-8
|
Java
| 534 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package Queue;
import java.util.*;
public class Main {
public static void main(String[] args) {
QueueFunctions obj = new QueueFunctions();
Scanner input = new Scanner(System.in);
for (int i=0;i<10;i++)
{
obj.push(i);
}
obj.display();
obj.popPrint();
obj.display();
obj.popPrint();
obj.display();
obj.popPrint();
obj.display();
System.out.println("Number of members in queue is "+obj.queueMemberNumber());
}
}
| 534 | 0.539326 | 0.533708 | 21 | 24.428572 | 18.826454 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false |
12
|
85fa153d195dbe3e0735a0bdd78ef76825788e52
| 13,589,276,525,860 |
e162f0d02ca769bbacb91bc0b4701181bc24dd95
|
/src/main/java/app/service/BookService.java
|
ca0d84fa17466d28bea5977211fa7d867f402fed
|
[] |
no_license
|
BlackPrinter/LAB_n
|
https://github.com/BlackPrinter/LAB_n
|
f2d1367cdf72bee51cd17d1ae9d6f1e0099c160f
|
b421926adae920036520cdfaf3540017381dc2fc
|
refs/heads/master
| 2023-02-06T15:49:26.519000 | 2020-12-28T21:45:46 | 2020-12-28T21:45:46 | 325,123,376 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package app.service;
import app.model.Book;
import java.util.List;
public interface BookService {
Book addBook(Book book);
List<Book> getAllBook();
void deleteBook(Integer id);
}
|
UTF-8
|
Java
| 196 |
java
|
BookService.java
|
Java
|
[] | null |
[] |
package app.service;
import app.model.Book;
import java.util.List;
public interface BookService {
Book addBook(Book book);
List<Book> getAllBook();
void deleteBook(Integer id);
}
| 196 | 0.709184 | 0.709184 | 13 | 14.076923 | 13.257576 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
12
|
9fee8d2b1999a5116629c91a76b1e73b93a314d7
| 8,529,805,115,678 |
71a4589e18dc51b9db07e6ee95b62a722c6f76e4
|
/src/main/java/net/sci/geom/geom2d/Point2D.java
|
99808ff593b0da6349b42d5bab36dffd30b8c669
|
[] |
no_license
|
SciCompJ/cs4j
|
https://github.com/SciCompJ/cs4j
|
0c9f2b7735c54349bd1351751c2aeafa46910650
|
20b92e832bf6cc3561de1daefb5e1b4cfc403ab1
|
refs/heads/master
| 2023-09-03T17:30:39.405000 | 2023-08-16T12:16:33 | 2023-08-16T12:16:33 | 244,849,869 | 0 | 0 | null | true | 2020-03-04T08:45:41 | 2020-03-04T08:45:41 | 2020-01-17T17:03:44 | 2020-02-04T17:24:24 | 36,773 | 0 | 0 | 0 | null | false | false |
/**
*
*/
package net.sci.geom.geom2d;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;
import net.sci.geom.Point;
/**
* A point in the two-dimensional plane.
*
* @author dlegland
*
*/
public class Point2D implements Geometry2D, Point
{
// ===================================================================
// Static methods
/**
* Computes the centroid of a collection of points.
* @param points the points to consider.
* @return the centroid of the input points.
*/
public static final Point2D centroid(Point2D... points)
{
double xc = 0;
double yc = 0;
int np = points.length;
for (Point2D p : points)
{
xc += p.x;
yc += p.y;
}
return new Point2D(xc / np, yc / np);
}
/**
* Interpolates the position of a new Point2D between the two points.
*
* @param p1
* the first point to interpolate
* @param p2
* the second point to interpolate
* @param t
* the relative position of the new point, between 0 and 1. If t
* is outside the [0,1] range, its value is clamped to enforce
* the resulting point to be between the two extremity points.
* @return the interpolated point
*/
public static final Point2D interpolate(Point2D p1, Point2D p2, double t)
{
if (t <= 0) return p1;
if (t >= 1) return p2;
double x = p1.x() * (1.0 - t) + p2.x() * t;
double y = p1.y() * (1.0 - t) + p2.y() * t;
return new Point2D(x, y);
}
/**
* Returns a new sorted list of the points in the collection given as
* parameter. The points are sorted in lexicographic order: first with
* increasing X order, and in case of equality by increasing Y order.
*
* @param points
* a collection of points to sort
* @return a new collection containing points sorted wrt their coordinates.
*/
public static final ArrayList<Point2D> sortPoints(Collection<Point2D> points)
{
// create result array
ArrayList<Point2D> res = new ArrayList<Point2D>(points.size());
res.addAll(points);
// create the comparator
Comparator<Point2D> comparator = new Comparator<Point2D>()
{
@Override
public int compare(Point2D p0, Point2D p1)
{
// compare X first
double dx = p0.x() - p1.x();
if (dx < 0) return -1;
if (dx > 0) return +1;
// add Y comparison
double dy = p0.y() - p1.y();
if (dy < 0) return -1;
if (dy > 0) return +1;
// point with same coordinates
return 0;
}
};
// sort the array of points
Collections.sort(res, comparator);
return res;
}
// ===================================================================
// class variables
/** x coordinate of the point */
final double x;
/** y coordinate of the point */
final double y;
// ===================================================================
// Constructors
/** Empty constructor, similar to Point(0,0) */
public Point2D()
{
this(0, 0);
}
/**
* New point given by its coordinates
*
* @param x the x coordinate of the new point
* @param y the y coordinate of the new point
*/
public Point2D(double x, double y)
{
this.x = x;
this.y = y;
}
// ===================================================================
// Specific methods
/**
* Returns the result of the given transformation applied to this point.
*
* @param trans
* the transformation to apply
* @return the transformed point
*/
public Point2D transform(AffineTransform2D trans)
{
return trans.transform(this);
}
/**
* Applies the translation defined by the two components to this point and
* returns the translated point.
*
* @param dx
* the x-component of the translation
* @param dy
* the y-component of the translation
* @return the translated point
*/
public Point2D translate(double dx, double dy)
{
return new Point2D(this.x + dx, this.y + dy);
}
/**
* Adds the specified vector to the point, and returns the result.
*
* @param v
* the vector to add
* @return the result of the addition of<code>v</code> to this point
*/
public Point2D plus(Vector2D v)
{
return new Point2D(this.x + v.x(), this.y + v.y());
}
/**
* Subtracts the specified vector from the point, and returns the result.
*
* @param v
* the vector to subtract
* @return the result of the subtraction of<code>v</code> to this point
*/
public Point2D minus(Vector2D v)
{
return new Point2D(this.x - v.x(), this.y - v.y());
}
/**
* Checks if the two points are equal up to the absolute tolerance value
* given as parameter. The tolerance is used for each of the x and y
* coordinates.
*
* @param point
* the point to compare with
* @param eps
* the (absolute) tolerance on coordinates
* @return true if all the coordinates of the points are within the
* <code>eps</code> interval.
*/
public boolean almostEquals(Point2D point, double eps)
{
if (Math.abs(point.x - x) > eps) return false;
if (Math.abs(point.y - y) > eps) return false;
return true;
}
// ===================================================================
// accessors
/**
* @return the x coordinate of this point
*/
public double x()
{
return x;
}
/**
* @return the y coordinate of this point
*/
public double y()
{
return y;
}
// ===================================================================
// Implementation of the Point interface
@Override
public double get(int dim)
{
switch(dim)
{
case 0: return this.x;
case 1: return this.y;
default:
throw new IllegalArgumentException("Dimension should be comprised between 0 and 1");
}
}
// ===================================================================
// Implementation of the Geometry2D interface
@Override
public boolean contains(Point2D point, double eps)
{
if (Math.abs(this.x - point.x) > eps) return false;
if (Math.abs(this.y - point.y) > eps) return false;
return true;
}
/**
* Computes the distance between this point and the point
* <code>point</code>.
*
* @param point
* another point
* @return the distance between the two points
*/
/*
* Overrides the default implementation in Geometry2D interface to directly
* compare point coordinates.
*/
@Override
public double distance(Point2D point)
{
return distance(point.x, point.y);
}
/**
* Computes the distance between current point and point with coordinate
* <code>(x,y)</code>. Uses the <code>Math.hypot()</code> function for
* better robustness than simple square root.
*
* @param x the x-coordinate of the other point
* @param y the y-coordinate of the other point
* @return the distance between the two points
*/
public double distance(double x, double y)
{
return Math.hypot(this.x - x, this.y - y);
}
// ===================================================================
// Implementation of the Geometry interface
/**
* Returns true, as a point is bounded by definition.
*/
public boolean isBounded()
{
return true;
}
@Override
public Bounds2D bounds()
{
return new Bounds2D(this.x, this.x, this.y, this.y);
}
@Override
public Point2D duplicate()
{
return new Point2D(x, y);
}
// public Point2d transform(Transform2d trans)
// {
// return trans.transform(this);
// }
// ===================================================================
// Override Object interface
@Override
public String toString()
{
return String.format(Locale.ENGLISH, "Point2D(%g,%g)", this.x, this.y);
}
}
|
UTF-8
|
Java
| 8,598 |
java
|
Point2D.java
|
Java
|
[
{
"context": "oint in the two-dimensional plane. \n * \n * @author dlegland\n *\n */\npublic class Point2D implements Geometry2D",
"end": 281,
"score": 0.9994140267372131,
"start": 273,
"tag": "USERNAME",
"value": "dlegland"
}
] | null |
[] |
/**
*
*/
package net.sci.geom.geom2d;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;
import net.sci.geom.Point;
/**
* A point in the two-dimensional plane.
*
* @author dlegland
*
*/
public class Point2D implements Geometry2D, Point
{
// ===================================================================
// Static methods
/**
* Computes the centroid of a collection of points.
* @param points the points to consider.
* @return the centroid of the input points.
*/
public static final Point2D centroid(Point2D... points)
{
double xc = 0;
double yc = 0;
int np = points.length;
for (Point2D p : points)
{
xc += p.x;
yc += p.y;
}
return new Point2D(xc / np, yc / np);
}
/**
* Interpolates the position of a new Point2D between the two points.
*
* @param p1
* the first point to interpolate
* @param p2
* the second point to interpolate
* @param t
* the relative position of the new point, between 0 and 1. If t
* is outside the [0,1] range, its value is clamped to enforce
* the resulting point to be between the two extremity points.
* @return the interpolated point
*/
public static final Point2D interpolate(Point2D p1, Point2D p2, double t)
{
if (t <= 0) return p1;
if (t >= 1) return p2;
double x = p1.x() * (1.0 - t) + p2.x() * t;
double y = p1.y() * (1.0 - t) + p2.y() * t;
return new Point2D(x, y);
}
/**
* Returns a new sorted list of the points in the collection given as
* parameter. The points are sorted in lexicographic order: first with
* increasing X order, and in case of equality by increasing Y order.
*
* @param points
* a collection of points to sort
* @return a new collection containing points sorted wrt their coordinates.
*/
public static final ArrayList<Point2D> sortPoints(Collection<Point2D> points)
{
// create result array
ArrayList<Point2D> res = new ArrayList<Point2D>(points.size());
res.addAll(points);
// create the comparator
Comparator<Point2D> comparator = new Comparator<Point2D>()
{
@Override
public int compare(Point2D p0, Point2D p1)
{
// compare X first
double dx = p0.x() - p1.x();
if (dx < 0) return -1;
if (dx > 0) return +1;
// add Y comparison
double dy = p0.y() - p1.y();
if (dy < 0) return -1;
if (dy > 0) return +1;
// point with same coordinates
return 0;
}
};
// sort the array of points
Collections.sort(res, comparator);
return res;
}
// ===================================================================
// class variables
/** x coordinate of the point */
final double x;
/** y coordinate of the point */
final double y;
// ===================================================================
// Constructors
/** Empty constructor, similar to Point(0,0) */
public Point2D()
{
this(0, 0);
}
/**
* New point given by its coordinates
*
* @param x the x coordinate of the new point
* @param y the y coordinate of the new point
*/
public Point2D(double x, double y)
{
this.x = x;
this.y = y;
}
// ===================================================================
// Specific methods
/**
* Returns the result of the given transformation applied to this point.
*
* @param trans
* the transformation to apply
* @return the transformed point
*/
public Point2D transform(AffineTransform2D trans)
{
return trans.transform(this);
}
/**
* Applies the translation defined by the two components to this point and
* returns the translated point.
*
* @param dx
* the x-component of the translation
* @param dy
* the y-component of the translation
* @return the translated point
*/
public Point2D translate(double dx, double dy)
{
return new Point2D(this.x + dx, this.y + dy);
}
/**
* Adds the specified vector to the point, and returns the result.
*
* @param v
* the vector to add
* @return the result of the addition of<code>v</code> to this point
*/
public Point2D plus(Vector2D v)
{
return new Point2D(this.x + v.x(), this.y + v.y());
}
/**
* Subtracts the specified vector from the point, and returns the result.
*
* @param v
* the vector to subtract
* @return the result of the subtraction of<code>v</code> to this point
*/
public Point2D minus(Vector2D v)
{
return new Point2D(this.x - v.x(), this.y - v.y());
}
/**
* Checks if the two points are equal up to the absolute tolerance value
* given as parameter. The tolerance is used for each of the x and y
* coordinates.
*
* @param point
* the point to compare with
* @param eps
* the (absolute) tolerance on coordinates
* @return true if all the coordinates of the points are within the
* <code>eps</code> interval.
*/
public boolean almostEquals(Point2D point, double eps)
{
if (Math.abs(point.x - x) > eps) return false;
if (Math.abs(point.y - y) > eps) return false;
return true;
}
// ===================================================================
// accessors
/**
* @return the x coordinate of this point
*/
public double x()
{
return x;
}
/**
* @return the y coordinate of this point
*/
public double y()
{
return y;
}
// ===================================================================
// Implementation of the Point interface
@Override
public double get(int dim)
{
switch(dim)
{
case 0: return this.x;
case 1: return this.y;
default:
throw new IllegalArgumentException("Dimension should be comprised between 0 and 1");
}
}
// ===================================================================
// Implementation of the Geometry2D interface
@Override
public boolean contains(Point2D point, double eps)
{
if (Math.abs(this.x - point.x) > eps) return false;
if (Math.abs(this.y - point.y) > eps) return false;
return true;
}
/**
* Computes the distance between this point and the point
* <code>point</code>.
*
* @param point
* another point
* @return the distance between the two points
*/
/*
* Overrides the default implementation in Geometry2D interface to directly
* compare point coordinates.
*/
@Override
public double distance(Point2D point)
{
return distance(point.x, point.y);
}
/**
* Computes the distance between current point and point with coordinate
* <code>(x,y)</code>. Uses the <code>Math.hypot()</code> function for
* better robustness than simple square root.
*
* @param x the x-coordinate of the other point
* @param y the y-coordinate of the other point
* @return the distance between the two points
*/
public double distance(double x, double y)
{
return Math.hypot(this.x - x, this.y - y);
}
// ===================================================================
// Implementation of the Geometry interface
/**
* Returns true, as a point is bounded by definition.
*/
public boolean isBounded()
{
return true;
}
@Override
public Bounds2D bounds()
{
return new Bounds2D(this.x, this.x, this.y, this.y);
}
@Override
public Point2D duplicate()
{
return new Point2D(x, y);
}
// public Point2d transform(Transform2d trans)
// {
// return trans.transform(this);
// }
// ===================================================================
// Override Object interface
@Override
public String toString()
{
return String.format(Locale.ENGLISH, "Point2D(%g,%g)", this.x, this.y);
}
}
| 8,598 | 0.52582 | 0.515469 | 330 | 25.054546 | 24.216763 | 96 | false | false | 0 | 0 | 0 | 0 | 68 | 0.071179 | 0.521212 | false | false |
12
|
e6742a20eb11b7c4085ca61ae78f8b1af4784fc8
| 8,469,675,548,044 |
e1b02c88da2aa2a73d337a3fce5b8330e068a2a4
|
/app/src/main/java/org/y20k/transistor/MainActivityFragment.java
|
8bd35bcd0cda62d5a45dfa59c0c678643e03fa49
|
[
"MIT"
] |
permissive
|
malah-code/Android-Open-Radio
|
https://github.com/malah-code/Android-Open-Radio
|
cbf997e49b6b1f010ebb8c3d77f2bbf9e1139f50
|
e00edd5d7a61dcd9edf4f1f29d2e2d78af7b5d49
|
refs/heads/master
| 2023-01-12T16:58:02.012000 | 2023-01-05T14:57:31 | 2023-01-05T14:57:31 | 81,898,625 | 16 | 9 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* MainActivityFragment.java
* Implements the main fragment of the main activity
* This fragment is a list view of radio stations
* <p>
* This file is part of
* TRANSISTOR - Radio App for Android
* <p>
* Copyright (c) 2015-17 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import org.y20k.transistor.core.Station;
import org.y20k.transistor.helpers.DialogAdd;
import org.y20k.transistor.helpers.DialogInitial;
import org.y20k.transistor.helpers.ImageHelper;
import org.y20k.transistor.helpers.LogHelper;
import org.y20k.transistor.helpers.NotificationHelper;
import org.y20k.transistor.helpers.PermissionHelper;
import org.y20k.transistor.helpers.SingletonProperties;
import org.y20k.transistor.helpers.SleepTimerService;
import org.y20k.transistor.helpers.StationFetcher;
import org.y20k.transistor.helpers.StorageHelper;
import org.y20k.transistor.helpers.TransistorKeys;
import org.y20k.transistor.sqlcore.StationsDbHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import static org.y20k.transistor.R.id.buttonRefreshInitData;
import static org.y20k.transistor.sqlcore.StationsDbContract.searchSuggestIntentAction;
/**
* MainActivityFragment class
*/
public final class MainActivityFragment extends Fragment {
/* Define log tag */
private static final String LOG_TAG = MainActivityFragment.class.getSimpleName();
/* Main class variables */
private Application mApplication;
private Activity mActivity;
private CollectionAdapter mCollectionAdapter = null;
private File mFolder;
private int mFolderSize;
private View mRootView;
private View mActionCallView;
private RecyclerView mRecyclerView;
private Button mButtonRefreshInitDataView;
private RelativeLayout mRelativeEmptyView;
private RecyclerView.LayoutManager mLayoutManager;
private StaggeredGridLayoutManager mStaggeredGridLayoutManagerManager;
private int RECYCLER_VIEW_LIST = 0;
private int RECYCLER_VIEW_GRID = 1;
private Parcelable mListState;
private BroadcastReceiver mCollectionChangedReceiver;
private BroadcastReceiver mImageChangeRequestReceiver;
private BroadcastReceiver mSleepTimerStartedReceiver;
private BroadcastReceiver mPlaybackStateChangedReceiver;
private int mStationIDSelected;
private int mTempStationID_Position;
private Station mTempStation;
private Uri mNewStationUri;
private boolean mTwoPane;
private boolean mPlayback;
private boolean mSleepTimerRunning;
private SleepTimerService mSleepTimerService;
private String mSleepTimerNotificationMessage;
private Snackbar mSleepTimerNotification;
private ProgressDialog progressDialogLoading;
private int mLayoutViewManager;
/* Constructor (default) */
public MainActivityFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
LogHelper.i("MainActivityFragment", "onCreate");
super.onCreate(savedInstanceState);
// fragment has options menu
setHasOptionsMenu(true);
// get activity and application contexts
mActivity = getActivity();
mApplication = mActivity.getApplication();
// get notification message
mSleepTimerNotificationMessage = mActivity.getString(R.string.snackbar_message_timer_set) + " ";
// initiate sleep timer service
mSleepTimerService = new SleepTimerService();
// set list state null
mListState = null;
// initialize id of currently selected station
mStationIDSelected = 0;
// initialize temporary station image id
mTempStationID_Position = -1;
// initialize two pane
mTwoPane = false;
// load playback state
loadAppState(mActivity);
// get collection folder
StorageHelper storageHelper = new StorageHelper(mActivity);
mFolder = storageHelper.getCollectionDirectory();
if (mFolder == null) {
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_no_external_storage), Toast.LENGTH_LONG).show();
mActivity.finish();
}
//get rows count from DB
final StationsDbHelper mDbHelper = new StationsDbHelper(mActivity);
mFolderSize = mDbHelper.GetStationsCount();//mFolder.listFiles().length;
//progress bar loading (not used now, will be used in next versions to make loading progredd while import stations)
progressDialogLoading = new ProgressDialog(mActivity);
progressDialogLoading.setTitle("Loading Stations..");
progressDialogLoading.setMessage("Please wait.");
progressDialogLoading.setCancelable(false);
// create collection adapter
if (mCollectionAdapter == null) {
mCollectionAdapter = new CollectionAdapter(mActivity, mFolder);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LogHelper.i("MainActivityFragment", "onCreateView");
// get list state from saved instance
if (savedInstanceState != null) {
mListState = savedInstanceState.getParcelable(TransistorKeys.INSTANCE_LIST_STATE);
}
// inflate root view from xml
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
// get reference to action call view from inflated root view
mActionCallView = mRootView.findViewById(R.id.main_actioncall_layout);
// get reference to recycler list view from inflated root view
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.main_recyclerview_collection);
mButtonRefreshInitDataView = (Button) mRootView.findViewById(buttonRefreshInitData);
mRelativeEmptyView = (RelativeLayout) mRootView.findViewById(R.id.relativeEmpty);
//btn refresh code
mButtonRefreshInitDataView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runInitialDataRefreshIfFirstTime();
}
});
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// TODO check if necessary here
//mRecyclerView.setHasFixedSize(true);
// set animator
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(mActivity);
mStaggeredGridLayoutManagerManager = new StaggeredGridLayoutManager(2, 1);
if (mLayoutViewManager == RECYCLER_VIEW_LIST) {
mRecyclerView.setLayoutManager(mLayoutManager);
} else {
mRecyclerView.setLayoutManager(mStaggeredGridLayoutManagerManager);
}
// attach adapter to list view
mRecyclerView.setAdapter(mCollectionAdapter);
return mRootView;
}
public void runInitialDataRefreshIfFirstTime() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
Boolean initialDataLoaded = settings.getBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, false);
if (!initialDataLoaded) {
StationsDbHelper dbHelper = new StationsDbHelper(mActivity);
//dbHelper.DeleteAllStations();
LogHelper.v(LOG_TAG, "initialDataLoaded = false");
if (dbHelper.GetStationsCount() == 0) {
LogHelper.v(LOG_TAG, "dbHelper.GetStationsCount() == 0");
//if no records only we will try to import init data
//First Show Init Layout and refresh button
mRelativeEmptyView.setVisibility(View.VISIBLE);
//load XML initial data
//check for internet connection
if (isOnline()) {
LogHelper.v(LOG_TAG, "User is Online.");
Toast.makeText(mActivity, "You're Online", Toast.LENGTH_SHORT).show();
//open new dialog to import/download init XML data
DialogInitial dialogInit = new DialogInitial(mActivity, mFolder);
dialogInit.show();
} else {
LogHelper.v(LOG_TAG, "User is not Online.");
//Toast.makeText(this, "You're not Online", Toast.LENGTH_SHORT).show();
Toast.makeText(mActivity, "You're not Online :(", Toast.LENGTH_SHORT).show();
}
} else {
//if there are records we shouldn't try again import init data
save_PREF_INITIAL_DATA_LOADED_State(mActivity);
LogHelper.v(LOG_TAG, "there are records we shouldn't try again import init data");
}
} else {
toggleActionCall();
}
}
/* Saves app state to save_PREF_INITIAL_DATA_LOADED_State */
private void save_PREF_INITIAL_DATA_LOADED_State(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, true);
editor.apply();
LogHelper.v(LOG_TAG, "Saving state. PREF_INITIAL_DATA_LOADED = true");
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
@Override
public void onResume() {
LogHelper.i("MainActivityFragment", "onResume");
super.onResume();
Log.v(LOG_TAG + "debugCollectionView", "start onResume");
// refresh app state
loadAppState(mActivity);
// update collection adapter
mCollectionAdapter.setTwoPane(mTwoPane);
mCollectionAdapter.refresh();
if (mCollectionAdapter.getItemCount() > 0) {
mCollectionAdapter.setStationIDSelected(mStationIDSelected, mPlayback, false);
}
// handles the activity's intent
Intent intent = mActivity.getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
handleStreamingLink(intent);
} else if (TransistorKeys.ACTION_SHOW_PLAYER.equals(intent.getAction())) {
handleShowPlayer(intent);
}
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// Handle the normal search query case
String query = intent.getStringExtra(SearchManager.QUERY);
} else if (searchSuggestIntentAction.equals(intent.getAction())) {
// Handle a suggestions click (because the suggestions all use ACTION_VIEW)
String data = intent.getDataString();
if (data != null && !data.isEmpty()) {
int pos = mCollectionAdapter.getItemPosition(Long.parseLong(data));
//simulate click item
mCollectionAdapter.handleSingleClick(pos, null);
//make the item selected
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
mLayoutManager.scrollToPosition(pos);
} else {
mStaggeredGridLayoutManagerManager.scrollToPosition(pos);
}
}
if(mActivity instanceof MainActivity){
((MainActivity)mActivity).ClearSearch();
}
}
// check if folder content has been changed
//get rows count from DB
StationsDbHelper mDbHelper = new StationsDbHelper(mActivity);
int folderSize = mDbHelper.GetStationsCount();//mFolder.listFiles().length;
if (mFolderSize != folderSize) {
mFolderSize = folderSize;
mCollectionAdapter = new CollectionAdapter(mActivity, mFolder);
mRecyclerView.setAdapter(mCollectionAdapter);
}
// show call to action, if necessary
toggleActionCall();
// show notification bar if timer is running
if (mSleepTimerRunning) {
showSleepTimerNotification(-1);
}
//check if initial xml data loaded
runInitialDataRefreshIfFirstTime();
}
@Override
public void onStart() {
LogHelper.i("MainActivityFragment", "onStart");
super.onStart();
// initialize broadcast receivers
initializeBroadcastReceivers();
}
@Override
public void onStop() {
LogHelper.i("MainActivityFragment", "onStop");
super.onStop();
// unregister Broadcast Receivers
unregisterBroadcastReceivers();
}
@Override
public void onDestroy() {
LogHelper.i("MainActivityFragment", "onDestroy");
super.onDestroy();
}
@Override
public void onDestroyView() {
LogHelper.i("MainActivityFragment", "onDestroyView");
super.onDestroyView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// CASE TIMER
case R.id.menu_timer:
handleMenuSleepTimerClick();
return true;
// CASE ADD
case R.id.menu_add:
DialogAdd dialog = new DialogAdd(mActivity, mFolder);
dialog.show();
return true;
// CASE ABOUT
case R.id.menu_about:
// get title and content
String aboutTitle = mActivity.getString(R.string.header_about);
// put title and content into intent and start activity
Intent aboutIntent = new Intent(mActivity, InfosheetActivity.class);
aboutIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_TITLE, aboutTitle);
aboutIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_CONTENT, TransistorKeys.INFOSHEET_CONTENT_ABOUT);
startActivity(aboutIntent);
return true;
// CASE HOWTO
case R.id.menu_howto:
// get title and content
String howToTitle = mActivity.getString(R.string.header_howto);
// put title and content into intent and start activity
Intent howToIntent = new Intent(mActivity, InfosheetActivity.class);
howToIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_TITLE, howToTitle);
howToIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_CONTENT, TransistorKeys.INFOSHEET_CONTENT_HOWTO);
startActivity(howToIntent);
return true;
// CASE menu_grid_view
case R.id.menu_grid_view:
//change the view
mRecyclerView.setLayoutManager(mStaggeredGridLayoutManagerManager);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_GRID);
editor.apply();
return true;
// CASE menu_grid_view
case R.id.menu_list_view:
//change the view
mRecyclerView.setLayoutManager(mLayoutManager);
SharedPreferences settings_v = PreferenceManager.getDefaultSharedPreferences(mActivity);
SharedPreferences.Editor editor_v = settings_v.edit();
editor_v.putInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST);
editor_v.apply();
return true;
// CASE DEFAULT
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
LogHelper.i("MainActivityFragment", "onSaveInstanceState");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mListState = mLayoutManager.onSaveInstanceState();
} else {
// save list view position
mListState = mStaggeredGridLayoutManagerManager.onSaveInstanceState();
}
outState.putParcelable(TransistorKeys.INSTANCE_LIST_STATE, mListState);
super.onSaveInstanceState(outState);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
LogHelper.i("MainActivityFragment", "onRequestPermissionsResult");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case TransistorKeys.PERMISSION_REQUEST_IMAGE_PICKER_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted - get system picker for images
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
mActivity.startActivityForResult(pickImageIntent, TransistorKeys.REQUEST_LOAD_IMAGE);
} else {
// permission denied
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_permission_denied) + " READ_EXTERNAL_STORAGE", Toast.LENGTH_LONG).show();
}
break;
}
case TransistorKeys.PERMISSION_REQUEST_STATION_FETCHER_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted - fetch station from given Uri
fetchNewStation(mNewStationUri);
} else {
// permission denied
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_permission_denied) + " READ_EXTERNAL_STORAGE", Toast.LENGTH_LONG).show();
}
break;
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
LogHelper.i("MainActivityFragment", "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
// retrieve selected image Uri from image picker
Uri newImageUri = null;
if (null != data) {
newImageUri = data.getData();
}
if (requestCode == TransistorKeys.REQUEST_LOAD_IMAGE && resultCode == Activity.RESULT_OK && newImageUri != null) {
ImageHelper imageHelper = new ImageHelper(newImageUri, mActivity, 500, 500);
Bitmap newImage = imageHelper.getInputImage();
if (newImage != null && mTempStationID_Position != -1) {
// write image to storage
File stationImageFile = mTempStation.getStationImageFileReference(mFolder);//get station file with correct path according to UniqueID of the station
try (FileOutputStream out = new FileOutputStream(stationImageFile)) {
newImage.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
//remve image from fresco cache
ImagePipeline imagePipeline = Fresco.getImagePipeline();
imagePipeline.evictFromCache(Uri.parse(stationImageFile.toURI().toString()));
} catch (IOException e) {
LogHelper.e(LOG_TAG, "Unable to save: " + newImage.toString());
}
// update adapter
mCollectionAdapter.notifyItemChanged(mTempStationID_Position);
Toast.makeText(mApplication, "Image Updated", Toast.LENGTH_SHORT).show();
} else {
LogHelper.e(LOG_TAG, "Unable to get image from media picker. Uri was: " + newImageUri.toString());
}
} else {
LogHelper.e(LOG_TAG, "Unable to get image from media picker. Did not receive an Uri");
}
}
/* Show or hide call to action view if necessary */
private void toggleActionCall() {
// show call to action, if necessary
if (mCollectionAdapter.getItemCount() == 0) {
mRelativeEmptyView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
if (mTwoPane && mActivity instanceof MainActivity) {
((MainActivity) mActivity).removePlayFragment();
}
} else {
mRelativeEmptyView.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
Boolean initialDataLoaded = settings.getBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, false);
if (!initialDataLoaded) {
mButtonRefreshInitDataView.setVisibility(View.VISIBLE);
} else {
mButtonRefreshInitDataView.setVisibility(View.GONE);
}
}
/* Check permissions and start image picker */
private void selectFromImagePicker() {
// request read permissions
PermissionHelper permissionHelper = new PermissionHelper(mActivity, mRootView);
if (permissionHelper.requestReadExternalStorage(TransistorKeys.PERMISSION_REQUEST_IMAGE_PICKER_READ_EXTERNAL_STORAGE)) {
// get system picker for images
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, TransistorKeys.REQUEST_LOAD_IMAGE);
}
}
/* Handles tap on streaming link */
private void handleStreamingLink(Intent intent) {
mNewStationUri = intent.getData();
// clear the intent
intent.setAction("");
// check for null and type "http"
if (mNewStationUri != null && mNewStationUri.getScheme().startsWith("http")) {
// download and add new station
fetchNewStation(mNewStationUri);
} else if (mNewStationUri != null && mNewStationUri.getScheme().startsWith("file")) {
// check for read permission
PermissionHelper permissionHelper = new PermissionHelper(mActivity, mRootView);
if (permissionHelper.requestReadExternalStorage(TransistorKeys.PERMISSION_REQUEST_STATION_FETCHER_READ_EXTERNAL_STORAGE)) {
// read and add new station
fetchNewStation(mNewStationUri);
}
}
// unsuccessful - log failure
else {
LogHelper.v(LOG_TAG, "Received an empty intent");
}
}
/* Handles intent to show player from notification or from shortcut */
private void handleShowPlayer(Intent intent) {
// get station from intent
Station station = null;
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get station from notification
station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
} else if (intent.hasExtra(TransistorKeys.EXTRA_STREAM_URI)) {
// get Uri of station from home screen shortcut
station = mCollectionAdapter.findStation(Uri.parse(intent.getStringExtra(TransistorKeys.EXTRA_STREAM_URI)));
} else if (intent.hasExtra(TransistorKeys.EXTRA_LAST_STATION) && intent.getBooleanExtra(TransistorKeys.EXTRA_LAST_STATION, false)) {
// try to get last station
loadAppState(mActivity);
long station_IDLast = SingletonProperties.getInstance().getLastRunningStation_ID();
if (station_IDLast > -1 && mCollectionAdapter.getItemCount() > 0) {
int posTmp = mCollectionAdapter.getItemPosition(station_IDLast);
if (posTmp > -1) {
station = mCollectionAdapter.getStation(posTmp);
}
}
}
if (station == null) {
Toast.makeText(mActivity, getString(R.string.toastalert_station_not_found), Toast.LENGTH_LONG).show();
}
// get playback action from intent
boolean startPlayback;
if (intent.hasExtra(TransistorKeys.EXTRA_PLAYBACK_STATE)) {
startPlayback = intent.getBooleanExtra(TransistorKeys.EXTRA_PLAYBACK_STATE, false);
} else {
startPlayback = false;
}
// prepare arguments or intent
if (mTwoPane && station != null) {
mCollectionAdapter.setStationIDSelected(mCollectionAdapter.getItemPosition(station._ID), station.getPlaybackState(), startPlayback);
} else if (station != null) {
// start player activity - on phone
Intent playerIntent = new Intent(mActivity, PlayerActivity.class);
playerIntent.setAction(TransistorKeys.ACTION_SHOW_PLAYER);
playerIntent.putExtra(TransistorKeys.EXTRA_STATION, station);
playerIntent.putExtra(TransistorKeys.EXTRA_PLAYBACK_STATE, startPlayback);
startActivity(playerIntent);
}
}
/* Handles tap timer icon in actionbar */
private void handleMenuSleepTimerClick() {
// load app state
loadAppState(mActivity);
// set duration
long duration = 900000; // equals 15 minutes
// CASE: No station is playing, no timer is running
if (!mPlayback && !mSleepTimerRunning) {
// unable to start timer
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_start_unable), Toast.LENGTH_SHORT).show();
}
// CASE: A station is playing, no sleep timer is running
else if (mPlayback && !mSleepTimerRunning) {
startSleepTimer(duration);
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_activated), Toast.LENGTH_SHORT).show();
}
// CASE: A station is playing, Sleep timer is running
else if (mPlayback) {
startSleepTimer(duration);
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_duration_increased) + " [+" + getReadableTime(duration) + "]", Toast.LENGTH_SHORT).show();
}
}
/* Starts timer service and notification */
private void startSleepTimer(long duration) {
// start timer service
if (mSleepTimerService == null) {
mSleepTimerService = new SleepTimerService();
}
mSleepTimerService.startActionStart(mActivity, duration);
// show timer notification
showSleepTimerNotification(duration);
mSleepTimerRunning = true;
LogHelper.v(LOG_TAG, "Starting timer service and notification.");
}
/* Stops timer service and notification */
private void stopSleepTimer() {
// stop timer service
if (mSleepTimerService != null) {
mSleepTimerService.startActionStop(mActivity);
}
// cancel notification
if (mSleepTimerNotification != null && mSleepTimerNotification.isShown()) {
mSleepTimerNotification.dismiss();
}
mSleepTimerRunning = false;
LogHelper.v(LOG_TAG, "Stopping timer service and notification.");
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_cancelled), Toast.LENGTH_SHORT).show();
}
/* Shows notification for a running sleep timer */
private void showSleepTimerNotification(long remainingTime) {
// set snackbar message
String message;
if (remainingTime > 0) {
message = mSleepTimerNotificationMessage + getReadableTime(remainingTime);
} else {
message = mSleepTimerNotificationMessage;
}
// show snackbar
mSleepTimerNotification = Snackbar.make(mRootView, message, Snackbar.LENGTH_INDEFINITE);
mSleepTimerNotification.setAction(R.string.dialog_generic_button_cancel, new View.OnClickListener() {
@Override
public void onClick(View view) {
// stop sleep timer service
mSleepTimerService.startActionStop(mActivity);
mSleepTimerRunning = false;
saveAppState(mActivity);
// notify user
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_cancelled), Toast.LENGTH_SHORT).show();
LogHelper.v(LOG_TAG, "Sleep timer cancelled.");
}
});
mSleepTimerNotification.show();
}
/* Translates milliseconds into minutes and seconds */
private String getReadableTime(long remainingTime) {
return String.format(Locale.getDefault(), "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(remainingTime),
TimeUnit.MILLISECONDS.toSeconds(remainingTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)));
}
/* Loads app state from preferences */
private void loadAppState(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
mStationIDSelected = settings.getInt(TransistorKeys.PREF_STATION_ID_SELECTED, 0);
mPlayback = settings.getBoolean(TransistorKeys.PREF_PLAYBACK, false);
mTwoPane = settings.getBoolean(TransistorKeys.PREF_TWO_PANE, false);
mSleepTimerRunning = settings.getBoolean(TransistorKeys.PREF_TIMER_RUNNING, false);
mLayoutViewManager = settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST);
LogHelper.v(LOG_TAG, "Loading state (" + SingletonProperties.getInstance().CurrentSelectedStation_ID + " / " + SingletonProperties.getInstance().getLastRunningStation_ID() + " / " + mPlayback + ")");
}
/* Saves app state to SharedPreferences */
private void saveAppState(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(TransistorKeys.PREF_STATION_ID_CURRENTLY_PLAYING, SingletonProperties.getInstance().CurrentSelectedStation_ID);
editor.putBoolean(TransistorKeys.PREF_PLAYBACK, mPlayback);
editor.putBoolean(TransistorKeys.PREF_TIMER_RUNNING, mSleepTimerRunning);
editor.apply();
LogHelper.v(LOG_TAG, "Saving state (" + SingletonProperties.getInstance().CurrentSelectedStation_ID + " / " + SingletonProperties.getInstance().getLastRunningStation_ID() + " / " + mPlayback + ")");
}
/* Fetch new station with given Uri */
private void fetchNewStation(Uri stationUri) {
// download and add new station
StationFetcher stationFetcher = new StationFetcher(mActivity, mFolder, stationUri);
stationFetcher.execute();
}
/* Initializes broadcast receivers for onCreate */
private void initializeBroadcastReceivers() {
// RECEIVER: state of playback has changed
mPlaybackStateChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(TransistorKeys.EXTRA_PLAYBACK_STATE_CHANGE)) {
handlePlaybackStateChanges(intent);
}
}
};
IntentFilter playbackStateChangedIntentFilter = new IntentFilter(TransistorKeys.ACTION_PLAYBACK_STATE_CHANGED);
LocalBroadcastManager.getInstance(mActivity).registerReceiver(mPlaybackStateChangedReceiver, playbackStateChangedIntentFilter);
// RECEIVER: station added, deleted, or changed
mCollectionChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.hasExtra(TransistorKeys.EXTRA_COLLECTION_CHANGE)) {
handleCollectionChanges(intent);
}
}
};
IntentFilter collectionChangedIntentFilter = new IntentFilter(TransistorKeys.ACTION_COLLECTION_CHANGED);
LocalBroadcastManager.getInstance(mApplication).registerReceiver(mCollectionChangedReceiver, collectionChangedIntentFilter);
// RECEIVER: listen for request to change station image
mImageChangeRequestReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get station and id from intent
mTempStation = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
mTempStationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, -1);
// start image picker
selectFromImagePicker();
}
}
};
IntentFilter imageChangeRequestIntentFilter = new IntentFilter(TransistorKeys.ACTION_IMAGE_CHANGE_REQUESTED);
LocalBroadcastManager.getInstance(mApplication).registerReceiver(mImageChangeRequestReceiver, imageChangeRequestIntentFilter);
// RECEIVER: sleep timer service sends updates
mSleepTimerStartedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// get duration from intent
long remaining = intent.getLongExtra(TransistorKeys.EXTRA_TIMER_REMAINING, 0);
if (mSleepTimerNotification != null && remaining > 0) {
// update existing notification
mSleepTimerNotification.setText(mSleepTimerNotificationMessage + getReadableTime(remaining));
} else if (mSleepTimerNotification != null) {
// cancel notification
mSleepTimerNotification.dismiss();
// save state and update user interface
mPlayback = false;
mSleepTimerRunning = false;
saveAppState(mActivity);
}
}
};
IntentFilter sleepTimerIntentFilter = new IntentFilter(TransistorKeys.ACTION_TIMER_RUNNING);
LocalBroadcastManager.getInstance(mActivity).registerReceiver(mSleepTimerStartedReceiver, sleepTimerIntentFilter);
}
/* Unregisters broadcast receivers */
private void unregisterBroadcastReceivers() {
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mPlaybackStateChangedReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mCollectionChangedReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mImageChangeRequestReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mSleepTimerStartedReceiver);
}
/* Handles changes in state of playback, eg. start, stop, loading stream */
private void handlePlaybackStateChanges(Intent intent) {
switch (intent.getIntExtra(TransistorKeys.EXTRA_PLAYBACK_STATE_CHANGE, 1)) {
// CASE: playback was stopped
case TransistorKeys.PLAYBACK_STOPPED:
// load app state
loadAppState(mActivity);
// stop sleep timer
if (mSleepTimerRunning && mSleepTimerService != null) {
stopSleepTimer();
}
break;
}
}
/* Handles adding, deleting and renaming of station */
private void handleCollectionChanges(Intent intent) {
// load app state
loadAppState(mActivity);
int newStationPosition = 0;
switch (intent.getIntExtra(TransistorKeys.EXTRA_COLLECTION_CHANGE, 1)) {
// CASE: station was added
case TransistorKeys.STATION_ADDED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get station from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
// add station to adapter, scroll to new position and update adapter
if (station != null && station.StreamURI != null && station.TITLE != null) {
newStationPosition = mCollectionAdapter.add(station);
} else if (intent.hasExtra(TransistorKeys.EXTRA_STATIONS)) {
//this is added as a batch from XML
ArrayList<Station> mInsertedStations = intent.getParcelableArrayListExtra(TransistorKeys.EXTRA_STATIONS);
if (mInsertedStations != null && mInsertedStations.size() > 0) {
for (int i = 0; i < mInsertedStations.size(); i++) {
newStationPosition = mCollectionAdapter.add(mInsertedStations.get(i));
}
}
}
if (mCollectionAdapter.getItemCount() > 0) {
toggleActionCall();
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
// CASE: station was renamed
case TransistorKeys.STATION_RENAMED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION_NEW_NAME) && intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get new name, station and station ID from intent
String newStationName = intent.getStringExtra(TransistorKeys.EXTRA_STATION_NEW_NAME);
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stationID_Position, null, null);
}
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.rename(newStationName, station, stationID_Position);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
case TransistorKeys.STATION_CHANGED_FAVORIT:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION_FAVORIT_VALUE) && intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get new Fav Value, station and station ID from intent
int newStationFavoritValue = intent.getIntExtra(TransistorKeys.EXTRA_STATION_FAVORIT_VALUE, 0);
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.changeFavoritValue(newStationFavoritValue, station, stationID_Position);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
case TransistorKeys.STATION_CHANGED_RATING:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get new name, station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stPossition = mCollectionAdapter.getItemPosition(station._ID);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stPossition, null, null);
}
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.updateItemAtPosition(station, stPossition);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(stPossition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(stPossition);
}
mCollectionAdapter.setStationIDSelected(stPossition, mPlayback, false);
// change station within in adapter, scroll to new position and update adapter
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
case TransistorKeys.STATION_CHANGED_IMAGE:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_DB_ID)) {
// get new name, station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID = intent.getIntExtra(TransistorKeys.EXTRA_STATION_DB_ID, 0);
int stPossition = mCollectionAdapter.getItemPosition(stationID);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stPossition, null, null);
}
// change station within in adapter, scroll to new position and update adapter
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
// CASE: station was deleted
case TransistorKeys.STATION_DELETED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stPossition = mCollectionAdapter.getItemPosition(station._ID);
int stationID_position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// dismiss notification
NotificationHelper.stop();
if (station.getPlaybackState()) {
// stop player service and notification using intent
Intent i = new Intent(mActivity, PlayerService.class);
i.setAction(TransistorKeys.ACTION_DISMISS);
mActivity.startService(i);
LogHelper.v(LOG_TAG, "Stopping player service.");
}
// remove station from adapter and update
newStationPosition = mCollectionAdapter.delete(station);
if (newStationPosition == -1 || mCollectionAdapter.getItemCount() == 0) {
// show call to action
toggleActionCall();
} else {
// scroll to new position
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
}
//mCollectionAdapter.notifyItemRemoved(stPossition); //not working well (try to know why)
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
}
}
}
|
UTF-8
|
Java
| 48,434 |
java
|
MainActivityFragment.java
|
Java
|
[] | null |
[] |
/**
* MainActivityFragment.java
* Implements the main fragment of the main activity
* This fragment is a list view of radio stations
* <p>
* This file is part of
* TRANSISTOR - Radio App for Android
* <p>
* Copyright (c) 2015-17 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import org.y20k.transistor.core.Station;
import org.y20k.transistor.helpers.DialogAdd;
import org.y20k.transistor.helpers.DialogInitial;
import org.y20k.transistor.helpers.ImageHelper;
import org.y20k.transistor.helpers.LogHelper;
import org.y20k.transistor.helpers.NotificationHelper;
import org.y20k.transistor.helpers.PermissionHelper;
import org.y20k.transistor.helpers.SingletonProperties;
import org.y20k.transistor.helpers.SleepTimerService;
import org.y20k.transistor.helpers.StationFetcher;
import org.y20k.transistor.helpers.StorageHelper;
import org.y20k.transistor.helpers.TransistorKeys;
import org.y20k.transistor.sqlcore.StationsDbHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import static org.y20k.transistor.R.id.buttonRefreshInitData;
import static org.y20k.transistor.sqlcore.StationsDbContract.searchSuggestIntentAction;
/**
* MainActivityFragment class
*/
public final class MainActivityFragment extends Fragment {
/* Define log tag */
private static final String LOG_TAG = MainActivityFragment.class.getSimpleName();
/* Main class variables */
private Application mApplication;
private Activity mActivity;
private CollectionAdapter mCollectionAdapter = null;
private File mFolder;
private int mFolderSize;
private View mRootView;
private View mActionCallView;
private RecyclerView mRecyclerView;
private Button mButtonRefreshInitDataView;
private RelativeLayout mRelativeEmptyView;
private RecyclerView.LayoutManager mLayoutManager;
private StaggeredGridLayoutManager mStaggeredGridLayoutManagerManager;
private int RECYCLER_VIEW_LIST = 0;
private int RECYCLER_VIEW_GRID = 1;
private Parcelable mListState;
private BroadcastReceiver mCollectionChangedReceiver;
private BroadcastReceiver mImageChangeRequestReceiver;
private BroadcastReceiver mSleepTimerStartedReceiver;
private BroadcastReceiver mPlaybackStateChangedReceiver;
private int mStationIDSelected;
private int mTempStationID_Position;
private Station mTempStation;
private Uri mNewStationUri;
private boolean mTwoPane;
private boolean mPlayback;
private boolean mSleepTimerRunning;
private SleepTimerService mSleepTimerService;
private String mSleepTimerNotificationMessage;
private Snackbar mSleepTimerNotification;
private ProgressDialog progressDialogLoading;
private int mLayoutViewManager;
/* Constructor (default) */
public MainActivityFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
LogHelper.i("MainActivityFragment", "onCreate");
super.onCreate(savedInstanceState);
// fragment has options menu
setHasOptionsMenu(true);
// get activity and application contexts
mActivity = getActivity();
mApplication = mActivity.getApplication();
// get notification message
mSleepTimerNotificationMessage = mActivity.getString(R.string.snackbar_message_timer_set) + " ";
// initiate sleep timer service
mSleepTimerService = new SleepTimerService();
// set list state null
mListState = null;
// initialize id of currently selected station
mStationIDSelected = 0;
// initialize temporary station image id
mTempStationID_Position = -1;
// initialize two pane
mTwoPane = false;
// load playback state
loadAppState(mActivity);
// get collection folder
StorageHelper storageHelper = new StorageHelper(mActivity);
mFolder = storageHelper.getCollectionDirectory();
if (mFolder == null) {
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_no_external_storage), Toast.LENGTH_LONG).show();
mActivity.finish();
}
//get rows count from DB
final StationsDbHelper mDbHelper = new StationsDbHelper(mActivity);
mFolderSize = mDbHelper.GetStationsCount();//mFolder.listFiles().length;
//progress bar loading (not used now, will be used in next versions to make loading progredd while import stations)
progressDialogLoading = new ProgressDialog(mActivity);
progressDialogLoading.setTitle("Loading Stations..");
progressDialogLoading.setMessage("Please wait.");
progressDialogLoading.setCancelable(false);
// create collection adapter
if (mCollectionAdapter == null) {
mCollectionAdapter = new CollectionAdapter(mActivity, mFolder);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LogHelper.i("MainActivityFragment", "onCreateView");
// get list state from saved instance
if (savedInstanceState != null) {
mListState = savedInstanceState.getParcelable(TransistorKeys.INSTANCE_LIST_STATE);
}
// inflate root view from xml
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
// get reference to action call view from inflated root view
mActionCallView = mRootView.findViewById(R.id.main_actioncall_layout);
// get reference to recycler list view from inflated root view
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.main_recyclerview_collection);
mButtonRefreshInitDataView = (Button) mRootView.findViewById(buttonRefreshInitData);
mRelativeEmptyView = (RelativeLayout) mRootView.findViewById(R.id.relativeEmpty);
//btn refresh code
mButtonRefreshInitDataView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runInitialDataRefreshIfFirstTime();
}
});
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// TODO check if necessary here
//mRecyclerView.setHasFixedSize(true);
// set animator
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(mActivity);
mStaggeredGridLayoutManagerManager = new StaggeredGridLayoutManager(2, 1);
if (mLayoutViewManager == RECYCLER_VIEW_LIST) {
mRecyclerView.setLayoutManager(mLayoutManager);
} else {
mRecyclerView.setLayoutManager(mStaggeredGridLayoutManagerManager);
}
// attach adapter to list view
mRecyclerView.setAdapter(mCollectionAdapter);
return mRootView;
}
public void runInitialDataRefreshIfFirstTime() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
Boolean initialDataLoaded = settings.getBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, false);
if (!initialDataLoaded) {
StationsDbHelper dbHelper = new StationsDbHelper(mActivity);
//dbHelper.DeleteAllStations();
LogHelper.v(LOG_TAG, "initialDataLoaded = false");
if (dbHelper.GetStationsCount() == 0) {
LogHelper.v(LOG_TAG, "dbHelper.GetStationsCount() == 0");
//if no records only we will try to import init data
//First Show Init Layout and refresh button
mRelativeEmptyView.setVisibility(View.VISIBLE);
//load XML initial data
//check for internet connection
if (isOnline()) {
LogHelper.v(LOG_TAG, "User is Online.");
Toast.makeText(mActivity, "You're Online", Toast.LENGTH_SHORT).show();
//open new dialog to import/download init XML data
DialogInitial dialogInit = new DialogInitial(mActivity, mFolder);
dialogInit.show();
} else {
LogHelper.v(LOG_TAG, "User is not Online.");
//Toast.makeText(this, "You're not Online", Toast.LENGTH_SHORT).show();
Toast.makeText(mActivity, "You're not Online :(", Toast.LENGTH_SHORT).show();
}
} else {
//if there are records we shouldn't try again import init data
save_PREF_INITIAL_DATA_LOADED_State(mActivity);
LogHelper.v(LOG_TAG, "there are records we shouldn't try again import init data");
}
} else {
toggleActionCall();
}
}
/* Saves app state to save_PREF_INITIAL_DATA_LOADED_State */
private void save_PREF_INITIAL_DATA_LOADED_State(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, true);
editor.apply();
LogHelper.v(LOG_TAG, "Saving state. PREF_INITIAL_DATA_LOADED = true");
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
@Override
public void onResume() {
LogHelper.i("MainActivityFragment", "onResume");
super.onResume();
Log.v(LOG_TAG + "debugCollectionView", "start onResume");
// refresh app state
loadAppState(mActivity);
// update collection adapter
mCollectionAdapter.setTwoPane(mTwoPane);
mCollectionAdapter.refresh();
if (mCollectionAdapter.getItemCount() > 0) {
mCollectionAdapter.setStationIDSelected(mStationIDSelected, mPlayback, false);
}
// handles the activity's intent
Intent intent = mActivity.getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
handleStreamingLink(intent);
} else if (TransistorKeys.ACTION_SHOW_PLAYER.equals(intent.getAction())) {
handleShowPlayer(intent);
}
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// Handle the normal search query case
String query = intent.getStringExtra(SearchManager.QUERY);
} else if (searchSuggestIntentAction.equals(intent.getAction())) {
// Handle a suggestions click (because the suggestions all use ACTION_VIEW)
String data = intent.getDataString();
if (data != null && !data.isEmpty()) {
int pos = mCollectionAdapter.getItemPosition(Long.parseLong(data));
//simulate click item
mCollectionAdapter.handleSingleClick(pos, null);
//make the item selected
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
mLayoutManager.scrollToPosition(pos);
} else {
mStaggeredGridLayoutManagerManager.scrollToPosition(pos);
}
}
if(mActivity instanceof MainActivity){
((MainActivity)mActivity).ClearSearch();
}
}
// check if folder content has been changed
//get rows count from DB
StationsDbHelper mDbHelper = new StationsDbHelper(mActivity);
int folderSize = mDbHelper.GetStationsCount();//mFolder.listFiles().length;
if (mFolderSize != folderSize) {
mFolderSize = folderSize;
mCollectionAdapter = new CollectionAdapter(mActivity, mFolder);
mRecyclerView.setAdapter(mCollectionAdapter);
}
// show call to action, if necessary
toggleActionCall();
// show notification bar if timer is running
if (mSleepTimerRunning) {
showSleepTimerNotification(-1);
}
//check if initial xml data loaded
runInitialDataRefreshIfFirstTime();
}
@Override
public void onStart() {
LogHelper.i("MainActivityFragment", "onStart");
super.onStart();
// initialize broadcast receivers
initializeBroadcastReceivers();
}
@Override
public void onStop() {
LogHelper.i("MainActivityFragment", "onStop");
super.onStop();
// unregister Broadcast Receivers
unregisterBroadcastReceivers();
}
@Override
public void onDestroy() {
LogHelper.i("MainActivityFragment", "onDestroy");
super.onDestroy();
}
@Override
public void onDestroyView() {
LogHelper.i("MainActivityFragment", "onDestroyView");
super.onDestroyView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// CASE TIMER
case R.id.menu_timer:
handleMenuSleepTimerClick();
return true;
// CASE ADD
case R.id.menu_add:
DialogAdd dialog = new DialogAdd(mActivity, mFolder);
dialog.show();
return true;
// CASE ABOUT
case R.id.menu_about:
// get title and content
String aboutTitle = mActivity.getString(R.string.header_about);
// put title and content into intent and start activity
Intent aboutIntent = new Intent(mActivity, InfosheetActivity.class);
aboutIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_TITLE, aboutTitle);
aboutIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_CONTENT, TransistorKeys.INFOSHEET_CONTENT_ABOUT);
startActivity(aboutIntent);
return true;
// CASE HOWTO
case R.id.menu_howto:
// get title and content
String howToTitle = mActivity.getString(R.string.header_howto);
// put title and content into intent and start activity
Intent howToIntent = new Intent(mActivity, InfosheetActivity.class);
howToIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_TITLE, howToTitle);
howToIntent.putExtra(TransistorKeys.EXTRA_INFOSHEET_CONTENT, TransistorKeys.INFOSHEET_CONTENT_HOWTO);
startActivity(howToIntent);
return true;
// CASE menu_grid_view
case R.id.menu_grid_view:
//change the view
mRecyclerView.setLayoutManager(mStaggeredGridLayoutManagerManager);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_GRID);
editor.apply();
return true;
// CASE menu_grid_view
case R.id.menu_list_view:
//change the view
mRecyclerView.setLayoutManager(mLayoutManager);
SharedPreferences settings_v = PreferenceManager.getDefaultSharedPreferences(mActivity);
SharedPreferences.Editor editor_v = settings_v.edit();
editor_v.putInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST);
editor_v.apply();
return true;
// CASE DEFAULT
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
LogHelper.i("MainActivityFragment", "onSaveInstanceState");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mListState = mLayoutManager.onSaveInstanceState();
} else {
// save list view position
mListState = mStaggeredGridLayoutManagerManager.onSaveInstanceState();
}
outState.putParcelable(TransistorKeys.INSTANCE_LIST_STATE, mListState);
super.onSaveInstanceState(outState);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
LogHelper.i("MainActivityFragment", "onRequestPermissionsResult");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case TransistorKeys.PERMISSION_REQUEST_IMAGE_PICKER_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted - get system picker for images
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
mActivity.startActivityForResult(pickImageIntent, TransistorKeys.REQUEST_LOAD_IMAGE);
} else {
// permission denied
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_permission_denied) + " READ_EXTERNAL_STORAGE", Toast.LENGTH_LONG).show();
}
break;
}
case TransistorKeys.PERMISSION_REQUEST_STATION_FETCHER_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted - fetch station from given Uri
fetchNewStation(mNewStationUri);
} else {
// permission denied
Toast.makeText(mActivity, mActivity.getString(R.string.toastalert_permission_denied) + " READ_EXTERNAL_STORAGE", Toast.LENGTH_LONG).show();
}
break;
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
LogHelper.i("MainActivityFragment", "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
// retrieve selected image Uri from image picker
Uri newImageUri = null;
if (null != data) {
newImageUri = data.getData();
}
if (requestCode == TransistorKeys.REQUEST_LOAD_IMAGE && resultCode == Activity.RESULT_OK && newImageUri != null) {
ImageHelper imageHelper = new ImageHelper(newImageUri, mActivity, 500, 500);
Bitmap newImage = imageHelper.getInputImage();
if (newImage != null && mTempStationID_Position != -1) {
// write image to storage
File stationImageFile = mTempStation.getStationImageFileReference(mFolder);//get station file with correct path according to UniqueID of the station
try (FileOutputStream out = new FileOutputStream(stationImageFile)) {
newImage.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
//remve image from fresco cache
ImagePipeline imagePipeline = Fresco.getImagePipeline();
imagePipeline.evictFromCache(Uri.parse(stationImageFile.toURI().toString()));
} catch (IOException e) {
LogHelper.e(LOG_TAG, "Unable to save: " + newImage.toString());
}
// update adapter
mCollectionAdapter.notifyItemChanged(mTempStationID_Position);
Toast.makeText(mApplication, "Image Updated", Toast.LENGTH_SHORT).show();
} else {
LogHelper.e(LOG_TAG, "Unable to get image from media picker. Uri was: " + newImageUri.toString());
}
} else {
LogHelper.e(LOG_TAG, "Unable to get image from media picker. Did not receive an Uri");
}
}
/* Show or hide call to action view if necessary */
private void toggleActionCall() {
// show call to action, if necessary
if (mCollectionAdapter.getItemCount() == 0) {
mRelativeEmptyView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
if (mTwoPane && mActivity instanceof MainActivity) {
((MainActivity) mActivity).removePlayFragment();
}
} else {
mRelativeEmptyView.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
Boolean initialDataLoaded = settings.getBoolean(TransistorKeys.PREF_INITIAL_DATA_LOADED, false);
if (!initialDataLoaded) {
mButtonRefreshInitDataView.setVisibility(View.VISIBLE);
} else {
mButtonRefreshInitDataView.setVisibility(View.GONE);
}
}
/* Check permissions and start image picker */
private void selectFromImagePicker() {
// request read permissions
PermissionHelper permissionHelper = new PermissionHelper(mActivity, mRootView);
if (permissionHelper.requestReadExternalStorage(TransistorKeys.PERMISSION_REQUEST_IMAGE_PICKER_READ_EXTERNAL_STORAGE)) {
// get system picker for images
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, TransistorKeys.REQUEST_LOAD_IMAGE);
}
}
/* Handles tap on streaming link */
private void handleStreamingLink(Intent intent) {
mNewStationUri = intent.getData();
// clear the intent
intent.setAction("");
// check for null and type "http"
if (mNewStationUri != null && mNewStationUri.getScheme().startsWith("http")) {
// download and add new station
fetchNewStation(mNewStationUri);
} else if (mNewStationUri != null && mNewStationUri.getScheme().startsWith("file")) {
// check for read permission
PermissionHelper permissionHelper = new PermissionHelper(mActivity, mRootView);
if (permissionHelper.requestReadExternalStorage(TransistorKeys.PERMISSION_REQUEST_STATION_FETCHER_READ_EXTERNAL_STORAGE)) {
// read and add new station
fetchNewStation(mNewStationUri);
}
}
// unsuccessful - log failure
else {
LogHelper.v(LOG_TAG, "Received an empty intent");
}
}
/* Handles intent to show player from notification or from shortcut */
private void handleShowPlayer(Intent intent) {
// get station from intent
Station station = null;
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get station from notification
station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
} else if (intent.hasExtra(TransistorKeys.EXTRA_STREAM_URI)) {
// get Uri of station from home screen shortcut
station = mCollectionAdapter.findStation(Uri.parse(intent.getStringExtra(TransistorKeys.EXTRA_STREAM_URI)));
} else if (intent.hasExtra(TransistorKeys.EXTRA_LAST_STATION) && intent.getBooleanExtra(TransistorKeys.EXTRA_LAST_STATION, false)) {
// try to get last station
loadAppState(mActivity);
long station_IDLast = SingletonProperties.getInstance().getLastRunningStation_ID();
if (station_IDLast > -1 && mCollectionAdapter.getItemCount() > 0) {
int posTmp = mCollectionAdapter.getItemPosition(station_IDLast);
if (posTmp > -1) {
station = mCollectionAdapter.getStation(posTmp);
}
}
}
if (station == null) {
Toast.makeText(mActivity, getString(R.string.toastalert_station_not_found), Toast.LENGTH_LONG).show();
}
// get playback action from intent
boolean startPlayback;
if (intent.hasExtra(TransistorKeys.EXTRA_PLAYBACK_STATE)) {
startPlayback = intent.getBooleanExtra(TransistorKeys.EXTRA_PLAYBACK_STATE, false);
} else {
startPlayback = false;
}
// prepare arguments or intent
if (mTwoPane && station != null) {
mCollectionAdapter.setStationIDSelected(mCollectionAdapter.getItemPosition(station._ID), station.getPlaybackState(), startPlayback);
} else if (station != null) {
// start player activity - on phone
Intent playerIntent = new Intent(mActivity, PlayerActivity.class);
playerIntent.setAction(TransistorKeys.ACTION_SHOW_PLAYER);
playerIntent.putExtra(TransistorKeys.EXTRA_STATION, station);
playerIntent.putExtra(TransistorKeys.EXTRA_PLAYBACK_STATE, startPlayback);
startActivity(playerIntent);
}
}
/* Handles tap timer icon in actionbar */
private void handleMenuSleepTimerClick() {
// load app state
loadAppState(mActivity);
// set duration
long duration = 900000; // equals 15 minutes
// CASE: No station is playing, no timer is running
if (!mPlayback && !mSleepTimerRunning) {
// unable to start timer
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_start_unable), Toast.LENGTH_SHORT).show();
}
// CASE: A station is playing, no sleep timer is running
else if (mPlayback && !mSleepTimerRunning) {
startSleepTimer(duration);
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_activated), Toast.LENGTH_SHORT).show();
}
// CASE: A station is playing, Sleep timer is running
else if (mPlayback) {
startSleepTimer(duration);
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_duration_increased) + " [+" + getReadableTime(duration) + "]", Toast.LENGTH_SHORT).show();
}
}
/* Starts timer service and notification */
private void startSleepTimer(long duration) {
// start timer service
if (mSleepTimerService == null) {
mSleepTimerService = new SleepTimerService();
}
mSleepTimerService.startActionStart(mActivity, duration);
// show timer notification
showSleepTimerNotification(duration);
mSleepTimerRunning = true;
LogHelper.v(LOG_TAG, "Starting timer service and notification.");
}
/* Stops timer service and notification */
private void stopSleepTimer() {
// stop timer service
if (mSleepTimerService != null) {
mSleepTimerService.startActionStop(mActivity);
}
// cancel notification
if (mSleepTimerNotification != null && mSleepTimerNotification.isShown()) {
mSleepTimerNotification.dismiss();
}
mSleepTimerRunning = false;
LogHelper.v(LOG_TAG, "Stopping timer service and notification.");
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_cancelled), Toast.LENGTH_SHORT).show();
}
/* Shows notification for a running sleep timer */
private void showSleepTimerNotification(long remainingTime) {
// set snackbar message
String message;
if (remainingTime > 0) {
message = mSleepTimerNotificationMessage + getReadableTime(remainingTime);
} else {
message = mSleepTimerNotificationMessage;
}
// show snackbar
mSleepTimerNotification = Snackbar.make(mRootView, message, Snackbar.LENGTH_INDEFINITE);
mSleepTimerNotification.setAction(R.string.dialog_generic_button_cancel, new View.OnClickListener() {
@Override
public void onClick(View view) {
// stop sleep timer service
mSleepTimerService.startActionStop(mActivity);
mSleepTimerRunning = false;
saveAppState(mActivity);
// notify user
Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_timer_cancelled), Toast.LENGTH_SHORT).show();
LogHelper.v(LOG_TAG, "Sleep timer cancelled.");
}
});
mSleepTimerNotification.show();
}
/* Translates milliseconds into minutes and seconds */
private String getReadableTime(long remainingTime) {
return String.format(Locale.getDefault(), "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(remainingTime),
TimeUnit.MILLISECONDS.toSeconds(remainingTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)));
}
/* Loads app state from preferences */
private void loadAppState(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
mStationIDSelected = settings.getInt(TransistorKeys.PREF_STATION_ID_SELECTED, 0);
mPlayback = settings.getBoolean(TransistorKeys.PREF_PLAYBACK, false);
mTwoPane = settings.getBoolean(TransistorKeys.PREF_TWO_PANE, false);
mSleepTimerRunning = settings.getBoolean(TransistorKeys.PREF_TIMER_RUNNING, false);
mLayoutViewManager = settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST);
LogHelper.v(LOG_TAG, "Loading state (" + SingletonProperties.getInstance().CurrentSelectedStation_ID + " / " + SingletonProperties.getInstance().getLastRunningStation_ID() + " / " + mPlayback + ")");
}
/* Saves app state to SharedPreferences */
private void saveAppState(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(TransistorKeys.PREF_STATION_ID_CURRENTLY_PLAYING, SingletonProperties.getInstance().CurrentSelectedStation_ID);
editor.putBoolean(TransistorKeys.PREF_PLAYBACK, mPlayback);
editor.putBoolean(TransistorKeys.PREF_TIMER_RUNNING, mSleepTimerRunning);
editor.apply();
LogHelper.v(LOG_TAG, "Saving state (" + SingletonProperties.getInstance().CurrentSelectedStation_ID + " / " + SingletonProperties.getInstance().getLastRunningStation_ID() + " / " + mPlayback + ")");
}
/* Fetch new station with given Uri */
private void fetchNewStation(Uri stationUri) {
// download and add new station
StationFetcher stationFetcher = new StationFetcher(mActivity, mFolder, stationUri);
stationFetcher.execute();
}
/* Initializes broadcast receivers for onCreate */
private void initializeBroadcastReceivers() {
// RECEIVER: state of playback has changed
mPlaybackStateChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(TransistorKeys.EXTRA_PLAYBACK_STATE_CHANGE)) {
handlePlaybackStateChanges(intent);
}
}
};
IntentFilter playbackStateChangedIntentFilter = new IntentFilter(TransistorKeys.ACTION_PLAYBACK_STATE_CHANGED);
LocalBroadcastManager.getInstance(mActivity).registerReceiver(mPlaybackStateChangedReceiver, playbackStateChangedIntentFilter);
// RECEIVER: station added, deleted, or changed
mCollectionChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.hasExtra(TransistorKeys.EXTRA_COLLECTION_CHANGE)) {
handleCollectionChanges(intent);
}
}
};
IntentFilter collectionChangedIntentFilter = new IntentFilter(TransistorKeys.ACTION_COLLECTION_CHANGED);
LocalBroadcastManager.getInstance(mApplication).registerReceiver(mCollectionChangedReceiver, collectionChangedIntentFilter);
// RECEIVER: listen for request to change station image
mImageChangeRequestReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get station and id from intent
mTempStation = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
mTempStationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, -1);
// start image picker
selectFromImagePicker();
}
}
};
IntentFilter imageChangeRequestIntentFilter = new IntentFilter(TransistorKeys.ACTION_IMAGE_CHANGE_REQUESTED);
LocalBroadcastManager.getInstance(mApplication).registerReceiver(mImageChangeRequestReceiver, imageChangeRequestIntentFilter);
// RECEIVER: sleep timer service sends updates
mSleepTimerStartedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// get duration from intent
long remaining = intent.getLongExtra(TransistorKeys.EXTRA_TIMER_REMAINING, 0);
if (mSleepTimerNotification != null && remaining > 0) {
// update existing notification
mSleepTimerNotification.setText(mSleepTimerNotificationMessage + getReadableTime(remaining));
} else if (mSleepTimerNotification != null) {
// cancel notification
mSleepTimerNotification.dismiss();
// save state and update user interface
mPlayback = false;
mSleepTimerRunning = false;
saveAppState(mActivity);
}
}
};
IntentFilter sleepTimerIntentFilter = new IntentFilter(TransistorKeys.ACTION_TIMER_RUNNING);
LocalBroadcastManager.getInstance(mActivity).registerReceiver(mSleepTimerStartedReceiver, sleepTimerIntentFilter);
}
/* Unregisters broadcast receivers */
private void unregisterBroadcastReceivers() {
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mPlaybackStateChangedReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mCollectionChangedReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mImageChangeRequestReceiver);
LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(mSleepTimerStartedReceiver);
}
/* Handles changes in state of playback, eg. start, stop, loading stream */
private void handlePlaybackStateChanges(Intent intent) {
switch (intent.getIntExtra(TransistorKeys.EXTRA_PLAYBACK_STATE_CHANGE, 1)) {
// CASE: playback was stopped
case TransistorKeys.PLAYBACK_STOPPED:
// load app state
loadAppState(mActivity);
// stop sleep timer
if (mSleepTimerRunning && mSleepTimerService != null) {
stopSleepTimer();
}
break;
}
}
/* Handles adding, deleting and renaming of station */
private void handleCollectionChanges(Intent intent) {
// load app state
loadAppState(mActivity);
int newStationPosition = 0;
switch (intent.getIntExtra(TransistorKeys.EXTRA_COLLECTION_CHANGE, 1)) {
// CASE: station was added
case TransistorKeys.STATION_ADDED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get station from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
// add station to adapter, scroll to new position and update adapter
if (station != null && station.StreamURI != null && station.TITLE != null) {
newStationPosition = mCollectionAdapter.add(station);
} else if (intent.hasExtra(TransistorKeys.EXTRA_STATIONS)) {
//this is added as a batch from XML
ArrayList<Station> mInsertedStations = intent.getParcelableArrayListExtra(TransistorKeys.EXTRA_STATIONS);
if (mInsertedStations != null && mInsertedStations.size() > 0) {
for (int i = 0; i < mInsertedStations.size(); i++) {
newStationPosition = mCollectionAdapter.add(mInsertedStations.get(i));
}
}
}
if (mCollectionAdapter.getItemCount() > 0) {
toggleActionCall();
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
// CASE: station was renamed
case TransistorKeys.STATION_RENAMED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION_NEW_NAME) && intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get new name, station and station ID from intent
String newStationName = intent.getStringExtra(TransistorKeys.EXTRA_STATION_NEW_NAME);
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stationID_Position, null, null);
}
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.rename(newStationName, station, stationID_Position);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
case TransistorKeys.STATION_CHANGED_FAVORIT:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION_FAVORIT_VALUE) && intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get new Fav Value, station and station ID from intent
int newStationFavoritValue = intent.getIntExtra(TransistorKeys.EXTRA_STATION_FAVORIT_VALUE, 0);
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID_Position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.changeFavoritValue(newStationFavoritValue, station, stationID_Position);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
mCollectionAdapter.notifyDataSetChanged();
}
break;
case TransistorKeys.STATION_CHANGED_RATING:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION)) {
// get new name, station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stPossition = mCollectionAdapter.getItemPosition(station._ID);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stPossition, null, null);
}
// change station within in adapter, scroll to new position and update adapter
newStationPosition = mCollectionAdapter.updateItemAtPosition(station, stPossition);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(stPossition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(stPossition);
}
mCollectionAdapter.setStationIDSelected(stPossition, mPlayback, false);
// change station within in adapter, scroll to new position and update adapter
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
case TransistorKeys.STATION_CHANGED_IMAGE:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_DB_ID)) {
// get new name, station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stationID = intent.getIntExtra(TransistorKeys.EXTRA_STATION_DB_ID, 0);
int stPossition = mCollectionAdapter.getItemPosition(stationID);
// update notification
if (station.getPlaybackState()) {
NotificationHelper.update(station, stPossition, null, null);
}
// change station within in adapter, scroll to new position and update adapter
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
// CASE: station was deleted
case TransistorKeys.STATION_DELETED:
if (intent.hasExtra(TransistorKeys.EXTRA_STATION) && intent.hasExtra(TransistorKeys.EXTRA_STATION_Position_ID)) {
// get station and station ID from intent
Station station = intent.getParcelableExtra(TransistorKeys.EXTRA_STATION);
int stPossition = mCollectionAdapter.getItemPosition(station._ID);
int stationID_position = intent.getIntExtra(TransistorKeys.EXTRA_STATION_Position_ID, 0);
// dismiss notification
NotificationHelper.stop();
if (station.getPlaybackState()) {
// stop player service and notification using intent
Intent i = new Intent(mActivity, PlayerService.class);
i.setAction(TransistorKeys.ACTION_DISMISS);
mActivity.startService(i);
LogHelper.v(LOG_TAG, "Stopping player service.");
}
// remove station from adapter and update
newStationPosition = mCollectionAdapter.delete(station);
if (newStationPosition == -1 || mCollectionAdapter.getItemCount() == 0) {
// show call to action
toggleActionCall();
} else {
// scroll to new position
mCollectionAdapter.setStationIDSelected(newStationPosition, mPlayback, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mActivity);
if (settings.getInt(TransistorKeys.PREF_LAYOUT_VIEW_MANAGER, RECYCLER_VIEW_LIST) == RECYCLER_VIEW_LIST) {
// save list view position
mLayoutManager.scrollToPosition(newStationPosition);
} else {
// save list view position
mStaggeredGridLayoutManagerManager.scrollToPosition(newStationPosition);
}
}
//mCollectionAdapter.notifyItemRemoved(stPossition); //not working well (try to know why)
mCollectionAdapter.notifyItemChanged(stPossition);
}
break;
}
}
}
| 48,434 | 0.639489 | 0.637362 | 1,083 | 43.722069 | 36.130386 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577101 | false | false |
12
|
dc7afc0021fd658616a3b3c481814d97f3b90672
| 28,750,511,127,857 |
11c1c0bccc1da8aba7cc597333f5eed3f7031f3a
|
/src/main/java/exception/GitCommandErrorException.java
|
2b74a3e41c2e0ce66f8509da5b7ff5144837ad74
|
[] |
no_license
|
ken-wang/multi-git-java
|
https://github.com/ken-wang/multi-git-java
|
3ae19114b1bb9c2a747c903a76696044db735710
|
b4a30cfe812e390bcf6746afeab514ce2b77ea79
|
refs/heads/master
| 2021-07-18T01:19:33.969000 | 2017-10-25T15:48:35 | 2017-10-25T15:48:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package exception;
public class GitCommandErrorException extends RuntimeException {
private static final String errorMsg = "' %s' is not a correct git command.";
public GitCommandErrorException(String cmd) {
super(String.format(errorMsg, cmd));
}
}
|
UTF-8
|
Java
| 263 |
java
|
GitCommandErrorException.java
|
Java
|
[] | null |
[] |
package exception;
public class GitCommandErrorException extends RuntimeException {
private static final String errorMsg = "' %s' is not a correct git command.";
public GitCommandErrorException(String cmd) {
super(String.format(errorMsg, cmd));
}
}
| 263 | 0.749049 | 0.749049 | 11 | 22.90909 | 28.134272 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
12
|
f132901aa0988592d57277d48f547c6d12966bd2
| 5,111,011,095,042 |
ad049dabb1ce5a819f521e36674506cbe660ecfc
|
/app/src/main/java/br/edu/ifba/mlabs/injection/component/AppComponent.java
|
3ffcff4d1d58177d46cb8fb1e00411532c516cdb
|
[] |
no_license
|
silasrs/mlabs-experiences-android
|
https://github.com/silasrs/mlabs-experiences-android
|
ec98c18aaa937ac26cd78a3d2a84a219461e24e3
|
465c274d03a5d6a82fc6e412cc8aa68b67c2b93e
|
refs/heads/master
| 2019-06-14T15:07:14.260000 | 2016-05-18T21:20:25 | 2016-05-18T21:20:25 | 57,148,588 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.edu.ifba.mlabs.injection.component;
import javax.inject.Singleton;
import br.edu.ifba.mlabs.data.DataManager;
import br.edu.ifba.mlabs.injection.module.AppModule;
import dagger.Component;
/**
*
*/
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
DataManager dataManager();
}
|
UTF-8
|
Java
| 327 |
java
|
AppComponent.java
|
Java
|
[] | null |
[] |
package br.edu.ifba.mlabs.injection.component;
import javax.inject.Singleton;
import br.edu.ifba.mlabs.data.DataManager;
import br.edu.ifba.mlabs.injection.module.AppModule;
import dagger.Component;
/**
*
*/
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
DataManager dataManager();
}
| 327 | 0.7737 | 0.7737 | 16 | 19.4375 | 18.316553 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
12
|
304f6f9fcddec01baf53214e01b52c54adf41339
| 1,116,691,505,081 |
7ba4d40598001b875ccd164c529f10d4f3315b40
|
/src/main/java/com/jgp/ljoa/hr/service/EmployeeService.java
|
4de372ad734bc7f32f624c2b707dba7a9190b600
|
[] |
no_license
|
AIRUISONG/ljoa
|
https://github.com/AIRUISONG/ljoa
|
5d2e39a3183d54d5e5c49dd4ce3f5525e319e4ad
|
9e1bde9efc600cfe6ff1a769fd4cd93b225367dc
|
refs/heads/master
| 2020-05-09T21:22:26.193000 | 2019-04-15T08:10:29 | 2019-04-15T08:10:29 | 181,437,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jgp.ljoa.hr.service;
import com.jgp.common.pojo.LabelValue;
import com.jgp.ljoa.hr.model.Employee;
import com.jgp.sys.ui.Pager;
import java.io.File;
import java.util.List;
/**
* 项目 ljoa
* 作者 liujinxu
* 时间 2018/7/5
*/
public interface EmployeeService {
/*
* 条件查询员工信息
* */
List<Employee> queryGroupEmployee(Employee employee, Pager pager);
List<Employee> queryGroupEmployeeByEmployeeType(Employee employee, Pager pager);
/*
* 查询单个员工
* */
Employee queryOneEmployee(String id);
/*
* 根据账号查询员工
* */
Employee queryOneEmployeeByAccount(String account);
/*
* 保存员工信息
* */
Employee saveEmployee(Employee employee, String orgId);
/*
* 保存员工信息
* */
Employee saveEmployee(Employee employee);
/*
* 删除单个员工
* */
void removeOneEmployee(String id);
/*
* 批量删除员工
* */
void removeSelectedEmployee(String[] array);
/*
* 全查
* */
List<Employee> queryAllEmployee();
/*
* 根据部门id查询该部门的所有员工,并组装成labelValue
* */
List<LabelValue> queryEmployeeByOrgId(String orgId);
/*
* 查询当前登陆用户的信息
* */
Employee queryCurrentEmployee();
/*
* 批量导入员工信息
* */
void importData(File file) throws Exception;
}
|
UTF-8
|
Java
| 1,455 |
java
|
EmployeeService.java
|
Java
|
[
{
"context": ";\nimport java.util.List;\n\n/**\n * 项目 ljoa\n * 作者 liujinxu\n * 时间 2018/7/5\n */\npublic interface EmployeeSer",
"end": 220,
"score": 0.9994537830352783,
"start": 212,
"tag": "USERNAME",
"value": "liujinxu"
}
] | null |
[] |
package com.jgp.ljoa.hr.service;
import com.jgp.common.pojo.LabelValue;
import com.jgp.ljoa.hr.model.Employee;
import com.jgp.sys.ui.Pager;
import java.io.File;
import java.util.List;
/**
* 项目 ljoa
* 作者 liujinxu
* 时间 2018/7/5
*/
public interface EmployeeService {
/*
* 条件查询员工信息
* */
List<Employee> queryGroupEmployee(Employee employee, Pager pager);
List<Employee> queryGroupEmployeeByEmployeeType(Employee employee, Pager pager);
/*
* 查询单个员工
* */
Employee queryOneEmployee(String id);
/*
* 根据账号查询员工
* */
Employee queryOneEmployeeByAccount(String account);
/*
* 保存员工信息
* */
Employee saveEmployee(Employee employee, String orgId);
/*
* 保存员工信息
* */
Employee saveEmployee(Employee employee);
/*
* 删除单个员工
* */
void removeOneEmployee(String id);
/*
* 批量删除员工
* */
void removeSelectedEmployee(String[] array);
/*
* 全查
* */
List<Employee> queryAllEmployee();
/*
* 根据部门id查询该部门的所有员工,并组装成labelValue
* */
List<LabelValue> queryEmployeeByOrgId(String orgId);
/*
* 查询当前登陆用户的信息
* */
Employee queryCurrentEmployee();
/*
* 批量导入员工信息
* */
void importData(File file) throws Exception;
}
| 1,455 | 0.619197 | 0.614477 | 74 | 16.175676 | 18.832375 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283784 | false | false |
12
|
d4dbf9c0e74df805f2029135c113b06eb8daf0ae
| 26,156,350,890,446 |
9be38be86e9e636776468a2a01b9b513de314458
|
/Torpedo/src/etri/sdn/controller/module/ml2/NetworkConfiguration.java
|
a76068c13ed8fa13416ad8260f6dbf8b596469d9
|
[
"Apache-2.0"
] |
permissive
|
uni2u/iNaaS
|
https://github.com/uni2u/iNaaS
|
118215f6622c097b51092fa02f687cb6c79e1676
|
f9deda42abb661932586ce53aa5da397b2779077
|
refs/heads/master
| 2021-01-10T18:46:05.668000 | 2020-07-28T01:16:57 | 2020-07-28T01:16:57 | 25,452,679 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package etri.sdn.controller.module.ml2;
import java.util.Arrays;
import etri.sdn.controller.OFModel;
class NetworkConfiguration extends OFModel {
private OFMOpenstackML2Connector parent = null;
private RESTApi[] apis = null;
public NetworkConfiguration(OFMOpenstackML2Connector parent)
{
this.parent = parent;
this.apis = Arrays.asList(
new RESTApi(RestNetwork.neutronNetAll, new RestNetwork(this)),
new RESTApi(RestNetwork.neutronNet, new RestNetwork(this)),
new RESTApi(RestNetwork.neutronNetIRIS, new RestNetwork(this)),
new RESTApi(RestPort.neutronPortAll, new RestPort(this)),
new RESTApi(RestPort.neutronPort, new RestPort(this)),
new RESTApi(RestPort.neutronPortIRIS, new RestPort(this)),
new RESTApi(RestSubnet.neutronSubnetAll, new RestSubnet(this)),
new RESTApi(RestSubnet.neutronSubnet, new RestSubnet(this)),
new RESTApi(RestSubnet.neutronSubnetIRIS, new RestSubnet(this))
).toArray( new RESTApi[0] );
}
OFMOpenstackML2Connector getModule() {
return this.parent;
}
@Override
public RESTApi[] getAllRestApi() {
return this.apis;
}
}
|
UTF-8
|
Java
| 1,100 |
java
|
NetworkConfiguration.java
|
Java
|
[] | null |
[] |
package etri.sdn.controller.module.ml2;
import java.util.Arrays;
import etri.sdn.controller.OFModel;
class NetworkConfiguration extends OFModel {
private OFMOpenstackML2Connector parent = null;
private RESTApi[] apis = null;
public NetworkConfiguration(OFMOpenstackML2Connector parent)
{
this.parent = parent;
this.apis = Arrays.asList(
new RESTApi(RestNetwork.neutronNetAll, new RestNetwork(this)),
new RESTApi(RestNetwork.neutronNet, new RestNetwork(this)),
new RESTApi(RestNetwork.neutronNetIRIS, new RestNetwork(this)),
new RESTApi(RestPort.neutronPortAll, new RestPort(this)),
new RESTApi(RestPort.neutronPort, new RestPort(this)),
new RESTApi(RestPort.neutronPortIRIS, new RestPort(this)),
new RESTApi(RestSubnet.neutronSubnetAll, new RestSubnet(this)),
new RESTApi(RestSubnet.neutronSubnet, new RestSubnet(this)),
new RESTApi(RestSubnet.neutronSubnetIRIS, new RestSubnet(this))
).toArray( new RESTApi[0] );
}
OFMOpenstackML2Connector getModule() {
return this.parent;
}
@Override
public RESTApi[] getAllRestApi() {
return this.apis;
}
}
| 1,100 | 0.765455 | 0.760909 | 37 | 28.729731 | 25.138157 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.972973 | false | false |
12
|
0d009b2be36ff483b769da20bdcd74b3c4a37570
| 7,773,890,808,622 |
a7026215dd9d083c0e62b5316736018c78725085
|
/base/src/main/java/com/activiti/base/entity/DelegateRule.java
|
4e9fd19599ead1c5e127879da8b562026eaa7061
|
[] |
no_license
|
zikkorn/finalpj
|
https://github.com/zikkorn/finalpj
|
fdecdb4eebe62d5b41c8d199104e7ce1a0708020
|
2e118366768796147994d58c8c454567f39d9859
|
refs/heads/master
| 2020-04-22T13:59:59.362000 | 2019-02-13T02:58:47 | 2019-02-13T02:59:32 | 170,428,450 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.activiti.base.entity;
import java.io.Serializable;
/**
* 委托规则
*
*/
public class DelegateRule implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6982625425057579427L;
//规则id
private String ruleId;
//规则名称
private String ruleName;
//规则key
private String ruleKey;
//值
private String ruleValue;
//类型
private String ruleType;
//运算符
private String ruleOperator;
//委托记录id
private String delegateId;
public String getRuleId() {
return ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getRuleKey() {
return ruleKey;
}
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public String getRuleOperator() {
return ruleOperator;
}
public void setRuleOperator(String ruleOperator) {
this.ruleOperator = ruleOperator;
}
public String getDelegateId() {
return delegateId;
}
public void setDelegateId(String delegateId) {
this.delegateId = delegateId;
}
}
|
UTF-8
|
Java
| 1,430 |
java
|
DelegateRule.java
|
Java
|
[] | null |
[] |
package com.activiti.base.entity;
import java.io.Serializable;
/**
* 委托规则
*
*/
public class DelegateRule implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6982625425057579427L;
//规则id
private String ruleId;
//规则名称
private String ruleName;
//规则key
private String ruleKey;
//值
private String ruleValue;
//类型
private String ruleType;
//运算符
private String ruleOperator;
//委托记录id
private String delegateId;
public String getRuleId() {
return ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getRuleKey() {
return ruleKey;
}
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public String getRuleOperator() {
return ruleOperator;
}
public void setRuleOperator(String ruleOperator) {
this.ruleOperator = ruleOperator;
}
public String getDelegateId() {
return delegateId;
}
public void setDelegateId(String delegateId) {
this.delegateId = delegateId;
}
}
| 1,430 | 0.723665 | 0.709957 | 73 | 17.986301 | 16.115587 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.369863 | false | false |
12
|
cbbacb840e208a10c79f1807ce5b1226d19c0845
| 2,929,167,760,987 |
381a0d6a5a1f81d4e2a90413599aeac3bee2f07f
|
/lab10/src/ShapeList.java
|
7ffada2197abb466313d3250d2914a0665687748
|
[] |
no_license
|
ErikBjare/ptdc-workspace
|
https://github.com/ErikBjare/ptdc-workspace
|
77d15f0bd73fc84b26464976cb2662af8c57dfd2
|
23fa0ab9dee91686dc4130234a4ed2b3170e9513
|
refs/heads/master
| 2020-05-30T20:37:36.628000 | 2013-12-06T09:04:42 | 2013-12-06T09:04:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import se.lth.cs.ptdc.shapes.Shape;
import se.lth.cs.ptdc.window.SimpleWindow;
import java.util.ArrayList;
public class ShapeList extends ArrayList<Shape> {
/**
* Skapar en tom lista.
*/
public ShapeList() {
super();
}
/**
* Lägger in en figur i listan.
*
* @param s
* figuren som ska läggas in i listan
*/
public void insert(Shape s) {
add(s);
}
/**
* Ritar upp figurerna i listan.
*
* @param w
* fönstret där figurerna ritas
*/
public void draw(SimpleWindow w) {
for(Shape s : this) {
s.draw(w);
}
}
/**
* Tar reda på en figur som ligger nära punkten xc,yc. Om flera figurer
* ligger nära så returneras den första som hittas, om ingen figur ligger
* nära returneras null.
*
* @param xc
* x-koordinaten
* @param yc
* y-koordinaten
*/
public Shape findHit(int xc, int yc) {
for(Shape s : this) {
if(s.near(xc, yc)) {
return s;
}
}
return null;
}
}
|
UTF-8
|
Java
| 1,054 |
java
|
ShapeList.java
|
Java
|
[] | null |
[] |
import se.lth.cs.ptdc.shapes.Shape;
import se.lth.cs.ptdc.window.SimpleWindow;
import java.util.ArrayList;
public class ShapeList extends ArrayList<Shape> {
/**
* Skapar en tom lista.
*/
public ShapeList() {
super();
}
/**
* Lägger in en figur i listan.
*
* @param s
* figuren som ska läggas in i listan
*/
public void insert(Shape s) {
add(s);
}
/**
* Ritar upp figurerna i listan.
*
* @param w
* fönstret där figurerna ritas
*/
public void draw(SimpleWindow w) {
for(Shape s : this) {
s.draw(w);
}
}
/**
* Tar reda på en figur som ligger nära punkten xc,yc. Om flera figurer
* ligger nära så returneras den första som hittas, om ingen figur ligger
* nära returneras null.
*
* @param xc
* x-koordinaten
* @param yc
* y-koordinaten
*/
public Shape findHit(int xc, int yc) {
for(Shape s : this) {
if(s.near(xc, yc)) {
return s;
}
}
return null;
}
}
| 1,054 | 0.558429 | 0.558429 | 54 | 18.333334 | 17.785763 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.944444 | false | false |
12
|
25f98fd7335c8b1fd131ecda13f76aa3ec31badd
| 22,539,988,436,024 |
dfe269ff20e771474303fb7529bc56a39181084a
|
/4-Aviary/src/test/java/WorldPointTest.java
|
cb4b3c6a0d03828caa6e7e583b19f689c535d093
|
[] |
no_license
|
9999years/cosi12b
|
https://github.com/9999years/cosi12b
|
bb70c05f73b40564e04c2a60c5103a33b6314d95
|
de027d1dbd267e9432b68da204e0d34bb661c044
|
refs/heads/main
| 2022-12-24T07:24:13.034000 | 2017-12-10T07:50:22 | 2017-12-10T07:50:22 | 106,130,721 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.awt.Point;
public class WorldPointTest {
WorldPoint make(int x, int y) {
return new WorldPoint(new Point(x, y), Bird.AviarySize);
}
@Test
public void edgesTest() {
WorldPoint p;
p = make(0, 0);
assertTrue(p.onEdge());
assertTrue(p.onTopEdge());
assertTrue(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertTrue(p.onCorner());
// size - 1
p = make(19, 19);
assertTrue(p.onEdge());
assertFalse(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertTrue(p.onRightEdge());
assertTrue(p.onBottomEdge());
assertTrue(p.onCorner());
p = make(1, 1);
assertFalse(p.onEdge());
assertFalse(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertFalse(p.onHorizontalEdge());
assertFalse(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
p = make(5, 0);
assertTrue(p.onEdge());
assertTrue(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertFalse(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
p = make(0, 10);
assertTrue(p.onEdge());
assertFalse(p.onTopEdge());
assertTrue(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertFalse(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
}
}
|
UTF-8
|
Java
| 1,654 |
java
|
WorldPointTest.java
|
Java
|
[] | null |
[] |
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.awt.Point;
public class WorldPointTest {
WorldPoint make(int x, int y) {
return new WorldPoint(new Point(x, y), Bird.AviarySize);
}
@Test
public void edgesTest() {
WorldPoint p;
p = make(0, 0);
assertTrue(p.onEdge());
assertTrue(p.onTopEdge());
assertTrue(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertTrue(p.onCorner());
// size - 1
p = make(19, 19);
assertTrue(p.onEdge());
assertFalse(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertTrue(p.onRightEdge());
assertTrue(p.onBottomEdge());
assertTrue(p.onCorner());
p = make(1, 1);
assertFalse(p.onEdge());
assertFalse(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertFalse(p.onHorizontalEdge());
assertFalse(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
p = make(5, 0);
assertTrue(p.onEdge());
assertTrue(p.onTopEdge());
assertFalse(p.onLeftEdge());
assertFalse(p.onHorizontalEdge());
assertTrue(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
p = make(0, 10);
assertTrue(p.onEdge());
assertFalse(p.onTopEdge());
assertTrue(p.onLeftEdge());
assertTrue(p.onHorizontalEdge());
assertFalse(p.onVerticalEdge());
assertFalse(p.onRightEdge());
assertFalse(p.onBottomEdge());
assertFalse(p.onCorner());
}
}
| 1,654 | 0.692261 | 0.683797 | 65 | 24.446154 | 12.525703 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.446154 | false | false |
12
|
c245af582c3d182002d993963d96bb4fef42beb9
| 24,627,342,544,675 |
d593ad37a82a6396effceaf11679e70fddcabc06
|
/step/FontDemoB1/src/com/androidside/fontdemob1/FontDemoB1.java
|
5a448057be78024392a2eadfb372a645185c5204
|
[] |
no_license
|
psh667/android
|
https://github.com/psh667/android
|
8a18ea22c8c977852ba2cd9361a8489586e06f05
|
8f7394de8e26ce5106d9828cf95eb1617afca757
|
refs/heads/master
| 2018-12-27T23:30:46.988000 | 2013-09-09T13:16:46 | 2013-09-09T13:16:46 | 12,700,292 | 3 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.androidside.fontdemob1;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class FontDemoB1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.myfont);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/cour.ttf");
text.setTypeface(face);
}
}
|
UTF-8
|
Java
| 552 |
java
|
FontDemoB1.java
|
Java
|
[] | null |
[] |
package com.androidside.fontdemob1;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class FontDemoB1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.myfont);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/cour.ttf");
text.setTypeface(face);
}
}
| 552 | 0.706522 | 0.702899 | 18 | 29.722221 | 22.771341 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false |
12
|
47bc1e2e0a120fd07347da01820ac47afab34585
| 25,159,918,492,039 |
f9ef3159de3f7716452526ba96f5865ecfcc396e
|
/fastruntime/src/plaid/generated/IreplaceA_ll$2$plaid.java
|
0f8130611a01c35389115405415ed2bd08b7b9cd
|
[] |
no_license
|
AEminium/plaid-lang
|
https://github.com/AEminium/plaid-lang
|
f1e5f4f971effef05c03471091ed9cbbf4494ff2
|
7662acbddcf0db840ff209e4e4a85e08acf40e45
|
refs/heads/master
| 2021-01-19T03:35:53.390000 | 2015-04-11T16:17:07 | 2015-04-11T16:17:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package plaid.generated;
import plaid.fastruntime.PlaidObject;
public interface IreplaceA_ll$2$plaid{
PlaidObject replaceA_ll(PlaidObject receiver, PlaidObject arg0, PlaidObject arg1);
}
|
UTF-8
|
Java
| 189 |
java
|
IreplaceA_ll$2$plaid.java
|
Java
|
[] | null |
[] |
package plaid.generated;
import plaid.fastruntime.PlaidObject;
public interface IreplaceA_ll$2$plaid{
PlaidObject replaceA_ll(PlaidObject receiver, PlaidObject arg0, PlaidObject arg1);
}
| 189 | 0.825397 | 0.809524 | 7 | 26.142857 | 28.017487 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false |
12
|
751ee3d5bc26bb215b43e5705c6b28c389169a7f
| 4,741,643,897,188 |
b3e9357abf22f1f9056a3f468ebb8d98025a16d5
|
/app/src/main/java/com/gpaschos_aikmpel/hotelbeaconapplication/globalVars/Params.java
|
147a1eee43d7166f79b13e9d294a8c0c216282a5
|
[] |
no_license
|
ntelalis/HotelBeaconApplication
|
https://github.com/ntelalis/HotelBeaconApplication
|
266cb6e96119efdc017f8de34b87cf9df5927983
|
3daea85624cbec7e66cbb6cf18a11cf2068255e4
|
refs/heads/master
| 2021-01-24T09:33:29.400000 | 2019-01-27T21:48:29 | 2019-01-27T21:48:29 | 123,018,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gpaschos_aikmpel.hotelbeaconapplication.globalVars;
public class Params {
public static final int maxReservationDateInYears = 1;
public static final int daysForCheckInUnlock=0;
public static final int eligibleForCheckIn =2;
public static final int notEligibleForCheckIn =1;
public static final int eligibleForCheckOut =4;
public static final int notEligibleForCheckOut =3;
public static final int CheckedOut=5;
public static final String beaconUUID = "3d8f1dc0-1b23-42f5-9fc1-849f161b2c0e";
//hotel name
public static final String HotelName = "My Hotel";
public static final String HotelCheckoutTime = "12:00";
//beacon region Types
public static final String roomRegionType = "room";
//~~~~~~~~~~~~~~~~~Notifications~~~~~~~~~~~~~~~~~~~~~~
//check in- check out default times
public static final String defaultCheckInTime = "16:00";
public static final String defaultCheckOutTime = "12:00";
//channels
public static final String NOTIFICATION_CHANNEL_ID = "CHANNEL1";
public static final String NOTIFICATION_CHANNEL_NAME = "Default channel";
//welcome messages
public static final int notificationWelcomeID = 2;
public static final String notificationWelcomeTitle = "Welcome to ";
public static final String notificationWelcomeBackTitle = "Welcome back to ";
public static final String notificationWelcomeGreeting = "Dear ";
public static final String notificationWelcomeGreeting3 = ", we are delighted with the opportunity" +
" to have you as our guest. We wish you a pleasant stay.";
//farewell messages
public static final int notificationFarewellID = 5;
public static final String notificationFarewellTitle = "Goodbye";
public static final String notificationFarewellGreeting1 = "We thank you for your stay and hope " +
"that you had an enjoyable experience.";
//checkIn messages
public static final int notificationCheckInID = 3;
public static final int notificationCheckInReminderID = 1;
public static final String notificationCheckInReminderTitle = "Reminder for Check-in";
public static final String notificationCheckInTitle = "Check-in";
public static final String notificationCheckInReminderMsg = "You can check in for your reservation at ";
public static final String notificationCheckInReminderMsg2 = " whenever you are ready";
public static final String notificationCheckInMsg = "You can check-in using your smartphone to get" +
" your room number and key";
//checkOut messages
public static final int notificationCheckoutID = 4;
public static final String notificationCheckoutTitle = "Reminder for Check-out";
public static final String notificationCheckoutReminder = "You can check-out using your smartphone." +
"Just remember that check-out time is ";
//OFFERS messages
public static final int notificationOfferID = 6;
//Features
public static final String DOOR_UNLOCK = "doorUnlock";
public static final String WELCOME = "welcome";
public static final String FAREWELL = "farewell";
public static final String OFFER = "offer";
public static final String ROOM = "room";
public static final String TELEPHONE = "0123456789";
}
|
UTF-8
|
Java
| 3,318 |
java
|
Params.java
|
Java
|
[] | null |
[] |
package com.gpaschos_aikmpel.hotelbeaconapplication.globalVars;
public class Params {
public static final int maxReservationDateInYears = 1;
public static final int daysForCheckInUnlock=0;
public static final int eligibleForCheckIn =2;
public static final int notEligibleForCheckIn =1;
public static final int eligibleForCheckOut =4;
public static final int notEligibleForCheckOut =3;
public static final int CheckedOut=5;
public static final String beaconUUID = "3d8f1dc0-1b23-42f5-9fc1-849f161b2c0e";
//hotel name
public static final String HotelName = "My Hotel";
public static final String HotelCheckoutTime = "12:00";
//beacon region Types
public static final String roomRegionType = "room";
//~~~~~~~~~~~~~~~~~Notifications~~~~~~~~~~~~~~~~~~~~~~
//check in- check out default times
public static final String defaultCheckInTime = "16:00";
public static final String defaultCheckOutTime = "12:00";
//channels
public static final String NOTIFICATION_CHANNEL_ID = "CHANNEL1";
public static final String NOTIFICATION_CHANNEL_NAME = "Default channel";
//welcome messages
public static final int notificationWelcomeID = 2;
public static final String notificationWelcomeTitle = "Welcome to ";
public static final String notificationWelcomeBackTitle = "Welcome back to ";
public static final String notificationWelcomeGreeting = "Dear ";
public static final String notificationWelcomeGreeting3 = ", we are delighted with the opportunity" +
" to have you as our guest. We wish you a pleasant stay.";
//farewell messages
public static final int notificationFarewellID = 5;
public static final String notificationFarewellTitle = "Goodbye";
public static final String notificationFarewellGreeting1 = "We thank you for your stay and hope " +
"that you had an enjoyable experience.";
//checkIn messages
public static final int notificationCheckInID = 3;
public static final int notificationCheckInReminderID = 1;
public static final String notificationCheckInReminderTitle = "Reminder for Check-in";
public static final String notificationCheckInTitle = "Check-in";
public static final String notificationCheckInReminderMsg = "You can check in for your reservation at ";
public static final String notificationCheckInReminderMsg2 = " whenever you are ready";
public static final String notificationCheckInMsg = "You can check-in using your smartphone to get" +
" your room number and key";
//checkOut messages
public static final int notificationCheckoutID = 4;
public static final String notificationCheckoutTitle = "Reminder for Check-out";
public static final String notificationCheckoutReminder = "You can check-out using your smartphone." +
"Just remember that check-out time is ";
//OFFERS messages
public static final int notificationOfferID = 6;
//Features
public static final String DOOR_UNLOCK = "doorUnlock";
public static final String WELCOME = "welcome";
public static final String FAREWELL = "farewell";
public static final String OFFER = "offer";
public static final String ROOM = "room";
public static final String TELEPHONE = "0123456789";
}
| 3,318 | 0.730561 | 0.712779 | 73 | 44.452053 | 31.612396 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575342 | false | false |
12
|
c39d5690ada10ca46eb25799d5b400768583703b
| 25,460,566,200,413 |
6ede747a6315bbce5d22a22d87f201d00dd01cc6
|
/keepbusyapp/src/main/java/com/udinic/keepbusyapp/ReqReceiver.java
|
30c76eac99a5a327098ffbc2b5d289ec7020d9ab
|
[
"MIT"
] |
permissive
|
dongdaqing/PerformanceDemo
|
https://github.com/dongdaqing/PerformanceDemo
|
d4da9d3d2b30293122e63662a3d5912c8d4108b0
|
ded26093b45b12f7e5f30fb2db8a65fc5d1c1a87
|
refs/heads/master
| 2020-04-01T19:03:06.849000 | 2015-09-06T08:00:44 | 2015-09-06T08:00:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.udinic.keepbusyapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Broadcast receiver to start that service that will keep the cpu busy.
*
* Usage:
* adb shell am broadcast -a com.udinic.keepbusyapp.ACTION_KEEP_BUSY
*
*/
public class ReqReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("ReqReceiver", "Starting BusyService");
context.startService(new Intent(context, BusyService.class));
}
}
|
UTF-8
|
Java
| 594 |
java
|
ReqReceiver.java
|
Java
|
[] | null |
[] |
package com.udinic.keepbusyapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Broadcast receiver to start that service that will keep the cpu busy.
*
* Usage:
* adb shell am broadcast -a com.udinic.keepbusyapp.ACTION_KEEP_BUSY
*
*/
public class ReqReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("ReqReceiver", "Starting BusyService");
context.startService(new Intent(context, BusyService.class));
}
}
| 594 | 0.73569 | 0.73569 | 21 | 27.285715 | 25.833059 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false |
12
|
f1c2a2c1f71843d35fd8c72cfb1a236dc4818d1a
| 28,157,805,603,716 |
bdba56b1a74dee21a18d466f935a9039b0356847
|
/src/universidad/Universidad.java
|
dbd5e960a47446212af29c110c01420d758e55be
|
[] |
no_license
|
JGho00/TP2PARADIGMAS
|
https://github.com/JGho00/TP2PARADIGMAS
|
1fa7d7e49e494fff9f68a7066499c8c5697fb97b
|
a352ef04720fe7f22a464d662c26a0753cba51f8
|
refs/heads/master
| 2022-08-23T02:24:01.804000 | 2020-05-22T07:16:20 | 2020-05-22T07:16:20 | 266,014,121 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package universidad;
/**
*
* @author jose-
*/
public class Universidad {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Persona persona;
persona = new Persona();
persona.setNombre("Jose");
persona.setApellido("Gho");
persona.setNumeroDocumento(34);
System.out.println(persona);
Profesor profesor;
profesor = new Profesor();
}
}
|
UTF-8
|
Java
| 703 |
java
|
Universidad.java
|
Java
|
[
{
"context": "ditor.\n */\npackage universidad;\n\n/**\n *\n * @author jose-\n */\npublic class Universidad {\n\n /**\n * @p",
"end": 229,
"score": 0.9993459582328796,
"start": 225,
"tag": "USERNAME",
"value": "jose"
},
{
"context": "rsona = new Persona();\n persona.setNombre(\"Jose\");\n persona.setApellido(\"Gho\");\n pe",
"end": 459,
"score": 0.9996806979179382,
"start": 455,
"tag": "NAME",
"value": "Jose"
},
{
"context": "a.setNombre(\"Jose\");\n persona.setApellido(\"Gho\");\n persona.setNumeroDocumento(34);\n ",
"end": 495,
"score": 0.9997382164001465,
"start": 492,
"tag": "NAME",
"value": "Gho"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package universidad;
/**
*
* @author jose-
*/
public class Universidad {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Persona persona;
persona = new Persona();
persona.setNombre("Jose");
persona.setApellido("Gho");
persona.setNumeroDocumento(34);
System.out.println(persona);
Profesor profesor;
profesor = new Profesor();
}
}
| 703 | 0.577525 | 0.57468 | 34 | 19.67647 | 19.021227 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false |
12
|
5c4c2f5b3b96e0c0db9a982087507314cfaa0429
| 30,073,361,010,309 |
f36732e6c5e924b4c808cc1ab22840f8153fa66a
|
/src2/设计模式/工厂模式/工厂方法模式/order/PizzaStore.java
|
f4da824daa659c6b75c775471eb287ad5a90c049
|
[] |
no_license
|
dxh1220/dxh--xml-uml-sheji
|
https://github.com/dxh1220/dxh--xml-uml-sheji
|
c33888ffdb46f569e8057d05e5b8365f9216dfb8
|
58da0acbf86f10bafe4ee8ace0fe74bc62e72291
|
refs/heads/master
| 2022-10-13T23:08:18.297000 | 2020-06-10T06:23:37 | 2020-06-10T06:23:37 | 271,191,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package 设计模式.工厂模式.工厂方法模式.order;
import java.util.Scanner;
public class PizzaStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入pizza产地:");
String loc = in.next();
if (loc.equals("bj")) {
new BJOrderPizza();
} else if (loc.equals("ldo")){
new LDOrderPizza();
} else{
System.out.println("此地并没有分店");
}
}
}
|
UTF-8
|
Java
| 466 |
java
|
PizzaStore.java
|
Java
|
[] | null |
[] |
package 设计模式.工厂模式.工厂方法模式.order;
import java.util.Scanner;
public class PizzaStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入pizza产地:");
String loc = in.next();
if (loc.equals("bj")) {
new BJOrderPizza();
} else if (loc.equals("ldo")){
new LDOrderPizza();
} else{
System.out.println("此地并没有分店");
}
}
}
| 466 | 0.616505 | 0.616505 | 21 | 17.619047 | 14.70172 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false |
12
|
b99c850af69b560201374553b47bb9ece5acf3cf
| 5,858,335,454,485 |
e9b19e89f6c4cfe66f615b7c9eac988ee7180ccc
|
/src/main/java/com/ydcx/core/linkApi/entity/CyhUserInfo.java
|
046117ae9999718f94dc6629442764fc5cbb8542
|
[
"Apache-2.0"
] |
permissive
|
mywifesaber/ydcx
|
https://github.com/mywifesaber/ydcx
|
f94d69ceddfe91f17516c37f9ab26e6d9dd973a1
|
e7b752fe7e7daef5c2543bafbf83ca629d9c462c
|
refs/heads/master
| 2020-08-23T12:56:02.549000 | 2019-10-21T17:41:48 | 2019-10-21T17:41:48 | 216,620,536 | 0 | 0 |
Apache-2.0
| false | 2021-04-26T19:36:40 | 2019-10-21T16:58:45 | 2019-10-21T17:41:59 | 2021-04-26T19:36:40 | 46,861 | 0 | 0 | 11 |
JavaScript
| false | false |
package com.ydcx.core.linkApi.entity;
public class CyhUserInfo {
private static final long serialVersionUID = 1L;
private String duid;
private String userName;
private String phone;
private String couponCode;
private String corpId;
private String registerSource;
private String customerId;
private String shopcode;
private String iconurl;
private String cyhCouPons;
private String duuid;
public String getDuuid() {
return duuid;
}
public void setDuuid(String duuid) {
this.duuid = duuid;
}
public String getDuid() {
return duid;
}
public void setDuid(String duid) {
this.duid = duid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public String getCorpId() {
return corpId;
}
public void setCorpId(String corpId) {
this.corpId = corpId;
}
public String getRegisterSource() {
return registerSource;
}
public void setRegisterSource(String registerSource) {
this.registerSource = registerSource;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getShopcode() {
return shopcode;
}
public void setShopcode(String shopcode) {
this.shopcode = shopcode;
}
public String getIconurl() {
return iconurl;
}
public void setIconurl(String iconurl) {
this.iconurl = iconurl;
}
public String getCyhCouPons() {
return cyhCouPons;
}
public void setCyhCouPons(String cyhCouPons) {
this.cyhCouPons = cyhCouPons;
}
}
|
UTF-8
|
Java
| 2,138 |
java
|
CyhUserInfo.java
|
Java
|
[
{
"context": " = 1L;\n private String duid;\n private String userName;\n private String phone;\n private String cou",
"end": 172,
"score": 0.9859206080436707,
"start": 164,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userNa",
"end": 764,
"score": 0.9963507652282715,
"start": 756,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "serName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n p",
"end": 816,
"score": 0.921377956867218,
"start": 808,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "serName(String userName) {\n this.userName = userName;\n }\n\n public String getPhone() {\n re",
"end": 852,
"score": 0.9972743391990662,
"start": 844,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.ydcx.core.linkApi.entity;
public class CyhUserInfo {
private static final long serialVersionUID = 1L;
private String duid;
private String userName;
private String phone;
private String couponCode;
private String corpId;
private String registerSource;
private String customerId;
private String shopcode;
private String iconurl;
private String cyhCouPons;
private String duuid;
public String getDuuid() {
return duuid;
}
public void setDuuid(String duuid) {
this.duuid = duuid;
}
public String getDuid() {
return duid;
}
public void setDuid(String duid) {
this.duid = duid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public String getCorpId() {
return corpId;
}
public void setCorpId(String corpId) {
this.corpId = corpId;
}
public String getRegisterSource() {
return registerSource;
}
public void setRegisterSource(String registerSource) {
this.registerSource = registerSource;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getShopcode() {
return shopcode;
}
public void setShopcode(String shopcode) {
this.shopcode = shopcode;
}
public String getIconurl() {
return iconurl;
}
public void setIconurl(String iconurl) {
this.iconurl = iconurl;
}
public String getCyhCouPons() {
return cyhCouPons;
}
public void setCyhCouPons(String cyhCouPons) {
this.cyhCouPons = cyhCouPons;
}
}
| 2,138 | 0.621609 | 0.621141 | 110 | 18.436363 | 16.6758 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false |
12
|
fa1c044a8ffc46891c552f1af08ad2f7cddf9238
| 266,288,016,596 |
df1e8e5feddc02390f6fa65f348a2cca423f7217
|
/app/src/main/java/com/project/doer/adminTask/AdminTaskListPresenter.java
|
edbab4770f5afbe8e4fcb5b2ac30be5b048079ff
|
[] |
no_license
|
ashraf-hussain/doer
|
https://github.com/ashraf-hussain/doer
|
4196f8064e8b0cddfdaa4d849c7e60182bb789c8
|
b5aeb64847fb91d04648b7470f295dc4bbfb4b18
|
refs/heads/master
| 2020-05-02T10:46:12.116000 | 2019-04-05T11:44:07 | 2019-04-05T11:44:07 | 177,906,975 | 0 | 0 | null | false | 2019-04-05T11:44:08 | 2019-03-27T02:52:57 | 2019-04-05T09:20:15 | 2019-04-05T11:44:08 | 1,670 | 0 | 0 | 0 |
Java
| false | false |
package com.project.doer.adminTask;
public interface AdminTaskListPresenter {
void loadAllCreatedTask(int groupId);
}
|
UTF-8
|
Java
| 123 |
java
|
AdminTaskListPresenter.java
|
Java
|
[] | null |
[] |
package com.project.doer.adminTask;
public interface AdminTaskListPresenter {
void loadAllCreatedTask(int groupId);
}
| 123 | 0.804878 | 0.804878 | 5 | 23.6 | 18.990524 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
0893f595a3df590a16fa1ce7e9f8df036a3c6f03
| 30,803,505,447,061 |
905e4376e0a4bbd99d70215b31caf8f0145519ae
|
/quyawar/src/pe/edu/upc/quyawar/core/rest/TipoCatalogoRestController.java
|
a28efb3dd7d64fc6c17a253ec03b338b775b2e1c
|
[] |
no_license
|
jobermz/quyawar
|
https://github.com/jobermz/quyawar
|
89ebd7d440e0c5648de690fbda5fadfd9c2a270a
|
c8c20f64d3f5fc03164ed956337c80d358a3d566
|
refs/heads/master
| 2020-12-03T06:40:34.973000 | 2017-07-24T23:56:19 | 2017-07-24T23:56:19 | 95,716,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pe.edu.upc.quyawar.core.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import pe.edu.upc.quyawar.core.model.entity.TipoCatalogo;
import pe.edu.upc.quyawar.core.service.TipoCatalogoService;
/**
* Clase Controller que da soporte para las solicitudes de manteniento de Tipo Catalogo
*
* @author Jober Mena
*
*/
@RestController
public class TipoCatalogoRestController {
@Autowired
private TipoCatalogoService tipoCatalogoService;
@RequestMapping(value = "/tipoCatalogo/", method = RequestMethod.GET)
public ResponseEntity<List<TipoCatalogo>> listAllTipoCatalogos() throws Exception {
List<TipoCatalogo> tipoCatalogos = tipoCatalogoService.buscar(new TipoCatalogo(), null);
if (tipoCatalogos.isEmpty()) {
return new ResponseEntity<List<TipoCatalogo>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<TipoCatalogo>>(tipoCatalogos, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TipoCatalogo> getTipoCatalogo(@PathVariable("id") Integer id) throws Exception {
System.out.println("Fetching TipoCatalogo with id " + id);
TipoCatalogo tipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (tipoCatalogo == null) {
System.out.println("TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<TipoCatalogo>(tipoCatalogo, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/", method = RequestMethod.POST)
public ResponseEntity<Void> createTipoCatalogo(@RequestBody TipoCatalogo tipoCatalogo, UriComponentsBuilder ucBuilder) throws Exception {
///System.out.println("Creating TipoCatalogo " + tipoCatalogo.getStrNombre());
if (tipoCatalogoService.buscarById(tipoCatalogo) != null) {
//System.out.println("A TipoCatalogo with name " + tipoCatalogo.getStrNombre() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
tipoCatalogoService.guardar(tipoCatalogo);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/tipoCatalogo/{id}").buildAndExpand(tipoCatalogo.getSrlIdCatalogo()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.PUT)
public ResponseEntity<TipoCatalogo> updateTipoCatalogo(@PathVariable("id") Integer id, @RequestBody TipoCatalogo tipoCatalogo) throws Exception {
System.out.println("Updating TipoCatalogo " + id);
TipoCatalogo currentTipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (currentTipoCatalogo == null) {
System.out.println("TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
tipoCatalogoService.guardar(tipoCatalogo);
return new ResponseEntity<TipoCatalogo>(currentTipoCatalogo, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.DELETE)
public ResponseEntity<TipoCatalogo> deleteTipoCatalogo(@PathVariable("id") Integer id) throws Exception {
System.out.println("Fetching & Deleting TipoCatalogo with id " + id);
TipoCatalogo tipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (tipoCatalogo == null) {
System.out.println("Unable to delete. TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
tipoCatalogoService.eliminar(new TipoCatalogo(id));
return new ResponseEntity<TipoCatalogo>(HttpStatus.NO_CONTENT);
}
}
|
UTF-8
|
Java
| 4,315 |
java
|
TipoCatalogoRestController.java
|
Java
|
[
{
"context": "s de manteniento de Tipo Catalogo\r\n * \r\n * @author Jober Mena\r\n * \r\n */\r\n\r\n@RestController\r\npublic class TipoCa",
"end": 930,
"score": 0.9998657703399658,
"start": 920,
"tag": "NAME",
"value": "Jober Mena"
}
] | null |
[] |
package pe.edu.upc.quyawar.core.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import pe.edu.upc.quyawar.core.model.entity.TipoCatalogo;
import pe.edu.upc.quyawar.core.service.TipoCatalogoService;
/**
* Clase Controller que da soporte para las solicitudes de manteniento de Tipo Catalogo
*
* @author <NAME>
*
*/
@RestController
public class TipoCatalogoRestController {
@Autowired
private TipoCatalogoService tipoCatalogoService;
@RequestMapping(value = "/tipoCatalogo/", method = RequestMethod.GET)
public ResponseEntity<List<TipoCatalogo>> listAllTipoCatalogos() throws Exception {
List<TipoCatalogo> tipoCatalogos = tipoCatalogoService.buscar(new TipoCatalogo(), null);
if (tipoCatalogos.isEmpty()) {
return new ResponseEntity<List<TipoCatalogo>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<TipoCatalogo>>(tipoCatalogos, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TipoCatalogo> getTipoCatalogo(@PathVariable("id") Integer id) throws Exception {
System.out.println("Fetching TipoCatalogo with id " + id);
TipoCatalogo tipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (tipoCatalogo == null) {
System.out.println("TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<TipoCatalogo>(tipoCatalogo, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/", method = RequestMethod.POST)
public ResponseEntity<Void> createTipoCatalogo(@RequestBody TipoCatalogo tipoCatalogo, UriComponentsBuilder ucBuilder) throws Exception {
///System.out.println("Creating TipoCatalogo " + tipoCatalogo.getStrNombre());
if (tipoCatalogoService.buscarById(tipoCatalogo) != null) {
//System.out.println("A TipoCatalogo with name " + tipoCatalogo.getStrNombre() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
tipoCatalogoService.guardar(tipoCatalogo);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/tipoCatalogo/{id}").buildAndExpand(tipoCatalogo.getSrlIdCatalogo()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.PUT)
public ResponseEntity<TipoCatalogo> updateTipoCatalogo(@PathVariable("id") Integer id, @RequestBody TipoCatalogo tipoCatalogo) throws Exception {
System.out.println("Updating TipoCatalogo " + id);
TipoCatalogo currentTipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (currentTipoCatalogo == null) {
System.out.println("TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
tipoCatalogoService.guardar(tipoCatalogo);
return new ResponseEntity<TipoCatalogo>(currentTipoCatalogo, HttpStatus.OK);
}
@RequestMapping(value = "/tipoCatalogo/{id}", method = RequestMethod.DELETE)
public ResponseEntity<TipoCatalogo> deleteTipoCatalogo(@PathVariable("id") Integer id) throws Exception {
System.out.println("Fetching & Deleting TipoCatalogo with id " + id);
TipoCatalogo tipoCatalogo = tipoCatalogoService.buscarById(new TipoCatalogo(id));
if (tipoCatalogo == null) {
System.out.println("Unable to delete. TipoCatalogo with id " + id + " not found");
return new ResponseEntity<TipoCatalogo>(HttpStatus.NOT_FOUND);
}
tipoCatalogoService.eliminar(new TipoCatalogo(id));
return new ResponseEntity<TipoCatalogo>(HttpStatus.NO_CONTENT);
}
}
| 4,311 | 0.765469 | 0.765469 | 95 | 43.442104 | 37.036175 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.736842 | false | false |
12
|
c6a0d445c11a9a2970460f0019852c548cf6cbb2
| 34,119,220,226,029 |
816342d16468e32d317921a9a2da230c17aefe72
|
/src/main/java/com/bysj/service/ArticleCommentService.java
|
bb5bbc6881aca6501137137dbf9cbd0bd88b40fe
|
[] |
no_license
|
zrsky/zh
|
https://github.com/zrsky/zh
|
8ce9f670e38ea2d13dce2431ba87e5c026dff765
|
5b3ecf5c9f9fd699ad74d76adf0086f98927f468
|
refs/heads/master
| 2020-03-19T11:31:30.205000 | 2018-06-07T10:28:38 | 2018-06-07T10:28:38 | 136,460,499 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bysj.service;
import com.bysj.pojo.ArticleComment;
import com.bysj.pojo.Comment;
import com.bysj.utils.JsonResult;
import java.util.List;
/**
* Created by super on 2018/4/20 10:30.
*/
public interface ArticleCommentService {
List<ArticleComment> getArticleCommentListByArticleId(int id);
JsonResult addArticleComment(Integer commentId, int questionId);
List<ArticleComment> getArticleCommentListByCommentList(List<Comment> commentList);
void getArticleCommentByCommentId(int id);
void deleteArticleCommentByArticleCommentId(Integer id);
}
|
UTF-8
|
Java
| 580 |
java
|
ArticleCommentService.java
|
Java
|
[
{
"context": "Result;\n\nimport java.util.List;\n\n/**\n * Created by super on 2018/4/20 10:30.\n */\npublic interface ArticleC",
"end": 176,
"score": 0.9068095088005066,
"start": 171,
"tag": "USERNAME",
"value": "super"
}
] | null |
[] |
package com.bysj.service;
import com.bysj.pojo.ArticleComment;
import com.bysj.pojo.Comment;
import com.bysj.utils.JsonResult;
import java.util.List;
/**
* Created by super on 2018/4/20 10:30.
*/
public interface ArticleCommentService {
List<ArticleComment> getArticleCommentListByArticleId(int id);
JsonResult addArticleComment(Integer commentId, int questionId);
List<ArticleComment> getArticleCommentListByCommentList(List<Comment> commentList);
void getArticleCommentByCommentId(int id);
void deleteArticleCommentByArticleCommentId(Integer id);
}
| 580 | 0.789655 | 0.77069 | 22 | 25.363636 | 26.617741 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
08a90429d8cfb64c142c18955677d56fd924f502
| 10,685,878,684,572 |
2ead9e98a58f200a41aab47a5293a3ce234431a1
|
/Solves/Solution_1021.java
|
e2b0cbd2ea770396dade6e45fcf7815356743f65
|
[] |
no_license
|
Xylitolwhc/Leetcode-Solutions
|
https://github.com/Xylitolwhc/Leetcode-Solutions
|
433f4b348116ef487a1a9cdf804cb9f09f0613d1
|
95f9bbe37a354be05be6f1a5c2dd51d25e2ed158
|
refs/heads/master
| 2022-02-02T22:48:28.826000 | 2019-05-20T12:48:13 | 2019-05-20T12:48:13 | 111,985,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Created by hanson on 2019/4/11
*
* @author Hanson
* 2019/4/11
* 1021. Remove Outermost Parentheses
* https://leetcode.com/problems/remove-outermost-parentheses/
*/
public class Solution_1021 {
public String removeOuterParentheses(String S) {
StringBuilder removedStr = new StringBuilder();
int outer = 0;
for (char c : S.toCharArray()) {
if (c == '(') {
if (outer != 0) {
removedStr.append(c);
}
outer += 1;
} else if (c == ')') {
if (outer != 1) {
removedStr.append(c);
}
outer -= 1;
}
}
return removedStr.toString();
}
}
|
UTF-8
|
Java
| 756 |
java
|
Solution_1021.java
|
Java
|
[
{
"context": "/**\n * Created by hanson on 2019/4/11\n *\n * @author Hanson\n * 2019/4/11\n *",
"end": 24,
"score": 0.9451439380645752,
"start": 18,
"tag": "NAME",
"value": "hanson"
},
{
"context": "**\n * Created by hanson on 2019/4/11\n *\n * @author Hanson\n * 2019/4/11\n * 1021. Remove Outermost Parenthese",
"end": 58,
"score": 0.9997866749763489,
"start": 52,
"tag": "NAME",
"value": "Hanson"
}
] | null |
[] |
/**
* Created by hanson on 2019/4/11
*
* @author Hanson
* 2019/4/11
* 1021. Remove Outermost Parentheses
* https://leetcode.com/problems/remove-outermost-parentheses/
*/
public class Solution_1021 {
public String removeOuterParentheses(String S) {
StringBuilder removedStr = new StringBuilder();
int outer = 0;
for (char c : S.toCharArray()) {
if (c == '(') {
if (outer != 0) {
removedStr.append(c);
}
outer += 1;
} else if (c == ')') {
if (outer != 1) {
removedStr.append(c);
}
outer -= 1;
}
}
return removedStr.toString();
}
}
| 756 | 0.464286 | 0.428571 | 28 | 26 | 16.40122 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
12
|
7d5358780b2175826ef5908e754b658dabe84156
| 8,933,532,020,736 |
fe5bb0bc96e5a1d7e73b431b3faad6edb42777dd
|
/src/main/java/cpp/codechecker/rules/ClassNameIsUpperCamel.java
|
13076828841087fbac96db7aedc626c7873fa975
|
[] |
no_license
|
pabiswas/CodeChecker
|
https://github.com/pabiswas/CodeChecker
|
e052741c77d3c0ef7264ddfaf9675d5f12814bc1
|
e973fe16df9f6649d99ef5b7e5d114de0c692e5e
|
refs/heads/master
| 2016-09-05T17:54:55.425000 | 2014-05-22T12:21:35 | 2014-05-22T12:21:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cpp.codechecker.rules;
import cpp.codechecker.CodeChecker;
import cpp.codechecker.IPrinter;
import cpp.codechecker.IXMLProcessor;
/**
*
* @author basme
*/
public class ClassNameIsUpperCamel implements IRule{
@Override
public void runRule(IXMLProcessor processor, IPrinter printer) {
for(String className : processor.getAllClassNames())
{
if(!className.matches("^[A-Z].*"))
{
printer.printError("Classname \'"+className+"\' should start with a upper case.");
}
}
}
}
|
UTF-8
|
Java
| 754 |
java
|
ClassNameIsUpperCamel.java
|
Java
|
[
{
"context": " cpp.codechecker.IXMLProcessor;\n\n/**\n *\n * @author basme\n */\npublic class ClassNameIsUpperCamel implements",
"end": 349,
"score": 0.9996086359024048,
"start": 344,
"tag": "USERNAME",
"value": "basme"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cpp.codechecker.rules;
import cpp.codechecker.CodeChecker;
import cpp.codechecker.IPrinter;
import cpp.codechecker.IXMLProcessor;
/**
*
* @author basme
*/
public class ClassNameIsUpperCamel implements IRule{
@Override
public void runRule(IXMLProcessor processor, IPrinter printer) {
for(String className : processor.getAllClassNames())
{
if(!className.matches("^[A-Z].*"))
{
printer.printError("Classname \'"+className+"\' should start with a upper case.");
}
}
}
}
| 754 | 0.660477 | 0.660477 | 29 | 25 | 26.934147 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.310345 | false | false |
12
|
7d2a6c90bc359894c67e51fe2800067cc473fc53
| 23,167,053,648,970 |
a701e5c02df42b54956c6fcd89888adcd8bf5a53
|
/src/main/java/com/lbyier/collectionInfo/service/CollectionInfoService.java
|
55c1c42d279a700ea71e14be17702d998884506b
|
[] |
no_license
|
xxkkll/ssm
|
https://github.com/xxkkll/ssm
|
f4619be33016ef50c9bea95c3fff3127a92b4e22
|
ed3be1492f87fe6a33079b24f591b135c383ae89
|
refs/heads/master
| 2023-01-22T00:51:15.372000 | 2020-11-24T14:45:16 | 2020-11-24T14:45:16 | 310,001,418 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lbyier.collectionInfo.service;
import com.util.ResponseVo;
/**
* @author LByier
* @date 2020/11/7 10:56
*/
public interface CollectionInfoService {
ResponseVo updateInfo();
}
|
UTF-8
|
Java
| 197 |
java
|
CollectionInfoService.java
|
Java
|
[
{
"context": "vice;\n\nimport com.util.ResponseVo;\n\n/**\n * @author LByier\n * @date 2020/11/7 10:56\n */\n\npublic interface Co",
"end": 94,
"score": 0.9985869526863098,
"start": 88,
"tag": "USERNAME",
"value": "LByier"
}
] | null |
[] |
package com.lbyier.collectionInfo.service;
import com.util.ResponseVo;
/**
* @author LByier
* @date 2020/11/7 10:56
*/
public interface CollectionInfoService {
ResponseVo updateInfo();
}
| 197 | 0.725888 | 0.670051 | 12 | 15.416667 | 15.569512 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
12
|
d5dd1eb46cdd9fdaa24eaf1558c40485d5795359
| 32,847,909,935,476 |
db009232879c9336fb1d5eee26b7d3443db936e0
|
/src/gen/java/jp/go/kishou/xml/jmaxml1/body/meteorology1/TypeWindSpeedPart.java
|
691fc2d74fa96fb97da093972d4ca96f5405ae4e
|
[] |
no_license
|
ArkUmbra/quaker
|
https://github.com/ArkUmbra/quaker
|
cd4b9238a597a81caa99f54085e38a5a973bb395
|
0cf4da426dc496fa87238dc7e339ae3c06050708
|
refs/heads/master
| 2020-12-22T02:42:15.098000 | 2020-09-06T06:52:31 | 2020-09-06T06:52:31 | 236,646,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jp.go.kishou.xml.jmaxml1.body.meteorology1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import jp.go.kishou.xml.jmaxml1.elementbasis1.TypeWindSpeed;
/**
* <p>Java class for type.WindSpeedPart complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="type.WindSpeedPart">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Sentence" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.Sentence" minOccurs="0"/>
* <element name="Base" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" minOccurs="0"/>
* <element name="Temporary" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Becoming" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="SubArea" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.SubAreaWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://xml.kishou.go.jp/jmaxml1/elementBasis1/}WindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="WindSpeedLevel" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.WindSpeedLevel" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Time" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="Remark" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "type.WindSpeedPart", propOrder = {
"sentence",
"base",
"temporary",
"becoming",
"subArea",
"windSpeed",
"windSpeedLevel",
"time",
"remark"
})
public class TypeWindSpeedPart {
@XmlElement(name = "Sentence")
protected TypeSentence sentence;
@XmlElement(name = "Base")
protected TypeBaseWindSpeed base;
@XmlElement(name = "Temporary")
protected List<TypeBaseWindSpeed> temporary;
@XmlElement(name = "Becoming")
protected List<TypeBaseWindSpeed> becoming;
@XmlElement(name = "SubArea")
protected List<TypeSubAreaWindSpeed> subArea;
@XmlElement(name = "WindSpeed", namespace = "http://xml.kishou.go.jp/jmaxml1/elementBasis1/")
protected List<TypeWindSpeed> windSpeed;
@XmlElement(name = "WindSpeedLevel")
protected List<TypeWindSpeedLevel> windSpeedLevel;
@XmlElement(name = "Time")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar time;
@XmlElement(name = "Remark")
protected String remark;
/**
* Gets the value of the sentence property.
*
* @return
* possible object is
* {@link TypeSentence }
*
*/
public TypeSentence getSentence() {
return sentence;
}
/**
* Sets the value of the sentence property.
*
* @param value
* allowed object is
* {@link TypeSentence }
*
*/
public void setSentence(TypeSentence value) {
this.sentence = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link TypeBaseWindSpeed }
*
*/
public TypeBaseWindSpeed getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link TypeBaseWindSpeed }
*
*/
public void setBase(TypeBaseWindSpeed value) {
this.base = value;
}
/**
* Gets the value of the temporary 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 temporary property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemporary().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeBaseWindSpeed }
*
*
*/
public List<TypeBaseWindSpeed> getTemporary() {
if (temporary == null) {
temporary = new ArrayList<TypeBaseWindSpeed>();
}
return this.temporary;
}
/**
* Gets the value of the becoming 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 becoming property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBecoming().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeBaseWindSpeed }
*
*
*/
public List<TypeBaseWindSpeed> getBecoming() {
if (becoming == null) {
becoming = new ArrayList<TypeBaseWindSpeed>();
}
return this.becoming;
}
/**
* Gets the value of the subArea 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 subArea property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSubArea().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeSubAreaWindSpeed }
*
*
*/
public List<TypeSubAreaWindSpeed> getSubArea() {
if (subArea == null) {
subArea = new ArrayList<TypeSubAreaWindSpeed>();
}
return this.subArea;
}
/**
* Gets the value of the windSpeed 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 windSpeed property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWindSpeed().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeWindSpeed }
*
*
*/
public List<TypeWindSpeed> getWindSpeed() {
if (windSpeed == null) {
windSpeed = new ArrayList<TypeWindSpeed>();
}
return this.windSpeed;
}
/**
* Gets the value of the windSpeedLevel 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 windSpeedLevel property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWindSpeedLevel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeWindSpeedLevel }
*
*
*/
public List<TypeWindSpeedLevel> getWindSpeedLevel() {
if (windSpeedLevel == null) {
windSpeedLevel = new ArrayList<TypeWindSpeedLevel>();
}
return this.windSpeedLevel;
}
/**
* Gets the value of the time property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTime() {
return time;
}
/**
* Sets the value of the time property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTime(XMLGregorianCalendar value) {
this.time = value;
}
/**
* Gets the value of the remark property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
}
}
|
UTF-8
|
Java
| 9,358 |
java
|
TypeWindSpeedPart.java
|
Java
|
[] | null |
[] |
package jp.go.kishou.xml.jmaxml1.body.meteorology1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import jp.go.kishou.xml.jmaxml1.elementbasis1.TypeWindSpeed;
/**
* <p>Java class for type.WindSpeedPart complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="type.WindSpeedPart">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Sentence" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.Sentence" minOccurs="0"/>
* <element name="Base" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" minOccurs="0"/>
* <element name="Temporary" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Becoming" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.BaseWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="SubArea" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.SubAreaWindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://xml.kishou.go.jp/jmaxml1/elementBasis1/}WindSpeed" maxOccurs="unbounded" minOccurs="0"/>
* <element name="WindSpeedLevel" type="{http://xml.kishou.go.jp/jmaxml1/body/meteorology1/}type.WindSpeedLevel" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Time" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="Remark" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "type.WindSpeedPart", propOrder = {
"sentence",
"base",
"temporary",
"becoming",
"subArea",
"windSpeed",
"windSpeedLevel",
"time",
"remark"
})
public class TypeWindSpeedPart {
@XmlElement(name = "Sentence")
protected TypeSentence sentence;
@XmlElement(name = "Base")
protected TypeBaseWindSpeed base;
@XmlElement(name = "Temporary")
protected List<TypeBaseWindSpeed> temporary;
@XmlElement(name = "Becoming")
protected List<TypeBaseWindSpeed> becoming;
@XmlElement(name = "SubArea")
protected List<TypeSubAreaWindSpeed> subArea;
@XmlElement(name = "WindSpeed", namespace = "http://xml.kishou.go.jp/jmaxml1/elementBasis1/")
protected List<TypeWindSpeed> windSpeed;
@XmlElement(name = "WindSpeedLevel")
protected List<TypeWindSpeedLevel> windSpeedLevel;
@XmlElement(name = "Time")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar time;
@XmlElement(name = "Remark")
protected String remark;
/**
* Gets the value of the sentence property.
*
* @return
* possible object is
* {@link TypeSentence }
*
*/
public TypeSentence getSentence() {
return sentence;
}
/**
* Sets the value of the sentence property.
*
* @param value
* allowed object is
* {@link TypeSentence }
*
*/
public void setSentence(TypeSentence value) {
this.sentence = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link TypeBaseWindSpeed }
*
*/
public TypeBaseWindSpeed getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link TypeBaseWindSpeed }
*
*/
public void setBase(TypeBaseWindSpeed value) {
this.base = value;
}
/**
* Gets the value of the temporary 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 temporary property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemporary().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeBaseWindSpeed }
*
*
*/
public List<TypeBaseWindSpeed> getTemporary() {
if (temporary == null) {
temporary = new ArrayList<TypeBaseWindSpeed>();
}
return this.temporary;
}
/**
* Gets the value of the becoming 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 becoming property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBecoming().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeBaseWindSpeed }
*
*
*/
public List<TypeBaseWindSpeed> getBecoming() {
if (becoming == null) {
becoming = new ArrayList<TypeBaseWindSpeed>();
}
return this.becoming;
}
/**
* Gets the value of the subArea 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 subArea property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSubArea().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeSubAreaWindSpeed }
*
*
*/
public List<TypeSubAreaWindSpeed> getSubArea() {
if (subArea == null) {
subArea = new ArrayList<TypeSubAreaWindSpeed>();
}
return this.subArea;
}
/**
* Gets the value of the windSpeed 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 windSpeed property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWindSpeed().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeWindSpeed }
*
*
*/
public List<TypeWindSpeed> getWindSpeed() {
if (windSpeed == null) {
windSpeed = new ArrayList<TypeWindSpeed>();
}
return this.windSpeed;
}
/**
* Gets the value of the windSpeedLevel 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 windSpeedLevel property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWindSpeedLevel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypeWindSpeedLevel }
*
*
*/
public List<TypeWindSpeedLevel> getWindSpeedLevel() {
if (windSpeedLevel == null) {
windSpeedLevel = new ArrayList<TypeWindSpeedLevel>();
}
return this.windSpeedLevel;
}
/**
* Gets the value of the time property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTime() {
return time;
}
/**
* Sets the value of the time property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTime(XMLGregorianCalendar value) {
this.time = value;
}
/**
* Gets the value of the remark property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
}
}
| 9,358 | 0.599701 | 0.594999 | 316 | 28.61076 | 28.707998 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.31962 | false | false |
12
|
08d1c5c47562e181e736f7cc4511b9a5498324fd
| 16,449,724,805,605 |
2798b1c963cb554f96f05898c04f1b4bfa98fce0
|
/MasterMind/src/main/java/com/tsg/fischer/mastermind/data/GameDAO.java
|
00927c75b37808a14496af817b9fa2018e401dcb
|
[] |
no_license
|
cfischera/MasterMind
|
https://github.com/cfischera/MasterMind
|
591e2dec3c2048e2928bd1fc2711bb673bc0044d
|
ace06bb99b2c640e890c49a54b7b16bf098a6855
|
refs/heads/master
| 2020-08-10T00:24:55.217000 | 2019-10-10T14:50:12 | 2019-10-10T14:50:12 | 214,209,514 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tsg.fischer.mastermind.data;
import com.tsg.fischer.mastermind.model.Game;
import com.tsg.fischer.mastermind.model.Round;
import java.util.List;
public interface GameDAO {
Game addGame(Game game);
List<Round> addRound(int gameID, Round round);
Game getGameByID(int id);
List<Game> getAllGames();
Game updateGameStatusToFinished(Game game);
Game deleteGameByID(int id);
}
|
UTF-8
|
Java
| 410 |
java
|
GameDAO.java
|
Java
|
[] | null |
[] |
package com.tsg.fischer.mastermind.data;
import com.tsg.fischer.mastermind.model.Game;
import com.tsg.fischer.mastermind.model.Round;
import java.util.List;
public interface GameDAO {
Game addGame(Game game);
List<Round> addRound(int gameID, Round round);
Game getGameByID(int id);
List<Game> getAllGames();
Game updateGameStatusToFinished(Game game);
Game deleteGameByID(int id);
}
| 410 | 0.746341 | 0.746341 | 15 | 26.333334 | 17.699968 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false |
12
|
ccfddd11cde668c084474d10f0afbcc8fdf4185b
| 24,283,745,147,102 |
bc70a4652a047a7afd15333747fc2aebfc90d2c4
|
/platform/dolphin-platform-remoting-client/src/main/java/com/canoo/platform/remoting/client/ControllerFactory.java
|
3a9f2492ffdb1e0102feb2d1339cc74fd51996b8
|
[
"Apache-2.0"
] |
permissive
|
potapczuk/dolphin-platform
|
https://github.com/potapczuk/dolphin-platform
|
91bc4f564f5accf61ea7b462701473622f63db5f
|
95c13dbd72b8c9c54caf8e9dd06a4933baeba490
|
refs/heads/master
| 2021-07-18T07:16:08.341000 | 2017-10-23T12:26:31 | 2017-10-23T12:26:31 | 108,169,860 | 1 | 0 | null | true | 2017-10-24T18:53:03 | 2017-10-24T18:53:03 | 2017-10-20T20:35:53 | 2017-10-24T15:07:53 | 73,764 | 0 | 0 | 0 | null | false | null |
package com.canoo.platform.remoting.client;
import java.util.concurrent.CompletableFuture;
public interface ControllerFactory {
<T> CompletableFuture<ControllerProxy<T>> createController(String name);
}
|
UTF-8
|
Java
| 211 |
java
|
ControllerFactory.java
|
Java
|
[] | null |
[] |
package com.canoo.platform.remoting.client;
import java.util.concurrent.CompletableFuture;
public interface ControllerFactory {
<T> CompletableFuture<ControllerProxy<T>> createController(String name);
}
| 211 | 0.805687 | 0.805687 | 9 | 22.444445 | 26.882919 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
12
|
55b06b2e7b520a7c6f851517c6db295c8dcb78fe
| 2,405,181,749,298 |
85f0d8482e4b742909b5c7652dbcb3ec5d9830a8
|
/kiji-schema/src/test/java/org/kiji/schema/cassandra/TestingCassandraFactory.java
|
b28f510068d66eb5d7b5a9218fed9d6d4a3859d2
|
[
"Apache-2.0"
] |
permissive
|
wibiclint/kiji-schema
|
https://github.com/wibiclint/kiji-schema
|
35d8cca381cf96bea4d134262b4b1c34aa94590d
|
041b002c277828a09f9c6aa443aef1218d867d0e
|
refs/heads/master
| 2021-01-15T17:46:04.564000 | 2014-04-15T18:46:04 | 2014-04-15T18:46:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* (c) Copyright 2012 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kiji.schema.cassandra;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kiji.delegation.Priority;
import org.kiji.schema.KijiIOException;
import org.kiji.schema.KijiURI;
import org.kiji.schema.RuntimeInterruptedException;
import org.kiji.schema.impl.cassandra.CassandraAdminFactory;
import org.kiji.schema.impl.cassandra.DefaultCassandraFactory;
import org.kiji.schema.impl.cassandra.TestingCassandraAdminFactory;
import org.kiji.schema.layout.impl.ZooKeeperClient;
import org.kiji.schema.util.LocalLockFactory;
import org.kiji.schema.util.LockFactory;
/** Factory for Cassandra instances based on URIs. */
public final class TestingCassandraFactory implements CassandraFactory {
private static final Logger LOG = LoggerFactory.getLogger(TestingCassandraFactory.class);
/** Factory to delegate to. */
private static final CassandraFactory DELEGATE = new DefaultCassandraFactory();
/** Lock object to protect MINI_ZOOKEEPER_CLUSTER and MINIZK_CLIENT. */
private static final Object MINIZK_CLUSTER_LOCK = new Object();
/** ZooKeeper mSession timeout, in milliseconds. */
private static final int ZKCLIENT_SESSION_TIMEOUT = 60 * 1000; // 1 second
/**
* Singleton MiniZooKeeperCluster for testing.
*
* Lazily instantiated when the first test requests a ZooKeeperClient for a .fake Kiji instance.
*
* Once started, the mini-cluster remains alive until the JVM shuts down.
*/
private static MiniZooKeeperCluster mMiniZkCluster;
/**
* Singleton Cassandra mSession for testing.
*
* Lazily instantiated when the first test requests a C* mSession for a .fake Kiji instance.
*
* Once started, will remain alive until the JVM shuts down.
*/
private static Session mCassandraSession = null;
/**
* ZooKeeperClient used to create chroot directories prior to instantiating test ZooKeeperClients.
* Lazily instantiated when the first test requests a ZooKeeperClient for a .fake Kiji instance.
*
* This client will not be closed properly until the JVM shuts down.
*/
private static ZooKeeperClient mMiniZkClient;
/** Map from fake HBase ID to fake (local) lock factories. */
private final Map<String, LockFactory> mLock = Maps.newHashMap();
/**
* Map from fake HBase ID to ZooKeeperClient.
*
* <p>
* ZooKeeperClient instances in this map are never released:
* unless client code releases ZooKeeperClient instance more than once,
* the retain counter is always ≥ 1.
* </p>
*/
private final Map<String, ZooKeeperClient> mZKClients = Maps.newHashMap();
/**
* Public constructor. This should not be directly invoked by users; you should
* use CassandraFactory.get(), which retains a singleton instance.
*
* This constructor needs to be public because the Java service loader must be able to
* instantiate it.
*/
public TestingCassandraFactory() {
}
/** URIs for fake HBase instances are "kiji://.fake.[fake-id]/instance/table". */
private static final String FAKE_CASSANDRA_ID_PREFIX = ".fake.";
//------------------------------------------------------------------------------------------------
// URI stuff
/** {@inheritDoc} */
@Override
public CassandraAdminFactory getCassandraAdminFactory(KijiURI uri) {
if (isFakeCassandraURI(uri)) {
String fakeCassandraID = getFakeCassandraID(uri);
Preconditions.checkNotNull(fakeCassandraID);
// Make sure that the EmbeddedCassandraService is started
try {
startEmbeddedCassandraServiceIfNotRunningAndOpenSession();
} catch (Exception e) {
throw new KijiIOException("Problem with embedded Cassandra mSession!" + e);
}
// Get an admin factory that will work with the embedded service
return createFakeCassandraAdminFactory(fakeCassandraID);
} else {
return DELEGATE.getCassandraAdminFactory(uri);
}
}
/**
* Extracts the ID of the fake C* from a Kiji URI.
*
* @param uri URI to extract a fake C* ID from.
* @return the fake C* ID, if any, or null.
*/
private static String getFakeCassandraID(KijiURI uri) {
if (uri.getZookeeperQuorum().size() != 1) {
return null;
}
final String zkHost = uri.getZookeeperQuorum().get(0);
if (!zkHost.startsWith(FAKE_CASSANDRA_ID_PREFIX)) {
return null;
}
assert(isFakeCassandraURI(uri));
return zkHost.substring(FAKE_CASSANDRA_ID_PREFIX.length());
}
/**
* Check whether this is the URI for a fake Cassandra instance.
*
* @param uri The URI in question.
* @return Whether the URI is for a fake instance or not.
*/
private static boolean isFakeCassandraURI(KijiURI uri) {
if (uri.getZookeeperQuorum().size() != 1) {
return false;
}
final String zkHost = uri.getZookeeperQuorum().get(0);
if (!zkHost.startsWith(FAKE_CASSANDRA_ID_PREFIX)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------
// Stuff for starting up C*
/**
* Return a fake C* admin factory for testing.
* @param fakeCassandraID
* @return A C* admin factory that will produce C* admins that will all use the shared
* EmbeddedCassandraService.
*/
private CassandraAdminFactory createFakeCassandraAdminFactory(String fakeCassandraID) {
Preconditions.checkNotNull(mCassandraSession);
return TestingCassandraAdminFactory.get(mCassandraSession);
}
/**
* Ensure that the EmbeddedCassandraService for unit tests is running. If it is not, then start
* it.
*/
private void startEmbeddedCassandraServiceIfNotRunningAndOpenSession() throws Exception {
LOG.debug("Ready to start a C* service if necessary...");
if (null != mCassandraSession) {
LOG.debug("C* is already running, no need to start the service.");
//Preconditions.checkNotNull(mCassandraSession);
return;
}
LOG.debug("Starting EmbeddedCassandra!");
try {
LOG.info("Starting EmbeddedCassandraService...");
// Use a custom YAML file that specifies different ports from normal for RPC and thrift.
File yamlFile = new File(getClass().getResource("/cassandra.yaml").getFile());
assert (yamlFile.exists());
System.setProperty("cassandra.config", "file:" + yamlFile.getAbsolutePath());
System.setProperty("cassandra-foreground", "true");
// Make sure that all of the directories for the commit log, data, and caches are empty.
// Thank goodness there are methods to get this information (versus parsing the YAML
// directly).
ArrayList<String> directoriesToDelete = new ArrayList<String>(Arrays.asList(
DatabaseDescriptor.getAllDataFileLocations()
));
directoriesToDelete.add(DatabaseDescriptor.getCommitLogLocation());
directoriesToDelete.add(DatabaseDescriptor.getSavedCachesLocation());
for (String dirName : directoriesToDelete) {
FileUtils.deleteDirectory(new File(dirName));
}
EmbeddedCassandraService embeddedCassandraService = new EmbeddedCassandraService();
embeddedCassandraService.start();
} catch (IOException ioe) {
throw new KijiIOException("Cannot start embedded C* service!");
}
// Use different port from normal here to avoid conflicts with any locally-running C* cluster.
// Port settings are controlled in "cassandra.yaml" in test resources.
String hostIp = "127.0.0.1";
int port = 9043;
Cluster cluster = Cluster.builder().addContactPoints(hostIp).withPort(port).build();
mCassandraSession = cluster.connect();
}
//------------------------------------------------------------------------------------------------
// Locks and ZooKeeper stuff
/** {@inheritDoc} */
@Override
public LockFactory getLockFactory(KijiURI uri, Configuration conf) throws IOException {
final String fakeID = getFakeCassandraID(uri);
if (fakeID != null) {
synchronized (mLock) {
final LockFactory factory = mLock.get(fakeID);
if (factory != null) {
return factory;
}
final LockFactory newFactory = new LocalLockFactory();
mLock.put(fakeID, newFactory);
return newFactory;
}
}
return DELEGATE.getLockFactory(uri, conf);
}
/** Resets the testing HBase factory. */
public void reset() {
mLock.clear();
}
/** {@inheritDoc} */
@Override
public int getPriority(Map<String, String> runtimeHints) {
// Higher priority than default factory.
return Priority.HIGH;
}
/**
* Returns the ZooKeeper mini cluster address with a chroot set to the provided fakeId.
*
* <p> The address will be to the testing MiniZooKeeperCluster. </p>
*
* @param fakeId the id of the test instance.
* @return the ZooKeeper address for the test instance.
* @throws IOException on I/O error when creating the mini cluster.
*/
private static String createZooKeeperAddressForFakeId(String fakeId) throws IOException {
// Initializes the Mini ZooKeeperCluster, if necessary:
final MiniZooKeeperCluster zkCluster = getMiniZKCluster();
// Create the chroot node for this fake ID, if necessary:
try {
final File zkChroot = new File("/" + fakeId);
if (mMiniZkClient.exists(zkChroot) == null) {
mMiniZkClient.createNodeRecursively(new File("/" + fakeId));
}
} catch (KeeperException ke) {
throw new KijiIOException(ke);
}
// Test ZooKeeperClients use a chroot to isolate testing environments.
return "localhost:" + zkCluster.getClientPort() + "/" + fakeId;
}
/**
* Creates a new MiniZooKeeperCluster if one does not already exist. Also creates and opens a
* ZooKeeperClient for the minicluster which is used to create chroot nodes before opening test
* ZooKeeperClients.
*
* @throws IOException in case of an error creating the temporary directory or starting the mini
* zookeeper cluster.
*/
private static MiniZooKeeperCluster getMiniZKCluster() throws IOException {
synchronized (MINIZK_CLUSTER_LOCK) {
if (mMiniZkCluster == null) {
final MiniZooKeeperCluster miniZK = new MiniZooKeeperCluster(new Configuration());
final File tempDir = File.createTempFile("mini-zk-cluster", "dir");
Preconditions.checkState(tempDir.delete());
Preconditions.checkState(tempDir.mkdirs());
try {
miniZK.startup(tempDir);
} catch (InterruptedException ie) {
throw new RuntimeInterruptedException(ie);
}
mMiniZkCluster = miniZK;
final String zkAddress ="localhost:" + mMiniZkCluster.getClientPort();
LOG.info("Creating testing utility ZooKeeperClient for {}", zkAddress);
mMiniZkClient = ZooKeeperClient.getZooKeeperClient(zkAddress);
}
return mMiniZkCluster;
}
}
/** {@inheritDoc} */
@Override
public ZooKeeperClient getZooKeeperClient(KijiURI uri) throws IOException {
return ZooKeeperClient.getZooKeeperClient(getZooKeeperEnsemble(uri));
}
/** {@inheritDoc} */
@Override
public String getZooKeeperEnsemble(KijiURI uri) {
final String fakeId = getFakeCassandraID(uri);
if (fakeId != null) {
try {
return createZooKeeperAddressForFakeId(fakeId);
} catch (IOException e) {
throw new KijiIOException(e.getCause());
}
}
// Not a test instance, delegate to default factory:
return DELEGATE.getZooKeeperEnsemble(uri);
}
}
|
UTF-8
|
Java
| 12,838 |
java
|
TestingCassandraFactory.java
|
Java
|
[
{
"context": "/**\n * (c) Copyright 2012 WibiData, Inc.\n *\n * See the NOTICE file distributed with ",
"end": 34,
"score": 0.9961158037185669,
"start": 26,
"tag": "NAME",
"value": "WibiData"
},
{
"context": "dra.yaml\" in test resources.\n String hostIp = \"127.0.0.1\";\n int port = 9043;\n Cluster cluster = Clus",
"end": 8793,
"score": 0.9997265934944153,
"start": 8784,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
/**
* (c) Copyright 2012 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kiji.schema.cassandra;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kiji.delegation.Priority;
import org.kiji.schema.KijiIOException;
import org.kiji.schema.KijiURI;
import org.kiji.schema.RuntimeInterruptedException;
import org.kiji.schema.impl.cassandra.CassandraAdminFactory;
import org.kiji.schema.impl.cassandra.DefaultCassandraFactory;
import org.kiji.schema.impl.cassandra.TestingCassandraAdminFactory;
import org.kiji.schema.layout.impl.ZooKeeperClient;
import org.kiji.schema.util.LocalLockFactory;
import org.kiji.schema.util.LockFactory;
/** Factory for Cassandra instances based on URIs. */
public final class TestingCassandraFactory implements CassandraFactory {
private static final Logger LOG = LoggerFactory.getLogger(TestingCassandraFactory.class);
/** Factory to delegate to. */
private static final CassandraFactory DELEGATE = new DefaultCassandraFactory();
/** Lock object to protect MINI_ZOOKEEPER_CLUSTER and MINIZK_CLIENT. */
private static final Object MINIZK_CLUSTER_LOCK = new Object();
/** ZooKeeper mSession timeout, in milliseconds. */
private static final int ZKCLIENT_SESSION_TIMEOUT = 60 * 1000; // 1 second
/**
* Singleton MiniZooKeeperCluster for testing.
*
* Lazily instantiated when the first test requests a ZooKeeperClient for a .fake Kiji instance.
*
* Once started, the mini-cluster remains alive until the JVM shuts down.
*/
private static MiniZooKeeperCluster mMiniZkCluster;
/**
* Singleton Cassandra mSession for testing.
*
* Lazily instantiated when the first test requests a C* mSession for a .fake Kiji instance.
*
* Once started, will remain alive until the JVM shuts down.
*/
private static Session mCassandraSession = null;
/**
* ZooKeeperClient used to create chroot directories prior to instantiating test ZooKeeperClients.
* Lazily instantiated when the first test requests a ZooKeeperClient for a .fake Kiji instance.
*
* This client will not be closed properly until the JVM shuts down.
*/
private static ZooKeeperClient mMiniZkClient;
/** Map from fake HBase ID to fake (local) lock factories. */
private final Map<String, LockFactory> mLock = Maps.newHashMap();
/**
* Map from fake HBase ID to ZooKeeperClient.
*
* <p>
* ZooKeeperClient instances in this map are never released:
* unless client code releases ZooKeeperClient instance more than once,
* the retain counter is always ≥ 1.
* </p>
*/
private final Map<String, ZooKeeperClient> mZKClients = Maps.newHashMap();
/**
* Public constructor. This should not be directly invoked by users; you should
* use CassandraFactory.get(), which retains a singleton instance.
*
* This constructor needs to be public because the Java service loader must be able to
* instantiate it.
*/
public TestingCassandraFactory() {
}
/** URIs for fake HBase instances are "kiji://.fake.[fake-id]/instance/table". */
private static final String FAKE_CASSANDRA_ID_PREFIX = ".fake.";
//------------------------------------------------------------------------------------------------
// URI stuff
/** {@inheritDoc} */
@Override
public CassandraAdminFactory getCassandraAdminFactory(KijiURI uri) {
if (isFakeCassandraURI(uri)) {
String fakeCassandraID = getFakeCassandraID(uri);
Preconditions.checkNotNull(fakeCassandraID);
// Make sure that the EmbeddedCassandraService is started
try {
startEmbeddedCassandraServiceIfNotRunningAndOpenSession();
} catch (Exception e) {
throw new KijiIOException("Problem with embedded Cassandra mSession!" + e);
}
// Get an admin factory that will work with the embedded service
return createFakeCassandraAdminFactory(fakeCassandraID);
} else {
return DELEGATE.getCassandraAdminFactory(uri);
}
}
/**
* Extracts the ID of the fake C* from a Kiji URI.
*
* @param uri URI to extract a fake C* ID from.
* @return the fake C* ID, if any, or null.
*/
private static String getFakeCassandraID(KijiURI uri) {
if (uri.getZookeeperQuorum().size() != 1) {
return null;
}
final String zkHost = uri.getZookeeperQuorum().get(0);
if (!zkHost.startsWith(FAKE_CASSANDRA_ID_PREFIX)) {
return null;
}
assert(isFakeCassandraURI(uri));
return zkHost.substring(FAKE_CASSANDRA_ID_PREFIX.length());
}
/**
* Check whether this is the URI for a fake Cassandra instance.
*
* @param uri The URI in question.
* @return Whether the URI is for a fake instance or not.
*/
private static boolean isFakeCassandraURI(KijiURI uri) {
if (uri.getZookeeperQuorum().size() != 1) {
return false;
}
final String zkHost = uri.getZookeeperQuorum().get(0);
if (!zkHost.startsWith(FAKE_CASSANDRA_ID_PREFIX)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------
// Stuff for starting up C*
/**
* Return a fake C* admin factory for testing.
* @param fakeCassandraID
* @return A C* admin factory that will produce C* admins that will all use the shared
* EmbeddedCassandraService.
*/
private CassandraAdminFactory createFakeCassandraAdminFactory(String fakeCassandraID) {
Preconditions.checkNotNull(mCassandraSession);
return TestingCassandraAdminFactory.get(mCassandraSession);
}
/**
* Ensure that the EmbeddedCassandraService for unit tests is running. If it is not, then start
* it.
*/
private void startEmbeddedCassandraServiceIfNotRunningAndOpenSession() throws Exception {
LOG.debug("Ready to start a C* service if necessary...");
if (null != mCassandraSession) {
LOG.debug("C* is already running, no need to start the service.");
//Preconditions.checkNotNull(mCassandraSession);
return;
}
LOG.debug("Starting EmbeddedCassandra!");
try {
LOG.info("Starting EmbeddedCassandraService...");
// Use a custom YAML file that specifies different ports from normal for RPC and thrift.
File yamlFile = new File(getClass().getResource("/cassandra.yaml").getFile());
assert (yamlFile.exists());
System.setProperty("cassandra.config", "file:" + yamlFile.getAbsolutePath());
System.setProperty("cassandra-foreground", "true");
// Make sure that all of the directories for the commit log, data, and caches are empty.
// Thank goodness there are methods to get this information (versus parsing the YAML
// directly).
ArrayList<String> directoriesToDelete = new ArrayList<String>(Arrays.asList(
DatabaseDescriptor.getAllDataFileLocations()
));
directoriesToDelete.add(DatabaseDescriptor.getCommitLogLocation());
directoriesToDelete.add(DatabaseDescriptor.getSavedCachesLocation());
for (String dirName : directoriesToDelete) {
FileUtils.deleteDirectory(new File(dirName));
}
EmbeddedCassandraService embeddedCassandraService = new EmbeddedCassandraService();
embeddedCassandraService.start();
} catch (IOException ioe) {
throw new KijiIOException("Cannot start embedded C* service!");
}
// Use different port from normal here to avoid conflicts with any locally-running C* cluster.
// Port settings are controlled in "cassandra.yaml" in test resources.
String hostIp = "127.0.0.1";
int port = 9043;
Cluster cluster = Cluster.builder().addContactPoints(hostIp).withPort(port).build();
mCassandraSession = cluster.connect();
}
//------------------------------------------------------------------------------------------------
// Locks and ZooKeeper stuff
/** {@inheritDoc} */
@Override
public LockFactory getLockFactory(KijiURI uri, Configuration conf) throws IOException {
final String fakeID = getFakeCassandraID(uri);
if (fakeID != null) {
synchronized (mLock) {
final LockFactory factory = mLock.get(fakeID);
if (factory != null) {
return factory;
}
final LockFactory newFactory = new LocalLockFactory();
mLock.put(fakeID, newFactory);
return newFactory;
}
}
return DELEGATE.getLockFactory(uri, conf);
}
/** Resets the testing HBase factory. */
public void reset() {
mLock.clear();
}
/** {@inheritDoc} */
@Override
public int getPriority(Map<String, String> runtimeHints) {
// Higher priority than default factory.
return Priority.HIGH;
}
/**
* Returns the ZooKeeper mini cluster address with a chroot set to the provided fakeId.
*
* <p> The address will be to the testing MiniZooKeeperCluster. </p>
*
* @param fakeId the id of the test instance.
* @return the ZooKeeper address for the test instance.
* @throws IOException on I/O error when creating the mini cluster.
*/
private static String createZooKeeperAddressForFakeId(String fakeId) throws IOException {
// Initializes the Mini ZooKeeperCluster, if necessary:
final MiniZooKeeperCluster zkCluster = getMiniZKCluster();
// Create the chroot node for this fake ID, if necessary:
try {
final File zkChroot = new File("/" + fakeId);
if (mMiniZkClient.exists(zkChroot) == null) {
mMiniZkClient.createNodeRecursively(new File("/" + fakeId));
}
} catch (KeeperException ke) {
throw new KijiIOException(ke);
}
// Test ZooKeeperClients use a chroot to isolate testing environments.
return "localhost:" + zkCluster.getClientPort() + "/" + fakeId;
}
/**
* Creates a new MiniZooKeeperCluster if one does not already exist. Also creates and opens a
* ZooKeeperClient for the minicluster which is used to create chroot nodes before opening test
* ZooKeeperClients.
*
* @throws IOException in case of an error creating the temporary directory or starting the mini
* zookeeper cluster.
*/
private static MiniZooKeeperCluster getMiniZKCluster() throws IOException {
synchronized (MINIZK_CLUSTER_LOCK) {
if (mMiniZkCluster == null) {
final MiniZooKeeperCluster miniZK = new MiniZooKeeperCluster(new Configuration());
final File tempDir = File.createTempFile("mini-zk-cluster", "dir");
Preconditions.checkState(tempDir.delete());
Preconditions.checkState(tempDir.mkdirs());
try {
miniZK.startup(tempDir);
} catch (InterruptedException ie) {
throw new RuntimeInterruptedException(ie);
}
mMiniZkCluster = miniZK;
final String zkAddress ="localhost:" + mMiniZkCluster.getClientPort();
LOG.info("Creating testing utility ZooKeeperClient for {}", zkAddress);
mMiniZkClient = ZooKeeperClient.getZooKeeperClient(zkAddress);
}
return mMiniZkCluster;
}
}
/** {@inheritDoc} */
@Override
public ZooKeeperClient getZooKeeperClient(KijiURI uri) throws IOException {
return ZooKeeperClient.getZooKeeperClient(getZooKeeperEnsemble(uri));
}
/** {@inheritDoc} */
@Override
public String getZooKeeperEnsemble(KijiURI uri) {
final String fakeId = getFakeCassandraID(uri);
if (fakeId != null) {
try {
return createZooKeeperAddressForFakeId(fakeId);
} catch (IOException e) {
throw new KijiIOException(e.getCause());
}
}
// Not a test instance, delegate to default factory:
return DELEGATE.getZooKeeperEnsemble(uri);
}
}
| 12,838 | 0.693254 | 0.690762 | 350 | 35.68 | 30.2638 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.394286 | false | false |
12
|
1c84a9862204519545be97352e6f5095e4f15685
| 4,638,564,723,446 |
40a48e363b8a4324b18092338d31ca16ddce9e86
|
/src/ide/Airthematic.java
|
ea791f1720ee001b62d0e5efe537764c5fc0fe10
|
[] |
no_license
|
AnkitMittal0501/AutomationClass
|
https://github.com/AnkitMittal0501/AutomationClass
|
0b8e4a5ff80d7ede28ea1bc2d0b38bd48d098f4d
|
cf4b1524c59e444c3dbdeeda6f03cd4376e05c49
|
refs/heads/master
| 2020-04-24T10:39:52.086000 | 2019-02-21T15:59:56 | 2019-02-21T15:59:56 | 171,901,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ide;
import org.junit.Test;
public class Airthematic {
public int sum(int a, int b)
{
return a+b;
}
@Test
public void hashing()
{
String str="Hello";
Integer i=10;
System.out.println(str.hashCode());
System.out.println(i.hashCode());
}
}
|
UTF-8
|
Java
| 267 |
java
|
Airthematic.java
|
Java
|
[] | null |
[] |
package ide;
import org.junit.Test;
public class Airthematic {
public int sum(int a, int b)
{
return a+b;
}
@Test
public void hashing()
{
String str="Hello";
Integer i=10;
System.out.println(str.hashCode());
System.out.println(i.hashCode());
}
}
| 267 | 0.655431 | 0.64794 | 20 | 12.35 | 12.370428 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false |
5
|
a5da4a94a5b2d5dae7c4a1e5f2a6acf2477b60b1
| 35,012,573,400,709 |
05b07c14d221f74dba0fc24e7945d666eedc205b
|
/src/main/java/com/prodyna/training/spring/config/ApplicationConfiguration.java
|
9b25f7b870067ee6a53ab31bb7f063a8bada54a5
|
[] |
no_license
|
cankesen/spring-training
|
https://github.com/cankesen/spring-training
|
25b8f3deaa59fe781fc7a7a307f37d44d9171b63
|
fcd4072c1d54ef0dbd512e1a9166eb4d41edf6b8
|
refs/heads/master
| 2020-06-23T14:01:22.560000 | 2019-08-01T08:40:39 | 2019-08-01T08:40:39 | 198,642,797 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.prodyna.training.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Primary
@Configuration
@ComponentScan(basePackages = "com.prodyna.training.spring.*")
public class ApplicationConfiguration {
}
|
UTF-8
|
Java
| 354 |
java
|
ApplicationConfiguration.java
|
Java
|
[] | null |
[] |
package com.prodyna.training.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Primary
@Configuration
@ComponentScan(basePackages = "com.prodyna.training.spring.*")
public class ApplicationConfiguration {
}
| 354 | 0.838983 | 0.838983 | 13 | 26.23077 | 25.789545 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
5
|
6bceff87ce2dfeeb42f98097ee72ebc9f380c9de
| 34,488,587,403,481 |
9373c961fd51f47048891514465adb86f26c1ce6
|
/app/src/main/java/com/zhaoyao/miaomiao/db/DBHelper.java
|
548907605cb01f12e5ceff6212a3e746895dc9cf
|
[] |
no_license
|
mickelfeng/MiaoMiao
|
https://github.com/mickelfeng/MiaoMiao
|
f23a263e0ebc38487c4fbf812493047fe6fd92f3
|
004c50c3872191e2caeda9412342b02e131bd6cc
|
refs/heads/master
| 2023-03-18T20:24:11.999000 | 2018-03-14T09:51:38 | 2018-03-14T09:51:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhaoyao.miaomiao.db;
import android.content.Context;
import com.tgb.lk.ahibernate.util.MyDBHelper;
import com.zhaoyao.miaomiao.entity.GdtAdExposureClickEntity;
public class DBHelper extends MyDBHelper {
private static final String DBNAME = "miaomiao.db";// 数据库名
private static final int DBVERSION = 1;
private static final Class<?>[] clazz = {GdtAdExposureClickEntity.class};// 要初始化的表
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION, clazz);
}
}
|
UTF-8
|
Java
| 539 |
java
|
DBHelper.java
|
Java
|
[] | null |
[] |
package com.zhaoyao.miaomiao.db;
import android.content.Context;
import com.tgb.lk.ahibernate.util.MyDBHelper;
import com.zhaoyao.miaomiao.entity.GdtAdExposureClickEntity;
public class DBHelper extends MyDBHelper {
private static final String DBNAME = "miaomiao.db";// 数据库名
private static final int DBVERSION = 1;
private static final Class<?>[] clazz = {GdtAdExposureClickEntity.class};// 要初始化的表
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION, clazz);
}
}
| 539 | 0.739884 | 0.737958 | 20 | 25 | 26.886799 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
5
|
f706d67eef0893ae775a3efee2b7769cf1acf1e5
| 12,841,952,283,256 |
1dfc7a1e3e627e6163b7b171f78a9658c3332659
|
/project/test/java/parallel/littlemr/TestFullPass.java
|
123b91b8e781ac05fd76636a748ada6a1f4192aa
|
[] |
no_license
|
LanceNorskog/parallel
|
https://github.com/LanceNorskog/parallel
|
eebc86c8513c7ba31e103ef3cefb9ffd7c96228a
|
d42809a8cf953f6e839ab65ac0daf9e79298c326
|
refs/heads/master
| 2020-04-06T04:47:53.574000 | 2010-11-18T05:14:26 | 2010-11-18T05:14:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package parallel.littlemr;
import junit.framework.TestCase;
import parallel.littlemr.Collector;
import parallel.littlemr.CountingReducer;
import parallel.littlemr.Emitter;
import parallel.littlemr.IdentityMapper;
import parallel.littlemr.IdentityReducer;
import parallel.littlemr.Job;
import parallel.littlemr.Mapper;
import parallel.littlemr.Reducer;
import parallel.littlemr.SimpleCollector;
import parallel.littlemr.SimpleEmitter;
import parallel.littlemr.Swapper;
public class TestFullPass extends TestCase {
private static final String[] list1 = { "1", "2", "3" };
public TestFullPass(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testIdentity() {
Mapper<Object, Object, Object, Object> mapper = new IdentityMapper<Object, Object, Object, Object>();
Reducer<Object, Object> reducer = new IdentityReducer<Object, Object>();
Collector collector = new SimpleCollector();
Swapper<Object, Object> swapper = new Swapper<Object, Object>(reducer);
Emitter<Object, Object> emitter = new SimpleEmitter<Object, Object>(
swapper);
Job<Object, Object, Object, Object> job = new Job<Object, Object, Object, Object>(
mapper, reducer, emitter, collector, swapper);
for (String data : list1) {
job.input("ikey", data);
}
job.swap();
job = new Job<Object, Object, Object, Object>(mapper, reducer, collector);
for (String data : list1) {
job.input("ikey", data);
}
job.swap();
}
public void testCounting() {
Mapper<Object, Integer, String, Integer> mapper = new IdentityMapper<Object, Integer, String, Integer>();
Reducer<String, Integer> reducer = new CountingReducer<String>();
Collector collector = new SimpleCollector();
Job<Object, Integer, String, Integer> job = new Job<Object, Integer, String, Integer>(mapper, reducer, collector);
job.input("A", 1);
job.input("A", 2);
job.input("B", 3);
job.swap();
}
}
|
UTF-8
|
Java
| 2,064 |
java
|
TestFullPass.java
|
Java
|
[] | null |
[] |
package parallel.littlemr;
import junit.framework.TestCase;
import parallel.littlemr.Collector;
import parallel.littlemr.CountingReducer;
import parallel.littlemr.Emitter;
import parallel.littlemr.IdentityMapper;
import parallel.littlemr.IdentityReducer;
import parallel.littlemr.Job;
import parallel.littlemr.Mapper;
import parallel.littlemr.Reducer;
import parallel.littlemr.SimpleCollector;
import parallel.littlemr.SimpleEmitter;
import parallel.littlemr.Swapper;
public class TestFullPass extends TestCase {
private static final String[] list1 = { "1", "2", "3" };
public TestFullPass(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testIdentity() {
Mapper<Object, Object, Object, Object> mapper = new IdentityMapper<Object, Object, Object, Object>();
Reducer<Object, Object> reducer = new IdentityReducer<Object, Object>();
Collector collector = new SimpleCollector();
Swapper<Object, Object> swapper = new Swapper<Object, Object>(reducer);
Emitter<Object, Object> emitter = new SimpleEmitter<Object, Object>(
swapper);
Job<Object, Object, Object, Object> job = new Job<Object, Object, Object, Object>(
mapper, reducer, emitter, collector, swapper);
for (String data : list1) {
job.input("ikey", data);
}
job.swap();
job = new Job<Object, Object, Object, Object>(mapper, reducer, collector);
for (String data : list1) {
job.input("ikey", data);
}
job.swap();
}
public void testCounting() {
Mapper<Object, Integer, String, Integer> mapper = new IdentityMapper<Object, Integer, String, Integer>();
Reducer<String, Integer> reducer = new CountingReducer<String>();
Collector collector = new SimpleCollector();
Job<Object, Integer, String, Integer> job = new Job<Object, Integer, String, Integer>(mapper, reducer, collector);
job.input("A", 1);
job.input("A", 2);
job.input("B", 3);
job.swap();
}
}
| 2,064 | 0.705426 | 0.701066 | 63 | 30.761906 | 28.066086 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.507936 | false | false |
5
|
a425b9da385f2bd6759b621d84eda1caa0dabb9f
| 5,111,011,150,323 |
f8231f43014e05241ea786527ffe44cbb31d68b0
|
/src/main/java/com/proj/common/util/UserUtils.java
|
cbb1367f00b29237b303231ad7b0d59b2669eb4e
|
[] |
no_license
|
edisongchen/2015Proj
|
https://github.com/edisongchen/2015Proj
|
d9c13ee2d3369bd4c778b29a731b4bd4868c4b02
|
3be11728a0a61dcba3d61838d5bcbffef62a218a
|
refs/heads/master
| 2021-09-21T02:09:38.100000 | 2018-08-19T12:02:34 | 2018-08-19T12:02:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.proj.common.util;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.google.common.collect.Maps;
import com.proj.common.security.SysAuthorizaingRealm.Principal;
import com.proj.dao.mybatis.sys.IUserDao;
import com.proj.entity.sys.User;
/***
*
* @author ctg
* @date 2016年6月16日
*/
public class UserUtils {
private static IUserDao userDao = ApplicationContextHelper.getBean(IUserDao.class);
public static User getUser() {
User user = (User) getCache(Constant.CACHE_USER);
if (user == null) {
try {
Subject subject = SecurityUtils.getSubject();
Principal principal = (Principal) subject.getPrincipal();
if (principal != null) {
// 缓存中没有user
user = userDao.findById(principal.getId());
if (user != null) {
putCache(Constant.CACHE_USER, user);
} else {
SecurityUtils.getSubject().logout();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return user;
}
// ===============User Cache Principal cacheMap
public static Object getCache(String key) {
return getCache(key, null);
}
public static Object getCache(String key, Object defaultValue) {
Object obj = getCacheMap().get(key);
return obj != null ? obj : defaultValue;
}
public static void removeCache(String key) {
getCacheMap().remove(key);
}
public static void putCache(String key, Object value) {
getCacheMap().put(key, value);
}
/**
* shiro will use cache by configed ecache
*/
public static Map<String, Object> getCacheMap() {
try {
Subject subject = SecurityUtils.getSubject();
Principal principal = (Principal) subject.getPrincipal();
if (principal != null) {
return principal.getCacheMap();
} else {
Map<String, Object> map = Maps.newHashMap();
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> map = Maps.newHashMap();
return map;
}
}
|
UTF-8
|
Java
| 1,976 |
java
|
UserUtils.java
|
Java
|
[
{
"context": "ort com.proj.entity.sys.User;\n\n/***\n * \n * @author ctg\n * @date 2016年6月16日\n */\npublic class UserUtils {\n",
"end": 336,
"score": 0.9996102452278137,
"start": 333,
"tag": "USERNAME",
"value": "ctg"
}
] | null |
[] |
package com.proj.common.util;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.google.common.collect.Maps;
import com.proj.common.security.SysAuthorizaingRealm.Principal;
import com.proj.dao.mybatis.sys.IUserDao;
import com.proj.entity.sys.User;
/***
*
* @author ctg
* @date 2016年6月16日
*/
public class UserUtils {
private static IUserDao userDao = ApplicationContextHelper.getBean(IUserDao.class);
public static User getUser() {
User user = (User) getCache(Constant.CACHE_USER);
if (user == null) {
try {
Subject subject = SecurityUtils.getSubject();
Principal principal = (Principal) subject.getPrincipal();
if (principal != null) {
// 缓存中没有user
user = userDao.findById(principal.getId());
if (user != null) {
putCache(Constant.CACHE_USER, user);
} else {
SecurityUtils.getSubject().logout();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return user;
}
// ===============User Cache Principal cacheMap
public static Object getCache(String key) {
return getCache(key, null);
}
public static Object getCache(String key, Object defaultValue) {
Object obj = getCacheMap().get(key);
return obj != null ? obj : defaultValue;
}
public static void removeCache(String key) {
getCacheMap().remove(key);
}
public static void putCache(String key, Object value) {
getCacheMap().put(key, value);
}
/**
* shiro will use cache by configed ecache
*/
public static Map<String, Object> getCacheMap() {
try {
Subject subject = SecurityUtils.getSubject();
Principal principal = (Principal) subject.getPrincipal();
if (principal != null) {
return principal.getCacheMap();
} else {
Map<String, Object> map = Maps.newHashMap();
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> map = Maps.newHashMap();
return map;
}
}
| 1,976 | 0.675 | 0.671429 | 82 | 22.902439 | 20.643082 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.207317 | false | false |
5
|
18765d03e0c67fc9002aa699938ebb61d4ab400b
| 21,328,807,658,997 |
5f179a192fdda1933f8dccda73f254548817825a
|
/docroot/WEB-INF/src/com/idetronic/subur/portlet/ItemTypeNavigationPortlet.java
|
b81bc0f3c152818d41bed660a3c30162d78dbe6f
|
[] |
no_license
|
merbauraya/Subur
|
https://github.com/merbauraya/Subur
|
4e71f2a130fd4f87a40f8c9058e2bd3410877ac5
|
49f229aa33c37f888835928817acf964f4bcf35f
|
refs/heads/master
| 2021-01-18T21:24:03.841000 | 2016-05-19T05:03:06 | 2016-05-19T05:03:06 | 40,219,551 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.idetronic.subur.portlet;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.xml.namespace.QName;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ItemType
*/
public class ItemTypeNavigationPortlet extends MVCPortlet
{
private static Log logger = LogFactoryUtil.getLog(ItemTypeNavigationPortlet.class);
@Override
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException,
PortletException {
String itemTypeIds = ParamUtil.getString(actionRequest, "itemTypeIds");
if (Validator.isNotNull(itemTypeIds)) {
actionResponse.setRenderParameter("itemTypeId", itemTypeIds);
QName qName =
new QName("http://liferay.com", "itemTypeNav", "x");
actionResponse.setEvent(qName, itemTypeIds);
} else {
actionResponse.setRenderParameter("itemTypeId", StringPool.BLANK);
}
actionResponse.setRenderParameter("resetCur", Boolean.TRUE.toString());
super.processAction(actionRequest, actionResponse);
}
}
|
UTF-8
|
Java
| 1,447 |
java
|
ItemTypeNavigationPortlet.java
|
Java
|
[] | null |
[] |
package com.idetronic.subur.portlet;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.xml.namespace.QName;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class ItemType
*/
public class ItemTypeNavigationPortlet extends MVCPortlet
{
private static Log logger = LogFactoryUtil.getLog(ItemTypeNavigationPortlet.class);
@Override
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException,
PortletException {
String itemTypeIds = ParamUtil.getString(actionRequest, "itemTypeIds");
if (Validator.isNotNull(itemTypeIds)) {
actionResponse.setRenderParameter("itemTypeId", itemTypeIds);
QName qName =
new QName("http://liferay.com", "itemTypeNav", "x");
actionResponse.setEvent(qName, itemTypeIds);
} else {
actionResponse.setRenderParameter("itemTypeId", StringPool.BLANK);
}
actionResponse.setRenderParameter("resetCur", Boolean.TRUE.toString());
super.processAction(actionRequest, actionResponse);
}
}
| 1,447 | 0.752592 | 0.752592 | 48 | 29.145834 | 28.075041 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3125 | false | false |
5
|
f15d645786784bd84510309927a123e82b40c826
| 4,698,694,253,189 |
a6f2080f4218de1bdde4c231c0fc27a7027ffe50
|
/src/net/augcloud/arisa/saboteur/api/PlayerResidence.java
|
0d6432457417bd5355b29f2b0ba7d6ce720a03cd
|
[
"Apache-2.0"
] |
permissive
|
mcbbspluginmatch/Saboteur
|
https://github.com/mcbbspluginmatch/Saboteur
|
501b7c8b605010b8b879f3a0dfa0e3c114000991
|
90692b4dc15d22652e4feb7414a1c0e4f0ac5147
|
refs/heads/master
| 2020-06-27T04:28:37.996000 | 2019-08-07T08:31:53 | 2019-08-07T08:31:53 | 199,844,402 | 2 | 1 | null | true | 2019-07-31T11:39:35 | 2019-07-31T11:39:34 | 2019-07-30T17:28:42 | 2019-07-30T17:39:44 | 6,732 | 0 | 0 | 0 | null | false | false |
/**
All rights Reserved, Designed By www.aug.cloud
PlayerResidence.java
@Package net.augcloud.arisa.saboteur.behavior_instruction
@Description:
@author: Arisa
@date: 2019年7月30日 上午12:59:04
@version V1.0
@Copyright: 2019
*/
package net.augcloud.arisa.saboteur.api;
import org.bukkit.Location;
/**
@author Arisa
@date 2019年7月30日 上午12:59:04*/
public class PlayerResidence {
protected Location loc;
protected String name;
/**
PlayerResidence
@Description:*/
public PlayerResidence(Location _loc, String _name) {
this.loc = _loc;
this.name = _name;
}
/**
getLoc
@Description: 外部成员通过getter访问getLoc字段
@return: Location*/
public Location getLoc() {
return this.loc;
}
/**
@Title: setLoc
@Description: 外部成员通过setter方法修改字段
@return: Location*/
public void setLoc(Location loc) {
this.loc = loc;
}
/**
getName
@Description: 外部成员通过getter访问getName字段
@return: String*/
public String getName() {
return this.name;
}
/**
@Title: setName
@Description: 外部成员通过setter方法修改字段
@return: String*/
public void setName(String name) {
this.name = name;
}
/**
hashCode
@Description:
@return
@see java.lang.Object#hashCode()*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((this.loc == null) ? 0 : this.loc.hashCode());
result = (prime * result) + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
/**
equals
@Description:
@param obj
@return
@see java.lang.Object#equals(java.lang.Object)*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (! (obj instanceof PlayerResidence)) return false;
PlayerResidence other = (PlayerResidence) obj;
if (this.loc == null) {
if (other.loc != null) return false;
} else if (! this.loc.equals(other.loc)) return false;
if (this.name == null) {
if (other.name != null) return false;
} else if (! this.name.equals(other.name)) return false;
return true;
}
/**
toString
@Description:
@return
@see java.lang.Object#toString()*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PlayerResidence [");
if (this.loc != null) {
builder.append("loc=");
builder.append(this.loc);
builder.append(", ");
}
if (this.name != null) {
builder.append("name=");
builder.append(this.name);
}
builder.append("]");
return builder.toString();
}
}
|
GB18030
|
Java
| 2,650 |
java
|
PlayerResidence.java
|
Java
|
[
{
"context": "teur.behavior_instruction\r\n@Description:\r\n@author: Arisa\r\n@date: 2019年7月30日 上午12:59:04\r\n@version V1.0\r\n@",
"end": 163,
"score": 0.9996213316917419,
"start": 158,
"tag": "NAME",
"value": "Arisa"
},
{
"context": "pi;\r\n\r\nimport org.bukkit.Location;\r\n\r\n/**\r\n@author Arisa\r\n@date 2019年7月30日 上午12:59:04*/\r\npublic class Play",
"end": 327,
"score": 0.9996093511581421,
"start": 322,
"tag": "NAME",
"value": "Arisa"
}
] | null |
[] |
/**
All rights Reserved, Designed By www.aug.cloud
PlayerResidence.java
@Package net.augcloud.arisa.saboteur.behavior_instruction
@Description:
@author: Arisa
@date: 2019年7月30日 上午12:59:04
@version V1.0
@Copyright: 2019
*/
package net.augcloud.arisa.saboteur.api;
import org.bukkit.Location;
/**
@author Arisa
@date 2019年7月30日 上午12:59:04*/
public class PlayerResidence {
protected Location loc;
protected String name;
/**
PlayerResidence
@Description:*/
public PlayerResidence(Location _loc, String _name) {
this.loc = _loc;
this.name = _name;
}
/**
getLoc
@Description: 外部成员通过getter访问getLoc字段
@return: Location*/
public Location getLoc() {
return this.loc;
}
/**
@Title: setLoc
@Description: 外部成员通过setter方法修改字段
@return: Location*/
public void setLoc(Location loc) {
this.loc = loc;
}
/**
getName
@Description: 外部成员通过getter访问getName字段
@return: String*/
public String getName() {
return this.name;
}
/**
@Title: setName
@Description: 外部成员通过setter方法修改字段
@return: String*/
public void setName(String name) {
this.name = name;
}
/**
hashCode
@Description:
@return
@see java.lang.Object#hashCode()*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((this.loc == null) ? 0 : this.loc.hashCode());
result = (prime * result) + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
/**
equals
@Description:
@param obj
@return
@see java.lang.Object#equals(java.lang.Object)*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (! (obj instanceof PlayerResidence)) return false;
PlayerResidence other = (PlayerResidence) obj;
if (this.loc == null) {
if (other.loc != null) return false;
} else if (! this.loc.equals(other.loc)) return false;
if (this.name == null) {
if (other.name != null) return false;
} else if (! this.name.equals(other.name)) return false;
return true;
}
/**
toString
@Description:
@return
@see java.lang.Object#toString()*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PlayerResidence [");
if (this.loc != null) {
builder.append("loc=");
builder.append(this.loc);
builder.append(", ");
}
if (this.name != null) {
builder.append("name=");
builder.append(this.name);
}
builder.append("]");
return builder.toString();
}
}
| 2,650 | 0.642801 | 0.628245 | 119 | 19.361345 | 16.923323 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.394958 | false | false |
5
|
1dac7c83d57f957277361626c3aad46f09359734
| 18,769,007,131,008 |
b22459053cd39fdbfdb4dd7ec66572c80a7265e3
|
/ProgramacionOO/Practica13ColaConExcepciones/src/SacarElementoDeColaVaciaException.java
|
5ad32b4b414c0719c6838f4b18f870445858341b
|
[] |
no_license
|
ProgramacionPolitecnicoMalaga/PPM-Antonio-Borja-Badia-Checa
|
https://github.com/ProgramacionPolitecnicoMalaga/PPM-Antonio-Borja-Badia-Checa
|
e77213c8d13942093466472ae7ec9146e7833cc2
|
da016b364dcb6049417051d08c159bb49f4d2a54
|
refs/heads/master
| 2020-08-30T05:10:24.447000 | 2020-02-17T23:54:29 | 2020-02-17T23:54:29 | 218,272,715 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class SacarElementoDeColaVaciaException extends ArrayIndexOutOfBoundsException {
public SacarElementoDeColaVaciaException(String mensaje){
super(mensaje);
System.out.println("La cola no contiene elementos. Por ello no es posible extraer elememtos");
}
public String advertenciaException(){
return "No es posible sacar elementos. La cola ya está vacia";
}
}
|
UTF-8
|
Java
| 384 |
java
|
SacarElementoDeColaVaciaException.java
|
Java
|
[] | null |
[] |
public class SacarElementoDeColaVaciaException extends ArrayIndexOutOfBoundsException {
public SacarElementoDeColaVaciaException(String mensaje){
super(mensaje);
System.out.println("La cola no contiene elementos. Por ello no es posible extraer elememtos");
}
public String advertenciaException(){
return "No es posible sacar elementos. La cola ya está vacia";
}
}
| 384 | 0.78329 | 0.78329 | 15 | 24.533333 | 34.310089 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
5
|
7c874ad1dd1521777fb1e440ebd91352902db138
| 28,544,352,690,725 |
1dd58f330cffa8d08d24bfe239dbbb51b333c02b
|
/Rent.java
|
3532b37d3a31a533379ccbc293bd175a2e8f0cec
|
[] |
no_license
|
200GAUTAM/spoj_solutions
|
https://github.com/200GAUTAM/spoj_solutions
|
d72d2d74050f570866e4495f10d5b844498d0bfd
|
927ebe36998f2377493b4199fb7250573169b367
|
refs/heads/master
| 2021-01-17T08:22:44.796000 | 2017-03-10T13:24:33 | 2017-03-10T13:24:33 | 83,887,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
class Jobs
{
int startTime;
int durationTime;
int cost;
Jobs(int startTime, int durationTime, int cost )
{
this.startTime = startTime;
this.durationTime = durationTime;
this.cost = cost;
}
}
class jobComparator implements Comparator<Jobs>
{
public int compare(Jobs a, Jobs b)
{
return a.durationTime < b.durationTime ? -1 : a.durationTime == b.durationTime ? 0 : 1;
}
}
public class Main{
private static Reader in;
private static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(System.out, true);
int T = in.nextInt();
Jobs job[] = null;
while (T-- > 0) {
int N = in.nextInt() ;
job = new Jobs[N];
int start;
int end;
int cos;
for(int i = 0; i<N; i++)
{
start = in.nextInt();
end = in.nextInt();
end += start;
cos = in.nextInt();
job[i] = new Jobs(start, end, cos);
}
solve(job, N);
}
}
public static void solve(Jobs[] job, int n)
{
int dp[] = new int[n];
Arrays.sort(job, new jobComparator());
dp[0] = job[0].cost;
for(int i = 1; i<n; i++)
{
int profit = job[i].cost;
int index = bsearch(job, i);
if(index != -1)
{
profit += dp[index];
}
dp[i] = Math.max(profit, dp[i-1]);
}
out.println(dp[n-1]);
}
public static int bsearch(Jobs[] job, int index )
{
int low = 0, high = index-1;
while(low<=high)
{
int mid = (low+high)/2;
if(job[mid].durationTime<= job[index].startTime)
{
if(job[mid+1].durationTime<= job[index].startTime)
{
low = mid+1;
}else{
return mid;
}
}else{
high = mid-1;
}
}
return -1;
}
}
/** Faster input **/
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while( (c=read()) != -1) {
buf[cnt++] = (byte)c;
if(c == '\n') break;
}
return new String(buf,0,cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while(c <= ' ') c = read();
boolean neg = c == '-';
if(neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if(c == '.')
while((c=read()) >= '0' && c <= '9') {
div *= 10;
ret = ret + (c - '0') / div;
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if(din == null) return;
din.close();
}
}
|
UTF-8
|
Java
| 4,558 |
java
|
Rent.java
|
Java
|
[] | null |
[] |
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
class Jobs
{
int startTime;
int durationTime;
int cost;
Jobs(int startTime, int durationTime, int cost )
{
this.startTime = startTime;
this.durationTime = durationTime;
this.cost = cost;
}
}
class jobComparator implements Comparator<Jobs>
{
public int compare(Jobs a, Jobs b)
{
return a.durationTime < b.durationTime ? -1 : a.durationTime == b.durationTime ? 0 : 1;
}
}
public class Main{
private static Reader in;
private static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(System.out, true);
int T = in.nextInt();
Jobs job[] = null;
while (T-- > 0) {
int N = in.nextInt() ;
job = new Jobs[N];
int start;
int end;
int cos;
for(int i = 0; i<N; i++)
{
start = in.nextInt();
end = in.nextInt();
end += start;
cos = in.nextInt();
job[i] = new Jobs(start, end, cos);
}
solve(job, N);
}
}
public static void solve(Jobs[] job, int n)
{
int dp[] = new int[n];
Arrays.sort(job, new jobComparator());
dp[0] = job[0].cost;
for(int i = 1; i<n; i++)
{
int profit = job[i].cost;
int index = bsearch(job, i);
if(index != -1)
{
profit += dp[index];
}
dp[i] = Math.max(profit, dp[i-1]);
}
out.println(dp[n-1]);
}
public static int bsearch(Jobs[] job, int index )
{
int low = 0, high = index-1;
while(low<=high)
{
int mid = (low+high)/2;
if(job[mid].durationTime<= job[index].startTime)
{
if(job[mid+1].durationTime<= job[index].startTime)
{
low = mid+1;
}else{
return mid;
}
}else{
high = mid-1;
}
}
return -1;
}
}
/** Faster input **/
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while( (c=read()) != -1) {
buf[cnt++] = (byte)c;
if(c == '\n') break;
}
return new String(buf,0,cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while(c <= ' ') c = read();
boolean neg = c == '-';
if(neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c >= '0' && c <= '9');
if(c == '.')
while((c=read()) >= '0' && c <= '9') {
div *= 10;
ret = ret + (c - '0') / div;
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if(din == null) return;
din.close();
}
}
| 4,558 | 0.478499 | 0.466213 | 207 | 21.019323 | 16.958307 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.449275 | false | false |
5
|
a08d7364b69f51ab2ef8d42225f2701af9bce25e
| 28,544,352,691,360 |
4ffaa2fc63f73683002deb81f3528af61d7dda3b
|
/src/main/java/com/buraksay/aegean/context/AppContext.java
|
f6620b13733014e10fd367abea7b851ade73612c
|
[
"Apache-2.0"
] |
permissive
|
buraksay/aegean
|
https://github.com/buraksay/aegean
|
6a84dfbf800c2aa7ec11ab00481ef2f8af5dafc5
|
251ae71dffde8ac8669858f6b77b0821542b49fa
|
refs/heads/master
| 2020-04-30T06:27:56.879000 | 2015-01-15T21:14:27 | 2015-01-15T21:14:27 | 25,282,830 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.buraksay.aegean.context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public abstract class AppContext {
private static ApplicationContext appContext = null;
private static final Logger LOGGER = LoggerFactory.getLogger(AppContext.class);
public static void setApplicationContext(final ApplicationContext applicationContext) {
appContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
if (appContext == null) {
appContext = new ClassPathXmlApplicationContext("spring-context.xml");
}
return appContext;
}
}
|
UTF-8
|
Java
| 772 |
java
|
AppContext.java
|
Java
|
[] | null |
[] |
package com.buraksay.aegean.context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public abstract class AppContext {
private static ApplicationContext appContext = null;
private static final Logger LOGGER = LoggerFactory.getLogger(AppContext.class);
public static void setApplicationContext(final ApplicationContext applicationContext) {
appContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
if (appContext == null) {
appContext = new ClassPathXmlApplicationContext("spring-context.xml");
}
return appContext;
}
}
| 772 | 0.756477 | 0.753886 | 26 | 28.692308 | 29.966352 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
5
|
142b3b2ebf10cf09a79e534d65b22fd7a3c44b5f
| 5,111,011,152,403 |
39b8085de0451ce6b99e4ad2645f125abc2e6c75
|
/Proyecto/src/com/alberto/matamarcianos/screens/DeadScreen.java
|
651be2dd3238fca4ea6cf218815218b2159408aa
|
[] |
no_license
|
telpalbrox/matamarcianos3000
|
https://github.com/telpalbrox/matamarcianos3000
|
08b40ed5167fe6f20e175fd9272fd443a6313dd8
|
7e1afb87985e9f13f277b2bd4fc62d3536e7fce7
|
refs/heads/master
| 2021-01-01T16:50:46.195000 | 2014-01-24T23:23:59 | 2014-01-24T23:23:59 | 15,317,353 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.alberto.matamarcianos.screens;
import java.util.Collection;
import com.alberto.matamarcianos.Espacio;
import com.alberto.matamarcianos.InfoUtils;
import com.alberto.matamarcianos.Screens;
import com.alberto.matamarcianos.conexion.Facade;
import com.alberto.matamarcianos.conexion.PuntuacionesDTO;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class DeadScreen implements Screen {
private Stage stage;
private TextureAtlas atlas;
private Skin skin;
private Table table;
private TextButton buttonExit, buttonContinue;
private BitmapFont white, black;
private Label heading;
final Espacio game;
int puntuacion;
OrthographicCamera camera;
Facade fachada = new Facade();
Collection<PuntuacionesDTO> puntuaciones = null;
InfoUtils informacion = new InfoUtils();
boolean conexion = false;
int contador = 0;
public DeadScreen(final Espacio gam, String jugador, int pun) {
game = gam;
puntuacion = pun;
camera = new OrthographicCamera();
camera.setToOrtho(false, InfoUtils.x(), InfoUtils.y());
if(informacion.hayConexion()) {
conexion = true;
if(!jugador.isEmpty()) { //Si le da a cancelar no se envia la puntuacion
fachada.insertarPuntuacion(jugador, pun);
}
puntuaciones = fachada.obtenerPuntuaciones();
}
else {
conexion = false;
}
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if(conexion) {
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.font.draw(game.batch, "Mejores Puntuaciones", 25, 650);
contador = 0;
for(PuntuacionesDTO puntuacion : puntuaciones) {
game.font.draw(game.batch, puntuacion.obtenerJugador(), 25, 600-(contador*25));
game.font.draw(game.batch, String.valueOf(puntuacion.obtenerPuntuacion()), 125, 600-(contador*25));
if(puntuacion.obtenerVersion() != null)
game.font.draw(game.batch, puntuacion.obtenerVersion(), 160, 600-(contador*25));
contador++;
}
game.font.draw(game.batch, "Has muerto...", 225, 750);
game.font.draw(game.batch, "Pulsa R o tecla menu para continuar", 225, 725);
game.font.draw(game.batch, "Has conseguido: "+puntuacion+" puntos.", 225, 700);
game.batch.end();
stage.act(delta);
stage.draw();
}
else {
game.setScreen(new ErrorScreen(game, "No hay conexion con la base de datos :("));
}
}
public void resume() {
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
atlas = new TextureAtlas("data/ui/button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(Gdx.graphics.getWidth() - 250, Gdx.graphics.getHeight() - 200, 200, 200);
white = new BitmapFont(Gdx.files.internal("data/fonts/fuente4.fnt"), false);
black = new BitmapFont(Gdx.files.internal("data/fonts/fuente3.fnt"), false);
// creando los botones
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("boton.up");
textButtonStyle.down = skin.getDrawable("boton.down");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = black;
buttonExit = new TextButton("SALIR", textButtonStyle);
buttonContinue = new TextButton("VOLVER A JUGAR", textButtonStyle);
buttonExit.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
buttonContinue.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(Screens.juego = new GameScreen(game));
}
});
buttonExit.pad(4);
buttonContinue.pad(4);
LabelStyle headingStyle = new LabelStyle(white, Color.WHITE);
heading = new Label("Matamarcianos 3000", headingStyle);
// aniadiendolo todo a la tabla para tenerlo todo junto
table.add(buttonContinue);
table.row();
table.add(buttonExit);
table.debug();
stage.addActor(table);
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
}
}
|
UTF-8
|
Java
| 5,264 |
java
|
DeadScreen.java
|
Java
|
[] | null |
[] |
package com.alberto.matamarcianos.screens;
import java.util.Collection;
import com.alberto.matamarcianos.Espacio;
import com.alberto.matamarcianos.InfoUtils;
import com.alberto.matamarcianos.Screens;
import com.alberto.matamarcianos.conexion.Facade;
import com.alberto.matamarcianos.conexion.PuntuacionesDTO;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class DeadScreen implements Screen {
private Stage stage;
private TextureAtlas atlas;
private Skin skin;
private Table table;
private TextButton buttonExit, buttonContinue;
private BitmapFont white, black;
private Label heading;
final Espacio game;
int puntuacion;
OrthographicCamera camera;
Facade fachada = new Facade();
Collection<PuntuacionesDTO> puntuaciones = null;
InfoUtils informacion = new InfoUtils();
boolean conexion = false;
int contador = 0;
public DeadScreen(final Espacio gam, String jugador, int pun) {
game = gam;
puntuacion = pun;
camera = new OrthographicCamera();
camera.setToOrtho(false, InfoUtils.x(), InfoUtils.y());
if(informacion.hayConexion()) {
conexion = true;
if(!jugador.isEmpty()) { //Si le da a cancelar no se envia la puntuacion
fachada.insertarPuntuacion(jugador, pun);
}
puntuaciones = fachada.obtenerPuntuaciones();
}
else {
conexion = false;
}
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if(conexion) {
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.font.draw(game.batch, "Mejores Puntuaciones", 25, 650);
contador = 0;
for(PuntuacionesDTO puntuacion : puntuaciones) {
game.font.draw(game.batch, puntuacion.obtenerJugador(), 25, 600-(contador*25));
game.font.draw(game.batch, String.valueOf(puntuacion.obtenerPuntuacion()), 125, 600-(contador*25));
if(puntuacion.obtenerVersion() != null)
game.font.draw(game.batch, puntuacion.obtenerVersion(), 160, 600-(contador*25));
contador++;
}
game.font.draw(game.batch, "Has muerto...", 225, 750);
game.font.draw(game.batch, "Pulsa R o tecla menu para continuar", 225, 725);
game.font.draw(game.batch, "Has conseguido: "+puntuacion+" puntos.", 225, 700);
game.batch.end();
stage.act(delta);
stage.draw();
}
else {
game.setScreen(new ErrorScreen(game, "No hay conexion con la base de datos :("));
}
}
public void resume() {
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
atlas = new TextureAtlas("data/ui/button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(Gdx.graphics.getWidth() - 250, Gdx.graphics.getHeight() - 200, 200, 200);
white = new BitmapFont(Gdx.files.internal("data/fonts/fuente4.fnt"), false);
black = new BitmapFont(Gdx.files.internal("data/fonts/fuente3.fnt"), false);
// creando los botones
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("boton.up");
textButtonStyle.down = skin.getDrawable("boton.down");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = black;
buttonExit = new TextButton("SALIR", textButtonStyle);
buttonContinue = new TextButton("VOLVER A JUGAR", textButtonStyle);
buttonExit.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
buttonContinue.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(Screens.juego = new GameScreen(game));
}
});
buttonExit.pad(4);
buttonContinue.pad(4);
LabelStyle headingStyle = new LabelStyle(white, Color.WHITE);
heading = new Label("Matamarcianos 3000", headingStyle);
// aniadiendolo todo a la tabla para tenerlo todo junto
table.add(buttonContinue);
table.row();
table.add(buttonExit);
table.debug();
stage.addActor(table);
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
}
}
| 5,264 | 0.705167 | 0.68807 | 179 | 27.407822 | 24.470165 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.167598 | false | false |
5
|
d9cea9a46d676777bb5b84ddd45e39e565a72f31
| 36,094,905,158,807 |
4228d9578d4ac16b22335516b71a7d7852f7f36e
|
/src/main/java/io/github/lujian213/simulator/manager/ScriptInfo.java
|
39ebfb9d77dcc06b932755f2893c1ae2fe74a78a
|
[
"Apache-2.0"
] |
permissive
|
lujian213/SmartSimulator
|
https://github.com/lujian213/SmartSimulator
|
e0ad0a211c7f378335824549e921dbe7c7d68fca
|
76bff8a50823cf729b1c0d8f0a39fde0f5f45c17
|
refs/heads/master
| 2022-11-26T05:26:31.319000 | 2020-03-01T13:07:56 | 2020-03-01T13:07:56 | 145,284,475 | 14 | 8 |
Apache-2.0
| false | 2022-11-16T08:55:36 | 2018-08-19T08:05:49 | 2021-04-17T12:22:04 | 2022-11-16T08:55:33 | 2,838 | 14 | 7 | 7 |
Java
| false | false |
package io.github.lujian213.simulator.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import io.github.lujian213.simulator.SimScript;
import io.github.lujian213.simulator.SimScript.TemplatePair;
public class ScriptInfo {
String name;
List<TemplatePairInfo> templatePairs = new ArrayList<>();
List<ScriptInfo> subScripts = new ArrayList<>();
Properties props = new Properties();
public ScriptInfo(String name, SimScript script) {
this(name, script, false);
}
public ScriptInfo(String name, SimScript script, boolean raw) {
this.name = name;
this.props = raw ? script.getLocalConfigAsRawProperties() : script.getConfigAsProperties();
script.getSubScripts().forEach((key, value)->subScripts.add(new ScriptInfo(key, value, raw)));
List<TemplatePair> templatePairs = raw ? script.getTemplatePairs() : script.getEffectiveTemplatePairs();
templatePairs.forEach((pair) ->this.templatePairs.add(new TemplatePairInfo(pair)));
}
public List<TemplatePairInfo> getTemplatePairs() {
return templatePairs;
}
public List<ScriptInfo> getSubScripts() {
return subScripts;
}
public Properties getProps() {
return props;
}
public String getName() {
return name;
}
}
|
UTF-8
|
Java
| 1,232 |
java
|
ScriptInfo.java
|
Java
|
[
{
"context": "package io.github.lujian213.simulator.manager;\n\nimport java.util.ArrayList;\ni",
"end": 27,
"score": 0.9995623826980591,
"start": 18,
"tag": "USERNAME",
"value": "lujian213"
},
{
"context": "t;\nimport java.util.Properties;\n\nimport io.github.lujian213.simulator.SimScript;\nimport io.github.lujian213.s",
"end": 155,
"score": 0.9995646476745605,
"start": 146,
"tag": "USERNAME",
"value": "lujian213"
},
{
"context": "b.lujian213.simulator.SimScript;\nimport io.github.lujian213.simulator.SimScript.TemplatePair;\n\npublic class S",
"end": 203,
"score": 0.9995034337043762,
"start": 194,
"tag": "USERNAME",
"value": "lujian213"
}
] | null |
[] |
package io.github.lujian213.simulator.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import io.github.lujian213.simulator.SimScript;
import io.github.lujian213.simulator.SimScript.TemplatePair;
public class ScriptInfo {
String name;
List<TemplatePairInfo> templatePairs = new ArrayList<>();
List<ScriptInfo> subScripts = new ArrayList<>();
Properties props = new Properties();
public ScriptInfo(String name, SimScript script) {
this(name, script, false);
}
public ScriptInfo(String name, SimScript script, boolean raw) {
this.name = name;
this.props = raw ? script.getLocalConfigAsRawProperties() : script.getConfigAsProperties();
script.getSubScripts().forEach((key, value)->subScripts.add(new ScriptInfo(key, value, raw)));
List<TemplatePair> templatePairs = raw ? script.getTemplatePairs() : script.getEffectiveTemplatePairs();
templatePairs.forEach((pair) ->this.templatePairs.add(new TemplatePairInfo(pair)));
}
public List<TemplatePairInfo> getTemplatePairs() {
return templatePairs;
}
public List<ScriptInfo> getSubScripts() {
return subScripts;
}
public Properties getProps() {
return props;
}
public String getName() {
return name;
}
}
| 1,232 | 0.757305 | 0.75 | 43 | 27.651163 | 29.141901 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.488372 | false | false |
5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.