blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
850f6a5e9b47f147ba792d5502d2fc6acb140199
b6548126a3c37b6dc7fa6c04b1940914ab24957a
/Proyecto Lucy's Mansion/NivelFacil.java
c3167836ded975d8c19682c7bd0e5b658a20ad9f
[]
no_license
objetos16171/Lucy-s-Mansion
a912a52631899667d5151611c09b88360463ec41
1376fcf0dddc665943a17d645527e69b102585a5
refs/heads/master
2021-01-09T23:35:53.710518
2016-12-07T23:34:33
2016-12-07T23:34:33
73,215,814
1
2
null
2016-12-07T23:34:33
2016-11-08T18:38:28
Java
UTF-8
Java
false
false
664
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class NivelFacil here. * * @author (your name) * @version (a version number or a date) */ class NivelFacil extends Boton{ private Jugador player; public NivelFacil(String nombreBoton){ super(nombreBoton); } /** * */ public void act(){ if(Greenfoot.mouseClicked(this)){ player = new Jugador(5, 425, 380, "Lucy0.png"); mundoSig = new Recepcion("FondoRecepcion.png", 4, player); Greenfoot.setWorld(mundoSig); } } }
1aa2863303e3983f7099dc5054ed9471bc6bc18d
626be6255421799844d5ed8eaaf0f1176adbdbca
/app/src/main/java/com/project/sportycart/CategoryProducts.java
e09be8a4493131b301239b1625f116919ba491a4
[]
no_license
ishu22994/SportyCart
fe321c25bd235b719587a4e7ee7cc2e07e8cfddd
b476928188562c31a9164863ce045523c5780af5
refs/heads/master
2020-12-20T08:25:20.213331
2020-01-24T11:34:03
2020-01-24T11:34:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,289
java
package com.project.sportycart; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import com.project.sportycart.adapter.CategoryAdapter; import com.project.sportycart.entity.Product; import com.project.sportycart.retrofit.GetProductsService; import com.project.sportycart.retrofit.RetrofitClientInstance; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CategoryProducts extends AppCompatActivity implements CategoryAdapter.ProductCommunication{ private RecyclerView categoryRecyclerView; private RecyclerView.Adapter categoryAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category_products); System.out.println("IN CATEGORY"); Intent intent=getIntent(); Integer categoryId=intent.getIntExtra("categoryId",3); System.out.println("InCategory:"+categoryId); GetProductsService getProductsService = RetrofitClientInstance.getRetrofitInstance().create(GetProductsService.class); Call<List<Product>> call= getProductsService.getCategoryProducts(1,categoryId); call.enqueue(new Callback<List<Product>>() { @Override public void onResponse(Call<List<Product>> call, Response<List<Product>> response) { generateDataList(response.body()); System.out.println("API HIT"); } @Override public void onFailure(Call<List<Product>> call, Throwable t) { Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show(); } }); } private void generateDataList(List<Product> list){ categoryRecyclerView=findViewById(R.id.cat_recycler_view); categoryAdapter=new CategoryAdapter(list,this); GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),2); categoryRecyclerView.setLayoutManager(gridLayoutManager); categoryRecyclerView.setAdapter(categoryAdapter); } @Override public void onClick(Product product) { Intent productIntent=new Intent( CategoryProducts.this, ProductDetails.class); productIntent.putExtra("Image", product.getImageUrl()); productIntent.putExtra("ProductName",product.getName()); productIntent.putExtra(("ProductDescription"),(String)product.getDescription()); if(product.getProductAttributes()!=null) { productIntent.putExtra(("ColorAttribute"), (String) product.getProductAttributes().getColor()); productIntent.putExtra(("SizeAttribute"), (String) product.getProductAttributes().getSize()); productIntent.putExtra(("MaterialAttribute"), (String) product.getProductAttributes().getMaterial()); productIntent.putExtra(("PID"),product.getProductId()); } else{ Toast.makeText(getApplicationContext(),"CATEGORY PRODUCT",Toast.LENGTH_SHORT).show(); } startActivity(productIntent); } }
dc137ac70a1b822f0a7589a127f60e379559c8df
36c913019bbe9c2b5474a9b548f0b75139442150
/workspaceCSCI4980-Ayinala/project0828-message-Ayinala/src/project0828_message_ayinala/Activator.java
45b1d8430b2dd9fa9277f302e270a44cca784cd3
[]
no_license
kteja-ayinala/workspaceCSCI4980
9b55ae074d4f6d5b4510cdaef7ee3aada20c63f9
59ba1296729f354e35268fe526efb89f3f6370e5
refs/heads/master
2020-03-27T16:17:01.823241
2019-03-13T18:57:54
2019-03-13T18:57:54
146,771,430
1
1
null
null
null
null
UTF-8
Java
false
false
734
java
package project0828_message_ayinala; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class Activator implements BundleActivator { private static BundleContext context; static BundleContext getContext() { return context; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext bundleContext) throws Exception { Activator.context = bundleContext; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) throws Exception { Activator.context = null; } }
47299f3d41aa7e06d4fdf120bcee4e33588ee6c2
24b27fb3aae15c9ff5dda8d01683e9c9220ce09c
/src/Pelicula.java
3b9c25645ddbce6c6edf752c0198e6c4decfbdfc
[]
no_license
Myu-War/Biblio
b15e524f09b255a1ac617ea22904c3cadd689326
ba63244fe9ede9d81b084b7ab0dc40e81d41389c
refs/heads/master
2020-06-02T21:23:34.672772
2015-04-23T16:07:03
2015-04-23T16:07:03
30,604,912
0
0
null
null
null
null
UTF-8
Java
false
false
701
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author introduccion02 */ public class Pelicula extends ArticuloBiblioteca { private String director; public Pelicula(String nombre, String director) { super(nombre); this.director = director; this.objeto = "Pelicula"; } public String copiado() { return "No se puede copiar"; } @Override public String toString() { StringBuilder cad = new StringBuilder(); cad.append(super.toString()); cad.append("\nDirector: " + director); return cad.toString(); } }
b1c16703d81aac90373346090002d3659de37f41
8f59676c50ac085484778b4edf0c923745e72929
/src/com/codecool/thao/eventmanagement/app/Main.java
5c8a2b0b3878bb8425b1dc7ee9ef1563bd63365e
[]
no_license
thaoPhLam/EventManagement
eb7378c5b97fee8d211d9fbb5bff1cb5ed312783
1d1fe15140c0e8166371d99f0e60f74be564e509
refs/heads/master
2020-04-26T18:19:58.529004
2019-03-04T12:35:02
2019-03-04T12:35:02
170,318,612
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package com.codecool.thao.eventmanagement.app; import com.codecool.thao.eventmanagement.BreakTimeActivity; import com.codecool.thao.eventmanagement.Company; import com.codecool.thao.eventmanagement.Party; import com.codecool.thao.eventmanagement.employee.Helper; import com.codecool.thao.eventmanagement.employee.Manager; public class Main { public static void main(String[] args) { Company company = new Company(); company.hireEmployee(new Manager("Thao", company)); company.hireEmployee(new Helper("Mai", BreakTimeActivity.COFFEE)); company.hireEmployee(new Helper("Miki", BreakTimeActivity.SMOKING)); company.organizeParty(Party.WEDDING); } }
ac0620391d5c4e1d90e2400674c6d7e3aaa01f80
580ff62ff2e0fa4f61ea59bc6d9ca87a85dc7385
/organizeme-core/src/main/java/com/talsoft/organizeme/core/util/log/Slf4JELSessionLogger.java
53dab56a826f4414b9d31b33ece32dfb7dd36e75
[]
no_license
piibl/organizeme
7064a9ce06bf495c81aff03a1152f96cf423a9b6
d31abcef3e81f22ae490cecf316132dc59caa55c
refs/heads/master
2020-05-04T19:12:07.064447
2014-06-26T10:16:20
2014-06-26T10:16:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,657
java
package com.talsoft.organizeme.core.util.log; import java.util.HashMap; import java.util.Map; import org.eclipse.persistence.logging.AbstractSessionLog; import org.eclipse.persistence.logging.SessionLog; import org.eclipse.persistence.logging.SessionLogEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; /** * Adaptateur SL4J pour le session logger d'EclipseLink * * @author pblanchard */ public class Slf4JELSessionLogger extends AbstractSessionLog { /** * Package de logging d'EL => namespace */ public static final String ECLIPSELINK_NAMESPACE = "org.eclipse.persistence.logging"; /** * Catégorie de traces par défaut = "default" */ public static final String DEFAULT_CATEGORY = "default"; private static final String DEFAULT_ECLIPSELINK_NAMESPACE = ECLIPSELINK_NAMESPACE + "." + DEFAULT_CATEGORY; /** * Niveaux de traces possibles */ private Map<Integer, LogLevel> mapLevels; /** * Catégories de traces possibles */ private Map<String, Logger> categoryLoggers = new HashMap<String, Logger>(); public Slf4JELSessionLogger() { super(); // INIT createCategoryLoggers(); initMapLevels(); } /** * comportement par défaut = debug */ @Override public void log(SessionLogEntry entry) { if (!shouldLog(entry.getLevel(), entry.getNameSpace())) { return; } Logger logger = getLogger(entry.getNameSpace()); LogLevel logLevel = getLogLevel(entry.getLevel()); StringBuilder message = new StringBuilder(); message.append(getSupplementDetailString(entry)); message.append(formatMessage(entry)); switch (logLevel) { case TRACE: logger.trace(message.toString()); break; case DEBUG: logger.debug(message.toString()); break; case INFO: logger.info(message.toString()); break; case WARN: logger.warn(message.toString()); break; case ERROR: logger.error(message.toString()); break; default: logger.debug(message.toString()); break; } } /** * comportement par défaut = debug */ @Override public boolean shouldLog(int level, String category) { Logger logger = getLogger(category); boolean resp = false; LogLevel logLevel = getLogLevel(level); switch (logLevel) { case TRACE: resp = logger.isTraceEnabled(); break; case DEBUG: resp = logger.isDebugEnabled(); break; case INFO: resp = logger.isInfoEnabled(); break; case WARN: resp = logger.isWarnEnabled(); break; case ERROR: resp = logger.isErrorEnabled(); break; default: resp = logger.isDebugEnabled(); break; } return resp; } @Override public boolean shouldLog(int level) { return shouldLog(level, "default"); } @Override public boolean shouldDisplayData() { if (this.shouldDisplayData != null) { return shouldDisplayData.booleanValue(); } else { return false; } } /** * Initialise les loggers pour les différentes catégories */ private void createCategoryLoggers() { for (String category : SessionLog.loggerCatagories) { addLogger(category, ECLIPSELINK_NAMESPACE + "." + category); } // Logger par défaut addLogger(DEFAULT_CATEGORY, DEFAULT_ECLIPSELINK_NAMESPACE); } /** * Ajoute un logger dans la map des catégories */ private void addLogger(String loggerCategory, String loggerNameSpace) { categoryLoggers.put(loggerCategory, LoggerFactory.getLogger(loggerNameSpace)); } /** * Retourne le logger correspondant à une catégorie donnée */ private Logger getLogger(String category) { if (!StringUtils.hasText(category) || !this.categoryLoggers.containsKey(category)) { category = DEFAULT_CATEGORY; } return categoryLoggers.get(category); } /** * Retourne la correspondance d'un niveau de trace EL en niveau slf4j */ private LogLevel getLogLevel(Integer level) { LogLevel logLevel = mapLevels.get(level); if (logLevel == null) logLevel = LogLevel.OFF; return logLevel; } /** * Niveaux de traces Slf4j */ enum LogLevel { TRACE, DEBUG, INFO, WARN, ERROR, OFF } /** * Initialise la map des correspondances entre les niveaux de traces d'EL et ceux de Slf4j */ private void initMapLevels() { mapLevels = new HashMap<Integer, LogLevel>(); mapLevels.put(SessionLog.ALL, LogLevel.TRACE); mapLevels.put(SessionLog.FINEST, LogLevel.TRACE); mapLevels.put(SessionLog.FINER, LogLevel.TRACE); mapLevels.put(SessionLog.FINE, LogLevel.DEBUG); mapLevels.put(SessionLog.CONFIG, LogLevel.INFO); mapLevels.put(SessionLog.INFO, LogLevel.INFO); mapLevels.put(SessionLog.WARNING, LogLevel.WARN); mapLevels.put(SessionLog.SEVERE, LogLevel.ERROR); } }
6b5cd84cd7e7e9f49a96cd3137294e76ecbf0d09
ce51b3104681db4689cdd159aca9981f773d9f3c
/app/src/main/java/com/example/administrator/day0121/activity/CreateActivity.java
0b1b312a3e325a153b9e21e8d7e6b59dc7bdde3c
[]
no_license
Mumblebo/ZhongYuVideo
d7c5009cac435c8a57de28ee71423c8ca97c26ee
3d6a5883a458a27d85b6387681bc15512dca7d36
refs/heads/master
2021-01-18T13:33:50.700912
2016-06-26T02:05:56
2016-06-26T02:05:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,623
java
package com.example.administrator.day0121.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.administrator.day0121.R; import com.example.administrator.day0121.utils.ConfigUtil; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.jpush.android.api.JPushInterface; import cn.smssdk.EventHandler; import cn.smssdk.SMSSDK; import cn.smssdk.utils.SMSLog; public class CreateActivity extends AppCompatActivity implements View.OnClickListener { private EditText phone, et_mima, et_mima2, cord, et_yaoqing; private TextView now, getCord, saveCord, tv_content, tv_login; private String iPhone, iCord; private int time = 60; private StringRequest stringRequest1, stringRequest2; private RequestQueue mQueue; private String szImei;//设备唯一标识 private SharedPreferences sp; private Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); showMessage(); initView(); initData(); initListener(); SMSSDK.initSDK(this, "1017746d6ae86", "689d17a739b8d33423f4f152c355b0d5"); EventHandler eh = new EventHandler() { @Override public void afterEvent(int event, int result, Object data) { Message msg = new Message(); msg.arg1 = event; msg.arg2 = result; msg.obj = data; handler.sendMessage(msg); } }; SMSSDK.registerEventHandler(eh); } private void showMessage() { new AlertDialog.Builder(this).setTitle("提示").setMessage("如果你在中域题库中有账号,请直接登录").setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(CreateActivity.this, LoginActivity.class); startActivity(intent); finish(); } }).setNegativeButton("取消", null).show(); } private void initData() { TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); szImei = TelephonyMgr.getDeviceId(); mQueue = Volley.newRequestQueue(this); } private void initListener() { getCord.setOnClickListener(this); saveCord.setOnClickListener(this); tv_content.setOnClickListener(this); tv_login.setOnClickListener(this); } private void initView() { phone = (EditText) findViewById(R.id.phone); cord = (EditText) findViewById(R.id.cord); now = (TextView) findViewById(R.id.now); getCord = (TextView) findViewById(R.id.getcord); saveCord = (TextView) findViewById(R.id.savecord); et_mima = (EditText) findViewById(R.id.et_mima); et_mima2 = (EditText) findViewById(R.id.et_mima2); tv_content = (TextView) findViewById(R.id.tv_content); et_yaoqing = (EditText) findViewById(R.id.et_yaoqing); tv_login = (TextView) findViewById(R.id.tv_login); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.getcord://获取验证码 if (!TextUtils.isEmpty(phone.getText().toString().trim())) { if (phone.getText().toString().trim().length() == 11) { iPhone = phone.getText().toString().trim(); SMSSDK.getVerificationCode("86", iPhone); cord.requestFocus(); getCord.setVisibility(View.GONE); } else { Toast.makeText(this, "请输入完整电话号码", Toast.LENGTH_LONG).show(); phone.requestFocus(); } } else { Toast.makeText(this, "请输入您的电话号码", Toast.LENGTH_LONG).show(); phone.requestFocus(); } break; case R.id.savecord://学员注册 if (et_yaoqing.getText().toString().length() < 8) { Toast.makeText(this, "请输入邀请码", Toast.LENGTH_SHORT).show(); return; } if (et_mima.getText().toString().length() < 6) { Toast.makeText(this, "请输入至少六位的密码", Toast.LENGTH_SHORT).show(); return; } if (!et_mima.getText().toString().equals(et_mima2.getText().toString())) { Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show(); return; } if (!TextUtils.isEmpty(cord.getText().toString().trim())) { //验证验证码 if (cord.getText().toString().trim().length() == 4) { iCord = cord.getText().toString().trim(); SMSSDK.submitVerificationCode("86", iPhone, iCord); //通过post请求把号码和密码传到服务器进行注册 } else { Toast.makeText(this, "请输入完整验证码", Toast.LENGTH_LONG).show(); cord.requestFocus(); } } else { Toast.makeText(this, "请输入验证码", Toast.LENGTH_LONG).show(); cord.requestFocus(); } break; case R.id.tv_content://联系客服 Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:4008-355-366")); startActivity(intent); break; case R.id.tv_login: Intent intent1 = new Intent(this, LoginActivity.class); startActivity(intent1); finish(); break; } } //验证码送成功后提示文字 private void reminderText() { now.setVisibility(View.VISIBLE); handlerText.sendEmptyMessageDelayed(1, 1000); } Handler handlerText = new Handler() { public void handleMessage(Message msg) { if (msg.what == 1) { if (time > 0) { now.setText("验证码已发送" + time + "秒"); time--; handlerText.sendEmptyMessageDelayed(1, 1000); } else { now.setText("提示信息"); time = 60; now.setVisibility(View.GONE); getCord.setVisibility(View.VISIBLE); } } else { cord.setText(""); now.setText("提示信息"); time = 60; now.setVisibility(View.GONE); getCord.setVisibility(View.VISIBLE); } } ; }; private Handler handler = new Handler() { public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); int event = msg.arg1; int result = msg.arg2; Object data = msg.obj; Log.e("event", "event=" + event); System.out.println("--------result---0" + event + "--------*" + result + "--------" + data); if (result == SMSSDK.RESULT_COMPLETE) { System.out.println("--------result---1" + event + "--------*" + result + "--------" + data); //短信注册成功后,返回MainActivity,然后提示新好友 if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功 create(); } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { //已经验证 Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show(); reminderText(); } } else { int status = 0; try { ((Throwable) data).printStackTrace(); Throwable throwable = (Throwable) data; JSONObject object = new JSONObject(throwable.getMessage()); String des = object.optString("detail"); status = object.optInt("status"); if (!TextUtils.isEmpty(des)) { Toast.makeText(CreateActivity.this, des, Toast.LENGTH_SHORT).show(); return; } } catch (Exception e) { SMSLog.getInstance().w(e); } } } }; private final String mPageName = "CreateActivity"; @Override protected void onResume() { super.onResume(); MobclickAgent.onPageStart(mPageName); MobclickAgent.onResume(this); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(mPageName); MobclickAgent.onPause(this); } @Override protected void onDestroy() { super.onDestroy(); SMSSDK.unregisterAllEventHandler(); } //注册逻辑 public void create() { dialog = new AlertDialog.Builder(this).setTitle("注册...").setCancelable(false).show(); String httpUrl = "http://www.zhongyuedu.com/api/sp/register.php";//公司服务器 stringRequest1 = new StringRequest(Request.Method.POST, httpUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { //服务器返回的内容 try { JSONObject jsonObject = new JSONObject(response); String resultCode = jsonObject.getString("resultCode"); String result = jsonObject.getString("result"); if (resultCode.equals("0")) { JSONObject jsonObject1 = jsonObject.getJSONObject("result"); String token = jsonObject1.getString("token"); String groupId = jsonObject1.getString("groupid"); String grouptitle = jsonObject1.getString("grouptitle"); String uid = jsonObject1.getString("uid"); sp = getSharedPreferences(ConfigUtil.spKey, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("number", phone.getText().toString()); editor.putString("password", et_mima.getText().toString()); editor.putString("groupId", groupId); editor.putString("uid", uid); editor.putString("token", token); editor.putString("grouptitle", grouptitle); editor.commit(); Toast.makeText(CreateActivity.this, "注册成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(CreateActivity.this, MainActivity.class); startActivity(intent); dialog.dismiss(); finish(); } else if (resultCode.equals("1")) { Toast.makeText(CreateActivity.this, "账号已存在,检验邀请码...", Toast.LENGTH_SHORT).show(); useInviteCode(); } else { Toast.makeText(CreateActivity.this, result, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); Toast.makeText(CreateActivity.this, "网络连接有问题", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("username", phone.getText().toString().trim()); map.put("password", et_mima.getText().toString().trim()); map.put("inviteCode", et_yaoqing.getText().toString().trim()); map.put("udid", szImei); return map; } }; mQueue.add(stringRequest1); } //判断邀请码 private void useInviteCode() { String httpUrl = "http://www.zhongyuedu.com/api/sp/useinvitecode.php";//公司服务器 stringRequest2 = new StringRequest(Request.Method.POST, httpUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String resultCode = jsonObject.getString("resultCode"); String result = jsonObject.getString("result"); if (resultCode.equals("0")) {//登录成功 JSONObject jsonObject1 = jsonObject.getJSONObject("result"); String token = jsonObject1.getString("token"); String groupId = jsonObject1.getString("groupid"); String grouptitle = jsonObject1.getString("grouptitle"); String uid = jsonObject1.getString("uid"); sp = getSharedPreferences(ConfigUtil.spKey, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("number", phone.getText().toString().trim()); editor.putString("groupId", groupId); editor.putString("uid", uid); editor.putString("token", token); editor.putString("grouptitle", grouptitle); editor.commit(); Toast.makeText(CreateActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(CreateActivity.this, MainActivity.class); startActivity(intent); dialog.dismiss(); finish(); } else {//登录失败 dialog.dismiss(); Toast.makeText(CreateActivity.this, result, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); Toast.makeText(CreateActivity.this, "网络连接有问题", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<>(); map.put("username", phone.getText().toString().trim()); map.put("inviteCode", et_yaoqing.getText().toString().trim()); map.put("udid", szImei); return map; } }; mQueue.add(stringRequest2); } }
5c11949bf027bbb17b1f31c5bf34b2353eb7d369
91ae0fdc7df2a9e862f4f1c3c5076bb7cc8cb292
/src/Permute.java
4591a3d987b848b8e0689c1cb3bbcda4ae0a39d4
[]
no_license
IJUh/Algorithm
1e4a4334285b133d6d8bf576a85d4ada25636526
c120c41f2e37048beaa3e5c02234853785f2eaeb
refs/heads/master
2020-12-04T00:14:42.893096
2020-02-06T02:45:28
2020-02-06T02:45:28
231,534,413
2
0
null
null
null
null
UTF-8
Java
false
false
999
java
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Permute { public static int solution(int[] A) { Set<Integer> set = new HashSet<Integer>(); Arrays.sort(A); int lastNumber = A[A.length-1]; int idx = 0; for(int numberLoop = 1; numberLoop <= lastNumber || idx < A.length; numberLoop++) { if(A[idx] == numberLoop && !set.contains(A[idx])) { set.add(A[idx]); idx++; continue; } else { return 0; } } return 1; } public static void main(String[] args) { int[] A = {4,1,3,2}; int[] A1 = {4,1,3}; int[] A2 = {5,1,3}; int[] A3 = {1,1,3}; int[] A4 = {1,1,1,1}; int[] A5 = {1,2}; int[] A6 = {1,1,1}; System.out.println(Permute.solution(A)); System.out.println(Permute.solution(A1)); System.out.println(Permute.solution(A2)); System.out.println(Permute.solution(A3)); System.out.println(Permute.solution(A4)); System.out.println(Permute.solution(A5)); System.out.println(Permute.solution(A6)); } }
cd832946f8c2956c0d9f7559b5349573f8604613
01e820a98d84439e4ef059c073f502fa581e9187
/orcid-java-client-master/src/main/java/org/orcid/jaxb/model/record_rc2/WorkExternalIdentifierId.java
7606bfc33d4e8ef9ae88d73932a953440486f53f
[ "Apache-2.0" ]
permissive
Galay125/orcid
7a39c2605ed2fc6c5fbeb4b0a808068a90cdb3b1
76e92ac52e261402adf136af14f8234cca73bb42
refs/heads/master
2016-08-12T22:35:34.077327
2016-03-11T20:38:37
2016-03-11T20:38:37
53,694,477
0
0
null
null
null
null
UTF-8
Java
false
false
2,815
java
/** * ============================================================================= * * ORCID (R) Open Source * http://orcid.org * * Copyright (c) 2012-2014 ORCID, Inc. * Licensed under an MIT-Style License (MIT) * http://orcid.org/open-source-license * * This copyright and license information (including a link to the full license) * shall be included in its entirety in all copies or substantial portion of * the software. * * ============================================================================= */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.08.13 at 11:03:27 AM BST // package org.orcid.jaxb.model.record_rc2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import java.io.Serializable; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType( propOrder = { "content" }) @XmlRootElement(name = "externalIdentifierId") public class WorkExternalIdentifierId implements Serializable { /** * */ private static final long serialVersionUID = 1L; @XmlValue protected String content; public WorkExternalIdentifierId() { super(); } public WorkExternalIdentifierId(String content) { super(); this.content = content; } /** * Gets the value of the content property. * * @return * possible object is * {@link String } * */ public String getContent() { return content; } /** * Sets the value of the content property. * * @param value * allowed object is * {@link String } * */ public void setContent(String value) { this.content = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof WorkExternalIdentifierId)) { return false; } WorkExternalIdentifierId that = (WorkExternalIdentifierId) o; if (content != null ? !content.equals(that.content) : that.content != null) { return false; } return true; } @Override public int hashCode() { return content != null ? content.hashCode() : 0; } }
05726f5c2a04ed15d0b73c6ef10fdc415a7d8e48
b9d382e45466ae6f251892a64c3421e6e80533a1
/src/main/java/com/example/my/web/fw/mvc/service/SampleService.java
26968d707f90d2fe23419f1f3fd6ca7b1ac45a50
[]
no_license
Dakatan/my-web-fw
8114a5f6b818c7643c4920d01c137b8941df4a8d
f75871730525facb6fa1eff7092c265431e4a203
refs/heads/master
2021-08-19T12:34:46.357972
2017-11-26T09:06:46
2017-11-26T09:06:46
112,061,206
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package com.example.my.web.fw.mvc.service; import com.example.my.web.fw.annotation.BeanComponent; @BeanComponent public class SampleService { public String hello() { return "hello"; } }
[ "tkdtkd0022gmail.com" ]
tkdtkd0022gmail.com
9802fb9eab946e40e781981b9a15d245696953b3
51c8b20f37be94ef0de3e0aa190eebbd760e3f33
/Dev_Spring_Boot_1-1/src/main/java/ua/service/impl/TransporterServiceImpl.java
03bf550163897eafbc4f698694559c471caaa250
[]
no_license
TabachyshynDanylo/Transporter
2ed0014e03514b38fea634f02f8e8fb99214ca88
cc64fedd97a7330afc90f10cc9093378437ac32a
refs/heads/master
2021-01-23T10:43:37.003736
2017-11-12T16:54:04
2017-11-12T16:54:04
102,628,500
0
0
null
null
null
null
UTF-8
Java
false
false
3,031
java
package ua.service.impl; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import ua.entity.Transporter; import ua.model.filter.SimpleFilter; import ua.model.request.TransporterRequest; import ua.model.view.TransporterView; import ua.repository.TransporterRepository; import ua.service.TransporterService; @Service public class TransporterServiceImpl implements TransporterService{ private final TransporterRepository repository; public TransporterServiceImpl(TransporterRepository repository) { this.repository=repository; } @Override public List<String> findAllModels() { return repository.findAllModels(); } @Override public List<String> findAllBrands() { return repository.findAllBrands(); } @Override public List<String> findAllCity() { return repository.findAllCity(); } @Override public List<TransporterView> findAllView() { return repository.findAllView(); } @Override public void save(TransporterRequest request) { Transporter transporter = new Transporter(); transporter.setBrand(request.getBrand()); transporter.setModel(request.getModel()); transporter.setAge(Integer.valueOf(request.getAge())); transporter.setCarAge(Integer.valueOf(request.getCarAge())); transporter.setMaxWeight(Integer.valueOf(request.getMaxWeight())); transporter.setPhone(String.valueOf(request.getPhone())); repository.save(transporter); } @Override public TransporterRequest findOne(Integer id) { Transporter transporter = repository.findOneRequest(id); TransporterRequest request=new TransporterRequest(); request.setBrand(transporter.getBrand()); request.setModel(transporter.getModel()); request.setAge(String.valueOf(transporter.getAge())); request.setCarAge(String.valueOf(transporter.getCarAge())); request.setMaxWeight(String.valueOf(transporter.getMaxWeight())); request.setPhone(String.valueOf(transporter.getPhone())); return request; } @Override public void delete(Integer id) { repository.delete(id); } @Override public Page<Transporter> findAllView(Pageable pageable, SimpleFilter filter) { return repository.findAll(filter(filter), pageable); } @Override public Page<Transporter> findAllCity(Pageable pageable, SimpleFilter filter) { return repository.findAll(filter(filter), pageable); } @Override public Page<Transporter> findAllModels(Pageable pageable, SimpleFilter filter) { return repository.findAll(filter(filter), pageable);} @Override public Page<Transporter> findAllBrands(Pageable pageable, SimpleFilter filter) { return repository.findAll(filter(filter), pageable); } private Specification<Transporter> filter(SimpleFilter filter) { return (root, query, cb) -> { if (filter.getSearch().isEmpty()) return null; return cb.like(root.get("name"), filter.getSearch() + "%"); }; } }
e2c146fe43905716f68209b7c735d1bfa49806e1
d046d3ea0b28a5ec0b92e5dbc88712fdd659aafb
/kingfisherbackend/src/main/java/com/niit/kingfisherbackend/model/ShippingAddress.java
93409e81a0cdb12c36e69c4b110d1be625609282
[]
no_license
HRRamya/Kingfisher
267e5628d98679e7ca7a634fc68597ea9c6dd475
116a9167b108c6b78b150160de99eaa1b20b5ed9
refs/heads/master
2021-01-25T07:44:34.679785
2017-06-07T17:45:21
2017-06-07T17:45:21
93,662,580
0
0
null
null
null
null
UTF-8
Java
false
false
1,971
java
package com.niit.kingfisherbackend.model; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.springframework.stereotype.Component; @Entity @Table @Component public class ShippingAddress { @Id private String Shippin_id; private String houseno; private String country; private String city; private String pincode; private String email; private String mono; private String firstname; private String lastname; @ManyToOne @JoinColumn(name="u_Id") User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public ShippingAddress() { Shippin_id = "Shippin"+UUID.randomUUID().toString().toString().substring(30).toUpperCase(); } public String getShippin_id() { return Shippin_id; } public void setShippin_id(String shippin_id) { Shippin_id = shippin_id; } public String getHouseno() { return houseno; } public void setHouseno(String houseno) { this.houseno = houseno; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMono() { return mono; } public void setMono(String mono) { this.mono = mono; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } }
ad45b68576cefdcdc5c7bafc151c3eac3c5601b0
47d0c52d8a73baf2271ec281160c575293821506
/Uebung1c/src/uebung1c/Hersteller.java
604a42b5ff31f32a5a941f3b0918d5df851d2452
[]
no_license
xchrx/VS2018
54631d4071d4fc5342ea11e67e94cf144b80ef18
e5c57e81cc1213547f75d36f58a6aed64ead4c6f
refs/heads/master
2020-03-19T10:02:00.146512
2018-06-20T15:21:56
2018-06-20T15:21:56
136,337,506
0
0
null
null
null
null
UTF-8
Java
false
false
848
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package uebung1c; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Chris */ public class Hersteller extends Thread{ Parkhaus parkhaus; public Hersteller(Parkhaus parkaus, String name) { super(name); this.parkhaus = parkaus; } @Override public void run(){ while(true) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Hersteller.class.getName()).log(Level.SEVERE, null, ex); } parkhaus.producedCar(new Auto()); } } }
01ea2692d5410c1f360d7d6df90fe3da63287b3d
dff25c083ea3c33816b7b3cecbc327ab29efbe51
/src/com/kdn/mtps/mobile/db/InputJPDao.java
ac8383588227bba36bc2e4438789d9ebf04ca02d
[]
no_license
one-KMobile/KDNMobile
0773a149888eb6c385099d5e15547da8b80b3869
dc2902d0c4eb02223e5d7ba054143b06a32e1bcb
refs/heads/master
2022-12-20T22:06:36.545910
2020-09-27T06:25:15
2020-09-27T06:25:15
293,450,064
0
0
null
null
null
null
UTF-8
Java
false
false
7,394
java
package com.kdn.mtps.mobile.db; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.kdn.mtps.mobile.input.JSInfo; public class InputJPDao extends BaseDao{ static InputJPDao inputJPDao; private InputJPDao(Context ctx) { tableName = "INPUT_JP"; this.ctx = ctx; } public static InputJPDao getInstance(Context ctx) { if (inputJPDao == null) inputJPDao = new InputJPDao(ctx); return inputJPDao; } public void Append(JSInfo row) { Append(row, -1); } public void Append(JSInfo row, int idx) { SQLiteDatabase db = DBHelper.getInstance(ctx); ContentValues updateRow = new ContentValues(); if (idx != -1) { updateRow.put(JSInfo.COLS.IDX, idx); } updateRow.put(JSInfo.COLS.MASTER_IDX, row.master_idx); updateRow.put(JSInfo.COLS.WEATHER, row.weather); updateRow.put(JSInfo.COLS.AREA_TEMP, row.area_temp); updateRow.put(JSInfo.COLS.CIRCUIT_NO, row.circuit_no); updateRow.put(JSInfo.COLS.CIRCUIT_NAME, row.circuit_name); updateRow.put(JSInfo.COLS.CURRENT_LOAD, row.current_load); updateRow.put(JSInfo.COLS.CONDUCTOR_CNT, row.conductor_cnt); updateRow.put(JSInfo.COLS.LOCATION, row.location); updateRow.put(JSInfo.COLS.C1_JS, row.c1_js); updateRow.put(JSInfo.COLS.C1_JSJ, row.c1_jsj); updateRow.put(JSInfo.COLS.C1_YB_RESULT, row.c1_yb_result); updateRow.put(JSInfo.COLS.C1_POWER_NO, row.c1_power_no); updateRow.put(JSInfo.COLS.C2_JS, row.c2_js); updateRow.put(JSInfo.COLS.C2_JSJ, row.c2_jsj); updateRow.put(JSInfo.COLS.C2_YB_RESULT, row.c2_yb_result); updateRow.put(JSInfo.COLS.C2_POWER_NO, row.c2_power_no); updateRow.put(JSInfo.COLS.C3_JS, row.c3_js); updateRow.put(JSInfo.COLS.C3_JSJ, row.c3_jsj); updateRow.put(JSInfo.COLS.C3_YB_RESULT, row.c3_yb_result); updateRow.put(JSInfo.COLS.C3_POWER_NO, row.c3_power_no); db.replace(tableName, null, updateRow); // dbCheck(); } public void Delete(String mIdx) { SQLiteDatabase db = DBHelper.getInstance(ctx); String fmt = "DELETE FROM %s WHERE master_idx = %s"; String sql = String.format(fmt, tableName, mIdx); db.execSQL(sql); } public void DeleteIdx(int idx) { SQLiteDatabase db = DBHelper.getInstance(ctx); String fmt = "DELETE FROM %s WHERE idx = %s"; String sql = String.format(fmt, tableName, idx); db.execSQL(sql); } public ArrayList<JSInfo> selectJS(String mIdx) { ArrayList<JSInfo> jsList = new ArrayList<JSInfo>(); try { SQLiteDatabase db = DBHelper.getReadableInstance(ctx); String fmt = "select * from %s where master_idx = %s"; String sql = String.format(fmt, tableName, mIdx); cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { int idx = cursor.getInt(cursor.getColumnIndex(JSInfo.COLS.IDX)); String master_idx = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.MASTER_IDX)); String wether = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.WEATHER)); String area_temp = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.AREA_TEMP)); String circuit_no = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.CIRCUIT_NO)); String circuit_name = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.CIRCUIT_NAME)); String current_load = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.CURRENT_LOAD)); String conductor_cnt = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.CONDUCTOR_CNT)); String location = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.LOCATION)); String c1_js = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C1_JS)); String c1_jsj = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C1_JSJ)); String c1_yb_result = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C1_YB_RESULT)); String c1_power_no = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C1_POWER_NO)); String c2_js = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C2_JS)); String c2_jsj = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C2_JSJ)); String c2_yb_result = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C2_YB_RESULT)); String c2_power_no = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C2_POWER_NO)); String c3_js = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C3_JS)); String c3_jsj = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C3_JSJ)); String c3_yb_result = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C3_YB_RESULT)); String c3_power_no = cursor.getString(cursor.getColumnIndex(JSInfo.COLS.C3_POWER_NO)); JSInfo info = new JSInfo(); info.idx = idx; info.master_idx = master_idx; info.weather = wether; info.area_temp = area_temp; info.circuit_no = circuit_no; info.circuit_name = circuit_name; info.current_load = current_load; info.conductor_cnt = conductor_cnt; info.location = location; info.c1_js= c1_js; info.c1_jsj = c1_jsj; info.c1_yb_result = c1_yb_result; info.c1_power_no = c1_power_no; info.c2_js = c2_js; info.c2_jsj = c2_jsj; info.c2_yb_result = c2_yb_result; info.c2_power_no = c2_power_no; info.c3_js = c3_js; info.c3_jsj = c3_jsj; info.c3_yb_result = c3_yb_result; info.c3_power_no = c3_power_no; jsList.add(info); } } catch (Exception e) { e.printStackTrace(); } finally { close(); } return jsList; } public boolean existJP(String mIdx) { try { SQLiteDatabase db = DBHelper.getReadableInstance(ctx); String fmt = "select * from %s where master_idx = %s"; String sql = String.format(fmt, tableName, mIdx); cursor = db.rawQuery(sql, null); if (cursor.moveToNext()) return true; } catch (Exception e) { e.printStackTrace(); } finally { close(); } return false; } public void dbCheck() { Log.d("Test", "############ DB value check #############"); try { SQLiteDatabase db = DBHelper.getReadableInstance(ctx); String fmt = "select * from %s"; String sql = String.format(fmt, tableName); cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { int idx = cursor.getInt(0); String master_idx = cursor.getString(1); String wether = cursor.getString(2); String worker_cnt = cursor.getString(3); String claim_content = cursor.getString(4); String check_result = cursor.getString(5); String etc = cursor.getString(6); // int ins_result_code = cursor.getInt(2); // int check_result_code = cursor.getInt(3); // int eqp_type_code = cursor.getInt(4); // int detail_item_code = cursor.getInt(5); // String spt_mgt_yn = cursor.getString(6); Log.d("Test", "idx : " + idx); Log.d("Test", "master_idx : " + master_idx); Log.d("Test", "wether : " + wether); Log.d("Test", "worker_cnt : " + worker_cnt); Log.d("Test", "claim_content : " + claim_content); Log.d("Test", "check_result : " + check_result); Log.d("Test", "etc : " + etc); // Log.d("Test", "ins_result_code : " + ins_result_code); // Log.d("Test", "check_result_code : " + check_result_code); // Log.d("Test", "eqp_type_code : " + eqp_type_code); // Log.d("Test", "detail_item_code : " + detail_item_code); // Log.d("Test", "spt_mgt_yn : " + spt_mgt_yn); } } catch (Exception e) { e.printStackTrace(); } finally { close(); } } }
aef33e9aa784b56d518b031dc8cf3ab13a35c824
efb0ca303613dd078ef20dc7358ca994a1558239
/olivelv/difficult/SearchInRotatedSortedArray.java
7c331394cab5a3861b582d0962f0fb0da803b89c
[]
no_license
OliveLv/LeetCode
3d60d50b133027a721707b1ba14f7ab533ffdf2f
bd15ca48153ac75b7278eb5f52574fbc81dfa227
refs/heads/master
2020-04-15T22:48:36.498221
2016-08-29T06:02:05
2016-08-29T06:02:05
25,817,275
2
0
null
null
null
null
WINDOWS-1252
Java
false
false
598
java
package olivelv.difficult; /** * Suppose a sorted array is rotated at some pivot unknown to you beforehand. * * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * * You are given a target value to search. If found in the array return its * index, otherwise return -1. * * You may assume no duplicate exists in the array. * * * @author olivelv * @version time: 2015Äê4ÔÂ8ÈÕ ÏÂÎç10:43:49 */ public class SearchInRotatedSortedArray { public int search(int[] A, int target) { for(int i=0;i<A.length;i++) if(A[i]==target)return i; return -1; } }
c06fc6e09d2448e2d28327ee6a20065879c959c6
453394d343fb2245e47030814cc75de51d88f9e1
/src/Fibonacci/src/it/unipr/sowide/actodes/service/mobile/Mover.java
f5fe2f4dc9f6eea686bf58d41f7838a660b8b85a
[]
no_license
cavallo5/Fibonacci-Chameneos_redux-Token_Ring-ActoDeS
ab6847656522e518e53ddc68f8ffcdc5ed219ce3
395d08004d07ca4981ae3b16fb5e45771125f244
refs/heads/master
2022-11-30T13:03:34.402053
2020-08-12T08:41:57
2020-08-12T08:41:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,782
java
package it.unipr.sowide.actodes.service.mobile; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import it.unipr.sowide.actodes.actor.Behavior; import it.unipr.sowide.actodes.actor.CaseFactory; import it.unipr.sowide.actodes.actor.Message; import it.unipr.sowide.actodes.actor.MessageHandler; import it.unipr.sowide.actodes.actor.MessagePattern; import it.unipr.sowide.actodes.actor.Shutdown; import it.unipr.sowide.actodes.controller.SpaceInfo; import it.unipr.sowide.actodes.filtering.constraint.IsInstance; import it.unipr.sowide.actodes.registry.Reference; import it.unipr.sowide.actodes.service.mobile.content.Accepted; import it.unipr.sowide.actodes.service.mobile.content.Active; import it.unipr.sowide.actodes.service.mobile.content.Move; /** * * The {@code Mover} class defines a behavior that moves the actor * to another actor space. * **/ public final class Mover extends Behavior { private static final long serialVersionUID = 1L; private final MobileState state; private final ArrayList<Message> messages; /** * Class constructor. * * @param d * * the reference of the service provider of the destination actor space. * * @param b * * the qualified class name of the initial behavior in the destination * actor space. * **/ public Mover(final Reference d, final Behavior b) { this.state = new MobileState(d, b); this.messages = new ArrayList<>(); } /** {@inheritDoc} **/ @Override public void cases(final CaseFactory c) { MessageHandler h = (m) -> { send(PROVIDER, new Move(this.state)); return null; }; c.define(START, h); h = (m) -> { if (m.getContent() instanceof Accepted) { Accepted a = (Accepted) m.getContent(); Iterator<Message> i = this.messages.iterator(); while (i.hasNext()) { Message e = i.next(); a.getCurrent().push(new Message( e.getIdentifier(), e.getSender(), List.of(a.getCurrent()), e.getContent(), e.getTime(), e.getType(), e.getInReplyTo())); i.remove(); } MobileReference r = (MobileReference) getReference(); r.redirect(r, a.getCurrent()); send(SpaceInfo.INFO.getProvider( a.getCurrent()), new Active(a.getCurrent())); return Shutdown.SHUTDOWN; } else { // Error management return Shutdown.SHUTDOWN; } }; c.define(MessagePattern.contentPattern(new IsInstance(Accepted.class)), h); h = (m) -> { this.messages.add(m); return null; }; c.define(ACCEPTALL, h); } }
0381aa27c3e2ac09bffde4333426d195bac08709
592d129b40739d4152649d5e8bf6c753a006cebc
/PushNotification/app/src/main/java/com/example/babarmustafa/pushnotification/MainActivity.java
3ebb1800b9e06ee1037d3cc79218e30214f45ad8
[]
no_license
babar-mustafa/FireBase-Work
0dd2871029c5fe015762b5c239f85d551b04b0b7
f316691b4a85f6d6d6c2370bb51bc2f5a15ceab5
refs/heads/master
2021-01-11T03:09:52.634427
2017-02-10T12:48:48
2017-02-10T12:48:48
70,145,959
0
0
null
null
null
null
UTF-8
Java
false
false
2,220
java
package com.example.babarmustafa.pushnotification; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Handle possible data accompanying notification message. // [START handle_data_extras] if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { Object value = getIntent().getExtras().get(key); Log.d(TAG, "Key: " + key + " Value: " + value); } } // [END handle_data_extras] Button subscribeButton = (Button) findViewById(R.id.subscribeButton); subscribeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // [START subscribe_topics] FirebaseMessaging.getInstance().subscribeToTopic("news"); // [END subscribe_topics] // Log and toast String msg = getString(R.string.msg_subscribed); Log.d(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); Button logTokenButton = (Button) findViewById(R.id.logTokenButton); logTokenButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get token String token = FirebaseInstanceId.getInstance().getToken(); // Log and toast String msg = getString(R.string.msg_token_fmt, token); Log.e(TAG, token); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } }
83b70e199871582393bb0af78f42b0097e8e802d
b78f4e4fb8689c0c3b71a1562a7ee4228a116cda
/JFramework/crypto/src/main/java/org/bouncycastle/crypto/generators/KDFDoublePipelineIterationBytesGenerator.java
20778e8b871f00874247bfa0db7db46b7a7557ff
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
richkmeli/JFramework
94c6888a6bb9af8cbff924e8a1525e6ec4765902
54250a32b196bb9408fb5715e1c677a26255bc29
refs/heads/master
2023-07-24T23:59:19.077417
2023-05-05T22:52:14
2023-05-05T22:52:14
176,379,860
5
6
Apache-2.0
2023-07-13T22:58:27
2019-03-18T22:32:12
Java
UTF-8
Java
false
false
5,115
java
package org.bouncycastle.crypto.generators; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.DerivationParameters; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.MacDerivationFunction; import org.bouncycastle.crypto.params.KDFDoublePipelineIterationParameters; import org.bouncycastle.crypto.params.KeyParameter; import java.math.BigInteger; /** * This KDF has been defined by the publicly available NIST SP 800-108 specification. */ public class KDFDoublePipelineIterationBytesGenerator implements MacDerivationFunction { private static final BigInteger INTEGER_MAX = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger TWO = BigInteger.valueOf(2); // please refer to the standard for the meaning of the variable names // all field lengths are in bytes, not in bits as specified by the standard // fields set by the constructor private final Mac prf; private final int h; // fields set by init private byte[] fixedInputData; private int maxSizeExcl; // ios is i defined as an octet string (the binary representation) private byte[] ios; private boolean useCounter; // operational private int generatedBytes; // k is used as buffer for all K(i) values private byte[] a; private byte[] k; public KDFDoublePipelineIterationBytesGenerator(Mac prf) { this.prf = prf; this.h = prf.getMacSize(); this.a = new byte[h]; this.k = new byte[h]; } public void init(DerivationParameters params) { if (!(params instanceof KDFDoublePipelineIterationParameters)) { throw new IllegalArgumentException("Wrong type of arguments given"); } KDFDoublePipelineIterationParameters dpiParams = (KDFDoublePipelineIterationParameters) params; // --- init mac based PRF --- this.prf.init(new KeyParameter(dpiParams.getKI())); // --- set arguments --- this.fixedInputData = dpiParams.getFixedInputData(); int r = dpiParams.getR(); this.ios = new byte[r / 8]; if (dpiParams.useCounter()) { // this is more conservative than the spec BigInteger maxSize = TWO.pow(r).multiply(BigInteger.valueOf(h)); this.maxSizeExcl = maxSize.compareTo(INTEGER_MAX) == 1 ? Integer.MAX_VALUE : maxSize.intValue(); } else { this.maxSizeExcl = Integer.MAX_VALUE; } this.useCounter = dpiParams.useCounter(); // --- set operational state --- generatedBytes = 0; } public Mac getMac() { return prf; } public int generateBytes(byte[] out, int outOff, int len) throws DataLengthException, IllegalArgumentException { int generatedBytesAfter = generatedBytes + len; if (generatedBytesAfter < 0 || generatedBytesAfter >= maxSizeExcl) { throw new DataLengthException( "Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); } if (generatedBytes % h == 0) { generateNext(); } // copy what is left in the currentT (1..hash int toGenerate = len; int posInK = generatedBytes % h; int leftInK = h - generatedBytes % h; int toCopy = Math.min(leftInK, toGenerate); System.arraycopy(k, posInK, out, outOff, toCopy); generatedBytes += toCopy; toGenerate -= toCopy; outOff += toCopy; while (toGenerate > 0) { generateNext(); toCopy = Math.min(h, toGenerate); System.arraycopy(k, 0, out, outOff, toCopy); generatedBytes += toCopy; toGenerate -= toCopy; outOff += toCopy; } return len; } private void generateNext() { if (generatedBytes == 0) { // --- step 4 --- prf.update(fixedInputData, 0, fixedInputData.length); prf.doFinal(a, 0); } else { // --- step 5a --- prf.update(a, 0, a.length); prf.doFinal(a, 0); } // --- step 5b --- prf.update(a, 0, a.length); if (useCounter) { int i = generatedBytes / h + 1; // encode i into counter buffer switch (ios.length) { case 4: ios[0] = (byte) (i >>> 24); // fall through case 3: ios[ios.length - 3] = (byte) (i >>> 16); // fall through case 2: ios[ios.length - 2] = (byte) (i >>> 8); // fall through case 1: ios[ios.length - 1] = (byte) i; break; default: throw new IllegalStateException("Unsupported size of counter i"); } prf.update(ios, 0, ios.length); } prf.update(fixedInputData, 0, fixedInputData.length); prf.doFinal(k, 0); } }
263fd9b2b0bb029aeeb952e911a37e2b8b1565d6
51b7aa8ca8dedd69039d17959701bec7cd99a4c1
/codegen/src/main/java/software/amazon/awssdk/codegen/AddMetadata.java
c77611ab0f1c3328cea03438f3928d57a1c9080f
[ "Apache-2.0" ]
permissive
MatteCarra/aws-sdk-java-v2
41d711ced0943fbd6b5a709e50f78b6564b5ed21
af9fb86db6715b1dbea79028aa353292559d5876
refs/heads/master
2021-06-30T05:21:08.988292
2017-09-18T15:33:38
2017-09-18T15:33:38
103,685,332
0
1
null
2017-09-15T17:45:50
2017-09-15T17:45:50
null
UTF-8
Java
false
false
6,815
java
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.codegen; import software.amazon.awssdk.codegen.internal.Constants; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.BasicCodeGenConfig; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * Constructs the metadata that is required for generating the java client from the service meta data. */ final class AddMetadata { private static final String AWS_PACKAGE_PREFIX = "software.amazon.awssdk.services"; public static Metadata constructMetadata(ServiceModel serviceModel, BasicCodeGenConfig codeGenConfig, CustomizationConfig customizationConfig) { final Metadata metadata = new Metadata(); final ServiceMetadata serviceMetadata = serviceModel.getMetadata(); final String serviceName; final String rootPackageName; // API Gateway uses additional codegen.config settings if (serviceMetadata.getProtocol().equals(Protocol.API_GATEWAY.getValue())) { // TODO: The meaning of root package name has changed a bit since this code was written. Specifically, the root for // AWS no longer includes the service name. This changed the behavior of the API gateway generation, but we're not // keeping it up to date at this time. Just be aware this has happened when updating the API gateway code. serviceName = codeGenConfig.getInterfaceName(); rootPackageName = codeGenConfig.getPackageName(); metadata.withDefaultEndpoint(codeGenConfig.getEndpoint()) .withDefaultEndpointWithoutHttpProtocol( Utils.getDefaultEndpointWithoutHttpProtocol(codeGenConfig.getEndpoint())) .withDefaultRegion(codeGenConfig.getDefaultRegion()); } else { serviceName = Utils.getServiceName(serviceMetadata, customizationConfig); rootPackageName = AWS_PACKAGE_PREFIX; } metadata.withApiVersion(serviceMetadata.getApiVersion()) .withAsyncClient(String.format(Constants.ASYNC_CLIENT_CLASS_NAME_PATTERN, serviceName)) .withAsyncInterface(String.format(Constants.ASYNC_CLIENT_INTERFACE_NAME_PATTERN, serviceName)) .withAsyncBuilder(String.format(Constants.ASYNC_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withAsyncBuilderInterface(String.format(Constants.ASYNC_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseBuilderInterface(String.format(Constants.BASE_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseBuilder(String.format(Constants.BASE_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withDocumentation(serviceModel.getDocumentation()) .withRootPackageName(rootPackageName) .withClientPackageName(Utils.getClientPackageName(serviceName, customizationConfig)) .withModelPackageName(Utils.getModelPackageName(serviceName, customizationConfig)) .withTransformPackageName(Utils.getTransformPackageName(serviceName, customizationConfig)) .withRequestTransformPackageName(Utils.getRequestTransformPackageName(serviceName, customizationConfig)) .withWaitersPackageName(Utils.getWaitersPackageName(serviceName, customizationConfig)) .withSmokeTestsPackageName(Utils.getSmokeTestPackageName(serviceName, customizationConfig)) .withServiceAbbreviation(serviceMetadata.getServiceAbbreviation()) .withServiceFullName(serviceMetadata.getServiceFullName()) .withSyncClient(String.format(Constants.SYNC_CLIENT_CLASS_NAME_PATTERN, serviceName)) .withSyncInterface(String.format(Constants.SYNC_CLIENT_INTERFACE_NAME_PATTERN, serviceName)) .withSyncBuilder(String.format(Constants.SYNC_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withSyncBuilderInterface(String.format(Constants.SYNC_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseExceptionName(String.format(Constants.BASE_EXCEPTION_NAME_PATTERN, serviceName)) .withProtocol(Protocol.fromValue(serviceMetadata.getProtocol())) .withJsonVersion(serviceMetadata.getJsonVersion()) .withEndpointPrefix(serviceMetadata.getEndpointPrefix()) .withSigningName(serviceMetadata.getSigningName()) .withAuthType(AuthType.fromValue(serviceMetadata.getSignatureVersion())) .withRequiresApiKey(requiresApiKey(serviceModel)) .withUid(serviceMetadata.getUid()); final String jsonVersion = getJsonVersion(metadata, serviceMetadata); metadata.setJsonVersion(jsonVersion); // TODO: iterate through all the operations and check whether any of // them accept stream input metadata.setHasApiWithStreamInput(false); return metadata; } private static String getJsonVersion(Metadata metadata, ServiceMetadata serviceMetadata) { // TODO this should be defaulted in the C2J build tool if (serviceMetadata.getJsonVersion() == null && metadata.isJsonProtocol()) { return "1.1"; } else { return serviceMetadata.getJsonVersion(); } } /** * If any operation requires an API key we generate a setter on the builder. * * @return True if any operation requires an API key. False otherwise. */ private static boolean requiresApiKey(ServiceModel serviceModel) { return serviceModel.getOperations().values().stream() .anyMatch(Operation::requiresApiKey); } }
a8518d5f7c28c1c0fd59f958d9fbfc68cc7392f1
2bc2eadc9b0f70d6d1286ef474902466988a880f
/tags/mule-2.2.1-HF2/transports/cxf/src/main/java/org/mule/transport/cxf/transport/MuleUniversalConduit.java
dfff8d8ceb395cf55d1217ca3389c7b174e1cca9
[]
no_license
OrgSmells/codehaus-mule-git
085434a4b7781a5def2b9b4e37396081eaeba394
f8584627c7acb13efdf3276396015439ea6a0721
refs/heads/master
2022-12-24T07:33:30.190368
2020-02-27T19:10:29
2020-02-27T19:10:29
243,593,543
0
0
null
2022-12-15T23:30:00
2020-02-27T18:56:48
null
UTF-8
Java
false
false
18,380
java
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.transport.cxf.transport; import static org.apache.cxf.message.Message.DECOUPLED_CHANNEL_MESSAGE; import static org.mule.api.config.MuleProperties.MULE_EVENT_PROPERTY; import org.mule.DefaultMuleEvent; import org.mule.DefaultMuleMessage; import org.mule.DefaultMuleSession; import org.mule.MuleServer; import org.mule.RequestContext; import org.mule.api.MuleContext; import org.mule.api.MuleEvent; import org.mule.api.MuleEventContext; import org.mule.api.MuleException; import org.mule.api.MuleMessage; import org.mule.api.MuleSession; import org.mule.api.config.MuleProperties; import org.mule.api.endpoint.ImmutableEndpoint; import org.mule.api.endpoint.OutboundEndpoint; import org.mule.api.registry.MuleRegistry; import org.mule.api.transformer.TransformerException; import org.mule.api.transport.MessageAdapter; import org.mule.api.transport.OutputHandler; import org.mule.api.transport.PropertyScope; import org.mule.endpoint.EndpointURIEndpointBuilder; import org.mule.transport.DefaultMessageAdapter; import org.mule.transport.NullPayload; import org.mule.transport.cxf.CxfConnector; import org.mule.transport.cxf.CxfConstants; import org.mule.transport.cxf.support.DelegatingOutputStream; import org.mule.transport.cxf.support.MuleProtocolHeadersOutInterceptor; import org.mule.transport.http.HttpConstants; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; import javax.xml.ws.BindingProvider; import javax.xml.ws.Holder; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.endpoint.ClientImpl; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.ExchangeImpl; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import org.apache.cxf.transport.Destination; import org.apache.cxf.transport.MessageObserver; import org.apache.cxf.ws.addressing.AttributedURIType; import org.apache.cxf.ws.addressing.EndpointReferenceType; import org.apache.cxf.wsdl.EndpointReferenceUtils; /** * A Conduit is primarily responsible for sending messages from CXF to somewhere * else. This conduit takes messages which are being written and sends them to the * Mule bus. */ public class MuleUniversalConduit extends AbstractConduit { private static final Logger LOGGER = LogUtils.getL7dLogger(MuleUniversalConduit.class); private EndpointInfo endpoint; private CxfConnector connector; private Destination decoupledDestination; private String decoupledEndpoint; private MuleUniversalTransport transport; private int decoupledDestinationRefCount; private boolean closeInput; private boolean applyTransformersToProtocol; private ImmutableEndpoint muleEndpoint; private Map<String,OutboundEndpoint> protocolEndpoints = new HashMap<String, OutboundEndpoint>(); /** * @param ei The Endpoint being invoked by this destination. * @param t The EPR associated with this Conduit - i.e. the reply destination. */ public MuleUniversalConduit(MuleUniversalTransport transport, CxfConnector connector, EndpointInfo ei, EndpointReferenceType t) { super(getTargetReference(ei, t)); this.transport = transport; this.endpoint = ei; this.connector = connector; } public void close(Message msg) throws IOException { OutputStream os = msg.getContent(OutputStream.class); if (os != null) { os.close(); } if (closeInput) { InputStream in = msg.getContent(InputStream.class); if (in != null) { in.close(); } } } @Override protected Logger getLogger() { return LOGGER; } public synchronized Destination getBackChannel() { if (decoupledDestination == null && decoupledEndpoint != null) { setUpDecoupledDestination(); } return decoupledDestination; } protected void setUpDecoupledDestination() { EndpointInfo ei = new EndpointInfo(); ei.setAddress(decoupledEndpoint); try { decoupledDestination = transport.getDestination(ei); decoupledDestination.setMessageObserver(new InterposedMessageObserver()); duplicateDecoupledDestination(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Prepare the message for writing. */ public void prepare(final Message message) throws IOException { // save in a separate place in case we need to resend the request final ByteArrayOutputStream cache = new ByteArrayOutputStream(); final DelegatingOutputStream delegating = new DelegatingOutputStream(cache); message.setContent(OutputStream.class, delegating); message.setContent(DelegatingOutputStream.class, delegating); AbstractPhaseInterceptor<Message> i = new AbstractPhaseInterceptor<Message>(Phase.PRE_STREAM) { public void handleMessage(Message m) throws Fault { try { dispatchMuleMessage(m); } catch (IOException e) { throw new Fault(e); } } }; i.getAfter().add(MuleProtocolHeadersOutInterceptor.class.getName()); message.getInterceptorChain().add(i); OutputHandler handler = new OutputHandler() { public void write(MuleEvent event, OutputStream out) throws IOException { out.write(cache.toByteArray()); delegating.setOutputStream(out); // resume writing! message.getInterceptorChain().doIntercept(message); } }; MuleEvent event = (MuleEvent) message.getExchange().get(MULE_EVENT_PROPERTY); DefaultMessageAdapter req; if (event == null) { req = new DefaultMessageAdapter(handler); } else { req = new DefaultMessageAdapter(handler, event.getMessage()); } message.getExchange().put(CxfConstants.MULE_MESSAGE, req); } protected void dispatchMuleMessage(Message m) throws IOException { String uri = setupURL(m); LOGGER.info("Sending message to " + uri); try { OutboundEndpoint protocolEndpoint = getProtocolEndpoint(uri); MessageAdapter req = (MessageAdapter) m.getExchange().get(CxfConstants.MULE_MESSAGE); req.setProperty(MuleProperties.MULE_ENDPOINT_PROPERTY, uri, PropertyScope.INVOCATION); MuleMessage result = sendStream(req, protocolEndpoint, m.getExchange()); if (result == null) { m.getExchange().put(ClientImpl.FINISHED, Boolean.TRUE); return; } // If we have a result, send it back to CXF InputStream is = getResponseBody(m, result); if (is != null) { Message inMessage = new MessageImpl(); String contentType = result.getStringProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/xml"); inMessage.put(Message.CONTENT_TYPE, contentType); inMessage.put(Message.ENCODING, result.getEncoding()); inMessage.put(CxfConstants.MULE_MESSAGE, result); inMessage.setContent(InputStream.class, is); inMessage.setExchange(m.getExchange()); getMessageObserver().onMessage(inMessage); } } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } IOException ex = new IOException("Could not send message to Mule."); ex.initCause(e); throw ex; } } protected OutboundEndpoint getProtocolEndpoint(String uri) throws MuleException { OutboundEndpoint ep = protocolEndpoints.get(uri); if (ep == null) { ep = initializeProtocolEndpoint(uri); } return ep; } protected synchronized OutboundEndpoint initializeProtocolEndpoint(String uri) throws MuleException { OutboundEndpoint ep = protocolEndpoints.get(uri); if (ep != null) return ep; MuleContext muleContext = MuleServer.getMuleContext(); MuleRegistry registry = muleContext.getRegistry(); // Someone is using a JAX-WS client directly and not going through MuleClient if (muleEndpoint == null) { return registry.lookupEndpointFactory().getOutboundEndpoint(uri); } // MuleClient/Dispatcher case EndpointURIEndpointBuilder builder = new EndpointURIEndpointBuilder(uri, muleContext); String connectorName = (String)muleEndpoint.getProperty("protocolConnector"); if (connectorName != null) { builder.setConnector(registry.lookupConnector(connectorName)); } ep = registry.lookupEndpointFactory().getOutboundEndpoint(builder); protocolEndpoints.put(uri, ep); return ep; } protected InputStream getResponseBody(Message m, MuleMessage result) throws TransformerException, IOException { boolean response = result != null && !NullPayload.getInstance().equals(result.getPayload()) && !isOneway(m.getExchange()); if (response) { // Sometimes there may not actually be a body, in which case // we want to act appropriately. E.g. one way invocations over a proxy InputStream is = (InputStream) result.getPayload(InputStream.class); PushbackInputStream pb = new PushbackInputStream(is); result.setPayload(pb); int b = pb.read(); if (b != -1) { pb.unread(b); return pb; } } return null; } protected boolean isOneway(Exchange exchange) { return exchange != null && exchange.isOneWay(); } protected String setupURL(Message message) throws MalformedURLException { String value = (String) message.get(Message.ENDPOINT_ADDRESS); String pathInfo = (String) message.get(Message.PATH_INFO); String queryString = (String) message.get(Message.QUERY_STRING); String username = (String) message.get(BindingProvider.USERNAME_PROPERTY); String password = (String) message.get(BindingProvider.PASSWORD_PROPERTY); String result = value != null ? value : getTargetOrEndpoint(); if (username != null) { int slashIdx = result.indexOf("//"); if (slashIdx != -1) { result = result.substring(0, slashIdx + 2) + username + ":" + password + "@" + result.substring(slashIdx+2); } } // REVISIT: is this really correct? if (null != pathInfo && !result.endsWith(pathInfo)) { result = result + pathInfo; } if (queryString != null) { result = result + "?" + queryString; } return result; } protected String getTargetOrEndpoint() { if (target != null) { return target.getAddress().getValue(); } return endpoint.getAddress().toString(); } public void onClose(final Message m) throws IOException { } protected MuleMessage sendStream(MessageAdapter sa, OutboundEndpoint ep, Exchange exchange) throws MuleException { MuleEventContext eventContext = RequestContext.getEventContext(); MuleSession session = null; if (eventContext != null) { session = eventContext.getSession(); } MuleMessage message = new DefaultMuleMessage(sa); if (session == null) { session = new DefaultMuleSession(message, connector.getSessionHandler(), connector.getMuleContext()); } // Filter out CXF client properties like wsdlLocation, inInterceptors, etc MuleEvent prev = RequestContext.getEvent(); // If you're invoking from a CXF generated client, the event can be null if (prev != null) { for (Iterator itr = prev.getEndpoint().getProperties().keySet().iterator(); itr.hasNext();) { String key = (String) itr.next(); message.removeProperty(key); } } message.removeProperty(CxfConstants.OPERATION); message.removeProperty(CxfConstants.INBOUND_OPERATION); message.removeProperty(CxfConstants.INBOUND_SERVICE); MuleEvent event = new DefaultMuleEvent(message, ep, session, true); event.setTimeout(MuleEvent.TIMEOUT_NOT_SET_VALUE); RequestContext.setEvent(event); // This is a little "trick" to apply transformers from the CXF endpoint // to the raw message instead of the pojos if (applyTransformersToProtocol) { message.applyTransformers(((OutboundEndpoint) prev.getEndpoint()).getTransformers()); // The underlying endpoint transformers event.transformMessage(); } MuleMessage msg = ep.send(event); // We need to grab this back in the CxfMessageDispatcher again. Holder<MuleMessage> holder = (Holder<MuleMessage>) exchange.get("holder"); // it's null if there is no dispatcher and the Client is being used directly over Mule if (holder != null) { holder.value = msg; } return msg; } public void close() { // in decoupled case, close response Destination if reference count // hits zero // if (decoupledDestination != null) { releaseDecoupledDestination(); } } protected synchronized void duplicateDecoupledDestination() { decoupledDestinationRefCount++; } protected synchronized void releaseDecoupledDestination() { if (--decoupledDestinationRefCount == 0) { // LOG.log(Level.INFO, "shutting down decoupled destination"); decoupledDestination.shutdown(); } } public String getDecoupledEndpoint() { return decoupledEndpoint; } public void setDecoupledEndpoint(String decoupledEndpoint) { this.decoupledEndpoint = decoupledEndpoint; } /** * Get the target endpoint reference. * * @param ei the corresponding EndpointInfo * @param t the given target EPR if available * @param bus the Bus * @return the actual target */ protected static EndpointReferenceType getTargetReference(EndpointInfo ei, EndpointReferenceType t) { EndpointReferenceType ref = null; if (null == t) { ref = new EndpointReferenceType(); AttributedURIType address = new AttributedURIType(); address.setValue(ei.getAddress()); ref.setAddress(address); if (ei.getService() != null) { EndpointReferenceUtils.setServiceAndPortName(ref, ei.getService().getName(), ei.getName() .getLocalPart()); } } else { ref = t; } return ref; } /** * Used to set appropriate message properties, exchange etc. as required for an * incoming decoupled response (as opposed what's normally set by the Destination * for an incoming request). */ protected class InterposedMessageObserver implements MessageObserver { /** * Called for an incoming message. * * @param inMessage */ public void onMessage(Message inMessage) { // disposable exchange, swapped with real Exchange on correlation inMessage.setExchange(new ExchangeImpl()); inMessage.put(DECOUPLED_CHANNEL_MESSAGE, Boolean.TRUE); inMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_OK); inMessage.remove(Message.ASYNC_POST_RESPONSE_DISPATCH); incomingObserver.onMessage(inMessage); } } public void setCloseInput(boolean closeInput) { this.closeInput = closeInput; } public void setApplyTransformersToProtocol(boolean applyTransformersToProtocol) { this.applyTransformersToProtocol = applyTransformersToProtocol; } protected CxfConnector getConnector() { return connector; } protected EndpointInfo getEndpoint() { return endpoint; } protected MuleUniversalTransport getTransport() { return transport; } public void setMuleEndpoint(ImmutableEndpoint muleEndpoint) { this.muleEndpoint = muleEndpoint; } }
[ "dzapata@bf997673-6b11-0410-b953-e057580c5b09" ]
dzapata@bf997673-6b11-0410-b953-e057580c5b09
22bbf09f12246c54c5729d0e65616a7b8fc41c72
089463f950c7d6ac532675e9f54e88a34d4cadf0
/src/test/java/application/core/projectiles/UpgradedProjectileTest.java
56a57a9036b8680bec06bb632ff0880612f03132
[]
no_license
arbreurkes/SEM
efa44b1fe6228502c147b142cd9b5ab76332e3a1
7fd5522bcf958572f9817ae5a19ebcb94a05ac38
refs/heads/master
2021-05-31T14:46:20.592158
2015-10-30T22:33:09
2015-10-30T22:33:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,784
java
package application.core.projectiles; import application.Main; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Test for UpgradedProjectile.java. * @author Arthur Breurkes. */ public class UpgradedProjectileTest { private UpgradedProjectile testProjectile; /** * Initialize variable for the test process. * @throws Exception possible Exception. */ @Before public void setUp() throws Exception { testProjectile = new UpgradedProjectile(0, 0, 1, 1); } /** * Test whether update() works correctly. * @throws Exception possible Exception. */ @Test public void testUpdate() throws Exception { testProjectile.setDirectionX(1); testProjectile.setDirectionY(1); testProjectile.setSpeed(1); testProjectile.update(); assertEquals(1.0, testProjectile.getX(), 0.0); assertEquals(1.0, testProjectile.getY(), 0.0); } /** * Test whether getX() returns the correct value. * @throws Exception possible Exception. */ @Test public void testGetX() throws Exception { testProjectile.setX(1.0f); assertEquals(1.0f, testProjectile.getX(), 0.0); } /** * Test whether getY() returns the correct value. * @throws Exception possible Exception. */ @Test public void testGetY() throws Exception { testProjectile.setY(1.0f); assertEquals(1.0f, testProjectile.getY(), 0.0); } /** * Test whether getImage() returns the correct Image. * @throws Exception possible Exception. */ @Test public void testGetImage() throws Exception { assertEquals(Main.PLAYER_PROJECTILE, testProjectile.getImage()); } }
20afb44798ef178ab758e33d01a84df4d7d38016
7608da1677950425e877f214f72700aa969c07cf
/Basicknowledge/src/DesignPatterns/factory/pizzafm/NYPizzaStore.java
1ec227817883f848ac2be947e52f55562ebec375
[]
no_license
zzq1/Spark
37adf5f86e2c744ad66a1770c0e6df6f431662a0
c504bb16df5046bca1b8e8ee2be3e636333e8d69
refs/heads/master
2020-03-17T02:54:04.624372
2018-05-14T05:27:09
2018-05-14T05:27:09
133,211,321
0
0
null
null
null
null
UTF-8
Java
false
false
441
java
package DesignPatterns.factory.pizzafm; public class NYPizzaStore extends PizzaStore { Pizza createPizza(String item) { if (item.equals("cheese")) { return new NYStyleCheesePizza(); } else if (item.equals("veggie")) { return new NYStyleVeggiePizza(); } else if (item.equals("clam")) { return new NYStyleClamPizza(); } else if (item.equals("pepperoni")) { return new NYStylePepperoniPizza(); } else return null; } }
0b58927a2d2e44bf96988d1cf93add42e76fab7a
e9b829a401af7ca2eab73420eddd9cb7cd271e37
/TestProject1/Intermediate/Android/armv7/src/com/StutterStudio/TestProject1/AlarmReceiver.java
4f27ec4a58bcd18cbf41b2ac2d278b9822bd26df
[]
no_license
Jableman19/StutterSpeak
1246b126f4d864e45853f41d01a5a23f676f7561
40c5c009d7169e87e2d3215ee36f6d9184a2cb19
refs/heads/main
2023-07-13T16:15:10.277263
2021-08-19T16:46:47
2021-08-19T16:46:47
368,318,989
0
0
null
null
null
null
UTF-8
Java
false
false
1,635
java
/* * Copyright (C) 2012 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.StutterStudio.TestProject1; import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; /** * You should start your derived downloader class when this receiver gets the message * from the alarm service using the provided service helper function within the * DownloaderClientMarshaller. This class must be then registered in your AndroidManifest.xml * file with a section like this: * <receiver android:name=".AlarmReceiver"/> */ public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, OBBDownloaderService.class); } catch (NameNotFoundException e) { e.printStackTrace(); } } }
863c90d4c83e4cb192ece8962c0e32d92d3ae908
e53daa94a988135b8b1379c2a1e19e25bb045091
/cp_movie/rxhttp/src/main/java/com/uyt/ying/rxhttp/net/utils/RxUtil.java
6be16c139adcabfaeaf78f2a62bc80f794c85226
[]
no_license
2020xiaotu/trunk
f90c9bf15c9000a1bb18c7c0a3c0a96d4daf8e68
ba19836c64828c2994e1f0db22fb5d26b4a014f5
refs/heads/master
2023-08-27T08:10:41.709940
2021-10-05T06:27:12
2021-10-05T06:27:12
413,684,673
0
0
null
null
null
null
UTF-8
Java
false
false
2,529
java
/* * Copyright (c) 2019. xxxx */ package com.uyt.ying.rxhttp.net.utils; import com.uyt.ying.rxhttp.net.common.ProgressUtils; import com.trello.lifecycle2.android.lifecycle.AndroidLifecycle; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment;; import androidx.lifecycle.Lifecycle; import io.reactivex.Observable; import io.reactivex.ObservableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class RxUtil { /** * @param activity Activity * @param showLoading 是否显示Loading * @return 转换后的ObservableTransformer */ public static <T> ObservableTransformer<T, T> rxSchedulerHelper(final AppCompatActivity activity, final boolean showLoading) { if (activity == null) return rxSchedulerHelper(); return observable -> { Observable<T> compose =observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(AndroidLifecycle.createLifecycleProvider(activity).bindUntilEvent(Lifecycle.Event.ON_DESTROY)); if (showLoading) { return compose.compose(ProgressUtils.applyProgressBar(activity)); } else { return compose; } }; } /** * @param fragment fragment * @param showLoading 是否显示Loading * @return 转换后的ObservableTransformer */ public static <T> ObservableTransformer<T, T> rxSchedulerHelper(final Fragment fragment, boolean showLoading) { if (fragment == null || fragment.getActivity() == null) return rxSchedulerHelper(); return observable -> { Observable<T> compose = observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(AndroidLifecycle.createLifecycleProvider(fragment.getActivity()).bindUntilEvent(Lifecycle.Event.ON_PAUSE)); if (showLoading) { return compose.compose(ProgressUtils.applyProgressBar(fragment.getActivity())); } else { return compose; } }; } /** * 统一线程处理 * @return 转换后的ObservableTransformer */ public static <T> ObservableTransformer<T, T> rxSchedulerHelper() { return observable -> observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }
db62bb32271084be150b8ba9fc1d263f7f565524
f1a065f13d13866b7b1bd5a36f1c84210b8ccc1f
/kodilla-rps/src/main/java/com/kodilla/rps/ExtendedGame.java
586a384b5a91ca7ca2da0f166f4c5c4383c70d53
[]
no_license
C0nn0rJ0hn/Pawel-Pieton-kodilla-java
3e0f812be83e553625f4de28f6fb2a6ad83c52c3
f74c63877286471698bd6cf29ddee24959e61115
refs/heads/master
2023-08-25T02:20:20.336087
2021-09-21T14:34:00
2021-09-21T14:34:00
334,997,162
0
0
null
null
null
null
UTF-8
Java
false
false
13,402
java
package com.kodilla.rps; import java.util.Random; import java.util.Scanner; public class ExtendedGame { GameMenus gameMenus = new GameMenus(); Random r = new Random(); boolean end = false; public void mainProgramExtended() { //1 - Rock, 2 - Paper, 3 - Scissors, 4 - Spock, 5 - Lizard int roundCount = 0; //how much round was played int playerScore = 0; int compScore = 0; int winRounds = GameMenus.numberOfWiningGames; Scanner input = new Scanner(System.in); System.out.println(); System.out.println("Please make your first move."); while (!end) { roundCount++; System.out.println(); System.out.println("Round number: " + roundCount); int playerChoice = input.nextInt(); int compChoice = r.nextInt(5) + 1; if (playerChoice == 1) { if (compChoice == 1) { System.out.println("You selected Rock"); System.out.println("Computer selected Rock"); System.out.println("It's a tie! No points will be awarded."); } else if (compChoice == 2) { System.out.println("You selected Rock"); System.out.println("Computer selected Scissors"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 3) { System.out.println("You selected Rock"); System.out.println("Computer selected Paper"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 4) { System.out.println("You selected Rock"); System.out.println("Computer selected Spock"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 5) { System.out.println("You selected Rock"); System.out.println("Computer selected Lizard"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } } else if (playerChoice == 2) { if (compChoice == 1) { System.out.println("You selected Paper"); System.out.println("Computer selected Rock"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 2) { System.out.println("You selected Paper"); System.out.println("Computer selected Paper"); System.out.println("It's a tie! No points will be awarded."); } else if (compChoice == 3) { System.out.println("You selected Paper"); System.out.println("Computer selected Scissors"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 4) { System.out.println("You selected Paper"); System.out.println("Computer selected Spock"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 5) { System.out.println("You selected Paper"); System.out.println("Computer selected Lizard"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } } else if (playerChoice == 3) { if (compChoice == 1) { System.out.println("You selected Scissors"); System.out.println("Computer selected Rock"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 2) { System.out.println("You selected Scissors"); System.out.println("Computer selected Paper"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 3) { System.out.println("You selected Scissors"); System.out.println("Computer selected Scissors"); System.out.println("It's a tie! No points will be awarded."); } else if (compChoice == 4) { System.out.println("You selected Scissors"); System.out.println("Computer selected Spock"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 5) { System.out.println("You selected Scissors"); System.out.println("Computer selected Lizard"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } } else if (playerChoice == 4) { if (compChoice == 1) { System.out.println("You selected Spock"); System.out.println("Computer selected Rock"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 2) { System.out.println("You selected Spock"); System.out.println("Computer selected Paper"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 3) { System.out.println("You selected Spock"); System.out.println("Computer selected Scissors"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 4) { System.out.println("You selected Spock"); System.out.println("Computer selected Spock"); System.out.println("It's a tie! No points will be awarded."); } else if (compChoice == 5) { System.out.println("You selected Spock"); System.out.println("Computer selected Lizard"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } } else if (playerChoice == 5) { if (compChoice == 1) { System.out.println("You selected Lizard"); System.out.println("Computer selected Rock"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 2) { System.out.println("You selected Lizard"); System.out.println("Computer selected Paper"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 3) { System.out.println("You selected Lizard"); System.out.println("Computer selected Scissors"); compScore++; System.out.println("Sorry " + GameMenus.playerName + "! You lost this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 4) { System.out.println("You selected Lizard"); System.out.println("Computer selected Spock"); playerScore++; System.out.println("Congratulations " + GameMenus.playerName + "! You won this round"); System.out.println(GameMenus.playerName + ": " + playerScore); System.out.println("Computer: " + compScore); } else if (compChoice == 5) { System.out.println("You selected Lizard"); System.out.println("Computer selected Lizard"); System.out.println("It's a tie! No points will be awarded."); } } if (playerScore == winRounds) { System.out.println(); System.out.println("YOU WON THE GAME! CONGRATS!"); System.out.println(); break; } if (compScore == winRounds) { System.out.println(); System.out.println("I AM SORRY, BUT YOU HAVE BEEN DEFEATED!"); System.out.println(); break; } } System.out.println("If you want to close the game please press \"X\"" + "\nIf you want to play again please press \"R\""); char endOrNewGame = input.next().charAt(0); if(endOrNewGame == 'X' || endOrNewGame == 'x') { System.out.println(); System.out.println("Thank you for the game. Goodbye!"); } else if (endOrNewGame == 'R' || endOrNewGame == 'r') { System.out.println(); System.out.println("Let's try this again :)"); gameMenus.numberOfWinGames(); gameMenus.choiceMenu(); mainProgramExtended(); } } }
7422054a9913c42c286e6a9eb3142b2505fa075c
7febf0a726f81dd5a59b3b83ef7696a728de267a
/app/src/main/java/com/odfd/android/geoquiz/QuizActivity.java
21bed877f167d3fe269053138977e3f1b9e5df61
[]
no_license
oflorez1381/GeoQuiz
6314eed569c5129e797bd27d3c6af49e86aff044
7c5abdfb86f7abdf91f5e66cff874b3be8e7e351
refs/heads/master
2021-09-02T16:31:48.620805
2018-01-02T02:44:45
2018-01-02T02:44:45
113,877,038
0
0
null
null
null
null
UTF-8
Java
false
false
4,398
java
package com.odfd.android.geoquiz; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class QuizActivity extends AppCompatActivity { private static final String TAG = "QuizActivity"; private static final String KEY_INDEX = "index"; private static final int REQUEST_CODE_CHEAT = 0; private Button mTrueButton; private Button mFalseButton; private Button mNextButton; private Button mCheatButton; private TextView mQuestionTextView; private Question[] mQuestionBank = new Question[] { new Question(R.string.question_australia, true), new Question(R.string.question_oceans, true), new Question(R.string.question_mideast, false), new Question(R.string.question_africa, false), new Question(R.string.question_americas, true), new Question(R.string.question_asia, true) }; private int mCurrentIndex = 0; private boolean mIsCheater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG,"onCreate(Bundle) called"); setContentView(R.layout.activity_quiz); if(savedInstanceState != null){ mCurrentIndex = savedInstanceState.getInt(KEY_INDEX); } mQuestionTextView = (TextView)findViewById(R.id.question_text_view); updateQuestion(); mTrueButton = (Button) findViewById(R.id.true_button); mTrueButton.setOnClickListener(view -> checkAnswer(true)); mFalseButton = (Button) findViewById(R.id.false_button); mFalseButton.setOnClickListener(view -> checkAnswer(false)); mNextButton = (Button) findViewById(R.id.next_button); mNextButton.setOnClickListener(view -> { mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; mIsCheater = false; updateQuestion(); }); mCheatButton = (Button) findViewById(R.id.cheat_button); mCheatButton.setOnClickListener(view -> { boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); Intent intent = CheatActivity.newIntent(QuizActivity.this, answerIsTrue); startActivityForResult(intent, REQUEST_CODE_CHEAT); }); } private void updateQuestion() { int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); } private void checkAnswer(boolean userPressedTrue){ boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); int messageResId = 0; if (mIsCheater){ messageResId = R.string.judgment_toast; } else { messageResId = R.string.incorrect_toast; if(userPressedTrue == answerIsTrue) { messageResId = R.string.correct_toast; } } Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show(); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ if(resultCode != Activity.RESULT_OK){ return; } if(requestCode == REQUEST_CODE_CHEAT){ if(data == null){ return; } mIsCheater = CheatActivity.wasAnswerShown(data);; } } @Override public void onStart(){ super.onStart(); Log.d(TAG, "onStart() called"); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume() called"); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause() called"); } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log.i(TAG,"onSaveInstanceState(Bundle)"); savedInstanceState.putInt(KEY_INDEX, mCurrentIndex); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop() called"); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() called"); } }
daa5bd0b962200ce8f1dbc56caf0127474ac44cb
9167d74191c6ab72fe949eaf6b41cde8e7b24fd0
/BetterHood/src/com/lcc3710/InfoBubble.java
0ec17b3571489f70406fa5fe6bd50ca2e3ca54e7
[]
no_license
adanjz1/betterhood
b83ca193ff7914d4dcae3a6194ad0a7c05a5bca4
b550de3976c163a2cc19a43edc0f74abc71c8064
refs/heads/master
2021-01-01T03:31:26.535214
2009-12-07T07:19:41
2009-12-07T07:19:41
56,122,796
0
0
null
null
null
null
UTF-8
Java
false
false
2,135
java
/** * */ package com.lcc3710; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.AttributeSet; import android.widget.RelativeLayout; import android.widget.TextView; public class InfoBubble extends RelativeLayout { private TextView title; private TextView creator; private TextView date; private TextView address; private TextView distance; /** * @param context */ public InfoBubble(Context context) { super(context); init(); } /** * @param context * @param attrs */ public InfoBubble(Context context, AttributeSet attrs) { super(context, attrs); init(); } /** * @param context * @param attrs * @param defStyle */ public InfoBubble(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { title = new TextView(this.getContext()); creator = new TextView(this.getContext()); date = new TextView(this.getContext()); address = new TextView(this.getContext()); distance = new TextView(this.getContext()); this.setBackgroundResource(R.drawable.map_dialogue_bubble); Bitmap graphic = BitmapFactory.decodeResource(this.getResources(), R.drawable.map_dialogue_bubble); RelativeLayout.LayoutParams attr = new RelativeLayout.LayoutParams(graphic.getWidth(), graphic.getHeight()); this.setLayoutParams(attr); } public void update(Template t) { /* // reset the text fields title.setText(""); creator.setText(""); date.setText(""); address.setText(""); distance.setText(""); // start filling in our text fields creator.setText(t.creator); TemplateWidget[] widgets = t.widgets; for (int i = 0; i < widgets.length; i++) { TemplateWidget w = widgets[i]; if (w.label.equals("Title")) { title.setText(w.value); } if (w.type.equals("Location")) { address.setText(w.value); } if (w.type.equals("StartDate")) { date.setText(w.value); } if (w.type.equals("EndDate")) { date.append(w.value); } // hard coding shit distance.setText("1.0 mi"); } */ } }
[ "gumplunger@776878ea-5f69-11de-b7a8-4be610c0df87" ]
gumplunger@776878ea-5f69-11de-b7a8-4be610c0df87
6a83d21c33d4a1a192a107e37e0d7647609ab2dd
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/transform/ListActionExecutionsResultJsonUnmarshaller.java
ab7e11b38c42f5378d5b60e910950fa005250593
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
3,289
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codepipeline.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codepipeline.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ListActionExecutionsResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListActionExecutionsResultJsonUnmarshaller implements Unmarshaller<ListActionExecutionsResult, JsonUnmarshallerContext> { public ListActionExecutionsResult unmarshall(JsonUnmarshallerContext context) throws Exception { ListActionExecutionsResult listActionExecutionsResult = new ListActionExecutionsResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return listActionExecutionsResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("actionExecutionDetails", targetDepth)) { context.nextToken(); listActionExecutionsResult.setActionExecutionDetails(new ListUnmarshaller<ActionExecutionDetail>(ActionExecutionDetailJsonUnmarshaller .getInstance()) .unmarshall(context)); } if (context.testExpression("nextToken", targetDepth)) { context.nextToken(); listActionExecutionsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return listActionExecutionsResult; } private static ListActionExecutionsResultJsonUnmarshaller instance; public static ListActionExecutionsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new ListActionExecutionsResultJsonUnmarshaller(); return instance; } }
[ "" ]
1830f54a0e36451eeb7e4235538c7d01ec265223
7353cc635b6b9ae0635a1275b833c4997241a334
/src/main/java/ru/samara/ant/ConsoleEventLogger.java
2b6a6775a993f66b52c1f345a66c9559e711298f
[]
no_license
papont/spring-project
68514f9b2ec6a9530c1bf616efffa443a449072c
75cf507946f7856f043eacf74b463bfca2691b5a
refs/heads/master
2021-01-12T11:32:36.151158
2016-11-06T16:34:38
2016-11-06T16:34:38
72,947,542
0
0
null
null
null
null
UTF-8
Java
false
false
147
java
package ru.samara.ant; public class ConsoleEventLogger { public void logEvent(String msg){ System.out.println("Log:" + msg); } }
1b88065cdc50467b71762157ea873704fec39f60
f2eac2342348732684cc05e229636f9e8b634e33
/src/main/java/jerryofouc/github/io/MergeSortedArray.java
ab71ec429bd2b3e1521a55d37a9e68cde2c7f8fe
[]
no_license
jerryofouc/leetcode
a0bf687a30fb373ffb8e235bd36c3fd6b9a63ed8
c1cbce9a7dad24cc860df24cf20f0f81b2ad76ae
refs/heads/master
2021-01-17T04:48:08.948479
2017-10-31T01:39:38
2017-10-31T01:39:38
16,881,085
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package jerryofouc.github.io; /** * Created with IntelliJ IDEA. * User: zhangxiaojie * Date: 5/8/14 * Time: 13:55 * To change this template use File | Settings | File Templates. */ public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { int c[] = new int[m+n]; int mi = 0,ni=0,ci = 0; for(; mi <m && ni <n;ci++) { if(A[mi] < B[ni]){ c[ci] = A[mi]; mi++; }else { c[ci] = B[ni]; ni++; } } while(mi <m ){ c[ci++] = A[mi++]; } while(ni < n ){ c[ci++] = B[ni++]; } for(int i=0;i<m+n;i++){ A[i] = c[i]; } } }
8f5ab1b8df9b54f8772dacc2099f4c98668c4ea5
cfb2c035bb9932ba159c18854ca5e0d6264b8160
/src/main/java/com/laom/medic/jpa/sessions/FinalidadesConsultasFacade.java
440309c025859d030f3434a5750914cd10b6da9f
[]
no_license
rgmcove/laommedic
c424168cd59828731ea4546f001b189deb6babb2
e19934fec95dc5647f02c8058d617f5dc5085e75
refs/heads/master
2022-07-19T03:03:12.956283
2020-02-28T00:41:52
2020-02-28T00:41:52
243,646,024
2
0
null
2022-06-29T19:49:14
2020-02-28T00:35:05
Java
UTF-8
Java
false
false
1,141
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.laom.medic.jpa.sessions; import com.laom.medic.jpa.entities.FinalidadesConsultas; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author neney */ @Stateless public class FinalidadesConsultasFacade extends AbstractFacade<FinalidadesConsultas> { @PersistenceContext(unitName = "com.laom.medic_LAOMMEDIC_war_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FinalidadesConsultasFacade() { super(FinalidadesConsultas.class); } public List<FinalidadesConsultas> findByNombre(String query) { return getEntityManager().createNamedQuery("FinalidadesConsultas.findByFinalidadConsulta") .setParameter("nombre", query + "%") .setMaxResults(8) .getResultList(); } }
a36571c0f793f5e5d0a47fb63ebeaaa170013b05
5933a2a6cbd82e642544d0dd7f132f92e0b0ad04
/herpuconPW/src/main/java/pe/edu/upc/entities/HerpuconCertification.java
a1b8a3ce43ac8569b5af67f03631afa17b546ede
[]
no_license
Germain2001/Progra_Web_grupo05
b79d36f80d8101d8e33f17e3b05fe323dd773a1b
8aebd1a6983ad4c1687237db47cee69c896f9a3c
refs/heads/master
2023-08-04T12:33:29.201062
2021-09-17T22:23:41
2021-09-17T22:23:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,102
java
package pe.edu.upc.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Certificacion") public class HerpuconCertification { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int CCertificacion; @Column(name="I_TipoCertificacion",nullable=false,length=40) private String I_TipoCertificacion; @Column(name="Vigencia",nullable=false,length=40) private String Vigencia; @Column(name="F_FechaCertificacion",nullable=false,length=40) private String F_FechaCertificacion; @Column(name="F_ValidoHasta",nullable=false,length=40) private String F_ValidoHasta; public HerpuconCertification() { super(); // TODO Auto-generated constructor stub } public HerpuconCertification(int cCertificacion, String i_TipoCertificacion, String vigencia, String f_FechaCertificacion, String f_ValidoHasta) { super(); this.CCertificacion = cCertificacion; this.I_TipoCertificacion = i_TipoCertificacion; this.Vigencia = vigencia; this.F_FechaCertificacion = f_FechaCertificacion; this.F_ValidoHasta = f_ValidoHasta; } public int getCCertificacion() { return CCertificacion; } public void setCCertificacion(int cCertificacion) { this.CCertificacion = cCertificacion; } public String getI_TipoCertificacion() { return I_TipoCertificacion; } public void setI_TipoCertificacion(String i_TipoCertificacion) { this.I_TipoCertificacion = i_TipoCertificacion; } public String getVigencia() { return Vigencia; } public void setVigencia(String vigencia) { this.Vigencia = vigencia; } public String getF_FechaCertificacion() { return F_FechaCertificacion; } public void setF_FechaCertificacion(String f_FechaCertificacion) { this.F_FechaCertificacion = f_FechaCertificacion; } public String getF_ValidoHasta() { return F_ValidoHasta; } public void setF_ValidoHasta(String f_ValidoHasta) { this.F_ValidoHasta = f_ValidoHasta; } }
[ "themo@DESKTOP-HCN29DM" ]
themo@DESKTOP-HCN29DM
75bbfe0a7a56c8aefa18d53750dbce1b3480197b
f58251d8553c55cc02b44081f502892b5d0bce11
/app/src/main/java/recipegen/hackdfwrecipe/adapters/RecipeRVAdapter.java
c8ec5a95f99ba022ed11c32f8fb30b47b09cad25
[]
no_license
britnesissom/foodify
dac01d7d3a74907c83995267c4f451ef977ba1c1
3ea715eeef643bc4b3d454f82aec4a5a96dd4af7
refs/heads/master
2020-12-11T16:14:32.494295
2016-06-02T08:33:07
2016-06-02T08:33:07
37,438,772
0
0
null
null
null
null
UTF-8
Java
false
false
4,170
java
package recipegen.hackdfwrecipe.adapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.design.widget.Snackbar; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.text.WordUtils; import java.util.ArrayList; import java.util.List; import recipegen.hackdfwrecipe.R; import recipegen.hackdfwrecipe.SharedPrefsUtility; import recipegen.hackdfwrecipe.models.Recipes; /** * Created by britne on 8/29/15. */ public class RecipeRVAdapter extends RecyclerView.Adapter<RecipeRVAdapter.ViewHolder> { private static final String TAG = "RecipeRecycler"; private List<Recipes> recipesList; private OnFaveRecipeListener listener; private Context context; public interface OnFaveRecipeListener { void onFaveRecipe(Recipes recipe); } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { TextView recipeTitle; ImageView image; ImageView faveStar; public ViewHolder(View v) { super(v); image = (ImageView) v.findViewById(R.id.food_image); faveStar = (ImageView) v.findViewById(R.id.fave_star_btn); recipeTitle = (TextView) v.findViewById(R.id.recipe_name); } } // Provide a suitable constructor (depends on the kind of dataset) public RecipeRVAdapter(List<Recipes> recipes, Context context, OnFaveRecipeListener listener) { recipesList = recipes; this.listener = listener; this.context = context; } // Create new views (invoked by the layout manager) @Override public RecipeRVAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_entry, parent, false); return new RecipeRVAdapter.ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, final int position) { final int pos = holder.getAdapterPosition(); //TODO: set already faved recipes to gold star Picasso.with(context).load(recipesList.get(position).getImage_url()) .into(holder.image); holder.image.setContentDescription(WordUtils.capitalize(StringEscapeUtils.unescapeHtml4(recipesList .get(position).getTitle()))); holder.image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(recipesList.get(pos).getSource_url())); context.startActivity(browserIntent); } }); holder.faveStar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recipesList.get(pos).setFavorited(true); // TODO: set fave to gold star listener.onFaveRecipe(recipesList.get(pos)); } }); holder.recipeTitle.setText(WordUtils.capitalize(StringEscapeUtils.unescapeHtml4 (recipesList.get(pos).getTitle()))); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { if (recipesList == null) { recipesList = new ArrayList<>(); } return recipesList.size(); } }
b7708ff43f650023695a42675f3f95b17ce0705d
47c761faea62cee70f313c22d0c59b2185b07794
/src/main/java/com/xnx3/wangmarket/admin/cache/AutoCreateDataFolder.java
c9cda193eaac4fc92214c2aeabb27c1548e2dfbd
[ "LicenseRef-scancode-mulanpsl-1.0-en", "MulanPSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xnx3/test
bc2deaefb956e039275d3bd162506eab27d81481
4a35f09c42f492c90af0b2f10c7c5c7c59c13a72
refs/heads/master
2023-03-16T14:12:14.248137
2021-02-26T06:14:18
2021-02-26T06:14:18
345,099,226
0
0
null
null
null
null
UTF-8
Java
false
false
704
java
package com.xnx3.wangmarket.admin.cache; import java.io.File; import org.springframework.stereotype.Component; import com.xnx3.FileUtil; import com.xnx3.j2ee.Global; import com.xnx3.j2ee.util.SystemUtil; import com.xnx3.wangmarket.admin.G; /** * 自动在/cache/下创建data文件夹,用于缓存js数据 * @author 管雷鸣 */ @Component public class AutoCreateDataFolder { public AutoCreateDataFolder() { //初始化缓存文件夹,若根目录下没有缓存文件夹,自动创建 if(!FileUtil.exists(SystemUtil.getProjectPath()+G.CACHE_FILE)){ String path = SystemUtil.getProjectPath(); System.out.println("create -- data --"+new File(path+G.CACHE_FILE).mkdir()); } } }
5b608a54240e1a28e05e5f86babb6b6ecc51bea1
8002de03b3feef4fd028e86d01d064e60f49a087
/app/src/main/java/com/bw/one_app/oneapp/MainActivity.java
6f73242581228ca7e8aba185e579ec0b5157a811
[]
no_license
LoBiner/exam
ab57f5481d9b13565dbfa3b05593150487c67586
0ae71e52da2468e5dea37537a22665f061858b79
refs/heads/master
2020-07-01T17:17:14.779145
2016-11-29T03:22:41
2016-11-29T03:22:41
74,267,677
0
0
null
null
null
null
UTF-8
Java
false
false
1,475
java
package com.bw.one_app.oneapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("这是-----Activity1>>>","onCreate"); } public void jump(View v){ Intent intent=new Intent(MainActivity.this,SecndActivity.class); startActivity(intent); } @Override protected void onStart() { super.onStart(); Log.d("这是-----Activity1>>>","onStart"); } @Override protected void onResume() { super.onResume(); Log.d("这是-----Activity1>>>","onResume"); } @Override protected void onPause() { super.onPause(); Log.d("这是-----Activity1>>>","onPause"); } @Override protected void onStop() { super.onStop(); Log.d("这是-----Activity1>>>","onStop"); } @Override protected void onRestart() { super.onRestart(); Log.d("这是-----Activity1>>>","onRestart"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("这是-----Activity1>>>","onDestroy"); } }
258616889d1bc89cd9d697f905d49c6b3d9ad70f
d85eea278f53c2d60197a0b479c074b5a52bdf1e
/Services/msk-seller/src/main/java/com/msk/seller/validator/ISL231180Validator.java
6f059f7bd8e1b6214da5e9cce1473f26c26c4288
[]
no_license
YuanChenM/xcdv1.5
baeaab6e566236d0f3e170ceae186b6d2999c989
77bf0e90102f5704fe186140e1792396b7ade91d
refs/heads/master
2021-05-26T04:51:12.441499
2017-08-14T03:06:07
2017-08-14T03:06:07
100,221,981
1
2
null
null
null
null
UTF-8
Java
false
false
33,340
java
package com.msk.seller.validator; import com.hoperun.plug.spring.base.BaseValidator; import com.msk.common.bean.RsRequest; import com.hoperun.core.consts.NumberConst; import com.msk.core.entity.*; import com.msk.core.entity.SlEpHonor; import com.hoperun.core.exception.BusinessException; import com.hoperun.core.utils.StringUtil; import com.msk.seller.bean.*; /** * Created by cx on 2016/2/23. */ public class ISL231180Validator extends BaseValidator<RsRequest<ISL231180RsParam>> { @Override public void validatorData(RsRequest<ISL231180RsParam> entity) { ISL231180RsParam isl231180RsParam =entity.getParam(); this.validatorRequired("创建者ID/更新者ID",isl231180RsParam.getLoginId()); if("1".equals(isl231180RsParam.getDelFlg())){ if (null != isl231180RsParam.getSlAccount()) { this.validatorRequired("卖家账号", isl231180RsParam.getSlAccount().getSlAccount()); } } if(null!=isl231180RsParam.getInsertFlag()) { if (null!=isl231180RsParam.getInsertFlag() && isl231180RsParam.getInsertFlag() == NumberConst.IntDef.INT_ZERO) { if (null != isl231180RsParam.getSlAccount()) { if(null!=isl231180RsParam.getManufactureFlag() && NumberConst.IntDef.INT_ONE==isl231180RsParam.getManufactureFlag()){ this.validatorRequired("注册来源", isl231180RsParam.getSlAccount().getFromFlg()); }else{ this.validatorRequired("卖家账号", isl231180RsParam.getSlAccount().getSlAccount()); this.validatorRequired("登录密码", isl231180RsParam.getSlAccount().getAccountPsd()); this.validatorRequired("登录手机号码", isl231180RsParam.getSlAccount().getSlTel()); this.validatorRequired("卖家显示名称", isl231180RsParam.getSlAccount().getSlShowName()); this.validatorRequired("联系人姓名", isl231180RsParam.getSlAccount().getSlContact()); this.validatorRequired("认证状态", isl231180RsParam.getSlAccount().getAuthStatus()); this.validatorRequired("注册来源", isl231180RsParam.getSlAccount().getFromFlg()); } } if (null != isl231180RsParam.getSlSeller()) { if(null!=isl231180RsParam.getManufactureFlag() && NumberConst.IntDef.INT_ONE==isl231180RsParam.getManufactureFlag()){ this.validatorRequired("生产国籍", isl231180RsParam.getSlSeller().getSlConFlg()); this.validatorRequired("省编码", isl231180RsParam.getSlSeller().getProvinceCode()); this.validatorRequired("地区编码", isl231180RsParam.getSlSeller().getCityCode()); this.validatorRequired("区编码", isl231180RsParam.getSlSeller().getDistrictCode()); this.validatorRequired("卖家主分类", isl231180RsParam.getSlSeller().getSlMainClass()); this.validatorRequired("神农客标志", isl231180RsParam.getSlSeller().getSnkFlg()); this.validatorRequired("自产型卖家标志", isl231180RsParam.getSlSeller().getSelfFlg()); this.validatorRequired("代理型卖家标志", isl231180RsParam.getSlSeller().getAgentFlg()); this.validatorRequired("OEM型卖家标志", isl231180RsParam.getSlSeller().getOemFlg()); this.validatorRequired("买手型卖家标志", isl231180RsParam.getSlSeller().getBuyerFlg()); }else{ this.validatorRequired("卖家账号", isl231180RsParam.getSlSeller().getSlAccount()); this.validatorRequired("生产国籍", isl231180RsParam.getSlSeller().getSlConFlg()); this.validatorRequired("省编码", isl231180RsParam.getSlSeller().getProvinceCode()); this.validatorRequired("地区编码", isl231180RsParam.getSlSeller().getCityCode()); this.validatorRequired("区编码", isl231180RsParam.getSlSeller().getDistrictCode()); this.validatorRequired("卖家主分类", isl231180RsParam.getSlSeller().getSlMainClass()); this.validatorRequired("神农客标志", isl231180RsParam.getSlSeller().getSnkFlg()); this.validatorRequired("自产型卖家标志", isl231180RsParam.getSlSeller().getSelfFlg()); this.validatorRequired("代理型卖家标志", isl231180RsParam.getSlSeller().getAgentFlg()); this.validatorRequired("OEM型卖家标志", isl231180RsParam.getSlSeller().getOemFlg()); this.validatorRequired("买手型卖家标志", isl231180RsParam.getSlSeller().getBuyerFlg()); } } if (null != isl231180RsParam.getPdClassesCodeList()) { for (SlPdClasses slPdClasses : isl231180RsParam.getPdClassesCodeList()) { this.validatorRequired("产品类别", slPdClasses.getPdClassesCode()); this.validatorRequired("产品加工程度编码", slPdClasses.getMachiningCode()); } } if (null != isl231180RsParam.getSlEnterprise()) { this.validatorRequired("企业名称", isl231180RsParam.getSlEnterprise().getEpName()); this.validatorRequired("三证合一营业执照标志", isl231180RsParam.getSlEnterprise().getLicType()); this.validatorRequired("营业执照_名称", isl231180RsParam.getSlEnterprise().getLicName()); this.validatorRequired("税务登记证_税务登记证号", isl231180RsParam.getSlEnterprise().getTaxNo()); this.validatorRequired("组织机构代码证_代码", isl231180RsParam.getSlEnterprise().getOrgNo()); } if (null != isl231180RsParam.getCertInfoList()) { for (ISL231127CertInfoList isl231127CertInfoList : isl231180RsParam.getCertInfoList()) { this.validatorRequired("证照名称", isl231127CertInfoList.getCertName()); if (null != isl231127CertInfoList.getCertItemList()) { for (SlEpCertItem slEpCertItem : isl231127CertInfoList.getCertItemList()) { this.validatorRequired("证照项目名称", slEpCertItem.getCertItemName()); this.validatorRequired("证照项目内容", slEpCertItem.getCertItemValue()); } } } } if (null != isl231180RsParam.getSlEpHonorList()) { for (SlEpHonor slEpHonor : isl231180RsParam.getSlEpHonorList()) { this.validatorRequired("荣誉描述", slEpHonor.getHonorDesc()); } } if (null != isl231180RsParam.getSlEpBrandList()) { for (ISL231180SlEpBrandList isl231180SlEpBrandList : isl231180RsParam.getSlEpBrandList()) { this.validatorRequired("品牌名称", isl231180SlEpBrandList.getBrandName()); this.validatorRequired("品牌分类", isl231180SlEpBrandList.getBrandClass()); this.validatorRequired("商标注册证", isl231180SlEpBrandList.getBrandNo()); if (null != isl231180SlEpBrandList.getSlEpBrandHonorList()) { for (SlEpBrandHonor slEpBrandHonor : isl231180SlEpBrandList.getSlEpBrandHonorList()) { this.validatorRequired("企业产品品牌荣誉描述", slEpBrandHonor.getHonorDes()); } } } } if (null != isl231180RsParam.getSlPdBrandList()) { for (ISlPdBrand slPdBrand : isl231180RsParam.getSlPdBrandList()) { //this.validatorRequired("品牌所属企业ID", slPdBrand.getBrandEpId()); //this.validatorRequired("品牌ID", slPdBrand.getBrandId()); this.validatorRequired("品牌分类", slPdBrand.getBrandClass()); } } if (null != isl231180RsParam.getSlEpWorkshopList()) { for (SlEpWorkshop slEpWorkshop : isl231180RsParam.getSlEpWorkshopList()) { this.validatorRequired("车间名称", slEpWorkshop.getWorkshopName()); } } if (null != isl231180RsParam.getSlEpCap()) { this.validatorRequired("厂区_总资产", isl231180RsParam.getSlEpCap().getFtyAsset()); this.validatorRequired("厂区_注册资本", isl231180RsParam.getSlEpCap().getFtyRegCapital()); this.validatorRequired("厂区_占地面积", isl231180RsParam.getSlEpCap().getFtyLandArea()); this.validatorRequired("厂区_厂房面积", isl231180RsParam.getSlEpCap().getFtyFloorArea()); this.validatorRequired("厂区_主要设备", isl231180RsParam.getSlEpCap().getFtyEquipment()); this.validatorRequired("厂区_设计产能", isl231180RsParam.getSlEpCap().getFtyDesignCap()); this.validatorRequired("厂区_实际产能", isl231180RsParam.getSlEpCap().getFtyActualCap()); this.validatorRequired("厂区_外贸销售占比", isl231180RsParam.getSlEpCap().getFtyFtRate()); this.validatorRequired("厂区_直销占比", isl231180RsParam.getSlEpCap().getFtyDsRate()); this.validatorRequired("厂区_代理销售占比", isl231180RsParam.getSlEpCap().getFtyAsRate()); this.validatorRequired("库容概括_原料库容", isl231180RsParam.getSlEpCap().getScapMaterial()); this.validatorRequired("库容概括_成品库容", isl231180RsParam.getSlEpCap().getScapProduct()); } if (null != isl231180RsParam.getSlEpAuthList()) { for (ISL231180SLEpAuth isl231180SLEpAuth : isl231180RsParam.getSlEpAuthList()) { this.validatorRequired("1:卖家代理及分销授权:2:卖家OEM委托授权标志", isl231180SLEpAuth.getFlag()); /*this.validatorRequired("生产商_企业ID", isl231180SLEpAuth.getProducerEpId());*/ } } if (null != isl231180RsParam.getSlEpManagerList()) { for (SlEpManager slEpManager : isl231180RsParam.getSlEpManagerList()) { this.validatorRequired("职务", slEpManager.getMemberDuties()); this.validatorRequired("姓名", slEpManager.getMemberName()); } } if (null != isl231180RsParam.getSlEcTeamList()) { for (SlEcTeam slEcTeam : isl231180RsParam.getSlEcTeamList()) { this.validatorRequired("是否负责人", slEcTeam.getLeaderFlg()); this.validatorRequired("姓名", slEcTeam.getMemberName()); } } if (null != isl231180RsParam.getSlEpDdList()) { for (SlEpDd slEpDd : isl231180RsParam.getSlEpDdList()) { this.validatorRequired("设备名称", slEpDd.getDdName()); } } } else if (null!=isl231180RsParam.getInsertFlag() && isl231180RsParam.getInsertFlag() == NumberConst.IntDef.INT_ONE) { if (null != isl231180RsParam.getSlAccount()) { this.validatorRequired("卖家账号", isl231180RsParam.getSlAccount().getSlAccount()); this.validatorRequired("登录密码", isl231180RsParam.getSlAccount().getAccountPsd()); this.validatorRequired("登录手机号码", isl231180RsParam.getSlAccount().getSlTel()); this.validatorRequired("卖家显示名称", isl231180RsParam.getSlAccount().getSlShowName()); this.validatorRequired("联系人姓名", isl231180RsParam.getSlAccount().getSlContact()); this.validatorRequired("认证状态", isl231180RsParam.getSlAccount().getAuthStatus()); this.validatorRequired("注册来源", isl231180RsParam.getSlAccount().getFromFlg()); } if (null != isl231180RsParam.getSlSeller()) { this.validatorRequired("卖家账号", isl231180RsParam.getSlSeller().getSlAccount()); this.validatorRequired("生产国籍", isl231180RsParam.getSlSeller().getSlConFlg()); this.validatorRequired("省编码", isl231180RsParam.getSlSeller().getProvinceCode()); this.validatorRequired("地区编码", isl231180RsParam.getSlSeller().getCityCode()); this.validatorRequired("区编码", isl231180RsParam.getSlSeller().getDistrictCode()); this.validatorRequired("卖家主分类", isl231180RsParam.getSlSeller().getSlMainClass()); this.validatorRequired("神农客标志", isl231180RsParam.getSlSeller().getSnkFlg()); this.validatorRequired("自产型卖家标志", isl231180RsParam.getSlSeller().getSelfFlg()); this.validatorRequired("代理型卖家标志", isl231180RsParam.getSlSeller().getAgentFlg()); this.validatorRequired("OEM型卖家标志", isl231180RsParam.getSlSeller().getOemFlg()); this.validatorRequired("买手型卖家标志", isl231180RsParam.getSlSeller().getBuyerFlg()); } if (null != isl231180RsParam.getPdClassesCodeList()) { for (SlPdClasses slPdClasses : isl231180RsParam.getPdClassesCodeList()) { this.validatorRequired("卖家ID", slPdClasses.getSlCode()); this.validatorRequired("产品类别", slPdClasses.getPdClassesCode()); this.validatorRequired("产品加工程度编码", slPdClasses.getMachiningCode()); } } if (null != isl231180RsParam.getSlEnterprise()) { this.validatorRequired("卖家ID", isl231180RsParam.getSlEnterprise().getSlCode()); this.validatorRequired("企业名称", isl231180RsParam.getSlEnterprise().getEpName()); this.validatorRequired("三证合一营业执照标志", isl231180RsParam.getSlEnterprise().getLicType()); this.validatorRequired("营业执照_名称", isl231180RsParam.getSlEnterprise().getLicName()); this.validatorRequired("税务登记证_税务登记证号", isl231180RsParam.getSlEnterprise().getTaxNo()); this.validatorRequired("组织机构代码证_代码", isl231180RsParam.getSlEnterprise().getOrgNo()); } if (null != isl231180RsParam.getCertInfoList()) { for (ISL231127CertInfoList isl231127CertInfoList : isl231180RsParam.getCertInfoList()) { this.validatorRequired("企业ID", isl231127CertInfoList.getEpId()); this.validatorRequired("证照名称", isl231127CertInfoList.getCertName()); if (null != isl231127CertInfoList.getCertItemList()) { for (SlEpCertItem slEpCertItem : isl231127CertInfoList.getCertItemList()) { this.validatorRequired("证照项目名称", slEpCertItem.getCertItemName()); this.validatorRequired("证照项目内容", slEpCertItem.getCertItemValue()); } } } } if (null != isl231180RsParam.getSlEpHonorList()) { for (SlEpHonor slEpHonor : isl231180RsParam.getSlEpHonorList()) { this.validatorRequired("企业ID", slEpHonor.getEpId()); this.validatorRequired("荣誉描述", slEpHonor.getHonorDesc()); } } if (null != isl231180RsParam.getSlEpBrandList()) { for (ISL231180SlEpBrandList isl231180SlEpBrandList : isl231180RsParam.getSlEpBrandList()) { if(StringUtil.isNullOrEmpty(StringUtil.toSafeString(isl231180SlEpBrandList.getEpId()))){ if (null != isl231180SlEpBrandList.getSlEpBrandHonorList()) { for (SlEpBrandHonor slEpBrandHonor : isl231180SlEpBrandList.getSlEpBrandHonorList()) { this.validatorRequired("企业ID", slEpBrandHonor.getEpId()); this.validatorRequired("企业产品品牌荣誉描述", slEpBrandHonor.getHonorDes()); } } }else { this.validatorRequired("企业ID", isl231180SlEpBrandList.getEpId()); this.validatorRequired("品牌名称", isl231180SlEpBrandList.getBrandName()); this.validatorRequired("品牌分类", isl231180SlEpBrandList.getBrandClass()); this.validatorRequired("商标注册证", isl231180SlEpBrandList.getBrandNo()); if (null != isl231180SlEpBrandList.getSlEpBrandHonorList()) { for (SlEpBrandHonor slEpBrandHonor : isl231180SlEpBrandList.getSlEpBrandHonorList()) { this.validatorRequired("企业ID", slEpBrandHonor.getEpId()); this.validatorRequired("企业产品品牌荣誉描述", slEpBrandHonor.getHonorDes()); } } } } } if (null != isl231180RsParam.getSlPdBrandList()) { for (ISlPdBrand slPdBrand : isl231180RsParam.getSlPdBrandList()) { this.validatorRequired("卖家ID", slPdBrand.getSlCode()); this.validatorRequired("品牌所属企业ID", slPdBrand.getBrandEpId()); this.validatorRequired("品牌分类", slPdBrand.getBrandClass()); } } if (null != isl231180RsParam.getSlEpWorkshopList()) { for (SlEpWorkshop slEpWorkshop : isl231180RsParam.getSlEpWorkshopList()) { this.validatorRequired("企业ID", slEpWorkshop.getEpId()); this.validatorRequired("车间名称", slEpWorkshop.getWorkshopName()); } } if (null != isl231180RsParam.getSlEpCap()) { this.validatorRequired("企业ID", isl231180RsParam.getSlEpCap().getEpId()); this.validatorRequired("厂区_总资产", isl231180RsParam.getSlEpCap().getFtyAsset()); this.validatorRequired("厂区_注册资本", isl231180RsParam.getSlEpCap().getFtyRegCapital()); this.validatorRequired("厂区_占地面积", isl231180RsParam.getSlEpCap().getFtyLandArea()); this.validatorRequired("厂区_厂房面积", isl231180RsParam.getSlEpCap().getFtyFloorArea()); this.validatorRequired("厂区_主要设备", isl231180RsParam.getSlEpCap().getFtyEquipment()); this.validatorRequired("厂区_设计产能", isl231180RsParam.getSlEpCap().getFtyDesignCap()); this.validatorRequired("厂区_实际产能", isl231180RsParam.getSlEpCap().getFtyActualCap()); this.validatorRequired("厂区_外贸销售占比", isl231180RsParam.getSlEpCap().getFtyFtRate()); this.validatorRequired("厂区_直销占比", isl231180RsParam.getSlEpCap().getFtyDsRate()); this.validatorRequired("厂区_代理销售占比", isl231180RsParam.getSlEpCap().getFtyAsRate()); this.validatorRequired("库容概括_原料库容", isl231180RsParam.getSlEpCap().getScapMaterial()); this.validatorRequired("库容概括_成品库容", isl231180RsParam.getSlEpCap().getScapProduct()); } if (null != isl231180RsParam.getSlEpAuthList()) { for (ISL231180SLEpAuth isl231180SLEpAuth : isl231180RsParam.getSlEpAuthList()) { this.validatorRequired("卖家ID", isl231180SLEpAuth.getSlCode()); this.validatorRequired("1:卖家代理及分销授权:2:卖家OEM委托授权标志", isl231180SLEpAuth.getFlag()); this.validatorRequired("生产商_企业ID", isl231180SLEpAuth.getProducerEpId()); this.validatorRequired("删除标志", isl231180SLEpAuth.getDelFlg()); } } if (null != isl231180RsParam.getSlEpManagerList()) { for (SlEpManager slEpManager : isl231180RsParam.getSlEpManagerList()) { this.validatorRequired("企业ID", slEpManager.getEpId()); this.validatorRequired("职务", slEpManager.getMemberDuties()); this.validatorRequired("姓名", slEpManager.getMemberName()); } } if (null != isl231180RsParam.getSlEcTeamList()) { for (SlEcTeam slEcTeam : isl231180RsParam.getSlEcTeamList()) { this.validatorRequired("卖家ID", slEcTeam.getSlCode()); this.validatorRequired("是否负责人", slEcTeam.getLeaderFlg()); this.validatorRequired("姓名", slEcTeam.getMemberName()); } } if (null != isl231180RsParam.getSlEpDdList()) { for (SlEpDd slEpDd : isl231180RsParam.getSlEpDdList()) { this.validatorRequired("企业ID", slEpDd.getEpId()); this.validatorRequired("设备名称", slEpDd.getDdName()); } } }else{ throw new BusinessException("insertFlag超出范围"); } } else { if (null != isl231180RsParam.getSlAccount()) { this.validatorRequired("卖家账号", isl231180RsParam.getSlAccount().getSlAccount()); this.validatorRequired("登录密码", isl231180RsParam.getSlAccount().getAccountPsd()); this.validatorRequired("登录手机号码", isl231180RsParam.getSlAccount().getSlTel()); this.validatorRequired("卖家显示名称", isl231180RsParam.getSlAccount().getSlShowName()); this.validatorRequired("联系人姓名", isl231180RsParam.getSlAccount().getSlContact()); this.validatorRequired("认证状态", isl231180RsParam.getSlAccount().getAuthStatus()); this.validatorRequired("注册来源", isl231180RsParam.getSlAccount().getFromFlg()); } if (null != isl231180RsParam.getSlSeller()) { this.validatorRequired("卖家ID", isl231180RsParam.getSlSeller().getSlCode()); this.validatorRequired("生产国籍", isl231180RsParam.getSlSeller().getSlConFlg()); this.validatorRequired("省编码", isl231180RsParam.getSlSeller().getProvinceCode()); this.validatorRequired("地区编码", isl231180RsParam.getSlSeller().getCityCode()); this.validatorRequired("区编码", isl231180RsParam.getSlSeller().getDistrictCode()); this.validatorRequired("卖家主分类", isl231180RsParam.getSlSeller().getSlMainClass()); this.validatorRequired("神农客标志", isl231180RsParam.getSlSeller().getSnkFlg()); this.validatorRequired("自产型卖家标志", isl231180RsParam.getSlSeller().getSelfFlg()); this.validatorRequired("代理型卖家标志", isl231180RsParam.getSlSeller().getAgentFlg()); this.validatorRequired("OEM型卖家标志", isl231180RsParam.getSlSeller().getOemFlg()); this.validatorRequired("买手型卖家标志", isl231180RsParam.getSlSeller().getBuyerFlg()); } if (null != isl231180RsParam.getPdClassesCodeList()) { for (SlPdClasses slPdClasses : isl231180RsParam.getPdClassesCodeList()) { this.validatorRequired("卖家ID", slPdClasses.getSlCode()); this.validatorRequired("产品类别", slPdClasses.getPdClassesCode()); this.validatorRequired("产品加工程度编码", slPdClasses.getMachiningCode()); } } if (null != isl231180RsParam.getSlEnterprise()) { this.validatorRequired("企业ID", isl231180RsParam.getSlEnterprise().getEpId()); this.validatorRequired("企业名称", isl231180RsParam.getSlEnterprise().getEpName()); this.validatorRequired("三证合一营业执照标志", isl231180RsParam.getSlEnterprise().getLicType()); this.validatorRequired("营业执照_名称", isl231180RsParam.getSlEnterprise().getLicName()); this.validatorRequired("税务登记证_税务登记证号", isl231180RsParam.getSlEnterprise().getTaxNo()); this.validatorRequired("组织机构代码证_代码", isl231180RsParam.getSlEnterprise().getOrgNo()); } if (null != isl231180RsParam.getCertInfoList()) { for (ISL231127CertInfoList isl231127CertInfoList : isl231180RsParam.getCertInfoList()) { this.validatorRequired("企业ID", isl231127CertInfoList.getEpId()); this.validatorRequired("证照ID", isl231127CertInfoList.getCertId()); this.validatorRequired("证照名称", isl231127CertInfoList.getCertName()); if (null != isl231127CertInfoList.getCertItemList()) { for (SlEpCertItem slEpCertItem : isl231127CertInfoList.getCertItemList()) { this.validatorRequired("证照项目ID", slEpCertItem.getCertItemId()); this.validatorRequired("证照项目名称", slEpCertItem.getCertItemName()); this.validatorRequired("证照项目内容", slEpCertItem.getCertItemValue()); } } } } if (null != isl231180RsParam.getSlEpHonorList()) { for (SlEpHonor slEpHonor : isl231180RsParam.getSlEpHonorList()) { this.validatorRequired("企业ID", slEpHonor.getEpId()); this.validatorRequired("荣誉ID", slEpHonor.getHonorId()); this.validatorRequired("荣誉描述", slEpHonor.getHonorDesc()); } } if (null != isl231180RsParam.getSlEpBrandList()) { for (ISL231180SlEpBrandList isl231180SlEpBrandList : isl231180RsParam.getSlEpBrandList()) { this.validatorRequired("企业ID", isl231180SlEpBrandList.getEpId()); this.validatorRequired("品牌ID", isl231180SlEpBrandList.getBrandId()); this.validatorRequired("品牌名称", isl231180SlEpBrandList.getBrandName()); this.validatorRequired("品牌分类", isl231180SlEpBrandList.getBrandClass()); this.validatorRequired("商标注册证", isl231180SlEpBrandList.getBrandNo()); if (null != isl231180SlEpBrandList.getSlEpBrandHonorList()) { for (SlEpBrandHonor slEpBrandHonor : isl231180SlEpBrandList.getSlEpBrandHonorList()) { this.validatorRequired("企业ID", slEpBrandHonor.getEpId()); this.validatorRequired("品牌ID", slEpBrandHonor.getBrandId()); this.validatorRequired("荣誉ID", slEpBrandHonor.getHonorId()); this.validatorRequired("企业产品品牌荣誉描述", slEpBrandHonor.getHonorDes()); } } } } if (null != isl231180RsParam.getSlPdBrandList()) { for (ISlPdBrand slPdBrand : isl231180RsParam.getSlPdBrandList()) { this.validatorRequired("卖家ID", slPdBrand.getSlCode()); this.validatorRequired("品牌所属企业ID", slPdBrand.getBrandEpId()); this.validatorRequired("品牌ID", slPdBrand.getBrandId()); this.validatorRequired("品牌分类", slPdBrand.getBrandClass()); } } if (null != isl231180RsParam.getSlEpWorkshopList()) { for (SlEpWorkshop slEpWorkshop : isl231180RsParam.getSlEpWorkshopList()) { this.validatorRequired("企业ID", slEpWorkshop.getEpId()); this.validatorRequired("车间ID", slEpWorkshop.getWorkshopId()); this.validatorRequired("车间名称", slEpWorkshop.getWorkshopName()); } } if (null != isl231180RsParam.getSlEpCap()) { this.validatorRequired("企业ID", isl231180RsParam.getSlEpCap().getEpId()); this.validatorRequired("厂区_总资产", isl231180RsParam.getSlEpCap().getFtyAsset()); this.validatorRequired("厂区_注册资本", isl231180RsParam.getSlEpCap().getFtyRegCapital()); this.validatorRequired("厂区_占地面积", isl231180RsParam.getSlEpCap().getFtyLandArea()); this.validatorRequired("厂区_厂房面积", isl231180RsParam.getSlEpCap().getFtyFloorArea()); this.validatorRequired("厂区_主要设备", isl231180RsParam.getSlEpCap().getFtyEquipment()); this.validatorRequired("厂区_设计产能", isl231180RsParam.getSlEpCap().getFtyDesignCap()); this.validatorRequired("厂区_实际产能", isl231180RsParam.getSlEpCap().getFtyActualCap()); this.validatorRequired("厂区_外贸销售占比", isl231180RsParam.getSlEpCap().getFtyFtRate()); this.validatorRequired("厂区_直销占比", isl231180RsParam.getSlEpCap().getFtyDsRate()); this.validatorRequired("厂区_代理销售占比", isl231180RsParam.getSlEpCap().getFtyAsRate()); this.validatorRequired("库容概括_原料库容", isl231180RsParam.getSlEpCap().getScapMaterial()); this.validatorRequired("库容概括_成品库容", isl231180RsParam.getSlEpCap().getScapProduct()); } if (null != isl231180RsParam.getSlEpAuthList()) { for (ISL231180SLEpAuth isl231180SLEpAuth : isl231180RsParam.getSlEpAuthList()) { this.validatorRequired("卖家ID", isl231180SLEpAuth.getSlCode()); this.validatorRequired("1:卖家代理及分销授权:2:卖家OEM委托授权标志", isl231180SLEpAuth.getFlag()); this.validatorRequired("生产商_企业ID", isl231180SLEpAuth.getProducerEpId()); } } if (null != isl231180RsParam.getSlEpManagerList()) { for (SlEpManager slEpManager : isl231180RsParam.getSlEpManagerList()) { this.validatorRequired("企业ID", slEpManager.getEpId()); this.validatorRequired("管理成员ID", slEpManager.getMemberId()); this.validatorRequired("职务", slEpManager.getMemberDuties()); this.validatorRequired("姓名", slEpManager.getMemberName()); } } if (null != isl231180RsParam.getSlEcTeamList()) { for (SlEcTeam slEcTeam : isl231180RsParam.getSlEcTeamList()) { this.validatorRequired("卖家ID", slEcTeam.getSlCode()); this.validatorRequired("成员ID", slEcTeam.getMemberId()); this.validatorRequired("是否负责人", slEcTeam.getLeaderFlg()); this.validatorRequired("姓名", slEcTeam.getMemberName()); } } if (null != isl231180RsParam.getSlEpDdList()) { for (SlEpDd slEpDd : isl231180RsParam.getSlEpDdList()) { this.validatorRequired("企业ID", slEpDd.getEpId()); this.validatorRequired("设备ID", slEpDd.getDdId()); this.validatorRequired("设备名称", slEpDd.getDdName()); } } this.validatorRequired("版本号",isl231180RsParam.getVer()); } } }
c51d392b113ed6c6eeeffe9503f394e1bfc25f23
c92689bfd97871e1f2d4d8102086e09fc3bc72ed
/app/src/main/java/com/tsqc/util/RoundRectCornerImageView.java
da3943d94ad84ad8a24492bda8bcc36d55996897
[]
no_license
anilobpoo/TSQC
b3317e717d45b0a870810987b475b4fe1f55b06d
38b5b3841dcba0177d10ae7f55679274d2ef67e4
refs/heads/master
2020-06-19T03:37:45.790253
2019-07-12T09:26:02
2019-07-12T09:26:02
194,795,473
0
0
null
null
null
null
UTF-8
Java
false
false
1,107
java
package com.tsqc.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.widget.ImageView; /** * Created by someo on 08-06-2017. */ public class RoundRectCornerImageView extends ImageView { private float radius = 20.0f; private Path path; private RectF rect; public RoundRectCornerImageView(Context context) { super(context); init(); } public RoundRectCornerImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RoundRectCornerImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { path = new Path(); } @Override protected void onDraw(Canvas canvas) { rect = new RectF(0, 0, this.getWidth(), this.getHeight()); path.addRoundRect(rect, radius, radius, Path.Direction.CW); canvas.clipPath(path); super.onDraw(canvas); } }
8019f4e97cf97e19c578bb1042ddd67ed299c221
832c1ba95777844c85b7cb5b766be141cfc99fc2
/app/src/main/java/com/example/somaiya/somaiyaclassroom/Main_Sign_In_Student.java
122355b0c3da62c0bdafed29532143d1cd921835
[ "MIT" ]
permissive
gayatri-01/Project-Somaiya-Classroom
d720588857d436c7bab6c28b0ddd74c7a8afc954
dc8bdadc412d68135cef53af0fb360b0f01d440e
refs/heads/master
2020-03-20T21:40:47.150269
2018-07-08T14:22:11
2018-07-08T14:22:11
137,753,858
1
0
null
2018-06-18T13:16:21
2018-06-18T13:16:21
null
UTF-8
Java
false
false
6,639
java
package com.example.somaiya.somaiyaclassroom; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Paint; import android.graphics.drawable.GradientDrawable; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class Main_Sign_In_Student extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{ private SignInButton SignIn; private GoogleSignInClient mGoogleSignInClient; private static final int REQ_CODE=901; private static final String TAG = "GoogleActivity"; private FirebaseAuth mAuth; private Switch isEnlarged; public static Boolean isZoom; private float zoomFactor = 1.25f; Magnify mag = new Magnify(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main__sign__in__student); SignIn = (SignInButton) findViewById(R.id.signin); GoogleSignInOptions googleSignInOptions= new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build(); mGoogleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions); SignIn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { SignIn(); } }); mAuth = FirebaseAuth.getInstance(); SignIn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { SignIn(); } }); isEnlarged = findViewById(R.id.switch1); isEnlarged.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mag.enlarge(isEnlarged.isChecked(),findViewById(android.R.id.content),zoomFactor); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); openStudActivity(currentUser); } private void SignIn(){ Intent intent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(intent, REQ_CODE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == REQ_CODE) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); // [START_EXCLUDE] openStudActivity(null); // [END_EXCLUDE] } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); // [START_EXCLUDE silent] //showProgressDialog(); // [END_EXCLUDE] AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); Toast.makeText(Main_Sign_In_Student.this,"Logged In Successfully",Toast.LENGTH_SHORT).show(); FirebaseUser user = mAuth.getCurrentUser(); openStudActivity(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); //Snackbar.make(findViewById(R.id.student_login), "Authentication Failed.", Snackbar.LENGTH_SHORT).show(); openStudActivity(null); } // [START_EXCLUDE] //hideProgressDialog(); // [END_EXCLUDE] } }); } private void openStudActivity(FirebaseUser user) { // hideProgressDialog(); if (user != null) { startActivity(new Intent(this,Student_Login_Activity.class)); } } public void GotoStuPortal(View v){ Intent i = new Intent(Main_Sign_In_Student.this,Student_Login_Activity.class); startActivity(i); } }
7d862b8dd671fbb69a3cb09ca720ad7569dac9b1
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/9/9_b7214357240f5db395b7638b222c25c9d01671bd/TestSuspiciousFileValidatorWithFilterInXml/9_b7214357240f5db395b7638b222c25c9d01671bd_TestSuspiciousFileValidatorWithFilterInXml_t.java
69f66a4828bdf827b0c2c822016bab67fe7db037
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
913
java
package org.jboss.wolf.validator.impl.suspicious; import static org.jboss.wolf.validator.impl.suspicious.TestSuspiciousFileValidator.touch; import static org.junit.Assert.assertEquals; import org.jboss.wolf.validator.impl.AbstractTest; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(locations = "classpath*:TestSuspiciousFileValidatorWithFilterInXml-context.xml", inheritLocations = false) public class TestSuspiciousFileValidatorWithFilterInXml extends AbstractTest { @Test public void shouldUseFilterDefinedInXml() { touch("readme.txt"); touch("expected-file.xml"); touch("unexpected-file"); validator.validate(ctx); assertEquals(ctx.getExceptions().size(), 1); assertExpectedException(SuspiciousFileException.class, "File unexpected-file is suspicious"); } }
46ad6751f0bfe1adfd61c6d73fe2cc8d4c4331a8
0433a0f1a5179f42e9080961461c253bac050b37
/src/logic/APlayLists.java
bc54e29a3a99e9e819fcd3181ab6d7128be2be52
[]
no_license
artaasadi/APotify
64728149496c27dc39112da3928610e944762df1
dac91c346c6a301223ed14b8b0a09bf24e4bc0a4
refs/heads/master
2022-02-02T04:11:30.394319
2019-06-30T12:01:25
2019-06-30T12:01:25
194,176,936
0
0
null
null
null
null
UTF-8
Java
false
false
1,937
java
package logic; import java.io.File; import java.util.ArrayList; import java.util.Random; public class APlayLists { private String name; private ArrayList<File> files = new ArrayList<>(); private boolean isChangeable; private boolean isRemoveable; private boolean isAlbumOrArtist = false; public APlayLists(String name) { if (name.equals("Favorite") || name.equals("Shared")) { isChangeable = false; isRemoveable = false; } else { isChangeable = true; isRemoveable = true; } this.name = name; } public void addSong(File file) { files.add(file); } public ArrayList<File> getFiles() { return files; } public int getIndex(File file) { return files.indexOf(file); } public void removeSong(File file) { files.remove(file); } public boolean contain(File file) { boolean found = false; for (int i = 0; i < files.size(); i++) { if (files.get(i).getName().equals(file.getName())) { found = true; break; } } return found; } public void changeName(String newName) { if (isChangeable) name = newName; } public boolean isRemoveable() { return isRemoveable; } public void changeOrder(File file, int order) { if (order < files.size()) { files.remove(file); files.add(order, file); } } public File shuffle() { Random r = new Random(); File shuffled = files.get(r.nextInt(files.size())); return shuffled; } public String getName() { return name; } public boolean isAlbumOrArtist() { return isAlbumOrArtist; } public void setAlbumOrArtist(boolean albumOrArtist) { isAlbumOrArtist = albumOrArtist; } }
28c18700e48a50e18d49563713f0923d40dba109
c16b8990ec3c297ac36aecabb662a6ce124dd940
/looks/src/org/compiere/swing/CTable.java
a660105e17423529802f99b50dddf35c8ceb03f8
[]
no_license
Lucas128/libertya
6decae77481ba0756a9a14998824f163001f4b7c
d2e8877a0342af5796c74809edabf726b9ff50dc
refs/heads/master
2021-01-10T16:52:41.332435
2015-05-26T19:34:39
2015-05-26T19:34:39
36,461,214
0
1
null
null
null
null
UTF-8
Java
false
false
11,591
java
/* * @(#)CTable.java 12.oct 2007 Versión 2.2 * * El contenido de este fichero está sujeto a la Licencia Pública openXpertya versión 1.1 (LPO) * en tanto en cuanto forme parte íntegra del total del producto denominado: openXpertya, solución * empresarial global , y siempre según los términos de dicha licencia LPO. * Una copia íntegra de dicha licencia está incluida con todas las fuentes del producto. * Partes del código son copyRight (c) 2002-2007 de Ingeniería Informática Integrada S.L., otras * partes son copyRight (c) 2003-2007 de Consultoría y Soporte en Redes y Tecnologías de la * Información S.L., otras partes son copyRight (c) 2005-2006 de Dataware Sistemas S.L., otras son * copyright (c) 2005-2006 de Indeos Consultoría S.L., otras son copyright (c) 2005-2006 de Disytel * Servicios Digitales S.A., y otras partes son adaptadas, ampliadas, traducidas, revisadas y/o * mejoradas a partir de código original de terceros, recogidos en el ADDENDUM A, sección 3 (A.3) * de dicha licencia LPO, y si dicho código es extraido como parte del total del producto, estará * sujeto a su respectiva licencia original. * Más información en http://www.openxpertya.org/ayuda/Licencia.html */ package org.compiere.swing; import org.openXpertya.util.MSort; //~--- Importaciones JDK ------------------------------------------------------ import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Vector; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; /** * Model Independent enhanced JTable. * Provides sizing and sorting * * @author Comunidad de Desarrollo openXpertya * *Basado en Codigo Original Modificado, Revisado y Optimizado de: * * Jorg Janke * @version $Id: CTable.java,v 1.7 2005/03/11 20:34:38 jjanke Exp $ */ public class CTable extends JTable { /** Last model index sorted */ protected int p_lastSortIndex = -1; /** Model Index of Key Column */ protected int p_keyColumnIndex = -1; /** Sort direction */ protected boolean p_asc = true; /** Sizing: making sure it fits in a column */ private final int SLACK = 15; /** Sizing: space for sort images in headers */ private final int SORT_SLACK = 10; /** Sizing: max size in pt */ private final int MAXSIZE = 250; /** * Default Constructor */ public CTable() { super(new DefaultTableModel()); setColumnSelectionAllowed(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); getTableHeader().addMouseListener(new CTableMouseListener()); } // CTable /** * Size Columns. * @param useColumnIdentifier if false uses plain content - * otherwise uses Column Identifier to indicate displayed columns */ public void autoSize(boolean useColumnIdentifier) { TableModel model = this.getModel(); int size = model.getColumnCount(); // for all columns for (int c = 0; c < size; c++) { TableColumn column = getColumnModel().getColumn(c); // Not displayed columns if (useColumnIdentifier && ((column.getIdentifier() == null) || (column.getMaxWidth() == 0) || (column.getIdentifier().toString().length() == 0))) { continue; } int width = 0; // Header TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = new DefaultTableCellRenderer(); } Component comp = null; if (renderer != null) { comp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false, false, 0, 0); } // if (comp != null) { width = comp.getPreferredSize().width + SLACK + SORT_SLACK; width = Math.max(width, comp.getWidth()); // Cells int col = column.getModelIndex(); int maxRow = Math.min(30, getRowCount()); try { for (int row = 0; row < maxRow; row++) { renderer = getCellRenderer(row, col); comp = renderer.getTableCellRendererComponent(this, getValueAt(row, col), false, false, row, col); int rowWidth = comp.getPreferredSize().width + SLACK; width = Math.max(width, rowWidth); } } catch (Exception e) { System.out.println(column.getIdentifier()); e.printStackTrace(); } // Width not greater than 250 width = Math.min(MAXSIZE, width); } // column.setPreferredWidth(width); // JOptionPane.showMessageDialog( null,"Columna = "+column.toString()+ " En CTable con column.setreferencedWidth= " + width,"..Fin", JOptionPane.INFORMATION_MESSAGE ); } // for all columns } // autoSize /** * Sort Table * @param modelColumnIndex model column sort index */ protected void sort(int modelColumnIndex) { DefaultTableModel model = (DefaultTableModel) getModel(); if (modelColumnIndex < 0 || modelColumnIndex >= model.getColumnCount()) return; int rows = getRowCount(); if (rows == 0) { return; } // other column if (modelColumnIndex != p_lastSortIndex) { p_asc = true; } else { p_asc = !p_asc; } p_lastSortIndex = modelColumnIndex; // // System.out.println("CTable.sort #" + modelColumnIndex + " - rows=" + rows + ", asc=" + p_asc); // Selection Object selected = null; int selRow = getSelectedRow(); int selCol = (p_keyColumnIndex == -1) ? 0 : p_keyColumnIndex; // used to identify current row if (getSelectedRow() >= 0) { selected = getValueAt(selRow, selCol); } // Prepare sorting MSort sort = new MSort(0, null); sort.setSortAsc(p_asc); // Create sortList ArrayList sortList = new ArrayList(rows); // fill with data entity for (int i = 0; i < rows; i++) { Object value = model.getValueAt(i, modelColumnIndex); sortList.add(new MSort(i, value)); } // sort list it Collections.sort(sortList, sort); HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for( int i = 0;i < rows;i++ ) { int index = (( MSort )sortList.get( i )).index; m.put(i, index); } reSort(m, model.getDataVector() ); // selection clearSelection(); if (selected != null) { for (int r = 0; r < rows; r++) { if (selected.equals(getValueAt(r, selCol))) { setRowSelectionInterval(r, r); break; } } } // selected != null } // sort public void reSort(HashMap<Integer, Integer> m, Vector rows) { // copiar los datos temporalmente a fin de limpiar rows ArrayList temp = new ArrayList(rows); rows.clear(); // insertar ordenado en rows int totalRows = m.size(); for( int index = 0;index < totalRows; index++ ) { rows.add(temp.get((Integer)m.get(index))); } // garbage collector temp.clear(); temp = null; } /** * Stop Table Editors and remove focus * @param saveValue save value */ public void stopEditor(boolean saveValue) { // MultiRow - remove editors ChangeEvent ce = new ChangeEvent(this); if (saveValue) { editingStopped(ce); } else { editingCanceled(ce); } // if (getInputContext() != null) { getInputContext().endComposition(); } // change focus to next transferFocus(); } // stopEditor /** * String Representation * @return info */ public String toString() { return new StringBuffer("CTable[").append(getModel()).append("]").toString(); } // toString //~--- get methods -------------------------------------------------------- /** * Get Model index of Key Column * @return model index */ public int getKeyColumnIndex() { return p_keyColumnIndex; } // getKeyColumnIndex /** * Get Current Row Key Column Value * @return value or null */ public Object getSelectedKeyColumnValue() { int row = getSelectedRow(); if ((row != -1) && (p_keyColumnIndex != -1)) { return getModel().getValueAt(row, p_keyColumnIndex); } return null; } // getKeyColumnValue /** * Get Selected Value or null * @return value */ public Object getSelectedValue() { int row = getSelectedRow(); int col = getSelectedColumn(); if ((row == -1) || (col == -1)) { return null; } return getValueAt(row, col); } // getSelectedValue //~--- set methods -------------------------------------------------------- /** * Set Model index of Key Column. * Used for identifying previous selected row after fort complete to set as selected row. * If not set, column 0 is used. * @param keyColumnIndex model index */ public void setKeyColumnIndex(int keyColumnIndex) { p_keyColumnIndex = keyColumnIndex; } // setKeyColumnIndex /** * MouseListener */ class CTableMouseListener extends MouseAdapter { /** * Constructor */ public CTableMouseListener() { super(); } // CTableMouseListener /** * Mouse clicked * @param e event */ public void mouseClicked(MouseEvent e) { if (isSorted()) { int vc = getColumnModel().getColumnIndexAtX(e.getX()); // log.info( "Sort " + vc + "=" + getColumnModel().getColumn(vc).getHeaderValue()); int mc = convertColumnIndexToModel(vc); sort(mc); } } } // CTableMouseListener /** Permite configurar si la tabla tiene capacidades de ordenamiento o no */ private boolean sorted = true; /** * @return the sorted */ public boolean isSorted() { return sorted; } /** * @param sorted the sorted to set */ public void setSorted(boolean sorted) { this.sorted = sorted; } } // CTable /* * @(#)CTable.java 02.jul 2007 * * Fin del fichero CTable.java * * Versión 2.2 - Fundesle (2007) * */ //~ Formateado de acuerdo a Sistema Fundesle en 02.jul 2007
0bb91cd2071aa1e982db9e5a0c303bf1c4309275
856aa11bdfa59fe43fa496b9db82f2e766146784
/app/src/main/java/com/hills/mcs_02/fragmentsPack/Fragment_remind.java
cb0cecce0137c9182e34b1b296c11146b9a8db95
[ "Apache-2.0" ]
permissive
Alozavander/CrowdOS_CompetitionVersion
666fb36bd27843a6cdd7a65b5d6c9a8fbac87334
94fb25c90ae966f5ffa8d725470c91fbccbacbdc
refs/heads/main
2023-05-12T00:36:48.506930
2021-05-17T08:04:35
2021-05-17T08:04:35
367,304,661
0
0
Apache-2.0
2021-05-17T08:04:36
2021-05-14T08:51:17
Java
UTF-8
Java
false
false
4,699
java
package com.hills.mcs_02.fragmentsPack; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import com.hills.mcs_02.R; import com.hills.mcs_02.viewsAdapters.FragmentPagerAdapter_remindPage; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * to handle interaction events. * Use the {@link Fragment_remind#newInstance} factory method to * create an instance of this fragment. */ public class Fragment_remind extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private static final String TAG = "Fragment_remind"; private String mParam1; private String mParam2; private Context mContext; private TabLayout mTabLayout; private List<Fragment> mFragments; private ViewPager mViewPager; private FragmentPagerAdapter_remindPage mFragmentPagerAdapter_remindPage; public Fragment_remind() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment Fragment_home. */ // TODO: Rename and change types and number of parameters public static Fragment_remind newInstance(String param1, String param2) { Fragment_remind fragment = new Fragment_remind(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_remind, container, false); mContext = getActivity().getApplicationContext(); //初始化tab列表及适配器 initTab_Pager(view); return view; } private void initTab_Pager(View view) { mTabLayout = view.findViewById(R.id.remindpage_tablayout); mFragments = new ArrayList<Fragment>(); mViewPager = view.findViewById(R.id.remindpage_viewpager); //创建fragment并通过tag区别 mFragments.add(new Fragment_remind_pager("doing")); mFragments.add(new Fragment_remind_pager("done")); mFragments.add(new Fragment_remind_pager("recommend")); mFragmentPagerAdapter_remindPage = new FragmentPagerAdapter_remindPage(getChildFragmentManager(),mContext,mFragments); mViewPager.setAdapter(mFragmentPagerAdapter_remindPage); //tablayout 与 viewpager的联动,在之后需要重新添加tab mTabLayout.setupWithViewPager(mViewPager); String[] tabNames = {getString(R.string.mine_minor2_accepted_processing), getActivity().getString(R.string.mine_minor2_accepted_done),getActivity().getString(R.string.recommend)}; for (int i = 0; i < tabNames.length; i++) { mTabLayout.getTabAt(i).setText(tabNames[i]); } } @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onDetach() { super.onDetach(); try { Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager"); childFragmentManager.setAccessible(true); childFragmentManager.set(this, null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
a1e7da7ee1f313b92c5b1a4d175325b26f2ef15d
66cfb13663e77c3a4c7a63742bc3d6eab5d48555
/app/src/main/java/cc/brainbook/viewpager/looppageradapter/app/MainActivity.java
4da14736a75c6be76bb8bfa167c3500635b98daa
[]
no_license
yongtiger/android-LoopPagerAdapter
763a03a6863b2355f93d4303de5a6d890c80724c
64982c7f08403a8e4cac7f97de2626cca891054e
refs/heads/master
2022-05-11T05:26:24.531187
2022-04-04T00:33:32
2022-04-04T00:33:32
128,693,726
0
0
null
null
null
null
UTF-8
Java
false
false
3,402
java
package cc.brainbook.viewpager.looppageradapter.app; import android.os.Bundle; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.ViewGroup; import java.lang.reflect.Field; import java.util.ArrayList; import cc.brainbook.viewpager.looppageradapter.LoopPagerAdapter; import cc.brainbook.viewpager.looppageradapter.ViewHolderCreator; import cc.brainbook.viewpager.transformer.CommonTransformer; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ///test: local images and LocalImageHolderView ArrayList<Integer> localImages = new ArrayList<>(); for (int position = 0; position < 5; position++) { ///test: page numbers is 0, 1, 2,...5 or more // localImages.add(getResId("ic_test_" + position, R.drawable.class)); localImages.add(getResources().getIdentifier("ic_test_" + position, "drawable", getPackageName())); } LoopPagerAdapter<Integer> adapter = new LoopPagerAdapter<Integer>(new ViewHolderCreator() { @Override public LocalImageViewHolder createViewHolder() { return new LocalImageViewHolder(); } }, localImages); ///test: OnStartUpdateListener adapter.setOnStartUpdateListener(new LoopPagerAdapter.OnStartUpdateListener() { @Override public void onStartUpdate(ViewGroup container, int updatePosition, int updateCount) { Log.d("TAG", "LoopPagerAdapter.OnStartUpdateListener#onStartUpdate: updatePosition: " + updatePosition); Log.d("TAG", "LoopPagerAdapter.OnStartUpdateListener#onStartUpdate: updateCount: " + updateCount); } }); ///test: setCanLoop // adapter.setCanLoop(false); ViewPager viewPager = findViewById(R.id.viewpager); viewPager.setAdapter(adapter); ///test: setCurrentItem // viewPager.setCurrentItem(3); ///test: one view page may show multiple pages viewPager.setPadding(50, 150,100, 150); viewPager.setClipToPadding(false); ///--------- Comment out for RotateDownTransformer --------- final String[][] params = { {"PivotX", "-1", "1", "0.5", "0.5", "-1", "1"}, {"PivotY", "-1", "1", "1", "1", "-1", "1"}, {"Rotation", "-1", "0", "-0.05", "0", "-1", "0"}, {"Rotation", "0", "0", "0", "0"}, {"Rotation", "0", "1", "0", "0.05", "0", "1"}, }; final CommonTransformer transformer = new CommonTransformer(params); viewPager.setPageTransformer(false, transformer); viewPager.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } /** * Get resource ID by file name. * * @param variableName The file name. * @param c The class. * @return The resource ID. */ public static int getResId(String variableName, Class<?> c) { try { Field idField = c.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } } }
5225520a4689b0c6ece3a746940945fd7031c4e6
569044837bc9922151eb3edee8c000caeb5038ae
/Spring Converter For Date/springi18n/src/main/java/com/bestcxx/stu/springsecurity/controller/Springi18nController.java
c1f20c80cf8b0736a61a94bcc2362fb8cf76e1a9
[]
no_license
Bestcxy/Spring-Converter
d655032b61065048466168d9817abeeb5a9f8abe
c3e51fe43d73b67aadac6bddf89f52c79cdadd52
refs/heads/master
2021-08-19T22:28:54.913120
2017-11-27T16:01:29
2017-11-27T16:01:29
112,216,568
0
0
null
null
null
null
UTF-8
Java
false
false
1,175
java
package com.bestcxx.stu.springsecurity.controller; import java.text.SimpleDateFormat; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.bestcxx.stu.springsecurity.entity.User; @Controller @RequestMapping("/home") public class Springi18nController{ /** * 国际化测试 * @param request * @return */ @GetMapping("/index") public String login(HttpServletRequest request){ return "index"; } /** * 自动将前台字符串转化为时间的时间格式转化器测试 * @param user * @param request * @return */ @PostMapping("/user") public String add(@ModelAttribute("user") User user,HttpServletRequest request,BindingResult result){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); request.setAttribute("time",sdf.format(user.getTime())); return "index"; } }
c103d32b66626e1dd5644c567675540236e3dc11
58cd3947ad68d2661919d1037ff89bd5919fd901
/src/ServerSide/src/main/java/vn/zalopay/ducnm8/da/interact/NotificationDAImpl.java
4e424dad99770678a5810d995dc3171165f36020
[]
no_license
minhduc2803/Snail-Project
8c5349e5a3089023d8fff3ed10f4d159d14c9892
cb3660917c6a82b19996cfdc1355a43a7a4bb389
refs/heads/master
2023-01-11T19:04:24.824330
2020-11-04T08:06:29
2020-11-04T08:06:29
294,295,932
0
0
null
null
null
null
UTF-8
Java
false
false
4,306
java
package vn.zalopay.ducnm8.da.interact; import io.vertx.core.Future; import org.apache.logging.log4j.Logger; import vn.zalopay.ducnm8.common.mapper.EntityMapper; import vn.zalopay.ducnm8.da.BaseTransactionDA; import vn.zalopay.ducnm8.da.Executable; import vn.zalopay.ducnm8.model.Notification; import vn.zalopay.ducnm8.utils.AsyncHandler; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class NotificationDAImpl extends BaseTransactionDA implements NotificationDA { private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AccountDAImpl.class); private final DataSource dataSource; private final AsyncHandler asyncHandler; private static final String INSERT_NOTIFICATION_STATEMENT = "INSERT INTO notification (`notification_type`,`user_id`,`partner_id`,`amount`,`message`,`seen`) VALUES (?, ?, ?, ?, ?, ?)"; private static final String SELECT_NOTIFICATION_BY_ACCOUNT_ID = "SELECT N.notification_type, N.user_id, N.partner_id, N.amount, N.message, N.seen,\n" + "C.user_name, C.full_name\n" + "FROM notification as N\n" + "INNER JOIN account as C\n" + "ON N.user_id = C.id\n" + "WHERE N.user_id = ?"; private static final String UPDATE_SEEN_A_NOTIFICATION = "UPDATE notification SET unread = true WHERE id = ?"; public NotificationDAImpl(DataSource dataSource, AsyncHandler asyncHandler) { this.dataSource = dataSource; this.asyncHandler = asyncHandler; } @Override public Future<Notification> insert(Notification notification) { log.info("insert a new notification for accountId {}", notification.getUserId()); Future<Notification> future = Future.future(); asyncHandler.run( () -> { Object[] params = {notification.getNotificationType(), notification.getUserId(), notification.getPartnerId(), notification.getAmount(), notification.getMessage(), notification.isSeen()}; try { long id = executeWithParamsAndGetId(dataSource::getConnection, INSERT_NOTIFICATION_STATEMENT, params, "insertNotification"); notification.setId(id); future.complete(notification); } catch (Exception e) { String reason = String.format("cannot insert a notification ~ cause: %s", e.getMessage()); future.fail(reason); log.error("cannot insert a notification, accountId = {} ~ cause: {}", notification.getUserId(), e.getMessage()); } }); return future; } @Override public Executable<Notification> updateSeenNotificationById(long id) { log.info("update seen a notification: AccountId={}", id); return connection -> { Future<Notification> future = Future.future(); asyncHandler.run( () -> { Object[] params = {id}; try { executeWithParamsAndGetId(connection.unwrap(), UPDATE_SEEN_A_NOTIFICATION, params, "updateNotification", false); Notification notification = Notification.builder().id(id).build(); future.complete(notification); } catch (Exception e) { future.fail(e); } }); return future; }; } @Override public Future<ArrayList<Notification>> selectNotificationByAccountId(long id) { log.info("select a list notifications, accountId = {}", id); Future<ArrayList<Notification>> future = Future.future(); asyncHandler.run( () -> { Object[] params = {id}; queryEntity( "queryNotification", future, SELECT_NOTIFICATION_BY_ACCOUNT_ID, params, this::mapRs2EntityNotification, dataSource::getConnection, false); }); return future; } private ArrayList<Notification> mapRs2EntityNotification(ResultSet resultSet) throws Exception { Notification notification = null; ArrayList<Notification> notificationList = new ArrayList<>(); while (resultSet.next()) { notification = new Notification(); EntityMapper.getInstance().loadResultSetIntoObject(resultSet, notification); notificationList.add(notification); } return notificationList; } }
64f11ca0b375e93177e583f82c3502b64d022b5a
0e23584de3fa7b1379d524a13f90cc45cf25dadc
/app/src/main/java/com/example/android/mymusicapp/OfflineActivity.java
b1087fdda9fa5ae10ff08db1fcad685aa1df8576
[]
no_license
sowmyadsl/MusicApp-1
ef1ac7fc27e16301de95dae3b935d737bc318330
8e07b53839e6185ab99d82ee639d5bd697a04f26
refs/heads/master
2020-12-26T03:34:58.672168
2016-06-29T15:39:51
2016-06-29T15:39:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,704
java
package com.example.android.mymusicapp; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.view.View.OnClickListener; public class OfflineActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_offline); TextView offline_search = (TextView) findViewById(R.id.offline_search); offline_search.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent offlineSearchIntent = new Intent(OfflineActivity.this, OfflineSearchActivity.class); startActivity(offlineSearchIntent); } }); TextView offline_albums = (TextView) findViewById(R.id.offline_albums); offline_albums.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent offlineAlbumsIntent = new Intent(OfflineActivity.this, OfflineAlbumsActivity.class); startActivity(offlineAlbumsIntent); } }); TextView offline_songs = (TextView) findViewById(R.id.offline_songs); offline_songs.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent offlineSongsIntent = new Intent(OfflineActivity.this, OfflineSongsActivity.class); startActivity(offlineSongsIntent); } }); } }
76cd6f6e14b736e9cb7126fb8735ef461a169fec
be6271008f221ff2841c14c81861536c0cffd6c9
/LabInfoSysMaven/src/tc_BasicDispatch/S103_CheckDoctorPayOffWhenDiscountTypeDoctorApprovedByDoctorAndItemLevelDiscountInPercentage.java
4efc6db3af01fe6a1da17bd5f2b064007e387e79
[]
no_license
kraj2504/mav2
3c5b998e9132d5910028b158de4bc0298e760720
3dff17ae45249116fe30fe21ad95a2e96e021a62
refs/heads/master
2020-03-26T13:37:56.844779
2018-08-16T07:10:44
2018-08-16T07:10:44
144,948,969
0
0
null
null
null
null
UTF-8
Java
false
false
8,592
java
//Full bill paid in registration. Due clearance not used. package tc_BasicDispatch; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import pageObjects.PO_BulkEntry; import pageObjects.PO_DoctorPayOff; import pageObjects.PO_DoctorPayoffReport; import pageObjects.PO_DueClearance; import pageObjects.PO_Registration; import pageObjects.PO_Login; import pageObjects.PO_ManageApproval; import pageObjects.PO_ManageDispatch; import pageObjects.PO_ManageSample; import pageObjects.PO_MasterControl; import pageObjects.PO_PatientList; import pageObjects.PO_WorkList; import utility.Constant; import utility.ExcelUtils; import utility.Log; import utility.Utils; public class S103_CheckDoctorPayOffWhenDiscountTypeDoctorApprovedByDoctorAndItemLevelDiscountInPercentage { private static WebDriver driver = null; private String sTestCaseName; private int iTestCaseRow; @BeforeTest public void beforeMethod() throws Exception { DOMConfigurator.configure(Constant.log4jXMLpath); sTestCaseName = Utils.getTestCaseName(this.toString()); Log.startTestCase(sTestCaseName); ExcelUtils.openExcelFile(Constant.Path_TestData + Constant.File_TestData,"Sheet1"); iTestCaseRow = ExcelUtils.getRowNumber(sTestCaseName,Constant.col_TestCaseName); driver = Utils.OpenBrowser(iTestCaseRow); } @Test(priority = 1) public void s103_CheckDoctorPayOffWhenDiscountTypeDoctorApprovedByDoctorAndItemLevelDiscountInPercentage() throws Exception { try { // Instantiate PageObjects class PO_MasterControl MasterControlObject = PageFactory.initElements(driver,PO_MasterControl.class); PO_Login loginPageObject = PageFactory.initElements(driver,PO_Login.class); PO_DoctorPayOff doctorPayoff = PageFactory.initElements(driver,PO_DoctorPayOff.class); PO_DoctorPayoffReport doctorPayoffReport = PageFactory.initElements(driver,PO_DoctorPayoffReport.class); PO_Registration generateBillPageObject = PageFactory.initElements(driver,PO_Registration.class); PO_PatientList patientListPageObjects = PageFactory.initElements(driver,PO_PatientList.class); PO_ManageSample manageSamplePageObjects = PageFactory.initElements(driver,PO_ManageSample.class); PO_WorkList workOrderObj = PageFactory.initElements(driver,PO_WorkList.class); PO_BulkEntry bulkEntryObj = PageFactory.initElements(driver,PO_BulkEntry.class); PO_ManageApproval ManageApprovalObj = PageFactory.initElements(driver,PO_ManageApproval.class); PO_DueClearance dueClearance = PageFactory.initElements(driver,PO_DueClearance.class); PO_ManageDispatch manageDispatchobj = PageFactory.initElements(driver,PO_ManageDispatch.class); // Fetching Data from excel file String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_UserName); String sPassword = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Password); String sDoctorName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_DoctorName); String sDepartmentName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Department1); String sValue = ExcelUtils.getCellData(iTestCaseRow, Constant.col_DepValue1); String sRange = ExcelUtils.getCellData(iTestCaseRow, Constant.col_DepRange1); String sInvestigationName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_InvestigationName1); String sTitle = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Title); String sFirstName = Utils.getRandomName(45); String sGender = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Gender); String sAge = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Age); String sAgeType = ExcelUtils.getCellData(iTestCaseRow, Constant.col_AgeType); String sMobileNo = Utils.getRandomNumber(13); String sMailID = ExcelUtils.getCellData(iTestCaseRow, Constant.col_EmailID); String sReferralType = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ReferralType); String sReferralName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ReferralName); String sServiceName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ServiceName1); String sItemDiscountType = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ItemDiscountType); String sItemDiscountValue = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ItemDiscountValue); String sBillDiscountType = ExcelUtils.getCellData(iTestCaseRow, Constant.col_BillDiscountType); String sApprovedBy = ExcelUtils.getCellData(iTestCaseRow, Constant.col_ApprovedBy); String sBillDiscountTypeAs = ExcelUtils.getCellData(iTestCaseRow, Constant.col_BillDiscountTypeAs); String sBillDiscountValue = ExcelUtils.getCellData(iTestCaseRow, Constant.col_DiscountValue); String sRemarks = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Remarks); //Admin Login loginPageObject.login(sUserName, sPassword); Assert.assertEquals(driver.getTitle(),"Registration","Login failed"); MasterControlObject.changeRole("ACCOUNTANT"); MasterControlObject.gotoPage("PayOff"); doctorPayoff.searchDoctor(sDoctorName); doctorPayoff.deleteAllInvestigation(); doctorPayoff.clearAllValueForAllSubDept(); doctorPayoff.clearAllRangeForAllSubDept(); doctorPayoff.clearAllValuesForAllDept(); doctorPayoff.clearAllRangeForAllDept(); doctorPayoff.enterValueForDept(sDepartmentName, sValue); doctorPayoff.enterRangeForDept(sDepartmentName, sRange); doctorPayoff.clickSave(); Assert.assertEquals(MasterControlObject.getAlertMsg(), "Updated Successfully", "*** Doctor payoff --> Alert not shown as expected ***"); MasterControlObject.acceptAlert(); doctorPayoff.searchDoctor(sDoctorName); doctorPayoff.verifyRangeForDept(sDepartmentName, sRange); doctorPayoff.verifyValueForDept(sDepartmentName, sValue); MasterControlObject.changeRole("RECEPTIONIST"); //Register patient and generate bill generateBillPageObject.selectTitle(sTitle); generateBillPageObject.EnterFirstName(sFirstName); generateBillPageObject.selectGender(sGender); generateBillPageObject.enterAge(sAge); generateBillPageObject.selectAgeType(sAgeType); generateBillPageObject.EnterMobileNumber(sMobileNo); generateBillPageObject.EnterMailID(sMailID); generateBillPageObject.selectReferralType(sReferralType); // generateBillPageObject.selectReferralName(sReferralName); generateBillPageObject.selectDoctorName(sDoctorName); generateBillPageObject.selectServiceName(sInvestigationName); generateBillPageObject.EnterItemDiscount(1, sItemDiscountType, sItemDiscountValue); generateBillPageObject.selectApprovedBy(sApprovedBy); generateBillPageObject.enterRemarks(sRemarks); String amount = generateBillPageObject.getDueAmount(); Log.info("Generated bill amount is : "+amount); generateBillPageObject.EnterCashAmount(amount); String cashamount = generateBillPageObject.getCashAmount(); generateBillPageObject.ClickGenerateBill(); MasterControlObject.gotoPage("Patient List"); patientListPageObjects.searchRecord(sFirstName); Assert.assertTrue(patientListPageObjects.getStatus().equalsIgnoreCase("Registered"),"***Patient not registered***"); MasterControlObject.changeRole("ACCOUNTANT"); MasterControlObject.gotoPage("PayOff Report"); doctorPayoffReport.searchDoctor(sDoctorName); Assert.assertTrue(doctorPayoffReport.getPatientName().equalsIgnoreCase(sFirstName),"*** Patient details not showing in Doctor payoff Report ***"); float paypercent = Float.parseFloat(sValue) - Float.parseFloat(sItemDiscountValue); doctorPayoffReport.verifyPayOffAmount(Float.toString(paypercent)); doctorPayoffReport.verifyOverAllAmount(); } catch(Exception e) { ExcelUtils.setCellData("Fail", iTestCaseRow, Constant.col_Result); Utils.takeScreenshot(driver, sTestCaseName); Log.error(e.getMessage()); throw (e); } } @AfterMethod public void updateResult(ITestResult result) throws Exception { if(result.getStatus() == ITestResult.SUCCESS) { ExcelUtils.setCellData("Pass", iTestCaseRow, Constant.col_Result); Log.info("Full due paid ==> Test Passed"); } else if(result.getStatus() == ITestResult.FAILURE) { ExcelUtils.setCellData("Fail", iTestCaseRow, Constant.col_Result); Log.info("Full due not paid ==> Test Failed"); Utils.takeScreenshot(driver, sTestCaseName); } Log.endTestCase(sTestCaseName); driver.close(); } }
39dc0262db1425de11a041c32c35418724721d5c
911d1aa6b9bafbf78770120f0a6c32094ffb3011
/coding-challenges/coding-challenge-4/src/RandomAITestForEclipse.java
32396a7891bce44d37769aa90c212b29bc705d47
[]
no_license
rupertraphael/cpsc-233
ef9bccc3e79a90e8aa2097e35119749db64bb6a6
4b629bd409bbb718353a86aeafc73563dcaef12c
refs/heads/master
2022-04-14T12:06:23.597315
2020-04-01T06:50:40
2020-04-01T06:50:40
233,700,428
0
0
null
null
null
null
UTF-8
Java
false
false
9,601
java
import static org.junit.Assert.*; import org.junit.Test; import java.io.*; public class RandomAITestForEclipse extends FormatTester { public static final String CLASSNAME = "RandomAI"; public RandomAITestForEclipse() { super(CLASSNAME, true); } private void testInterface() { String[] instanceVars = {"int level"}; assertTrue("Instance variables should be private with correct name and type.", instanceVariablesArePrivate(instanceVars)); assertTrue("Class should not have the default constructor.", noDefaultConstructor()); assertFalse("Should not override takeTurn.", hasMethod("void takeTurn")); assertFalse("Should not override (or call) updateScore.", hasMethod("updateScore")); assertFalse("Should not override or call getid", hasMethod("getId")); assertFalse("Should not override or call getScore", hasMethod("getScore")); } // Testing constructors @Test public void test_Constructor_level_Zero_GoodId(){ testInterface(); RandomAI c = new RandomAI(1234,0); assertEquals("Created randomAI with invalid 0 level", 1, c.getLevel()); assertEquals("Created randomAI with valid 1234 id.", 1234, c.getId()); } @Test public void test_Constructor_level_11_GoodId(){ testInterface(); RandomAI c = new RandomAI(1234,11); assertEquals("Created randomAI with invalid 11 level", 1, c.getLevel()); assertEquals("Created randomAI with valid 1234 id.", 1234, c.getId()); } @Test public void test_Constructor_level_3(){ testInterface(); RandomAI c = new RandomAI(1234,3); assertEquals("Created randomAI with valid evel 3", 3, c.getLevel()); } @Test public void test_CopyConstructor() { testInterface(); RandomAI c = new RandomAI(4321,10); RandomAI c2 = new RandomAI(c); assertEquals("Copied randomAI with level 10", 10, c2.getLevel()); assertEquals("Created randomAI with 4321 id.", 4321, c2.getId()); } @Test public void test_CopyConstructor2() { testInterface(); RandomAI c = new RandomAI(5467, 7); RandomAI c2 = new RandomAI(c); assertEquals("Copied randomAI with 7 level", 7, c2.getLevel()); assertEquals("Created randomAI with 5467 id.", 5467, c2.getId()); } // Testing setter and getters @Test public void test_setter_and_getter_level_0(){ testInterface(); RandomAI c = new RandomAI(5555,2); c.setLevel(0); assertEquals("Set level to invalid 0, should have left unchanged from 2", 2, c.getLevel()); } @Test public void test_setter_and_getter_level_1(){ testInterface(); RandomAI c = new RandomAI(5555,2); c.setLevel(1); assertEquals("Set level to lowest valid: 1", 1, c.getLevel()); } @Test public void test_setter_and_getter_level_99(){ testInterface(); RandomAI c = new RandomAI(5555,2); c.setLevel(10); assertEquals("Set level to highest valid: 10", 10, c.getLevel()); } @Test public void test_setter_and_getter_level_100(){ testInterface(); RandomAI c = new RandomAI(5555,2); c.setLevel(11); assertEquals("Set level to invalid 11, should have been unchanged from 2", 2, c.getLevel()); } @Test public void test_nextMove() { testInterface(); RandomAI c = new RandomAI(1234,1); assertEquals("nextMove should always return 'Random'", "Random", c.nextMove()); c = new RandomAI(4532,7); assertEquals("nextMove should always return 'Random'", "Random", c.nextMove()); c = new RandomAI(1,1); assertEquals("nextMove should always return 'Random'", "Random", c.nextMove()); } @Test public void test_chooseMove_from0ScoreLevel1() { testInterface(); int[] scores = new int[10]; for (int index = 0; index < 10; index ++) { scores[index] = 0; } for (int counter = 0; counter < 10000; counter++){ RandomAI c = new RandomAI(1234, 1); int score = c.chooseMove(); assertFalse("At level one, move should be between 0 and 9 points (inclusive), not " + score, score<0 || score>9); scores[score]++; } assertTrue("Expected 0 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[0] > 0); assertTrue("Expected 1 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[1] > 0); assertTrue("Expected 2 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[2] > 0); assertTrue("Expected 3 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[3] > 0); assertTrue("Expected 4 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[4] > 0); assertTrue("Expected 5 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[5] > 0); assertTrue("Expected 6 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[6] > 0); assertTrue("Expected 7 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[7] > 0); assertTrue("Expected 8 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[8] > 0); assertTrue("Expected 9 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[9] > 0); } @Test public void test_chooseMove_from0ScoreLevel9() { testInterface(); int[] scores = new int[10]; for (int index = 0; index < 10; index ++) { scores[index] = 0; } for (int counter = 0; counter < 10000; counter++){ RandomAI c = new RandomAI(1234, 9); int score = c.chooseMove(); assertFalse("At level nine, move should be between 0 and 81 points (inclusive), not " + score, score<0 || score>81); scores[score/9]++; } assertTrue("Expected 0 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[0] > 0); assertTrue("Expected 9 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[1] > 0); assertTrue("Expected 18 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[2] > 0); assertTrue("Expected 27 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[3] > 0); assertTrue("Expected 36 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[4] > 0); assertTrue("Expected 45 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[5] > 0); assertTrue("Expected 54 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[6] > 0); assertTrue("Expected 63 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[7] > 0); assertTrue("Expected 72 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[8] > 0); assertTrue("Expected 81 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[9] > 0); } @Test public void test_chooseMove_from0ScoreLevel5() { testInterface(); int[] scores = new int[10]; for (int index = 0; index < 10; index ++) { scores[index] = 0; } for (int counter = 0; counter < 10000; counter++){ RandomAI c = new RandomAI(1234, 5); int score = c.chooseMove(); assertFalse("At level five, move should be between 0 and 45 points (inclusive), not " + score, score<0 || score>45); scores[score/5]++; } assertTrue("Expected 0 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[0] > 0); assertTrue("Expected 5 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[1] > 0); assertTrue("Expected 10 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[2] > 0); assertTrue("Expected 15 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[3] > 0); assertTrue("Expected 20 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[4] > 0); assertTrue("Expected 25 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[5] > 0); assertTrue("Expected 30 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[6] > 0); assertTrue("Expected 35 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[7] > 0); assertTrue("Expected 40 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[8] > 0); assertTrue("Expected 45 to be randomly chosen at least once when doing 10000 random choices, but it was not.", scores[9] > 0); } // ToString @Test public void test_toString1() { testInterface(); assertTrue("Should override toString and it should invoke parent toString (not getter methods in parent).", toStrInvokesParentToStr()); RandomAI c = new RandomAI(3421, 5); c.updateScore(50); assertEquals("[Random Level 5] ID: 3421 Score: 50 nextMove: Random", c.toString()); } @Test public void test_toString2() { testInterface(); assertTrue("Should override toString and it should invoke parent toString (not getter methods in parent).", toStrInvokesParentToStr()); RandomAI c = new RandomAI(1234, 2); c.updateScore(21); assertEquals("[Random Level 2] ID: 1234 Score: 21 nextMove: Random", c.toString()); } }
d06d6c6841d8ff84099a6f06d221bb9dbc87b4ea
ec326f59b017b012aa6f021b8c2a664cb779a7da
/src/main/java/com/geekbrains/geekmarketwinter/services/FileAssetService.java
404b5fde013de72bf26c52e24ee9b65233dbe9da
[]
no_license
AlexandrStegnin/geek-market-winter
1e3da42929ccf822122a515615173ade01827276
8fc0027a9ef1c63944d6f0d6b8abc01045015d62
refs/heads/master
2020-04-17T19:21:21.512877
2019-03-15T16:52:49
2019-03-15T16:52:49
166,641,968
0
0
null
null
null
null
UTF-8
Java
false
false
5,733
java
package com.geekbrains.geekmarketwinter.services; import com.geekbrains.geekmarketwinter.entites.FileAsset; import com.geekbrains.geekmarketwinter.exceptions.EntityNotFoundException; import com.geekbrains.geekmarketwinter.exceptions.InvalidEntityException; import com.geekbrains.geekmarketwinter.providers.ConfigurationProvider; import com.geekbrains.geekmarketwinter.providers.FileStorageProvider; import com.geekbrains.geekmarketwinter.repositories.FileAssetRepository; import org.springframework.stereotype.Service; import java.io.File; import java.time.Duration; import java.time.LocalDateTime; import java.util.List; import static com.geekbrains.geekmarketwinter.utils.EncryptionUtils.getFileHash; /** * @author stegnin */ @Service public class FileAssetService implements FileStorageService<FileAsset> { private final FileAssetRepository fileAssetRepository; private final FileStorageProvider fileStorageProvider; private final ConfigurationProvider configurationProvider; public FileAssetService(FileAssetRepository fileAssetRepository, FileStorageProvider fileStorageProvider, ConfigurationProvider configurationProvider) { this.fileAssetRepository = fileAssetRepository; this.fileStorageProvider = fileStorageProvider; this.configurationProvider = configurationProvider; } public FileAsset createFileAsset(FileAsset fileAsset, File content) { return fileAssetRepository.findByHash(getFileHash(content)).orElseGet(() -> { validateFileAsset(fileAsset); validateFileContent(content); File savedContent = fileStorageProvider.uploadFile(content); try { return persist(fileAsset, savedContent); } catch (RuntimeException ex) { fileStorageProvider.deleteFile(savedContent); throw ex; } }); } public List<FileAsset> getFileAssets() { return fileAssetRepository.findAll(); } public FileAsset findByFileName(String fileName) { return fileAssetRepository .findByFileName(fileName) .orElse(null); } public List<FileAsset> findExpiredFiles() { return fileAssetRepository.findByExpiringDateTimeBefore(LocalDateTime.now()); } public void deleteFileAssets(List<FileAsset> assets) { fileAssetRepository.deleteAll(assets); } public FileAsset getFileAsset(Long id) { return fileAssetRepository .findById(id) .filter(fileAsset -> fileAsset .getHash() .equalsIgnoreCase(getFileHash(fileStorageProvider.getFile(fileAsset.getFileName())))) .orElseThrow(() -> new EntityNotFoundException(FileAsset.class)); } public FileAsset getFileAsset(String hash) { return fileAssetRepository .findByHash(hash) .filter(fileAsset -> fileAsset .getHash() .equalsIgnoreCase(getFileHash(fileStorageProvider.getFile(fileAsset.getFileName())))) .orElseThrow(() -> new EntityNotFoundException(FileAsset.class)); } public void deleteFileAsset(Long id) { FileAsset fileAsset = getFileAsset(id); fileStorageProvider.deleteFile(fileStorageProvider.getFile(fileAsset.getFileName())); fileAssetRepository.delete(fileAsset); } private FileAsset persist(FileAsset entity, File savedFile) { entity = setCreatedDateTime(entity); entity = setExpirationDateTime(entity); entity = setHash(entity, savedFile); entity = setFileName(entity, savedFile); return fileAssetRepository.save(entity); } private FileAsset setFileName(FileAsset entity, File savedFile) { entity.setFileName(savedFile.getName()); return entity; } private FileAsset setHash(FileAsset entity, File savedFile) { entity.setHash(getFileHash(savedFile)); return entity; } private FileAsset setExpirationDateTime(FileAsset entity) { validateFileAsset(entity); if (null == entity.getExpiringDateTime()) { return setDefaultExpirationDate(entity); } if (entity.getExpiringDateTime().isBefore(LocalDateTime.now())) { return setDefaultExpirationDate(entity); } if (Duration.between(LocalDateTime.now(), entity.getExpiringDateTime()).toDays() > configurationProvider.getMaxExpirationDays()) { return setDefaultExpirationDate(entity); } return entity; } private FileAsset setCreatedDateTime(FileAsset entity) { validateFileAsset(entity); entity.setCreatedDateTime(LocalDateTime.now()); return entity; } private FileAsset setDefaultExpirationDate(FileAsset entity) { entity.setExpiringDateTime(LocalDateTime.now().plusDays(configurationProvider.getExpirationDays())); return entity; } private void validateFileAsset(FileAsset asset) { if (null == asset) { throw new InvalidEntityException(FileAsset.class, "No file asset presented."); } if (null == asset.getName()) { throw new InvalidEntityException(FileAsset.class, "No file name presented."); } } private void validateFileContent(File content) { if (null == content) { throw new InvalidEntityException(FileAsset.class, "No file presented."); } if (0 == content.length()) { throw new InvalidEntityException(FileAsset.class, "File is empty."); } } }
de10a0ae5cd9e79dbce2509c372a2e0de1d899dd
fea2b945facb32325cb3750b010dfae12db48003
/peppol-smp-server-xml/src/main/java/com/helger/peppol/smpserver/data/xml/mgr/XMLBusinessCardManager.java
c01eb50a79d2477162f38f30fe73e18e8c7817ce
[]
no_license
jdrew1303/peppol-smp-server
b99538a9b0eb3af56d863bb28e8ba1685ee42875
e8a71b08ae0ff3cf72d738adf2a4eab9fe5a64a9
refs/heads/master
2020-05-24T20:44:33.186462
2017-03-09T15:09:05
2017-03-09T15:09:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,623
java
/** * Copyright (C) 2015-2016 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * 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.helger.peppol.smpserver.data.xml.mgr; import java.util.List; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.ELockType; import com.helger.commons.annotation.IsLocked; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.collection.CollectionHelper; import com.helger.commons.collection.ext.ICommonsList; import com.helger.commons.state.EChange; import com.helger.peppol.smpserver.domain.businesscard.ISMPBusinessCard; import com.helger.peppol.smpserver.domain.businesscard.ISMPBusinessCardManager; import com.helger.peppol.smpserver.domain.businesscard.SMPBusinessCard; import com.helger.peppol.smpserver.domain.businesscard.SMPBusinessCardEntity; import com.helger.peppol.smpserver.domain.servicegroup.ISMPServiceGroup; import com.helger.photon.basic.app.dao.impl.AbstractMapBasedWALDAO; import com.helger.photon.basic.app.dao.impl.DAOException; import com.helger.photon.basic.audit.AuditHelper; /** * Manager for all {@link SMPBusinessCard} objects. * * @author Philip Helger */ public final class XMLBusinessCardManager extends AbstractMapBasedWALDAO <ISMPBusinessCard, SMPBusinessCard> implements ISMPBusinessCardManager { private static final Logger s_aLogger = LoggerFactory.getLogger (XMLBusinessCardManager.class); public XMLBusinessCardManager (@Nonnull @Nonempty final String sFilename) throws DAOException { super (SMPBusinessCard.class, sFilename); } @Nonnull @IsLocked (ELockType.WRITE) private ISMPBusinessCard _createSMPBusinessCard (@Nonnull final SMPBusinessCard aSMPBusinessCard) { m_aRWLock.writeLocked ( () -> { internalCreateItem (aSMPBusinessCard); }); AuditHelper.onAuditCreateSuccess (SMPBusinessCard.OT, aSMPBusinessCard.getID (), aSMPBusinessCard.getServiceGroupID (), Integer.valueOf (aSMPBusinessCard.getEntityCount ())); return aSMPBusinessCard; } @Nonnull @IsLocked (ELockType.WRITE) private ISMPBusinessCard _updateSMPBusinessCard (@Nonnull final SMPBusinessCard aSMPBusinessCard) { m_aRWLock.writeLocked ( () -> { internalUpdateItem (aSMPBusinessCard); }); AuditHelper.onAuditModifySuccess (SMPBusinessCard.OT, aSMPBusinessCard.getID (), aSMPBusinessCard.getServiceGroupID (), Integer.valueOf (aSMPBusinessCard.getEntityCount ())); return aSMPBusinessCard; } /** * Create or update a business card for a service group. * * @param aServiceGroup * Service group * @param aEntities * The entities of the business card. May not be <code>null</code>. * @return The new or updated {@link ISMPBusinessCard}. Never * <code>null</code>. */ @Nonnull public ISMPBusinessCard createOrUpdateSMPBusinessCard (@Nonnull final ISMPServiceGroup aServiceGroup, @Nonnull final List <SMPBusinessCardEntity> aEntities) { ValueEnforcer.notNull (aServiceGroup, "ServiceGroup"); ValueEnforcer.notNull (aEntities, "Entities"); s_aLogger.info ("createOrUpdateSMPBusinessCard (" + aServiceGroup.getParticpantIdentifier ().getURIEncoded () + ", " + CollectionHelper.getSize (aEntities) + " entities)"); final ISMPBusinessCard aOldBusinessCard = getSMPBusinessCardOfServiceGroup (aServiceGroup); final SMPBusinessCard aNewBusinessCard = new SMPBusinessCard (aServiceGroup, aEntities); if (aOldBusinessCard != null) { // Reuse old ID _updateSMPBusinessCard (aNewBusinessCard); s_aLogger.info ("createOrUpdateSMPBusinessCard update successful"); } else { // Create new ID _createSMPBusinessCard (aNewBusinessCard); s_aLogger.info ("createOrUpdateSMPBusinessCard create successful"); } return aNewBusinessCard; } @Nonnull public EChange deleteSMPBusinessCard (@Nullable final ISMPBusinessCard aSMPBusinessCard) { if (aSMPBusinessCard == null) return EChange.UNCHANGED; s_aLogger.info ("deleteSMPBusinessCard (" + aSMPBusinessCard.getID () + ")"); m_aRWLock.writeLock ().lock (); try { final SMPBusinessCard aRealBusinessCard = internalDeleteItem (aSMPBusinessCard.getID ()); if (aRealBusinessCard == null) { AuditHelper.onAuditDeleteFailure (SMPBusinessCard.OT, "no-such-id", aSMPBusinessCard.getID ()); return EChange.UNCHANGED; } } finally { m_aRWLock.writeLock ().unlock (); } AuditHelper.onAuditDeleteSuccess (SMPBusinessCard.OT, aSMPBusinessCard.getID (), aSMPBusinessCard.getServiceGroupID (), Integer.valueOf (aSMPBusinessCard.getEntityCount ())); s_aLogger.info ("deleteSMPBusinessCard successful"); return EChange.CHANGED; } @Nonnull @ReturnsMutableCopy public ICommonsList <ISMPBusinessCard> getAllSMPBusinessCards () { return getAll (); } @Nullable public ISMPBusinessCard getSMPBusinessCardOfServiceGroup (@Nullable final ISMPServiceGroup aServiceGroup) { if (aServiceGroup == null) return null; return getSMPBusinessCardOfID (aServiceGroup.getID ()); } @Nullable public ISMPBusinessCard getSMPBusinessCardOfID (@Nullable final String sID) { return getOfID (sID); } @Nonnegative public int getSMPBusinessCardCount () { return getCount (); } }
e1f1c461bcff6393d32caab5d6ea9dad298b8067
b22bfd89e0689039e36090bb6963ca3680f9bc0d
/app/src/test/java/com/meburbstudios/recyclerviewexample/ExampleUnitTest.java
5effcfc4f99dfb618b6f917076573253a1b2c26d
[]
no_license
MEBurbs/RecyclerViewExample-App
6d28ddcaeea9c18b25ac1f5e94cd3312dde21084
dda6c1b554c3486d8ecf754da863ad0ed4478136
refs/heads/master
2023-05-17T06:13:19.698432
2021-06-08T00:39:52
2021-06-08T00:39:52
374,835,599
0
0
null
null
null
null
UTF-8
Java
false
false
398
java
package com.meburbstudios.recyclerviewexample; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
70f77936a00306b92cec8605904ba5c41ee6b3e3
2a90430284de4d46d43b5b0093f33c4d5a5010fa
/LexicalAnalyzerProject4/src/Load.java
643f1672fcd3de33784a538f3199775154cbdf46
[]
no_license
AmitCharran/LexicalAnalyzer
279db7bba696cc41b24a797b8cf3e94cb3a5fc49
6f3860ed647a120a3af6276a27b32191db530a64
refs/heads/master
2020-09-06T06:34:37.602066
2020-03-22T15:11:52
2020-03-22T15:11:52
220,352,748
0
0
null
null
null
null
UTF-8
Java
false
false
1,055
java
abstract class Load extends Instruction { int index; // vars[index] to be pushed onto operand stack Load(int i) { index = i; } public String toString() { return instName() + " " + index; } void execute() { AR topAR = VM.runtimeStack[VM.topR]; VM.top++; if ( VM.top == VM.opStackSize ) // operand stack overflow VM.runtimeError(1, VM.pc, toString(), 0); Data val = topAR.vars[index]; if ( val == null ) VM.runtimeError(3, VM.pc, toString(), 0); VM.opStack[VM.top] = val.cloneData(); VM.pc++; VM.updateOpStackPeakSize(); } static final class Fload extends Load { Fload(int i) { super(i); } String instName() { return "fload"; } } static final class Iload extends Load { Iload(int i) { super(i); } String instName() { return "iload"; } } }
57324212f646aff3cdfbecde6bcff9e4fcc592fa
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Chart/26/org/jfree/chart/plot/FastScatterPlot_getPaint_317.java
e4e6d3a30d0c0fcf99f6649db1297d46917ddf93
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
1,157
java
org jfree chart plot fast scatter plot fast scatter plot fastscatterplot plot axi plot valueaxisplot return paint plot data point code color red code paint set paint setpaint paint paint paint getpaint paint
7683f80ee7025e92b2c2b15fd9da575bfeaa81ca
b3f00b4461dfb6c68d3d634c04b843e6440bdd84
/src/meet/you/MainActivity.java
a2aa4907d5d8bd4341b14f2d7356e0dacdce1f2c
[]
no_license
stormand/MainActivity
d537a11d297fcfb6676c6cceb26c986c436d8335
8878a6df694a735fc3a09bdd4521685a2813cf9b
refs/heads/master
2020-04-05T23:15:30.100588
2016-08-08T02:17:28
2016-08-08T02:17:28
65,165,835
0
0
null
null
null
null
UTF-8
Java
false
false
11,942
java
package meet.you; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import org.json.JSONObject; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import meet.you.CalendarController.EventHandler; import meet.you.CalendarController.EventInfo; import meet.you.CalendarController.EventType; import meet.you.data.MeetCursorLoader; import meet.you.data.MeetData; import meet.you.wxapi.WXEntryActivity; import android.app.ActionBar; import android.app.Activity; import android.app.FragmentTransaction; import android.app.LoaderManager; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements EventHandler, OnClickListener, OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { private CalendarController mController; android.app.Fragment mMonthFragment; Fragment mDayFragment; private EventInfo mEvent; private boolean mDayView; private long mTime; private long mEventID; boolean mEventView; Boolean floatWhether; private final String TAG = "MA"; // add by allen liu private Button mCreateBtn; private GridView mHourGrid; private ListView mMeetList; private TextView mNoMeet; Bundle shareParams = null; private Tencent mTencent; private static final String APP_ID = "1104561257"; private ActionBarDrawerToggle mActionBarDrawerToggle; private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cal_layout); // getWindow().requestFeature(Window.FEATURE_ACTION_BAR); new ImportEntries().execute(this); mController = CalendarController.getInstance(this); Toolbar toolbar = (Toolbar) findViewById(R.id.id_toolbar); setSupportActionBar(toolbar); // ActionBar actionBar=getActionBar(); // actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); // actionBar.setDisplayShowCustomEnabled(true); // LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // View mView = inflator.inflate(R.layout.action_bar, null); // // actionBar.setCustomView(mView); // // mView.findViewById(R.id.addBtn).setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // Intent createMeet = new Intent(); // long selectTime = ((MonthByWeekFragment) mMonthFragment) // .getSelectedTime(); // createMeet.putExtra(MeetData.EXTRA_FOCUS_DATE, selectTime); // createMeet.setClass(MainActivity.this, WXEntryActivity.class); // startActivity(createMeet); // } // }); mMeetList = (ListView) findViewById(R.id.meet_list); mMeetList.setOnItemClickListener(this); mNoMeet = (TextView) findViewById(R.id.no_meet_promp); final long today = System.currentTimeMillis(); mMonthFragment = new MonthByWeekFragment(today, false); android.app.FragmentManager fm=getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); transaction.replace(R.id.cal_frame, mMonthFragment).commit(); mController.registerEventHandler(R.id.cal_frame, (EventHandler) mMonthFragment); mController.registerFirstEventHandler(0, this); mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout); mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close); mActionBarDrawerToggle.syncState(); mDrawerLayout.setDrawerListener(mActionBarDrawerToggle); SettingFragment mSettingFragment =(SettingFragment)fm.findFragmentById(R.id.id_left_menu_container); if (mSettingFragment==null){ mSettingFragment=new SettingFragment(); } FragmentTransaction transaction1 = fm.beginTransaction(); transaction1.replace(R.id.id_left_menu_container,mSettingFragment).commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar // if it is present. getMenuInflater().inflate(R.menu.entry_menu, menu); return true; } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); long selectTime = ((SimpleDayPickerFragment) mMonthFragment) .getSelectedTime(); Bundle bundle = new Bundle(); bundle.putLong(MeetData.EXTRA_FOCUS_DATE, selectTime); int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; String dateLabel = DateUtils.formatDateTime(this, selectTime, flags); Log.v(TAG, dateLabel); getLoaderManager().restartLoader(LOADER_FOCUS_DAY_MEET, bundle, this); SharedPreferences sharedPreferences = getSharedPreferences(SetUp.FloatWindow, Activity.MODE_PRIVATE); floatWhether = sharedPreferences.getBoolean(SetUp.FloatWindow, true); if (floatWhether) { Log.i("dududu", "启动悬浮"); floatWindow(); }else{ Intent intent=new Intent(MainActivity.this, FxService.class); stopService(intent); Log.i("dududu", "关闭悬浮"); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.add_meet_btn: Intent createMeet = new Intent(); long selectTime = ((MonthByWeekFragment) mMonthFragment) .getSelectedTime(); createMeet.putExtra(MeetData.EXTRA_FOCUS_DATE, selectTime); createMeet.setClass(MainActivity.this, WXEntryActivity.class); startActivity(createMeet); break; default: return true; } return super.onOptionsItemSelected(item); } @Override public long getSupportedEventTypes() { return EventType.GO_TO | EventType.VIEW_EVENT | EventType.UPDATE_TITLE; } @Override public void handleEvent(EventInfo event) { final int type = event.eventType; switch (type) { case EventType.GO_TO: /* * mEvent = event; mDayView = true; FragmentTransaction ft = * getFragmentManager().beginTransaction(); mDayFragment = new * DayFragment(event.startTime .toMillis(true), 1); * ft.replace(R.id.cal_frame, mDayFragment).addToBackStack * (null).commit(); */ long timeMillis = event.startTime.toMillis(true); Bundle bundle = new Bundle(); bundle.putLong(MeetData.EXTRA_FOCUS_DATE, timeMillis); getLoaderManager().restartLoader(LOADER_FOCUS_DAY_MEET, bundle, this); break; case EventType.VIEW_EVENT: mDayView = false; mEventView = true; this.mEvent = event; floatWindow(); // FragmentTransaction ft = // getFragmentManager().beginTransaction(); // edit = new EditEvent(event.id); // ft.replace(R.id.cal_frame, // edit).addToBackStack(null).commit(); break; default: break; } } @Override public void eventsChanged() { } @Override public void onClick(View v) { // TODO Auto-generated method stub // final int id = v.getId(); /* * switch(id){ case R.id.create: Intent createMeet = new Intent(); * createMeet.setClass(this, EditMeetingActivity.class); * startActivity(createMeet); break; default: break; } */ } @Override public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { // TODO create new event with a specific time Integer recId = (Integer) view.getTag(); Uri uri = ContentUris.withAppendedId(MeetData.URI_ID, recId.intValue()); Intent viewMeet = new Intent(MeetData.ACTION_MEET_VIEW); viewMeet.setData(uri); viewMeet.setClass(this, WXEntryActivity.class); startActivity(viewMeet); } private void showFocusDateMeet(Time focusTime) { GregorianCalendar focusDate = new GregorianCalendar(focusTime.year, focusTime.month, focusTime.monthDay); long dayStart = focusDate.getTimeInMillis(); focusDate.roll(Calendar.DAY_OF_MONTH, true); long dayEnd = focusDate.getTimeInMillis(); ContentResolver cr = getContentResolver(); Cursor cs = cr .query(MeetData.URI, MeetListAdapter.DATA_COL, MeetData.KEY_WHEN + ">=? " + " AND " + MeetData.KEY_WHEN + "< ?", new String[] { String.valueOf(dayStart), String.valueOf(dayEnd) }, null); if (cs != null) { final int N = cs.getCount(); if (N > 0) { MeetListAdapter mla = new MeetListAdapter(this, cs, false); mMeetList.setAdapter(mla); } // for (int i = 0; i < N; i++) { // if (cs.moveToPosition(i)) { // Meet meet = new Meet(); // // meet.topic = cs.getString(0); // meet.location = cs.getString(1); // meet.dateMillis = cs.getLong(2); // } // } // cs.close(); } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); MeetListAdapter mla = (MeetListAdapter) mMeetList.getAdapter(); if (mla != null) { mla.changeCursor(null); } } private final int LOADER_FOCUS_DAY_MEET = 0; @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // TODO Auto-generated method stub switch (id) { case LOADER_FOCUS_DAY_MEET: long day = data.getLong(MeetData.EXTRA_FOCUS_DATE); return new MeetCursorLoader(this, day, MeetListAdapter.DATA_COL); default: break; } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cs) { // TODO Auto-generated method stub final int id = loader.getId(); switch (id) { case LOADER_FOCUS_DAY_MEET: if (cs != null && cs.getCount() > 0) { MeetListAdapter mla = (MeetListAdapter) mMeetList.getAdapter(); if (mla != null) { mla.changeCursor(cs); } else { mla = new MeetListAdapter(this, cs, false); mMeetList.setAdapter(mla); } mMeetList.setVisibility(View.VISIBLE); mNoMeet.setVisibility(View.GONE); } else { mMeetList.setVisibility(View.GONE); mNoMeet.setVisibility(View.VISIBLE); } break; default: break; } } @Override public void onLoaderReset(Loader<Cursor> loader) { // TODO Auto-generated method stub } public void floatWindow() { Time today = new Time(); today.setToNow(); long time = System.currentTimeMillis(); GregorianCalendar focusDate = new GregorianCalendar(today.year, today.month, today.monthDay); long dayStart = focusDate.getTimeInMillis(); focusDate.roll(Calendar.DAY_OF_MONTH, true); long dayEnd = focusDate.getTimeInMillis(); ContentResolver cr = getContentResolver(); Cursor cs = cr .query(MeetData.URI, MeetListAdapter.DATA_COL, MeetData.KEY_WHEN + ">=? " + " AND " + MeetData.KEY_WHEN + "< ?", new String[] { String.valueOf(time), String.valueOf(dayEnd) }, null); if (cs != null) { final int N = cs.getCount(); if (N > 0) { Intent intent = new Intent(MainActivity.this, FxService.class); startService(intent); } } } }
a429c3ecd0e07751a92213220c0f5831fce973d7
2edf97cf25ca3794b612480e987478307708d457
/api/kogito-api/src/main/java/org/kie/kogito/rules/DataProcessor.java
3ebbe0ac03c1fb0e2f95d6a5e63363c32ef0c505
[ "Apache-2.0" ]
permissive
antmendoza/kogito-runtimes
9cbf8d2fd9cdcd10140a07bec61683324dac2c60
e61d7e7f369fb7a93b11ada1e240b0eebfaed111
refs/heads/master
2022-02-17T10:48:35.501016
2019-07-17T00:50:01
2019-07-17T00:50:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
934
java
/* * Copyright 2005 JBoss Inc * * 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.kie.kogito.rules; import org.kie.api.runtime.rule.FactHandle; public interface DataProcessor { default void insert(Object object) { insert( null, object ); } FactHandle insert( DataHandle handle, Object object); void update(DataHandle handle, Object object); void delete(DataHandle handle); }
d9f25f9684d30112e25c33a59435d6941a30242b
14aa7a85e4778556f3d158be3c87bd4e75c7de0b
/src/day38_spring/demo8/service/UserService.java
6cedd7b42c3177e96d508c340acd6ef1cbc245ae
[]
no_license
CLgithub/JavaLearn2
0c7f9016eebe8f2a56f5c530a6922622ba1d96fe
321b8287b837d8efa39fac46f29e679fb54ffa48
refs/heads/master
2020-05-22T01:40:00.406672
2016-12-27T08:22:50
2016-12-27T08:22:50
57,429,718
2
0
null
null
null
null
UTF-8
Java
false
false
100
java
package day38_spring.demo8.service; public interface UserService { public void sayHello(); }
2970f79827dfad972618ae79448b6da50173d425
a2148a5067bdaba27baa8c709b202884bc08eb8f
/app/src/main/java/com/example/sangameswaran/practice/JsonObjectBaseRequest.java
437e5554b982d4093c3f3657c207ad3ed3ab5ce5
[]
no_license
SangameswaranRS/ip1
65bb46da3a015973d009b4f93f8b7d01bca52195
793abb31c620cf0721495f6065fa48c744ba931b
refs/heads/master
2021-01-20T12:33:54.142896
2017-05-16T08:32:50
2017-05-16T08:32:50
90,376,957
0
0
null
null
null
null
UTF-8
Java
false
false
1,246
java
package com.example.sangameswaran.practice; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONObject; /** * Created by Sangameswaran on 08-05-2017. */ public class JsonObjectBaseRequest extends JsonObjectRequest { public JsonObjectBaseRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(method, url, jsonRequest, listener, errorListener); setRetryPolicy(new DefaultRetryPolicy(2000,5,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); } public JsonObjectBaseRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(url, jsonRequest, listener, errorListener); setRetryPolicy(new DefaultRetryPolicy(2000,5,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); } @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { return super.parseNetworkResponse(response); } }
5f217a3ab9f8b73c219e527d008a03c210eac536
0e30f234a830c8e1ba78687d36eab01ab81f492b
/org.jpat.scuba.external.slf4j/logback-1.2.3/logback-examples/src/main/java/chapters/mdc/NumberCruncherClient.java
efccad9ff765a3406118834cd2774fc84a3fb272
[ "MIT", "EPL-1.0", "LGPL-2.1-only" ]
permissive
JPAT-ROSEMARY/SCUBA
6b724d070b12f70cf68386c3f830448435714af1
0d7dcee9e62e724af8dc006e1399d5c3e7b77dd1
refs/heads/master
2022-07-23T05:06:54.121412
2021-04-04T21:14:29
2021-04-04T21:14:29
39,628,474
2
1
MIT
2022-06-29T18:54:38
2015-07-24T11:13:38
HTML
UTF-8
Java
false
false
2,798
java
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package chapters.mdc; import java.io.BufferedReader; import java.io.InputStreamReader; import java.rmi.Naming; import java.rmi.RemoteException; /** * NumberCruncherClient is a simple client for factoring integers. A * remote NumberCruncher is contacted and asked to factor an * integer. The factors returned by the {@link NumberCruncherServer} * are displayed on the screen. * */ public class NumberCruncherClient { public static void main(String[] args) { if (args.length == 1) { try { String url = "rmi://" + args[0] + "/Factor"; NumberCruncher nc = (NumberCruncher) Naming.lookup(url); loop(nc); } catch (Exception e) { e.printStackTrace(); } } else { usage("Wrong number of arguments."); } } static void usage(String msg) { System.err.println(msg); System.err.println("Usage: java chapters.mdc.NumberCruncherClient HOST\n" + " where HOST is the machine where the NumberCruncherServer is running."); System.exit(1); } static void loop(NumberCruncher nc) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int i = 0; while (true) { System.out.print("Enter a number to factor, '-1' to quit: "); try { i = Integer.parseInt(in.readLine()); } catch (Exception e) { e.printStackTrace(); } if (i == -1) { System.out.print("Exiting loop."); return; } else { try { System.out.println("Will attempt to factor " + i); int[] factors = nc.factor(i); System.out.print("The factors of " + i + " are"); for (int k = 0; k < factors.length; k++) { System.out.print(" " + factors[k]); } System.out.println("."); } catch (RemoteException e) { System.err.println("Could not factor " + i); e.printStackTrace(); } } } } }
8e55037898fca8807dd908014a2abeb1626ecbe6
523b257a71a2aca612abb1340500d1dbcbf25ffa
/src/main/java/com/sakk/princess/patient/service/exception/MotorVehicleAccidentNotFoundException.java
5c5174af86a6a58928682474d83a8ae1dba8cd73
[]
no_license
sakyika/princess
6d1fe721a1ff2aadd4de72489a5f94bf1ca3295f
ad4c1dd5f194b464adf6106e2651c6b9a42308ed
refs/heads/master
2021-01-10T03:58:45.043988
2015-10-23T04:49:33
2015-10-23T04:49:33
44,458,114
0
0
null
null
null
null
UTF-8
Java
false
false
774
java
package com.sakk.princess.patient.service.exception; public class MotorVehicleAccidentNotFoundException extends RuntimeException { private static final long serialVersionUID = 2663040220470909688L; public MotorVehicleAccidentNotFoundException() { } public MotorVehicleAccidentNotFoundException(String message) { super(message); } public MotorVehicleAccidentNotFoundException(Throwable cause) { super(cause); } public MotorVehicleAccidentNotFoundException(String message, Throwable cause) { super(message, cause); } public MotorVehicleAccidentNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
37dfbc1bd312dacb37f7adbeda1cddb0012ac64b
d06669ef43bb0a5c746a6ff33482cd53d848e322
/src/org/basiccompiler/compiler/Compiler.java
2f93b9f5366ae1970aabc56995f2379a113dc408
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause-Views" ]
permissive
adammendoza/BASICCompiler
a5055ff6b4256237d9bdbe71265e83a4259d253a
60011533de6ba8bb3d6a76d9a3d04cbaaccd978b
refs/heads/master
2020-04-05T23:31:28.119983
2015-07-21T09:49:42
2015-07-21T09:49:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
56,675
java
/* * Copyright (c) 2015, Lorenz Wiest * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ package org.basiccompiler.compiler; import static org.basiccompiler.bytecode.ClassModel.JavaClass.RUNTIME_EXCEPTION; import static org.basiccompiler.bytecode.ClassModel.JavaMethod.EXCEPTION_GET_MESSAGE; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import org.basiccompiler.bytecode.ClassModel; import org.basiccompiler.bytecode.info.ExceptionTableInfo; import org.basiccompiler.compiler.etc.ByteOutStream; import org.basiccompiler.compiler.etc.CompileException; import org.basiccompiler.compiler.etc.LineNumberTable; import org.basiccompiler.compiler.etc.LocalVariableTable; import org.basiccompiler.compiler.etc.ReturnTable; import org.basiccompiler.compiler.library.LibraryManager; import org.basiccompiler.compiler.library.LibraryManager.MethodEnum; import org.basiccompiler.parser.Parser; import org.basiccompiler.parser.nodes.INode; import org.basiccompiler.parser.nodes.NodeType; import org.basiccompiler.parser.nodes.impl.BinaryNode; import org.basiccompiler.parser.nodes.impl.FnFunctionNode; import org.basiccompiler.parser.nodes.impl.FunctionNode; import org.basiccompiler.parser.nodes.impl.LocalVariableNode; import org.basiccompiler.parser.nodes.impl.NumNode; import org.basiccompiler.parser.nodes.impl.StrNode; import org.basiccompiler.parser.nodes.impl.TokenNode; import org.basiccompiler.parser.nodes.impl.UnaryNode; import org.basiccompiler.parser.nodes.impl.VariableNode; import org.basiccompiler.parser.statements.Statement; import org.basiccompiler.parser.statements.impl.DataStatement; import org.basiccompiler.parser.statements.impl.DefFnStatement; import org.basiccompiler.parser.statements.impl.DimStatement; import org.basiccompiler.parser.statements.impl.EndStatement; import org.basiccompiler.parser.statements.impl.ForStatement; import org.basiccompiler.parser.statements.impl.GosubStatement; import org.basiccompiler.parser.statements.impl.GotoStatement; import org.basiccompiler.parser.statements.impl.IfStatement; import org.basiccompiler.parser.statements.impl.InputStatement; import org.basiccompiler.parser.statements.impl.LetStatement; import org.basiccompiler.parser.statements.impl.LineNumberStatement; import org.basiccompiler.parser.statements.impl.NextStatement; import org.basiccompiler.parser.statements.impl.OnGosubStatement; import org.basiccompiler.parser.statements.impl.OnGotoStatement; import org.basiccompiler.parser.statements.impl.PrintStatement; import org.basiccompiler.parser.statements.impl.ReadStatement; import org.basiccompiler.parser.statements.impl.RemStatement; import org.basiccompiler.parser.statements.impl.RestoreStatement; import org.basiccompiler.parser.statements.impl.ReturnStatement; import org.basiccompiler.parser.statements.impl.StopStatement; import org.basiccompiler.parser.statements.impl.SwapStatement; import org.basiccompiler.parser.statements.impl.WendStatement; import org.basiccompiler.parser.statements.impl.WhileStatement; import org.basiccompiler.parser.tokens.FunctionToken; import org.basiccompiler.parser.tokens.Token; public class Compiler { private static final String TAB = "\t"; public static final String CR = System.getProperty("line.separator"); public static final String FIELD_CURSOR_POS = "_cursorPos"; public static final String FIELD_LAST_RND = "_lastRnd"; public static final String FIELD_GOSUB_STACK = "_gosubStack"; public static final String FIELD_GOSUB_STACK_INDEX = "_gosubStackIndex"; public static final int GOSUB_STACK_SIZE = 256; // holds this many nested GOSUB calls public static final int GOSUB_STACK_FRAME_SIZE = 1; // holds 1 int per GOSUB stack frame private static final String FOR_POSTFIX_END_VAR = "_end"; private static final String FOR_POSTFIX_STEP_VAR = "_step"; public static final String FIELD_DATA = "_data"; public static final String FIELD_DATA_INFO = "_dataInfo"; public static final String FIELD_DATA_INDEX = "_dataIndex"; private final static String IS_DEF_PREFIX = "_isdef_"; private static final String LABEL_END = "END"; private final ClassModel classModel; private ByteOutStream o; private final LibraryManager libraryManager; private final LineNumberTable lineNumberTable; private final ReturnTable returnTable; private final Stack<WhileInfo> whileCompiletimeStack; private final Stack<ForInfo> forCompiletimeStack; private final TreeMap<String /* line number */, List<String> /* constants */> dataMap; private final TreeMap<String /* line number */, List<RestoreInfo>> restoreMap; private final Set<String /* varName */> strVariables; private final Map<String /* varName */, Integer /* var position */> localFnVariables; private final List<DefFnStatement> defFns; private final LocalVariableTable localVariables; private Map<String /* arrName */, String /* field descriptor*/> arrVariables; public Compiler(String className) { this.classModel = new ClassModel(className); this.o = new ByteOutStream(ClassModel.MAX_METHOD_LENGTH); this.libraryManager = new LibraryManager(this.classModel); this.lineNumberTable = new LineNumberTable(); this.returnTable = new ReturnTable(); this.whileCompiletimeStack = new Stack<WhileInfo>(); this.forCompiletimeStack = new Stack<ForInfo>(); this.dataMap = new TreeMap<String, List<String>>(); this.restoreMap = new TreeMap<String, List<RestoreInfo>>(); this.strVariables = new HashSet<String>(); this.defFns = new ArrayList<DefFnStatement>(); this.localFnVariables = new HashMap<String, Integer>(); this.localVariables = new LocalVariableTable(); this.arrVariables = new HashMap<String, String>(); } public ClassModel getClassModel() { return this.classModel; } public void compile(Statement statement) { if (statement instanceof DataStatement) { emitData((DataStatement) statement); } else if (statement instanceof DefFnStatement) { emitDefFn((DefFnStatement) statement); } else if (statement instanceof DimStatement) { emitDim((DimStatement) statement); } else if (statement instanceof EndStatement) { emitEnd(); } else if (statement instanceof ForStatement) { emitFor((ForStatement) statement); } else if (statement instanceof GosubStatement) { emitGosub((GosubStatement) statement); } else if (statement instanceof GotoStatement) { emitGoto((GotoStatement) statement); } else if (statement instanceof IfStatement) { emitIf((IfStatement) statement); } else if (statement instanceof InputStatement) { emitInput((InputStatement) statement); } else if (statement instanceof LetStatement) { emitLet((LetStatement) statement); } else if (statement instanceof LineNumberStatement) { emitLineNumber((LineNumberStatement) statement); } else if (statement instanceof NextStatement) { emitNext((NextStatement) statement); } else if (statement instanceof OnGosubStatement) { emitOnGosub((OnGosubStatement) statement); } else if (statement instanceof OnGotoStatement) { emitOnGoto((OnGotoStatement) statement); } else if (statement instanceof PrintStatement) { emitPrint((PrintStatement) statement); } else if (statement instanceof ReadStatement) { emitRead((ReadStatement) statement); } else if (statement instanceof RemStatement) { // ignore } else if (statement instanceof RestoreStatement) { emitRestore((RestoreStatement) statement); } else if (statement instanceof ReturnStatement) { emitReturn(); } else if (statement instanceof StopStatement) { emitStop(); } else if (statement instanceof SwapStatement) { emitSwap((SwapStatement) statement); } else if (statement instanceof WendStatement) { emitWend(); } else if (statement instanceof WhileStatement) { emitWhile((WhileStatement) statement); } else { throw new CompileException("Unknown statement"); } } public void flush() { this.o.label(LABEL_END); this.o.return_(); flushData(); flushForNext(); flushRestore(); flushWhileWend(); this.lineNumberTable.flush(this.o); this.returnTable.flush(this.o); int posExceptionHandler = this.o.pos(); flushExceptionHandler(); this.o.flush(); byte[] bodyByteCode = this.o.toByteArray(); flushDefFns(); // after flushing body byte code, before initialization byte code! byte[] initByteCode = getInitializationByteCode(); byte[] byteCode = combineByteCodeParts(initByteCode, bodyByteCode); ExceptionTableInfo[] exceptionTable = getExceptionTable(initByteCode.length + posExceptionHandler); int numLocals = this.localVariables.size(); this.classModel.addMainMethod(numLocals, byteCode, exceptionTable); this.libraryManager.flush(); this.o.closeGracefully(); } private void flushDefFns() { for (DefFnStatement defFn : this.defFns) { String funcName = defFn.getFuncName(); NodeType funcType = defFn.getFuncExpr().getType(); int numLocals = defFn.getFuncVars().length; this.localFnVariables.clear(); String descriptor = "("; for (int i = 0; i < numLocals; i++) { VariableNode funcVar = defFn.getFuncVars()[i]; descriptor += (funcVar.getType() == NodeType.NUM) ? "F" : "[C"; this.localFnVariables.put(funcVar.getVariableName(), i); // TODO: we lose type information here } descriptor += ")"; descriptor += (funcType == NodeType.NUM) ? "F" : "[C"; ByteOutStream saveStream = this.o; ByteOutStream o = new ByteOutStream(ClassModel.MAX_METHOD_LENGTH); this.o = o; // runtime definition flag String fieldName = IS_DEF_PREFIX + funcName; o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(fieldName, "Z")); o.ifne("isDefinedAtRuntime"); o.ldc(this.classModel.getStringIndex("Undefined function " + funcName + "().")); this.libraryManager.getMethod(MethodEnum.THROW_RUNTIME_EXCEPTION).emitCall(o); o.label("isDefinedAtRuntime"); INode funcExpr = defFn.getFuncExpr(); if (funcType == NodeType.NUM) { emitNumExpressionToStack(funcExpr); o.freturn(); } else if (funcType == NodeType.STR) { emitStrExpressionToStack(funcExpr); o.areturn(); } o.flushAndCloseGracefully(); this.o = saveStream; this.classModel.addMethod(funcName, descriptor, numLocals, o.toByteArray()); } } private void flushExceptionHandler() { this.o.ldc(this.classModel.getStringIndex(Compiler.CR + "ERROR: ")); this.libraryManager.getMethod(MethodEnum.PRINT_STRING_FROM_STACK).emitCall(this.o); this.o.invokevirtual(this.classModel.getJavaMethodRefIndex(EXCEPTION_GET_MESSAGE)); this.libraryManager.getMethod(MethodEnum.PRINT_STRING_FROM_STACK).emitCall(this.o); this.o.goto_(LABEL_END); } private byte[] getInitializationByteCode() { ByteOutStream o = new ByteOutStream(); initStrVars(o); initArrVars(o); initLocalVars(o); initData(o); initGosubStack(o); o.pad4ByteBoundary(); // padding for tableswitch in body code o.flushAndCloseGracefully(); return o.toByteArray(); } private void initStrVars(ByteOutStream o) { if (this.strVariables.size() > 0) { o.iconst_0(); o.newarray_char(); if (this.strVariables.size() == 1) { o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(this.strVariables.iterator().next(), "[C")); } else { for (String strVar : this.strVariables) { o.dup(); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(strVar, "[C")); } o.pop(); } } } private void initArrVars(ByteOutStream o) { for (String arrVarName : this.arrVariables.keySet()) { String arrVarFieldDescriptor = this.arrVariables.get(arrVarName); o.iconst_1(); o.anewarray(this.classModel.getClassIndex(arrVarFieldDescriptor.substring(1))); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(arrVarName, arrVarFieldDescriptor)); } } private void initLocalVars(ByteOutStream o) { List<LocalVariableNode> numLocVars = new ArrayList<LocalVariableNode>(); List<LocalVariableNode> strLocVars = new ArrayList<LocalVariableNode>(); LocalVariableNode[] sortedLocVars = this.localVariables.sortByLocalIndex(); for (int i = 0; i < sortedLocVars.length; i++) { LocalVariableNode locVarNode = sortedLocVars[i]; if (locVarNode.getType() == NodeType.NUM) { numLocVars.add(locVarNode); } else if (locVarNode.getType() == NodeType.STR) { strLocVars.add(locVarNode); } } int numLocVarsCount = numLocVars.size(); if (numLocVarsCount > 0) { for (int i = 0; i < numLocVarsCount; i++) { o.fconst_0(); o.fstore(numLocVars.get(i).getLocalIndex()); } } int strLocVarsCount = strLocVars.size(); if (strLocVarsCount > 0) { o.iconst_0(); o.newarray_char(); if (strLocVarsCount == 1) { o.astore(strLocVars.get(0).getLocalIndex()); } else { for (int i = 0; i < strLocVarsCount; i++) { o.dup(); o.astore(strLocVars.get(i).getLocalIndex()); } o.pop(); } } } private void initGosubStack(ByteOutStream o) { if (this.returnTable.isUsed()) { this.classModel.addField(Compiler.FIELD_GOSUB_STACK, "[I"); o.iconst_0(); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(Compiler.FIELD_GOSUB_STACK_INDEX, "I")); this.libraryManager.getMethod(MethodEnum.GOSUB_STACK_INITIALIZE).emitCall(o); } } private void initData(ByteOutStream o) { if (this.strDataIndex > 0) { o.ldc(this.strDataIndex); this.libraryManager.getMethod(MethodEnum.STRING_TO_CHARS).emitCall(o); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(Compiler.FIELD_DATA, "[C")); o.ldc(this.strDataInfoIndex); this.libraryManager.getMethod(MethodEnum.STRING_TO_CHARS).emitCall(o); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(Compiler.FIELD_DATA_INFO, "[C")); o.iconst_0(); o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(Compiler.FIELD_DATA_INDEX, "I")); } } private byte[] combineByteCodeParts(byte[] initByteCode, byte[] bodyByteCode) { int lenInit = initByteCode.length; int lenBody = bodyByteCode.length; byte[] byteCode = new byte[lenInit + lenBody]; System.arraycopy(initByteCode, 0, byteCode, 0, lenInit); System.arraycopy(bodyByteCode, 0, byteCode, lenInit, lenBody); return byteCode; } private ExceptionTableInfo[] getExceptionTable(int posCatch) { int posTryBegin = 0; int posTryEnd = posCatch; return new ExceptionTableInfo[] { // new ExceptionTableInfo(posTryBegin, posTryEnd, posCatch, this.classModel.getJavaClassRefIndex(RUNTIME_EXCEPTION)), // }; } private int branchOffset(int from, int to) { return (to - from) + 1; } ////////////////////////////////////////////////////////////////////////////// private void emitData(DataStatement dataStatement) { String lineNumber = dataStatement.getLineNumber(); String[] constants = dataStatement.getConstants(); if (this.dataMap.containsKey(lineNumber) == false) { this.dataMap.put(lineNumber, new ArrayList<String>()); } this.dataMap.get(lineNumber).addAll(Arrays.asList(constants)); } private int strDataIndex; private int strDataInfoIndex; private void flushData() { StringBuffer strData = new StringBuffer(); StringBuffer strDataInfo = new StringBuffer(); for (List<String> dataElements : this.dataMap.values()) { // sorted by line number. DEFAULT_LABEL is first. for (String dataElement : dataElements) { int index = strData.length(); // assert index < 2^16 = 65536 int length = dataElement.length(); // assert length < 2^16 = 65536 strData.append(dataElement); strDataInfo.append((char) index); strDataInfo.append((char) length); } } boolean hasData = strData.length() > 0; this.strDataIndex = hasData ? this.classModel.getStringIndex(strData.toString()) : 0; this.strDataInfoIndex = hasData ? this.classModel.getStringIndex(strDataInfo.toString()) : 0; } private void emitDefFn(DefFnStatement defFnStatement) { this.defFns.add(defFnStatement); String fieldName = IS_DEF_PREFIX + defFnStatement.getFuncName(); this.o.iconst_1(); this.o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(fieldName, "Z")); } private void emitDim(DimStatement dimStatement) { for (VariableNode var : dimStatement.getVariables()) { String varName = var.getVariableName(); int numDims = var.getDimExpressions().length; if (numDims == 1) { if (var.getType() == NodeType.NUM) { this.arrVariables.put(varName, "[[F"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[F")); emitNumExpressionToStack(var.getDimExpressions()[0]); this.libraryManager.getMethod(MethodEnum.DIM_1D_FLOAT_ARRAY).emitCall(this.o); } else if (var.getType() == NodeType.STR) { this.arrVariables.put(varName, "[[[C"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[C")); emitNumExpressionToStack(var.getDimExpressions()[0]); this.libraryManager.getMethod(MethodEnum.DIM_1D_STRING_ARRAY).emitCall(this.o); } } else if (numDims == 2) { if (var.getType() == NodeType.NUM) { this.arrVariables.put(varName, "[[[F"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[F")); emitNumExpressionToStack(var.getDimExpressions()[0]); emitNumExpressionToStack(var.getDimExpressions()[1]); this.libraryManager.getMethod(MethodEnum.DIM_2D_FLOAT_ARRAY).emitCall(this.o); } else if (var.getType() == NodeType.STR) { this.arrVariables.put(varName, "[[[[C"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[[C")); emitNumExpressionToStack(var.getDimExpressions()[0]); emitNumExpressionToStack(var.getDimExpressions()[1]); this.libraryManager.getMethod(MethodEnum.DIM_2D_STRING_ARRAY).emitCall(this.o); } } } } private void emitEnd() { this.o.goto_(LABEL_END); } private static class ForInfo { private final String forLabel; private final VariableNode loopVar; private final int patchPosToSkipForNextLoop; public ForInfo(String forLabel, VariableNode loopVar, int patchPosToSkipForNextLoop) { this.forLabel = forLabel; this.loopVar = loopVar; this.patchPosToSkipForNextLoop = patchPosToSkipForNextLoop; } public String getForLabel() { return this.forLabel; } public VariableNode getLoopVar() { return this.loopVar; } public int getPatchPosToSkipForNextLoop() { return this.patchPosToSkipForNextLoop; } } private void emitFor(ForStatement forStatement) { VariableNode loopVar = forStatement.getLoopVariable(); INode startExpr = forStatement.getStartExpression(); INode endExpr = forStatement.getEndExpression(); INode stepExpr = forStatement.getStepExpression(); String loopVarName = loopVar.getVariableName(); LocalVariableNode stepVar = this.localVariables.addAndGetLocalVariableNode(loopVarName + FOR_POSTFIX_STEP_VAR, NodeType.NUM); LocalVariableNode endVar = this.localVariables.addAndGetLocalVariableNode(loopVarName + FOR_POSTFIX_END_VAR, NodeType.NUM); int loopVarFieldRefIndex = this.classModel.addFieldAndGetFieldRefIndex(loopVar.getVariableName(), "F"); emitNumExpressionToStack(startExpr); emitFloatFromStackToNumVariable(loopVar); emitNumExpressionToStack(stepExpr); emitFloatFromStackToNumVariable(stepVar); emitNumExpressionToStack(endExpr); emitFloatFromStackToNumVariable(endVar); String forLabel = "_for" + ByteOutStream.generateLabel(); this.o.label(forLabel); // skip FOR-NEXT if <loopVar> * SGN(<stepExpr>) > <endExpr> * SGN(<stepExpr>) this.o.fload_opt(stepVar.getLocalIndex()); this.libraryManager.getMethod(MethodEnum.SGN).emitCall(this.o); this.o.dup(); this.o.getstatic(loopVarFieldRefIndex); this.o.fmul(); this.o.swap(); this.o.fload_opt(endVar.getLocalIndex()); this.o.fmul(); this.o.fcmpg(); this.o.ifgt(); // ifgt(...) int patchPosToSkipForNextLoop = this.o.pos(); this.o.write_u2(0x0000); // ...will be patched this.forCompiletimeStack.push(new ForInfo(forLabel, loopVar, patchPosToSkipForNextLoop)); } private void emitNext(NextStatement nextStatement) { VariableNode[] loopVars = nextStatement.getLoopVariables(); if (loopVars.length > 0) { for (VariableNode loopVar : loopVars) { emitInternalNext(loopVar); } } else { emitInternalNext(null); } } private void emitInternalNext(VariableNode nextLoopVar) { if (this.forCompiletimeStack.isEmpty()) { throw new CompileException("NEXT without FOR"); } ForInfo forInfo = this.forCompiletimeStack.pop(); String forLabel = forInfo.getForLabel(); VariableNode forLoopVar = forInfo.getLoopVar(); int patchPosToSkipForNextLoop = forInfo.getPatchPosToSkipForNextLoop(); if (nextLoopVar != null) { String forLoopVarName = forLoopVar.getVariableName(); String nextLoopVarName = nextLoopVar.getVariableName(); if (forLoopVarName.equals(nextLoopVarName) == false) { throw new CompileException("NEXT does not match FOR"); } } emitFloatFromNumVariableToStack(forLoopVar); String stepVarName = forLoopVar.getVariableName() + FOR_POSTFIX_STEP_VAR; this.o.fload_opt(this.localVariables.get(stepVarName).getLocalIndex()); this.o.fadd(); emitFloatFromStackToNumVariable(forLoopVar); this.o.goto_(forLabel); int branchOffset = branchOffset(patchPosToSkipForNextLoop, this.o.pos()); this.o.patch_u2(patchPosToSkipForNextLoop, branchOffset); } private void flushForNext() { while (this.forCompiletimeStack.isEmpty() == false) { ForInfo forInfo = this.forCompiletimeStack.pop(); int patchPosToSkipForNextLoop = forInfo.getPatchPosToSkipForNextLoop(); this.o.patchThereToLabel(patchPosToSkipForNextLoop, LABEL_END); } } private void emitGoto(GotoStatement gotoStatement) { String lineNumber = gotoStatement.getLineNumber(); this.o.goto_(); // goto(...) this.lineNumberTable.patchHere_u2(this.o.pos(), lineNumber); this.o.write_u2(0x0000); // ...will be patched } private void emitOnGoto(OnGotoStatement onGotoStatement) { INode numExpr = onGotoStatement.getExpression(); String[] lineNumbers = onGotoStatement.getLineNumbers(); emitNumExpressionToStack(numExpr); this.libraryManager.getMethod(LibraryManager.MethodEnum.ROUND_TO_INT).emitCall(this.o); this.o.dup(); this.libraryManager.getMethod(LibraryManager.MethodEnum.CHECK_ON_GOTO_GOSUB_ARG).emitCall(this.o); this.o.tableswitch(); int posAfterTableSwitch = this.o.pos(); this.o.pad4ByteBoundary(); int numLineNumbers = lineNumbers.length; int posDefaultSwitch = this.o.pos(); this.o.write_u4(0x00000000); // ...will be patched this.o.write_u4(1); this.o.write_u4(numLineNumbers); for (int i = 0; i < numLineNumbers; i++) { this.lineNumberTable.patchThere_u4(this.o.pos(), posAfterTableSwitch, lineNumbers[i]); this.o.write_u4(0x00000000); // ...will be patched } // switch "default" will point here this.o.patch_u4(posDefaultSwitch, branchOffset(posAfterTableSwitch, this.o.pos())); } private void emitGosub(GosubStatement gosubStatement) { String lineNumber = gosubStatement.getLineNumber(); int gosubId = this.returnTable.nextIndex(); this.o.iconst(gosubId); this.libraryManager.getMethod(MethodEnum.GOSUB_STACK_PUSH).emitCall(this.o); emitGoto(new GotoStatement(lineNumber)); this.returnTable.addReturnPos(gosubId, this.o.pos()); } private void emitOnGosub(OnGosubStatement onGosubStatement) { INode numExpr = onGosubStatement.getExpression(); String[] lineNumbers = onGosubStatement.getLineNumbers(); int gosubId = this.returnTable.nextIndex(); this.o.iconst(gosubId); this.libraryManager.getMethod(MethodEnum.GOSUB_STACK_PUSH).emitCall(this.o); emitOnGoto(new OnGotoStatement(numExpr, lineNumbers)); this.returnTable.addReturnPos(gosubId, this.o.pos()); } private void emitReturn() { // pop gosubId this.libraryManager.getMethod(MethodEnum.GOSUB_STACK_POP).emitCall(this.o); this.o.goto_(); // goto <tableswitch> this.returnTable.patchToTableSwitch(this.o.pos()); this.o.write_u2(0x0000); // ...will be patched } private void emitIf(IfStatement ifStatement) { INode numExpr = ifStatement.getExpression(); if (isNumRelationalExpression(numExpr)) { emitIfRelational(ifStatement); } else { emitNumExpressionToStack(numExpr); this.o.fconst_0(); this.o.fcmpg(); String ifId = ByteOutStream.generateLabel(); String afterThenId = "_afterThen" + ifId; String afterElseId = "_afterElse" + ifId; this.o.ifeq(afterThenId); for (Statement thenStatement : ifStatement.getThenStatements()) { compile(thenStatement); } Statement[] elseStatements = ifStatement.getElseStatements(); if (elseStatements.length > 0) { this.o.goto_(afterElseId); } this.o.label(afterThenId); for (Statement elseStatement : elseStatements) { compile(elseStatement); } if (elseStatements.length > 0) { this.o.label(afterElseId); } } } private GotoStatement getSingleGotoOfIf(Statement[] statements) { if (statements.length == 1) { if (statements[0] instanceof GotoStatement) { return (GotoStatement) statements[0]; } } return null; } private void emitIfRelational(IfStatement ifStatement) { BinaryNode binaryNode = (BinaryNode) ifStatement.getExpression(); emitNumExpressionToStack(binaryNode.getLeftNode()); emitNumExpressionToStack(binaryNode.getRightNode()); Token opToken = binaryNode.getOp(); this.o.fcmpg(); String ifId = ByteOutStream.generateLabel(); String afterThenId = "_afterThen" + ifId; String afterElseId = "_afterElse" + ifId; Statement[] thenStatements = ifStatement.getThenStatements(); Statement[] elseStatements = ifStatement.getElseStatements(); GotoStatement thenGotoStatement = getSingleGotoOfIf(thenStatements); if (thenGotoStatement != null) { if (opToken == Token.EQUAL) { this.o.ifeq(); // ifeq(...) } else if (opToken == Token.NOT_EQUAL) { this.o.ifne(); // ifne(...) } else if (opToken == Token.LESS_OR_EQUAL) { this.o.ifle(); // ifle(...) } else if (opToken == Token.GREATER_OR_EQUAL) { this.o.ifge(); // ifge(...) } else if (opToken == Token.LESS) { this.o.iflt(); // iflt(...) } else if (opToken == Token.GREATER) { this.o.ifgt(); // ifgt(...) } String lineNumber = thenGotoStatement.getLineNumber(); this.lineNumberTable.patchHere_u2(this.o.pos(), lineNumber); this.o.write_u2(0x0000); // ...will be patched } else { if (opToken == Token.EQUAL) { this.o.ifne(afterThenId); } else if (opToken == Token.NOT_EQUAL) { this.o.ifeq(afterThenId); } else if (opToken == Token.LESS_OR_EQUAL) { this.o.ifgt(afterThenId); } else if (opToken == Token.GREATER_OR_EQUAL) { this.o.iflt(afterThenId); } else if (opToken == Token.LESS) { this.o.ifge(afterThenId); } else if (opToken == Token.GREATER) { this.o.ifle(afterThenId); } for (Statement thenStatement : thenStatements) { compile(thenStatement); } if (elseStatements.length > 0) { this.o.goto_(afterElseId); } this.o.label(afterThenId); } GotoStatement elseGotoStatement = getSingleGotoOfIf(elseStatements); if (elseGotoStatement != null) { this.o.goto_(); // goto(...) String lineNumber = elseGotoStatement.getLineNumber(); this.lineNumberTable.patchHere_u2(this.o.pos(), lineNumber); this.o.write_u2(0x0000); // ...will be patched } else { for (Statement elseStatement : elseStatements) { compile(elseStatement); } } if (elseStatements.length > 0) { this.o.label(afterElseId); } } private void emitInput(InputStatement inputStatement) { StringBuffer buffer = new StringBuffer(); String prompt = inputStatement.getPrompt(); if (prompt != null) { buffer.append(prompt); } boolean showQuestionMark = inputStatement.getSeparator() == Token.SEMICOLON; if (showQuestionMark) { buffer.append("?"); } if (buffer.length() > 0) { emitPrintStringConstFromStack(buffer.toString()); } VariableNode[] vars = inputStatement.getVariables(); StringBuffer typeBuffer = new StringBuffer(); for (VariableNode var : vars) { if (var.getType() == NodeType.NUM) { typeBuffer.append("F"); } else if (var.getType() == NodeType.STR) { typeBuffer.append("S"); } } emitStrExpressionToStack(StrNode.createStringNode(typeBuffer.toString())); this.libraryManager.getMethod(LibraryManager.MethodEnum.INPUT).emitCall(this.o); for (int i = 0; i < vars.length; i++) { if (i < (vars.length - 1)) { this.o.dup(); } this.o.iconst(i); this.o.aaload(); VariableNode var = vars[i]; if (var.getType() == NodeType.NUM) { this.libraryManager.getMethod(LibraryManager.MethodEnum.VAL).emitCall(this.o); emitFloatFromStackToNumVariable(var); } else if (vars[i].getType() == NodeType.STR) { emitCharsFromStackToStrVariable(var); } } } private void emitLet(LetStatement letStatement) { VariableNode var = (VariableNode) letStatement.getVariable(); if (var.getType() == NodeType.NUM) { emitNumExpressionToStack(letStatement.getExpression()); emitFloatFromStackToNumVariable(var); } else if (var.getType() == NodeType.STR) { emitStrExpressionToStack(letStatement.getExpression()); emitCharsFromStackToStrVariable(var); } } private void emitLineNumber(LineNumberStatement lineNumberStatement) { String lineNumber = lineNumberStatement.getLineNumber(); this.lineNumberTable.add(this.o.pos(), lineNumber); } private void emitPrint(PrintStatement printStatement) { for (INode expr : printStatement.getExpressions()) { if (expr instanceof TokenNode) { TokenNode tokenNode = (TokenNode) expr; if (tokenNode.getToken() == Token.SEMICOLON) { // do nothing } else if (tokenNode.getToken() == Token.COMMA) { emitPrintStringConstFromStack(TAB); } } else if (isFunctionExpressionOf(expr, FunctionToken.TAB)) { INode arg = ((FunctionNode) expr).getArgNodes()[0]; emitNumExpressionToStack(arg); this.libraryManager.getMethod(LibraryManager.MethodEnum.TAB).emitCall(this.o); } else if (isFunctionExpressionOf(expr, FunctionToken.SPC)) { INode arg = ((FunctionNode) expr).getArgNodes()[0]; emitNumExpressionToStack(arg); this.libraryManager.getMethod(LibraryManager.MethodEnum.SPC).emitCall(this.o); } else { if (expr.getType() == NodeType.NUM) { emitNumExpressionToStack(expr); this.libraryManager.getMethod(LibraryManager.MethodEnum.PRINT_FLOAT_FROM_STACK).emitCall(this.o); } else if (expr.getType() == NodeType.STR) { if (expr instanceof StrNode) { emitPrintStringConstFromStack(((StrNode) expr).getValue()); } else { emitStrExpressionToStack(expr); this.libraryManager.getMethod(LibraryManager.MethodEnum.PRINT_CHARS_FROM_STACK).emitCall(this.o); } } } } boolean addPrintln = false; INode[] exprs = printStatement.getExpressions(); if (exprs.length == 0) { addPrintln = true; } else { addPrintln = true; INode lastExpr = exprs[exprs.length - 1]; if (lastExpr instanceof TokenNode) { Token op = ((TokenNode) lastExpr).getToken(); if ((op == Token.SEMICOLON) || (op == Token.COMMA)) { addPrintln = false; } } } if (addPrintln) { emitPrintStringConstFromStack(CR); } } private void emitRead(ReadStatement readStatement) { VariableNode[] vars = readStatement.getVariables(); for (VariableNode var : vars) { if (var.getType() == NodeType.NUM) { emitReadNumFromDataToStack(); emitFloatFromStackToNumVariable(var); } else if (var.getType() == NodeType.STR) { emitReadStrFromDataToStack(); emitCharsFromStackToStrVariable(var); } } } private void emitReadStrFromDataToStack() { this.libraryManager.getMethod(LibraryManager.MethodEnum.READ_STRING_FROM_DATA_TO_STACK).emitCall(this.o); } private void emitReadNumFromDataToStack() { this.libraryManager.getMethod(LibraryManager.MethodEnum.READ_NUM_FROM_DATA_TO_STACK).emitCall(this.o); } private static class RestoreInfo { private final int patchPos; public RestoreInfo(int patchPos) { this.patchPos = patchPos; } public int getPatchPos() { return this.patchPos; } } private void emitRestore(RestoreStatement restoreStatement) { String lineNumber = restoreStatement.getLineNumber(); if (this.restoreMap.containsKey(lineNumber) == false) { this.restoreMap.put(lineNumber, new ArrayList<RestoreInfo>()); } List<RestoreInfo> restoreInfos = this.restoreMap.get(lineNumber); restoreInfos.add(new RestoreInfo(this.o.pos() + 1)); // _dataElementIndex := <patched index> int dataIndexFieldRef = this.classModel.getFieldRefIndex(Compiler.FIELD_DATA_INDEX, "I"); this.o.sipush(0x0000); // ...will be patched in flush() this.o.putstatic(dataIndexFieldRef); } private void flushRestore() { Map<String /* line number */, Integer /* dataInfoIndex */> dataInfoIndexMap = new LinkedHashMap<String, Integer>(); int dataInfoIndex = 0; for (Entry<String /* line number */, List<String> /* constants */> e : this.dataMap.entrySet()) { // sorted by line number. DEFAULT_LABEL is first. String lineNumber = e.getKey(); dataInfoIndexMap.put(lineNumber, dataInfoIndex); List<String> dataElements = e.getValue(); dataInfoIndex += dataElements.size(); } if (this.restoreMap.isEmpty() == false) { // add default entry for RESTORE statement dataInfoIndexMap.put(Parser.RESTORE_DEFAULT_LINE_NUMBER, 0); } for (Entry<String /* line number */, List<RestoreInfo> /* RestoreInfo */> e : this.restoreMap.entrySet()) { String lineNumber = e.getKey(); if (dataInfoIndexMap.containsKey(lineNumber) == false) { throw new CompileException("No DATA to RESTORE at " + lineNumber); } List<RestoreInfo> restoreInfos = e.getValue(); for (RestoreInfo restoreInfo : restoreInfos) { int patchPos = restoreInfo.getPatchPos(); dataInfoIndex = dataInfoIndexMap.get(lineNumber); this.o.patch_u2(patchPos, dataInfoIndex); } } } private void emitStop() { this.o.goto_(LABEL_END); } private void emitSwap(SwapStatement swapStatement) { VariableNode var1 = swapStatement.getVariable1(); VariableNode var2 = swapStatement.getVariable2(); if (var1.getType() == NodeType.NUM) { emitNumExpressionToStack(var1); emitNumExpressionToStack(var2); emitFloatFromStackToNumVariable(var1); emitFloatFromStackToNumVariable(var2); } else if (var1.getType() == NodeType.STR) { emitStrExpressionToStack(var1); emitStrExpressionToStack(var2); emitCharsFromStackToStrVariable(var1); emitCharsFromStackToStrVariable(var2); } } private static class WhileInfo { private final String whileLabel; private final int patchPosToSkipWhileWendLoop; public WhileInfo(String whileLabel, int patchPosToSkipWhileWendLoop) { this.whileLabel = whileLabel; this.patchPosToSkipWhileWendLoop = patchPosToSkipWhileWendLoop; } public String getWhileLabel() { return this.whileLabel; } public int getPatchPosToSkipWhileWendLoop() { return this.patchPosToSkipWhileWendLoop; } } private void emitWhile(WhileStatement whileStatement) { INode numExpr = whileStatement.getExpression(); String whileLabel = "_while" + ByteOutStream.generateLabel(); this.o.label(whileLabel); emitNumExpressionToStack(numExpr); this.o.fconst_0(); this.o.fcmpg(); this.o.ifeq(); // ifeq(...) int patchPosToSkipWhileWendLoop = this.o.pos(); this.o.write_u2(0x0000); // ...will be patched this.whileCompiletimeStack.push(new WhileInfo(whileLabel, patchPosToSkipWhileWendLoop)); } private void emitWend() { if (this.whileCompiletimeStack.isEmpty()) { throw new CompileException("WEND without WHILE"); } WhileInfo whileInfo = this.whileCompiletimeStack.pop(); String whileLabel = whileInfo.getWhileLabel(); int patchPosToSkipWhileWendLoop = whileInfo.getPatchPosToSkipWhileWendLoop(); this.o.goto_(whileLabel); int branchOffset = branchOffset(patchPosToSkipWhileWendLoop, this.o.pos()); this.o.patch_u2(patchPosToSkipWhileWendLoop, branchOffset); } private void flushWhileWend() { while (this.whileCompiletimeStack.isEmpty() == false) { WhileInfo whileInfo = this.whileCompiletimeStack.pop(); int patchPosToSkipWhileWendLoop = whileInfo.getPatchPosToSkipWhileWendLoop(); this.o.patchThereToLabel(patchPosToSkipWhileWendLoop, LABEL_END); } } /// HELPER METHODS /////////////////////////////////////////////////////////// private void emitPrintStringConstFromStack(String string) { if (string.length() == 1) { // Code size optimization: may save inclusion of library methods this.o.iconst(string.charAt(0)); this.libraryManager.getMethod(LibraryManager.MethodEnum.PRINT_CHAR_FROM_STACK).emitCall(this.o); } else { this.o.ldc(this.classModel.getStringIndex(string)); this.libraryManager.getMethod(LibraryManager.MethodEnum.PRINT_STRING_FROM_STACK).emitCall(this.o); } } private void emitFloatFromStackToNumVariable(VariableNode numVar) { String varName = numVar.getVariableName(); if (numVar instanceof LocalVariableNode) { LocalVariableNode numLocVar = (LocalVariableNode) numVar; this.o.fstore_opt(numLocVar.getLocalIndex()); } else { int numDims = numVar.getDimExpressions().length; if (numDims == 0) { this.o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "F")); } else if (numDims == 1) { this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[F")); emitNumExpressionToStack(numVar.getDimExpressions()[0]); this.libraryManager.getMethod(LibraryManager.MethodEnum.STORE_FLOAT_IN_1D_ARRAY).emitCall(this.o); } else if (numDims == 2) { this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[F")); emitNumExpressionToStack(numVar.getDimExpressions()[0]); emitNumExpressionToStack(numVar.getDimExpressions()[1]); this.libraryManager.getMethod(LibraryManager.MethodEnum.STORE_FLOAT_IN_2D_ARRAY).emitCall(this.o); } } } private void emitCharsFromStackToStrVariable(VariableNode strVar) { String varName = strVar.getVariableName(); if (strVar instanceof LocalVariableNode) { LocalVariableNode strLocVar = (LocalVariableNode) strVar; this.o.astore_opt(strLocVar.getLocalIndex()); } else { int numDims = strVar.getDimExpressions().length; if (numDims == 0) { this.o.putstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[C")); } else if (numDims == 1) { this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[C")); emitNumExpressionToStack(strVar.getDimExpressions()[0]); this.libraryManager.getMethod(LibraryManager.MethodEnum.STORE_STRING_IN_1D_ARRAY).emitCall(this.o); } else if (numDims == 2) { this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[[C")); emitNumExpressionToStack(strVar.getDimExpressions()[0]); emitNumExpressionToStack(strVar.getDimExpressions()[1]); this.libraryManager.getMethod(LibraryManager.MethodEnum.STORE_STRING_IN_2D_ARRAY).emitCall(this.o); } } } private void emitNumExpressionToStack(INode expr) { if (expr instanceof BinaryNode) { BinaryNode binNode = (BinaryNode) expr; INode leftNode = binNode.getLeftNode(); INode rightNode = binNode.getRightNode(); if (leftNode.getType() == NodeType.NUM) { // not fully correct, but we use the return type of the left node as a result type indicator emitNumExpressionToStack(leftNode); emitNumExpressionToStack(rightNode); } else if (leftNode.getType() == NodeType.STR) { emitStrExpressionToStack(leftNode); emitStrExpressionToStack(rightNode); } Token opToken = binNode.getOp(); if (isArithmeticOpToken(opToken)) { if (opToken == Token.ADD) { this.o.fadd(); } else if (opToken == Token.SUBTRACT) { this.o.fsub(); } else if (opToken == Token.MULTIPLY) { this.o.fmul(); } else if (opToken == Token.DIVIDE) { this.libraryManager.getMethod(LibraryManager.MethodEnum.DIVISION).emitCall(this.o); } else if (opToken == Token.INT_DIVIDE) { this.libraryManager.getMethod(LibraryManager.MethodEnum.INTEGER_DIVISION).emitCall(this.o); } else if (opToken == Token.MOD) { this.libraryManager.getMethod(LibraryManager.MethodEnum.MOD).emitCall(this.o); } else if (opToken == Token.POWER) { this.libraryManager.getMethod(LibraryManager.MethodEnum.POWER).emitCall(this.o); } } else if (isLogicalBinaryOpToken(opToken)) { if (opToken == Token.AND) { this.libraryManager.getMethod(LibraryManager.MethodEnum.AND).emitCall(this.o); } else if (opToken == Token.OR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.OR).emitCall(this.o); } else if (opToken == Token.XOR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.XOR).emitCall(this.o); } } else if (isNumRelationalOpToken(opToken)) { String label1 = ByteOutStream.generateLabel(); String label2 = ByteOutStream.generateLabel(); this.o.fcmpg(); if (opToken == Token.LESS) { this.o.iflt(label1); } else if (opToken == Token.LESS_OR_EQUAL) { this.o.ifle(label1); } else if (opToken == Token.EQUAL) { this.o.ifeq(label1); } else if (opToken == Token.GREATER_OR_EQUAL) { this.o.ifge(label1); } else if (opToken == Token.GREATER) { this.o.ifgt(label1); } else if (opToken == Token.NOT_EQUAL) { this.o.ifne(label1); } this.o.fconst_0(); this.o.goto_(label2); this.o.label(label1); this.o.fconst_1(); this.o.fneg(); this.o.label(label2); } else if (isStrRelationalOpToken(opToken)) { if (opToken == Token.STRING_LESS) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_LESS_THAN).emitCall(this.o); } else if (opToken == Token.STRING_LESS_OR_EQUAL) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_LESS_OR_EQUAL).emitCall(this.o); } else if (opToken == Token.STRING_EQUAL) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_EQUAL).emitCall(this.o); } else if (opToken == Token.STRING_GREATER_OR_EQUAL) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_GREATER_OR_EQUAL).emitCall(this.o); } else if (opToken == Token.STRING_GREATER) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_GREATER_THAN).emitCall(this.o); } else if (opToken == Token.STRING_NOT_EQUAL) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_NOT_EQUAL).emitCall(this.o); } } } else if (expr instanceof UnaryNode) { UnaryNode unaryNode = (UnaryNode) expr; INode nodeExpr = unaryNode.getArgNode(); emitNumExpressionToStack(nodeExpr); Token opToken = unaryNode.getOp(); if (opToken == Token.NOT) { this.libraryManager.getMethod(LibraryManager.MethodEnum.NOT).emitCall(this.o); } else if (opToken == Token.OPEN) { // do nothing } else if (opToken == Token.UNARY_MINUS) { this.o.fneg(); } } else if (expr instanceof NumNode) { NumNode numNode = (NumNode) expr; float floatValue = numNode.getValue(); if (floatValue == 0.0f) { this.o.fconst_0(); } else if (floatValue == 1.0f) { this.o.fconst_1(); } else if (floatValue == 2.0f) { this.o.fconst_2(); } else { this.o.ldc(this.classModel.getFloatIndex(floatValue)); } } else if (expr instanceof VariableNode) { emitFloatFromNumVariableToStack((VariableNode) expr); } else if (expr instanceof FunctionNode) { FunctionNode functionNode = (FunctionNode) expr; FunctionToken functionToken = functionNode.getFunctionToken(); INode[] args = functionNode.getArgNodes(); NodeType[] argTypes = functionToken.getArgTypes(); for (int i = 0; i < args.length; i++) { INode arg = args[i]; NodeType nodeType = argTypes[i]; if (nodeType == NodeType.NUM) { emitNumExpressionToStack(arg); } else if (nodeType == NodeType.STR) { emitStrExpressionToStack(arg); } } if (functionToken == FunctionToken.ABS) { this.libraryManager.getMethod(LibraryManager.MethodEnum.ABS).emitCall(this.o); } else if (functionToken == FunctionToken.ASC) { this.libraryManager.getMethod(LibraryManager.MethodEnum.ASC).emitCall(this.o); } else if (functionToken == FunctionToken.ATN) { this.libraryManager.getMethod(LibraryManager.MethodEnum.ATN).emitCall(this.o); } else if (functionToken == FunctionToken.COS) { this.libraryManager.getMethod(LibraryManager.MethodEnum.COS).emitCall(this.o); } else if (functionToken == FunctionToken.EXP) { this.libraryManager.getMethod(LibraryManager.MethodEnum.EXP).emitCall(this.o); } else if (functionToken == FunctionToken.FIX) { this.libraryManager.getMethod(LibraryManager.MethodEnum.FIX).emitCall(this.o); } else if (functionToken == FunctionToken.INSTR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.INSTR).emitCall(this.o); } else if (functionToken == FunctionToken.INT) { this.libraryManager.getMethod(LibraryManager.MethodEnum.INT).emitCall(this.o); } else if (functionToken == FunctionToken.LEN) { this.libraryManager.getMethod(LibraryManager.MethodEnum.LEN).emitCall(this.o); } else if (functionToken == FunctionToken.LOG) { this.libraryManager.getMethod(LibraryManager.MethodEnum.LOG).emitCall(this.o); } else if (functionToken == FunctionToken.POS) { this.libraryManager.getMethod(LibraryManager.MethodEnum.POS).emitCall(this.o); } else if (functionToken == FunctionToken.RND) { this.libraryManager.getMethod(LibraryManager.MethodEnum.RND).emitCall(this.o); } else if (functionToken == FunctionToken.SGN) { this.libraryManager.getMethod(LibraryManager.MethodEnum.SGN).emitCall(this.o); } else if (functionToken == FunctionToken.SIN) { this.libraryManager.getMethod(LibraryManager.MethodEnum.SIN).emitCall(this.o); } else if (functionToken == FunctionToken.SQR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.SQR).emitCall(this.o); } else if (functionToken == FunctionToken.TAN) { this.libraryManager.getMethod(LibraryManager.MethodEnum.TAN).emitCall(this.o); } else if (functionToken == FunctionToken.VAL) { this.libraryManager.getMethod(LibraryManager.MethodEnum.VAL).emitCall(this.o); } } else if (expr instanceof FnFunctionNode) { emitFunctionCall((FnFunctionNode) expr); } else { throw new UnsupportedOperationException("Unknown number expression."); } } private void emitFloatFromNumVariableToStack(VariableNode numVar) { String varName = numVar.getVariableName(); if (this.localFnVariables.containsKey(varName)) { int localVarIndex = this.localFnVariables.get(varName).intValue(); this.o.fload_opt(localVarIndex); } else { int numDims = numVar.getDimExpressions().length; if (numDims == 0) { this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "F")); } else if (numDims == 1) { this.arrVariables.put(varName, "[[F"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[F")); emitNumExpressionToStack(numVar.getDimExpressions()[0]); this.libraryManager.getMethod(LibraryManager.MethodEnum.LOAD_FLOAT_FROM_1D_ARRAY).emitCall(this.o); } else if (numDims == 2) { this.arrVariables.put(varName, "[[[F"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[F")); emitNumExpressionToStack(numVar.getDimExpressions()[0]); emitNumExpressionToStack(numVar.getDimExpressions()[1]); this.libraryManager.getMethod(LibraryManager.MethodEnum.LOAD_FLOAT_FROM_2D_ARRAY).emitCall(this.o); } } } private void emitStrExpressionToStack(INode expr) { if (expr instanceof BinaryNode) { BinaryNode binNode = (BinaryNode) expr; Token opToken = binNode.getOp(); if (opToken == Token.STRING_ADD) { emitStrExpressionToStack(binNode.getLeftNode()); emitStrExpressionToStack(binNode.getRightNode()); this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_CONCATENATION).emitCall(this.o); // TOOD } } else if (expr instanceof StrNode) { StrNode strNode = (StrNode) expr; String string = strNode.getValue(); this.o.ldc(this.classModel.getStringIndex(string)); this.libraryManager.getMethod(LibraryManager.MethodEnum.STRING_TO_CHARS).emitCall(this.o); } else if (expr instanceof VariableNode) { emitCharsFromStrVariableToStack((VariableNode) expr); } else if (expr instanceof FunctionNode) { FunctionNode functionNode = (FunctionNode) expr; FunctionToken functionToken = functionNode.getFunctionToken(); INode[] args = functionNode.getArgNodes(); NodeType[] argTypes = functionToken.getArgTypes(); for (int i = 0; i < args.length; i++) { INode arg = args[i]; NodeType nodeType = argTypes[i]; if (nodeType == NodeType.NUM) { emitNumExpressionToStack(arg); } else if (nodeType == NodeType.STR) { emitStrExpressionToStack(arg); } } if (functionToken == FunctionToken.CHR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.CHR).emitCall(this.o); } else if (functionToken == FunctionToken.LEFT) { this.libraryManager.getMethod(LibraryManager.MethodEnum.LEFT).emitCall(this.o); } else if (functionToken == FunctionToken.MID) { this.libraryManager.getMethod(LibraryManager.MethodEnum.MID).emitCall(this.o); } else if (functionToken == FunctionToken.RIGHT) { this.libraryManager.getMethod(LibraryManager.MethodEnum.RIGHT).emitCall(this.o); } else if (functionToken == FunctionToken.SPACE) { this.libraryManager.getMethod(LibraryManager.MethodEnum.SPACE).emitCall(this.o); } else if (functionToken == FunctionToken.STR) { this.libraryManager.getMethod(LibraryManager.MethodEnum.STR).emitCall(this.o); } } else if (expr instanceof FnFunctionNode) { emitFunctionCall((FnFunctionNode) expr); } else { throw new UnsupportedOperationException("Unknown string expression."); } } private void emitCharsFromStrVariableToStack(VariableNode strVar) { String varName = strVar.getVariableName(); if (this.localFnVariables.containsKey(varName)) { int localVarIndex = this.localFnVariables.get(varName).intValue(); this.o.aload_opt(localVarIndex); } else { int numDims = strVar.getDimExpressions().length; if (numDims == 0) { this.strVariables.add(varName); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[C")); } else if (numDims == 1) { this.arrVariables.put(varName, "[[[C"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[C")); emitNumExpressionToStack(strVar.getDimExpressions()[0]); this.libraryManager.getMethod(LibraryManager.MethodEnum.LOAD_STRING_FROM_1D_ARRAY).emitCall(this.o); } else if (numDims == 2) { this.arrVariables.put(varName, "[[[[C"); this.o.getstatic(this.classModel.addFieldAndGetFieldRefIndex(varName, "[[[[C")); emitNumExpressionToStack(strVar.getDimExpressions()[0]); emitNumExpressionToStack(strVar.getDimExpressions()[1]); this.libraryManager.getMethod(LibraryManager.MethodEnum.LOAD_STRING_FROM_2D_ARRAY).emitCall(this.o); } } } private void emitFunctionCall(FnFunctionNode fnFuncNode) { INode[] funcArgExprs = fnFuncNode.getFuncArgExprs(); for (INode funcArgExpr : funcArgExprs) { if (funcArgExpr.getType() == NodeType.NUM) { emitNumExpressionToStack(funcArgExpr); } else if (funcArgExpr.getType() == NodeType.STR) { emitStrExpressionToStack(funcArgExpr); } } String methodName = fnFuncNode.getFuncName(); String descriptor = "("; for (INode arg : funcArgExprs) { descriptor += (arg.getType() == NodeType.NUM) ? "F" : "[C"; } descriptor += ")"; descriptor += (fnFuncNode.getType() == NodeType.NUM) ? "F" : "[C"; this.o.invokestatic(this.classModel.getMethodRefIndex(methodName, descriptor)); } private boolean isArithmeticOpToken(Token opToken) { if ((opToken == Token.ADD) || // (opToken == Token.SUBTRACT) || // (opToken == Token.MULTIPLY) || // (opToken == Token.DIVIDE) || // (opToken == Token.INT_DIVIDE) || // (opToken == Token.MOD) || // (opToken == Token.POWER)) { return true; } return false; } private boolean isLogicalBinaryOpToken(Token opToken) { if ((opToken == Token.AND) || // (opToken == Token.OR) || // (opToken == Token.XOR)) { return true; } return false; } private boolean isStrRelationalOpToken(Token opToken) { if ((opToken == Token.STRING_EQUAL) || // (opToken == Token.STRING_NOT_EQUAL) || // (opToken == Token.STRING_LESS) || // (opToken == Token.STRING_LESS_OR_EQUAL) || // (opToken == Token.STRING_GREATER_OR_EQUAL) || // (opToken == Token.STRING_GREATER)) { return true; } return false; } private boolean isNumRelationalOpToken(Token opToken) { if ((opToken == Token.EQUAL) || // (opToken == Token.NOT_EQUAL) || // (opToken == Token.LESS) || // (opToken == Token.LESS_OR_EQUAL) || // (opToken == Token.GREATER_OR_EQUAL) || // (opToken == Token.GREATER)) { return true; } return false; } private boolean isNumRelationalExpression(INode expr) { if (expr instanceof BinaryNode) { BinaryNode binaryNode = (BinaryNode) expr; Token opToken = binaryNode.getOp(); return isNumRelationalOpToken(opToken); } return false; } private boolean isFunctionExpressionOf(INode expr, FunctionToken functionToken) { if (expr instanceof FunctionNode) { if (((FunctionNode) expr).getFunctionToken() == functionToken) { return true; } } return false; } }
f865e40e2fbcdd13bf696d897ba3a712fc3531b9
07858cda0ed4e8172414c7e4cd153d97f9afb48c
/admin/src/main/java/com/ckstack/ckpush/common/security/PlymindLoginFailureHandler.java
5def0dcb5150212bd0b7a5b060000f433e6669be
[]
no_license
kodaji/doitfive
701cb54dc524f2081ed1f24bdcd2463fa83f6eb9
79b26931aa546f115d6a1d39f1459aa523d1bad5
refs/heads/master
2021-01-19T05:31:48.203045
2016-07-11T05:35:52
2016-07-11T05:35:52
63,039,468
0
0
null
null
null
null
UTF-8
Java
false
false
2,070
java
package com.ckstack.ckpush.common.security; import com.ckstack.ckpush.domain.user.MemberEntity; import com.ckstack.ckpush.service.user.MemberService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.web.util.UrlPathHelper; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by kodaji on 2016. 1. 22.. */ public class PlymindLoginFailureHandler implements AuthenticationFailureHandler { private final static Logger LOG = LoggerFactory.getLogger(PlymindLoginFailureHandler.class); @Autowired private MemberService memberService; @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String userId = request.getParameter("user_id"); String userPasswd = request.getParameter("user_password"); HttpSession httpSession = request.getSession(); httpSession.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception); UrlPathHelper urlPathHelper = new UrlPathHelper(); String redirectPage = urlPathHelper.getContextPath(request) + "/user/open/login"; MemberEntity memberEntity = memberService.getMemberInfo(userId); if(memberEntity == null) { LOG.info("failed login. not found user_id["+userId+"]"); redirectPage += "?error=1"; response.sendRedirect(redirectPage); return; } else { LOG.info("failed login. password wrong ["+userId+"]"); redirectPage += "?error=2"; } response.sendRedirect(redirectPage); } }
0fc02b7f0a6aca5a4167e1b6d9bd466d82327fde
d21cfba78b0165c1893baf3bd5e1d26de14d8b01
/modules/activiti-pvm/src/test/java/org/activiti/pvm/test/PvmEventTest.java
3301d37ea72025ea9bca4e0fb7faa76fdd617415
[]
no_license
sandyjohn/activiti
6d1deb050b1573b03366a14b8464c7ec05eface7
2273a2a8fdfb5a42d396dfae16e713ee8c10784f
refs/heads/master
2020-03-31T16:23:24.932146
2010-08-10T07:41:20
2010-08-10T07:41:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,857
java
/* 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.activiti.pvm.test; import java.util.ArrayList; import java.util.List; import org.activiti.pvm.ProcessDefinitionBuilder; import org.activiti.pvm.event.EventListener; import org.activiti.pvm.process.PvmProcessDefinition; import org.activiti.pvm.runtime.PvmExecution; import org.activiti.pvm.runtime.PvmProcessInstance; import org.activiti.test.pvm.activities.Automatic; import org.activiti.test.pvm.activities.EmbeddedSubProcess; import org.activiti.test.pvm.activities.End; import org.activiti.test.pvm.activities.ParallelGateway; import org.activiti.test.pvm.activities.WaitState; /** * @author Tom Baeyens */ public class PvmEventTest extends PvmTestCase { public void testStartEndEvents() { EventCollector eventCollector = new EventCollector(); PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder("events") .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .createActivity("start") .initial() .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .startTransition("end") .eventListener(eventCollector) .endTransition() .endActivity() .createActivity("end") .behavior(new End()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .endActivity() .buildProcessDefinition(); PvmProcessInstance processInstance = processDefinition.createProcessInstance(); processInstance.start(); List<String> expectedEvents = new ArrayList<String>(); expectedEvents.add("start on ProcessDefinition(events)"); expectedEvents.add("end on Activity(start)"); expectedEvents.add("take on (start)-->(end)"); expectedEvents.add("start on Activity(end)"); expectedEvents.add("end on ProcessDefinition(events)"); assertEquals(expectedEvents, eventCollector.events); } public void testNestedActivitiesEventsOnTransitionEvents() { EventCollector eventCollector = new EventCollector(); PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder("events") .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .createActivity("start") .initial() .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .startTransition("wait") .eventListener(eventCollector) .endTransition() .endActivity() .createActivity("outerscope") .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .createActivity("innerscope") .scope() .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .createActivity("wait") .behavior(new WaitState()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("end") .endActivity() .endActivity() .endActivity() .createActivity("end") .behavior(new WaitState()) .endActivity() .buildProcessDefinition(); PvmProcessInstance processInstance = processDefinition.createProcessInstance(); processInstance.start(); List<String> expectedEvents = new ArrayList<String>(); expectedEvents.add("start on ProcessDefinition(events)"); expectedEvents.add("end on Activity(start)"); expectedEvents.add("take on (start)-->(wait)"); expectedEvents.add("start on Activity(outerscope)"); expectedEvents.add("start on Activity(innerscope)"); expectedEvents.add("start on Activity(wait)"); assertEquals(expectedEvents, eventCollector.events); PvmExecution execution = processInstance.findExecution("wait"); execution.signal(null, null); expectedEvents.add("end on Activity(wait)"); expectedEvents.add("end on Activity(innerscope)"); expectedEvents.add("end on Activity(outerscope)"); assertEquals(expectedEvents, eventCollector.events); } public void testEmbeddedSubProcessEvents() { EventCollector eventCollector = new EventCollector(); PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder() .createActivity("start") .initial() .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("embeddedsubprocess") .endActivity() .createActivity("embeddedsubprocess") .scope() .behavior(new EmbeddedSubProcess()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .createActivity("startInside") .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("endInside") .endActivity() .createActivity("endInside") .behavior(new End()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .endActivity() .transition("end") .endActivity() .createActivity("end") .behavior(new WaitState()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .endActivity() .buildProcessDefinition(); PvmProcessInstance processInstance = processDefinition.createProcessInstance(); processInstance.start(); for (String event: eventCollector.events) { System.err.println(event); } List<String> expectedEvents = new ArrayList<String>(); expectedEvents.add("end on Activity(start)"); expectedEvents.add("start on Activity(embeddedsubprocess)"); expectedEvents.add("end on Activity(startInside)"); expectedEvents.add("start on Activity(endInside)"); expectedEvents.add("end on Activity(embeddedsubprocess)"); expectedEvents.add("start on Activity(end)"); assertEquals(expectedEvents, eventCollector.events); } public void testSimpleAutmaticConcurrencyEvents() { EventCollector eventCollector = new EventCollector(); PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder() .createActivity("start") .initial() .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("fork") .endActivity() .createActivity("fork") .behavior(new ParallelGateway()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("c1") .transition("c2") .endActivity() .createActivity("c1") .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("join") .endActivity() .createActivity("c2") .behavior(new Automatic()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("join") .endActivity() .createActivity("join") .behavior(new ParallelGateway()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .transition("end") .endActivity() .createActivity("end") .behavior(new End()) .eventListener(EventListener.EVENTNAME_START, eventCollector) .eventListener(EventListener.EVENTNAME_END, eventCollector) .endActivity() .buildProcessDefinition(); PvmProcessInstance processInstance = processDefinition.createProcessInstance(); processInstance.start(); List<String> expectedEvents = new ArrayList<String>(); expectedEvents.add("end on Activity(start)"); expectedEvents.add("start on Activity(fork)"); expectedEvents.add("end on Activity(fork)"); expectedEvents.add("start on Activity(c1)"); expectedEvents.add("end on Activity(c1)"); expectedEvents.add("start on Activity(join)"); expectedEvents.add("end on Activity(fork)"); expectedEvents.add("start on Activity(c2)"); expectedEvents.add("end on Activity(c2)"); expectedEvents.add("start on Activity(join)"); expectedEvents.add("end on Activity(join)"); expectedEvents.add("start on Activity(end)"); assertEquals(expectedEvents, eventCollector.events); } }
[ "tombaeyens@51b7ce9a-3489-0410-86de-dc9a27cf12c7" ]
tombaeyens@51b7ce9a-3489-0410-86de-dc9a27cf12c7
28a22bf23d0570aa9c447f6b4faf044a714f3941
cb92b75920e168c57edb651aa83c1406ddd591fd
/Classes/Fornecedor.java
cad44c219fb77b34a436c52d4b4549860abbcc83
[]
no_license
Natalialimas/Poo
c1016b4fd4700d6d84230ee411b938bae96ad7e5
11ed80bbbc64ea9b205952c1b316f9bbb7153d21
refs/heads/master
2022-11-14T21:57:44.152401
2020-07-16T00:51:24
2020-07-16T00:51:24
279,456,736
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,646
java
/*2. Considere, como subclasse da classe Pessoa (desenvolvida no exercício anterior) * a classe Fornecedor. Considere que cada instância da classe Fornecedor tem, * para além dos atributos que caracterizam a classe Pessoa, os atributos valorCredito * (correspondente ao crédito máximo atribuído ao fornecedor) e valorDivida * (montante da dívida para com o fornecedor). Implemente na classe Fornecedor, para além dos usuais métodos * seletores e modificadores, um método obterSaldo() que devolve a diferença entre os valores dos atributos * valorCredito e valorDivida. Depois de implementada a classe Fornecedor, crie um programa de teste adequado * que lhe permita verificar o funcionamento dos métodos implementados na classe Fornecedor e os herdados da classe * Pessoa. */ package Poo; public class Fornecedor extends Pessoa { private double valorCredito; private double valorDivida; public Fornecedor (String nome, String endereco, String telefone, double valorCredito, double valorDivida) { super (nome, endereco, telefone); this.valorCredito = valorCredito; this.valorDivida = valorDivida; } public Fornecedor () { } public double getValorCredito() { return valorCredito; } public void setValorCredito(float valorCredito) { this.valorCredito = valorCredito; } public double getValorDivida() { return valorDivida; } public void setValorDivida(float valorDivida) { this.valorDivida = valorDivida; } public double obterSaldo() { double obterSaldo = valorCredito - valorDivida; return obterSaldo; } }
2c00248803d3fb8a9a7240207d51a36238c6abe0
43ce7d43b071292791651b999e11254c95cd0899
/leopard-jdbc/src/main/java/io/leopard/jdbc/builder/QueryBuilder.java
01b08c1ed3d8c061638f427b2faea58eca58cf0a
[ "Apache-2.0" ]
permissive
tanhaichao/leopard-data
ee2282fcb414ae36c8292a32d1077406a80fa922
2fae872f34f68ca6a23bcfe4554d47821b503281
refs/heads/master
2021-01-23T09:25:53.455915
2016-10-18T18:16:29
2016-10-18T18:16:29
41,264,390
1
3
null
null
null
null
UTF-8
Java
false
false
7,794
java
package io.leopard.jdbc.builder; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.springframework.util.StringUtils; import io.leopard.jdbc.Jdbc; import io.leopard.jdbc.StatementParameter; import io.leopard.lang.Paging; import io.leopard.lang.TimeRange; public class QueryBuilder { private String tableName; private String rangeFieldName; private TimeRange range; private String orderFieldName; // 按desc 还是asc private String orderDirection; private String groupbyFieldName; private Integer limitStart; private Integer limitSize; private Map<String, Object> whereMap = new LinkedHashMap<String, Object>(); private List<String> whereExpressionList = new ArrayList<String>(); private Map<String, String> likeMap = new LinkedHashMap<String, String>(); public QueryBuilder(String tableName) { this.tableName = tableName; } public QueryBuilder range(String fieldName, TimeRange range) { if (range == null) { return this; } this.rangeFieldName = fieldName; this.range = range; return this; } public QueryBuilder addWhere(String expression) { whereExpressionList.add(expression); return this; } public QueryBuilder addString(String fieldName, String value) { return this.addString(fieldName, value, false); } public QueryBuilder addString(String fieldName, String value, boolean like) { if (StringUtils.hasLength(value)) { if (like) { this.addLike(fieldName, value); } else { this.addWhere(fieldName, value); } } return this; } public QueryBuilder addLong(String fieldName, long value) { if (value > 0) { this.addWhere(fieldName, value); } return this; } public QueryBuilder addWhere(String fieldName, Object value) { whereMap.put(fieldName, value); return this; } public QueryBuilder addLike(String fieldName, String value) { if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("参数不能为空."); } value = value.replace("%", ""); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("参数不能包含特殊字符[" + value + "]."); } likeMap.put(fieldName, value); return this; } public QueryBuilder order(String fieldName) { return this.order(fieldName, "desc"); } public QueryBuilder order(String fieldName, String orderDirection) { this.orderFieldName = fieldName; this.orderDirection = orderDirection; return this; } public QueryBuilder groupby(String fieldName) { this.groupbyFieldName = fieldName; return this; } public QueryBuilder limit(int start, int size) { this.limitStart = start; this.limitSize = size; return this; } protected String getRangeSQL(StatementParameter param) { StringBuilder rangeSQL = new StringBuilder(); if (this.range != null) { if (range.getStartTime() != null) { rangeSQL.append(this.rangeFieldName + ">=?"); param.setDate(range.getStartTime()); } if (range.getEndTime() != null) { if (rangeSQL.length() > 0) { rangeSQL.append(" and "); } rangeSQL.append(this.rangeFieldName + "<=?"); param.setDate(range.getEndTime()); } } return rangeSQL.toString(); } protected String getWhereExpressionSQL() { if (this.whereExpressionList.isEmpty()) { return ""; } StringBuilder whereSQL = new StringBuilder(); for (String expression : this.whereExpressionList) { if (whereSQL.length() > 0) { whereSQL.append(" and "); } whereSQL.append(expression); } return whereSQL.toString(); } protected String getWhereSQL(StatementParameter param) { StringBuilder whereSQL = new StringBuilder(); for (Entry<String, Object> entry : this.whereMap.entrySet()) { String fieldName = entry.getKey(); Object value = entry.getValue(); if (whereSQL.length() > 0) { whereSQL.append(" and "); } if (value instanceof List) { @SuppressWarnings("rawtypes") List list = (List) value; String sql = this.getWhereInSql(fieldName, list); whereSQL.append(" ").append(sql); } else { whereSQL.append(fieldName).append("=?"); param.setObject(value.getClass(), value); } } return whereSQL.toString(); } protected String getWhereInSql(String fieldName, @SuppressWarnings("rawtypes") List list) { if (list == null || list.isEmpty()) { throw new IllegalArgumentException("list参数不能为空."); } StringBuilder sql = new StringBuilder(); sql.append(fieldName).append(" in ("); for (Object obj : list) { String str = (String) obj; str = escapeSQLParam(str); sql.append("'" + str + "',"); } sql.deleteCharAt(sql.length() - 1); sql.append(")"); return sql.toString(); } protected String getLikeSQL(StatementParameter param) { StringBuilder whereSQL = new StringBuilder(); for (Entry<String, String> entry : this.likeMap.entrySet()) { String fieldName = entry.getKey(); String value = entry.getValue(); if (whereSQL.length() > 0) { whereSQL.append(" and "); } whereSQL.append(fieldName).append(" like '%" + escapeSQLParam(value) + "%'"); } return whereSQL.toString(); } /** * 对SQL语句进行转义 * * @param param SQL语句 * @return 转义后的字符串 */ private static String escapeSQLParam(final String param) { int stringLength = param.length(); StringBuilder buf = new StringBuilder((int) (stringLength * 1.1)); for (int i = 0; i < stringLength; ++i) { char c = param.charAt(i); switch (c) { case 0: /* Must be escaped for 'mysql' */ buf.append('\\'); buf.append('0'); break; case '\n': /* Must be escaped for logs */ buf.append('\\'); buf.append('n'); break; case '\r': buf.append('\\'); buf.append('r'); break; case '\\': buf.append('\\'); buf.append('\\'); break; case '\'': buf.append('\\'); buf.append('\''); break; case '"': /* Better safe than sorry */ buf.append('\\'); buf.append('"'); break; case '\032': /* This gives problems on Win32 */ buf.append('\\'); buf.append('Z'); break; default: buf.append(c); } } return buf.toString(); } public <T> Paging<T> queryForPaging(Jdbc jdbc, Class<T> elementType) { StatementParameter param = new StatementParameter(); StringBuilder sb = new StringBuilder(); sb.append("select * from " + tableName); StringBuilder where = new StringBuilder(); { String rangeSQL = this.getRangeSQL(param); if (rangeSQL.length() > 0) { where.append(rangeSQL); } { String whereSQL = this.getWhereSQL(param); if (whereSQL.length() > 0) { if (where.length() > 0) { where.append(" and "); } where.append(whereSQL); } } { String whereSQL = this.getWhereExpressionSQL(); if (whereSQL.length() > 0) { if (where.length() > 0) { where.append(" and "); } where.append(whereSQL); } } { String whereSQL = this.getLikeSQL(param); if (whereSQL.length() > 0) { if (where.length() > 0) { where.append(" and "); } where.append(whereSQL); } } } if (where.length() > 0) { sb.append(" where " + where.toString()); } // System.err.println("groupbyFieldName:" + groupbyFieldName + " orderFieldName:" + orderFieldName); if (groupbyFieldName != null && groupbyFieldName.length() > 0) { sb.append(" group by " + groupbyFieldName); } if (orderFieldName != null && orderFieldName.length() > 0) { sb.append(" order by " + orderFieldName + " " + orderDirection); } sb.append(" limit ?,?"); param.setInt(limitStart); param.setInt(limitSize); String sql = sb.toString(); // System.err.println("sql:" + sql); return jdbc.queryForPaging(sql, elementType, param); } }
b24b1475c507c76a490aaedfc00d4f10f4802acc
39abf1267eb452733cdfcf4f8f69077cc2d13716
/Data Structures/src/Sorting/Shell.java
5a2309177695fd922cf79c6b6376dde28e89b2ac
[]
no_license
rehrumesh/DataStructures
45e2a4a99be55f0e046420bab9357d20b6c9c01a
f0456e9659eeff0d3a956e7dd41cd27513b5ec0d
refs/heads/master
2016-09-05T10:59:31.323258
2013-09-21T18:26:02
2013-09-21T18:26:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,312
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Sorting; /** * * @author Rumesh */ public class Shell { public static void main(String[] args) { int[] x = {5, 13, 7, 6, 4, 9}; int incr = x.length / 2; while (incr > 0) { for (int index1 = incr+1; index1 < x.length; index1++) { int index2=index1-incr; while(index2>0){ if(x[index2]>x[index2-incr]){ int t =x[index2]; x[index2]=x[index2-incr]; x[index2-incr] = t; index2=index2-incr; }else{ index2=0; } } } incr=incr/2; } print(x); } //for (index1=incr+1;index1<Arraysize; ++index1 //Index2=index1-incr //While index2>=0 //If (Element[index2] > Element[index2-incr] //swap(Element(index2,Element[index2-incr]) //Index2=index2-incr //else //Index2=0 //Incr=incr/2 static void print(int[] x) { for (int i = 0; i < x.length; i++) { System.out.print(x[i] + " ,"); } System.out.println(""); } }
f039b6c2ef763c3d7d18dd8f558b389bb9c4336c
00fb4335c0a9d1b3160a46e5f101a0c23c5e735a
/gestionFinal/src/vista/ListaObras.java
8d23298bb5453c88a5bc70ef6ca4a1063b16d382
[]
no_license
IskayTeam/GestionDeDatos
eee57564568fbbf6cc617fcc41c75e5b2e5c18dc
2e13e952323e96aab710ebeb001e35099586e812
refs/heads/master
2021-01-10T17:54:27.184463
2016-02-22T20:26:42
2016-02-22T20:26:42
52,302,761
0
0
null
null
null
null
UTF-8
Java
false
false
9,766
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista; import Controlador.Fecha; import controlador.Conectar; import java.awt.Dialog; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Luca */ public class ListaObras extends javax.swing.JDialog { Callback2 callback2; Conectar cc = new Conectar(); Connection cn = cc.conexion(); public ListaObras(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public void setCallback2(Callback2 callback2) { this.callback2 = callback2; } public JTable getjTable1() { return jTable1; } public void llenarTabla(){ String sql = "SELECT idObra, nombre, direccion FROM obra"; cc.conexion(); try { Statement st = cn.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); DefaultTableModel modelo = (DefaultTableModel)this.getjTable1().getModel(); Object datosFila[] = new Object [3]; while (rs.next()){ for(int i=0; i< datosFila.length; i++){ datosFila[i]=rs.getObject(i+1); } modelo.addRow(datosFila); } } catch (SQLException ex) { Logger.getLogger(ListaObras.class.getName()).log(Level.SEVERE, null, ex); } } void llenarCamposObra(){ int row = jTable1.getSelectedRow(); int idObra = (int) jTable1.getValueAt(row, 0); String nombre = jTable1.getValueAt(row, 1).toString(); String direccion = jTable1.getValueAt(row, 2).toString(); String sql = "SELECT fechaInicio, fechaFinalizacion, egresos FROM obra WHERE idObra='"+idObra+"'"; cc.conexion(); Statement st; try { st = cn.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); rs.next(); Date fechaInicio = rs.getDate("fechaInicio"); Date fechaFin = rs.getDate("fechaFinalizacion"); double egresos = rs.getDouble("egresos"); callback2.notificarObra(idObra, nombre, direccion, fechaInicio, fechaFin, egresos); } catch (SQLException ex) { Logger.getLogger(ListaObras.class.getName()).log(Level.SEVERE, null, ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("Seleccione una obra:"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Id Obra", "Nombre", "Direccion" } )); jScrollPane1.setViewportView(jTable1); jButton1.setText("Seleccionar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(15, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(85, 85, 85) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(91, 91, 91) .addComponent(jButton1) .addGap(46, 46, 46) .addComponent(jButton2))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel1) .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton2) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(28, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int fila; fila = jTable1.getSelectedRow(); if(fila == -1){ JOptionPane.showMessageDialog(rootPane, "Debe seleccionar una obra", "ADVERTENCIA", JOptionPane.ERROR_MESSAGE); } else{ llenarCamposObra(); this.dispose(); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ListaObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ListaObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ListaObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ListaObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ListaObras dialog = new ListaObras(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }
[ "Luca@Luca" ]
Luca@Luca
091e40baada61911790726c8e224d38d3946b66c
6c709541a7d86c7a63c67cf1fd56227199448a23
/day02/src/com/itheima/demo00_反馈和回顾/TestDemo.java
7db41d2d911c23b4de3c1992987c67cb9f7c5eff
[]
no_license
942669366/java_projects
ed8c2b66acaada6a88126bcd4ea16ef0b0bdc4ed
2ce3f822b3a7a3bf865d02628f46f384f9b350a1
refs/heads/master
2020-06-19T14:50:43.334278
2019-07-13T18:01:01
2019-07-13T18:01:01
196,750,757
0
0
null
null
null
null
GB18030
Java
false
false
1,163
java
package com.itheima.demo00_反馈和回顾; /* * 类名作为方法的参数 * 案例:杀人 * 总结:在调用方法时,我们需要传递的是 该类的对象,不是别类的对象也不是该类 * * * * 类名作为方法的返回值: * 案例:生孩子 * 实际上需要返回的是 该类的对象 不是该类,也不是别的类的对象 * * * */ public class TestDemo { public static void main(String[] args) { // TODO Auto-generated method stub //调用 Person p = new Person(); p.age = 18; p.name = "张三"; /*Dog d = new Dog(); d.name = "张三";*/ killPerson(p); //===== /* int a = 10; killInt(a);*/ //调用 Person p2 = newBaby(); System.out.println(p2.age+"..."+p2.name); } //生孩子 public static Person newBaby(){ //返回一个孩子对象 Person pp = new Person(); pp.age = 3; pp.name = "哪吒"; //返回这个孩子 return pp; } //杀人方法 public static void killPerson(Person person){//Person person = new Person() //怎么杀人 System.out.println("给老子去死:"+person.name); } /* public static void killInt(int a){ } */ }
835a8572c4576916f44c532faf87256b106e0570
589dcd422402477ce80e9c349bd483c2d36b80cd
/trunk/adhoc-internal/src/main/java/com/alimama/quanjingmonitor/topology/SumReduceBolt.java
3a17a00913e9395b6ce245ee5c68298e97231e53
[ "Apache-2.0", "LicenseRef-scancode-unicode-mappings", "BSD-3-Clause", "CDDL-1.0", "Python-2.0", "MIT", "ICU", "CPL-1.0" ]
permissive
baojiawei1230/mdrill
e3d92f4f1f85b34f0839f8463e7e5353145a9c78
edacdb4dc43ead6f14d83554c1f402aa1ffdec6a
refs/heads/master
2021-06-10T17:42:11.076927
2021-03-15T16:43:06
2021-03-15T16:43:06
95,193,877
0
0
Apache-2.0
2021-03-15T16:43:06
2017-06-23T07:15:00
Java
UTF-8
Java
false
false
4,160
java
package com.alimama.quanjingmonitor.topology; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.IRichBolt; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Tuple; /** create table quanjingmointor_pid( thedate string , hour string , miniute tdate , miniute5 tdate , logtype string , pid string, namemodle string, groupName string, datanum_a tlong, datanum_b tlong ) create table quanjingmointor_host( thedate string , hour string , miniute tdate , logtype string , groupName string, nodename string, dns_ip string, nodegroup string, product_name string, site string, datanum_a tlong, datanum_b tlong ) http://110.75.67.137:9999/sql.jsp?connstr=jdbc%3Amdrill%3A%2F%2Fpreadhoc.kgb.cm6%3A9999&sql=select+miniute%2Clogtype%2Ccount%28*%29%2Csum%28datanum%29+from+quanjingmointor+where+thedate%3C%3D%2720131025%27+and+thedate%3E%3D%2720131020%27+group+by+miniute%2Clogtype+order+by+miniute+desc++limit+0%2C1000&go=%E6%8F%90%E4%BA%A4%E6%9F%A5%E8%AF%A2 select miniute,logtype,count(*),sum(datanum_a) from quanjingmointor_pid where thedate='20131028' group by miniute,logtype order by miniute desc limit 0,100 select thedate,hour,miniute,logtype,pid,process,nodename,dns_ip,nodegroup,product_name,site,count(*),sum(datanum),sum(datanum_b),sum(datanum_c) from quanjingmointor where thedate='20131025' group by thedate,hour,miniute,logtype,pid,process,nodename,dns_ip,nodegroup,product_name,site order by miniute desc limit 0,10 */ public class SumReduceBolt implements IRichBolt { private static Logger LOG = Logger.getLogger(SumReduceBolt.class); private static final long serialVersionUID = 1L; public String type=""; public SumReduceBolt(String type) { this.type = type; } private OutputCollector collector=null; private volatile long index=0; private HashMap<BoltStatKey, BoltStatVal> nolockbuffer=null; private LastTimeBolt_chain1 lasttimeUp_chain1=null;//new LastTimeBolt(); private TimeOutCheck timeoutCheck=null; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.timeoutCheck=new TimeOutCheck(60*1000l); this.lasttimeUp_chain1=new LastTimeBolt_chain1(this, new LastTimeBolt_chain2_pid(this),new LastTimeBolt_chain2_host(this)); this.collector=collector; this.nolockbuffer=new HashMap<BoltStatKey, BoltStatVal>(10000); } private static int BUFFER_SIZE=10000; @Override public synchronized void execute(Tuple input) { BoltStatKey key=(BoltStatKey) input.getValue(0); BoltStatVal bv=(BoltStatVal)input.getValue(1); BoltStatVal statval=nolockbuffer.get(key); if(statval==null) { statval=new BoltStatVal(); nolockbuffer.put(key, statval); } statval.cnt+=bv.cnt; statval.cntnonclear+=bv.cntnonclear; this.index++; if((this.index%1000!=0)) { this.collector.ack(input); return; } boolean isNotOvertime=!this.timeoutCheck.istimeout(); if(isNotOvertime&&nolockbuffer.size()<BUFFER_SIZE) { this.collector.ack(input); return; } this.timeoutCheck.reset(); HashMap<BoltStatKey, BoltStatVal> buffer=nolockbuffer; nolockbuffer=new HashMap<BoltStatKey, BoltStatVal>(BUFFER_SIZE); this.lasttimeUp_chain1.updateAll(buffer,(Long)key.list[0]); LOG.info("bolt total="+this.index+",buffersize="+buffer.size()+","+this.lasttimeUp_chain1.toDebugString()); this.index=0; this.collector.ack(input); } @Override public void cleanup() { } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public Map<String, Object> getComponentConfiguration() { return new HashMap<String, Object>(); } }
eee42932d27777dd613075d5685eae25b7995c1f
0c11613c21ebe12f48d6cebb6339887e10e72219
/taobao-sdk-java/src/main/java/com/taobao/api/request/ItemcatsAuthorizeGetRequest.java
b52109aa639ce4bf43e964aa1fa6c1513bf4c1c5
[]
no_license
mustang2247/demo
a3347a2994448086814383c67757f659208368cd
35598ed0a3900afc759420b7100a7d310db2597d
refs/heads/master
2021-05-09T17:28:22.631386
2014-06-10T12:03:26
2014-06-10T12:03:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,111
java
package com.taobao.api.request; import java.util.Map; import java.util.Date; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.TaobaoRequest; /** * TOP API: taobao.itemcats.authorize.get request * * @author auto create * @since 1.0, 2010-08-13 10:11:33.0 */ public class ItemcatsAuthorizeGetRequest implements TaobaoRequest { private Long timestamp; private TaobaoHashMap textParams = new TaobaoHashMap(); /** * 需要返回的字段。目前支持有: brand.vid, brand.name, item_cat.cid, item_cat.name, item_cat.status,item_cat.sort_order,item_cat.parent_cid,item_cat.is_parent **/ private String fields; public void setFields(String fields) { this.fields = fields; } public String getFields() { return this.fields; } public String getApiMethodName() { return "taobao.itemcats.authorize.get"; } public Map<String, String> getTextParams() { textParams.put("fields", this.fields); return textParams; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
[ "Administrator@.(none)" ]
Administrator@.(none)
54c99b22c2d52f8547666042877daaee6e959031
6c925a0951d8e1c02b0e54e6b09596d3b3d823e9
/src/main/java/com/withing/Application.java
53e1fdb21f88749181c6afd64e6a72d53bf8524a
[]
no_license
Withingwolf/Struct-Spring4-Hibernate5
8f881897ed50fc6410390ded09ee7a2526565e6b
2ab390c89584ac6f7c5e8c2fb11df62f1640e48a
refs/heads/javaConfig
2022-12-28T22:04:36.120579
2019-07-23T15:33:13
2019-07-23T15:33:13
156,065,975
0
0
null
2022-12-16T11:53:52
2018-11-04T09:14:46
Java
UTF-8
Java
false
false
308
java
package com.withing; import org.hibernate.cfg.Configuration; import org.springframework.context.annotation.ComponentScan; @ComponentScan({"com.withing"}) public class Application { public static void main(String args[]) { Configuration configuration = new Configuration().configure(); } }
76328f803ecee89c8861821e78b11b9b454bc750
d2e5622fd4fa1f0bb3155887267e2fe2e1539130
/ch06/Loops.java
4f59564b07291716b98f6d4dd27ccaa581817f72
[ "MIT" ]
permissive
kylewehrung/ThinkJavaCode2
083b78ab4f6b630ac1bd3c0d8057ffe08b4602a8
9357e311d5828fa5648f6309ca1017f7b4e36804
refs/heads/master
2023-08-09T04:06:29.703745
2023-07-31T04:04:22
2023-07-31T04:04:22
668,109,325
0
0
MIT
2023-07-31T04:04:23
2023-07-19T03:47:27
Java
UTF-8
Java
false
false
2,032
java
/** * Demonstrates uses of loops. */ public class Loops { public static void countdown(int n) { while (n > 0) { System.out.println(n); n = n - 1; } System.out.println("Blastoff!"); } public static void sequence(int n) { while (n != 1) { System.out.println(n); if (n % 2 == 0) { // n is even n = n / 2; } else { // n is odd n = n * 3 + 1; } } } public static void plusplus() { int i = 1; while (i <= 5) { System.out.println(i); i++; // add 1 to i } } public static void appreciate() { int i = 2; while (i <= 8) { System.out.print(i + ", "); i += 2; // add 2 to i } System.out.println("Who do we appreciate?"); } public static void appreciate2() { for (int i = 2; i <= 8; i += 2) { System.out.print(i + ", "); } System.out.println("Who do we appreciate?"); } public static void loopvar() { int n; for (n = 3; n > 0; n--) { System.out.println(n); } System.out.println("n is now " + n); } public static void nested() { for (int x = 1; x <= 10; x++) { for (int y = 1; y <= 10; y++) { System.out.printf("%4d", x * y); } System.out.println(); } } public static void main(String[] args) { System.out.println("\ncountdown"); countdown(3); System.out.println("\nsequence"); sequence(10); System.out.println("\nplusplus"); plusplus(); System.out.println("\nappreciate"); appreciate(); System.out.println("\nappreciate2"); appreciate2(); System.out.println("\nloopvar"); loopvar(); System.out.println("\nnested"); nested(); } }
c9a49a014aaf386ac958b9f75fea5251b5ab5e05
fe31cf5611bc8c903b7ad685471c103203bd9ac4
/src/main/java/com/run/dataConversion/service/DeviceService.java
cb03cfbfacb60dfbc8abb175a6109068e9cb5943
[]
no_license
zhfly1992/dataConversion
c6673332db311d28b1be59b6f17ca9870b8ddb69
ae824cdd783856e76a083de1645cdd376550d47d
refs/heads/master
2023-01-13T07:35:50.887653
2020-11-04T06:58:15
2020-11-04T06:58:15
309,917,015
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package com.run.dataConversion.service; import com.alibaba.fastjson.JSONObject; import com.run.entity.common.Result; public interface DeviceService { /** * 向第三方IOT平台拉取设备信息 * * @param paramJson * @return */ public <T> Result<T> getDeviceInfoFromIOT(JSONObject paramJson); /** * 查询设备信息列表 * * @param paramJson * @return */ public Result<?> getDeviceInfoList(JSONObject paramJson); /** * * @Description:推送设备数据到locman,暂用 * @param paramJson * @return */ public Result<String> pushDeviceToLocman(JSONObject paramJson); }
[ "zhanghe" ]
zhanghe
dc08ae30a8bcdd2a9305e7e3e256691906be1c26
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/checkstyle_cluster/702/tar_1.java
cf6a5104dd9854c406d3d31e1b2f3da7789133e3
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
22,783
java
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.AbstractLoader; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Loads a configuration from a standard configuration XML file. * * @author Oliver Burn */ public final class ConfigurationLoader { /** Logger for ConfigurationLoader. */ private static final Log LOG = LogFactory.getLog(ConfigurationLoader.class); /** the public ID for version 1_0 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_0 = "-//Puppy Crawl//DTD Check Configuration 1.0//EN"; /** the resource for version 1_0 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_0 = "com/puppycrawl/tools/checkstyle/configuration_1_0.dtd"; /** the public ID for version 1_1 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_1 = "-//Puppy Crawl//DTD Check Configuration 1.1//EN"; /** the resource for version 1_1 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_1 = "com/puppycrawl/tools/checkstyle/configuration_1_1.dtd"; /** the public ID for version 1_2 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_2 = "-//Puppy Crawl//DTD Check Configuration 1.2//EN"; /** the resource for version 1_2 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_2 = "com/puppycrawl/tools/checkstyle/configuration_1_2.dtd"; /** the public ID for version 1_3 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_3 = "-//Puppy Crawl//DTD Check Configuration 1.3//EN"; /** the resource for version 1_3 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_3 = "com/puppycrawl/tools/checkstyle/configuration_1_3.dtd"; /** * Implements the SAX document handler interfaces, so they do not * appear in the public API of the ConfigurationLoader. */ private final class InternalLoader extends AbstractLoader { /** module elements */ private static final String MODULE = "module"; /** name attribute */ private static final String NAME = "name"; /** property element */ private static final String PROPERTY = "property"; /** value attribute */ private static final String VALUE = "value"; /** default attribute */ private static final String DEFAULT = "default"; /** name of the severity property */ private static final String SEVERITY = "severity"; /** name of the message element */ private static final String MESSAGE = "message"; /** name of the key attribute */ private static final String KEY = "key"; /** * Creates a new InternalLoader. * @throws SAXException if an error occurs * @throws ParserConfigurationException if an error occurs */ public InternalLoader() throws SAXException, ParserConfigurationException { // super(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); super(createIdToResourceNameMap()); } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (qName.equals(MODULE)) { //create configuration final String name = atts.getValue(NAME); final DefaultConfiguration conf = new DefaultConfiguration(name); if (configuration == null) { configuration = conf; } //add configuration to it's parent if (!configStack.isEmpty()) { final DefaultConfiguration top = configStack.peek(); top.addChild(conf); } configStack.push(conf); } else if (qName.equals(PROPERTY)) { //extract value and name final String value; try { value = replaceProperties(atts.getValue(VALUE), overridePropsResolver, atts.getValue(DEFAULT)); } catch (final CheckstyleException ex) { throw new SAXException(ex.getMessage()); } final String name = atts.getValue(NAME); //add to attributes of configuration final DefaultConfiguration top = configStack.peek(); top.addAttribute(name, value); } else if (qName.equals(MESSAGE)) { //extract key and value final String key = atts.getValue(KEY); final String value = atts.getValue(VALUE); //add to messages of configuration final DefaultConfiguration top = configStack.peek(); top.addMessage(key, value); } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (qName.equals(MODULE)) { final Configuration recentModule = configStack.pop(); // remove modules with severity ignore if these modules should // be omitted SeverityLevel level = null; try { final String severity = recentModule.getAttribute(SEVERITY); level = SeverityLevel.getInstance(severity); } catch (final CheckstyleException e) { LOG.debug("Severity not set, ignoring exception", e); } // omit this module if these should be omitted and the module // has the severity 'ignore' final boolean omitModule = omitIgnoredModules && SeverityLevel.IGNORE == level; if (omitModule && !configStack.isEmpty()) { final DefaultConfiguration parentModule = configStack.peek(); parentModule.removeChild(recentModule); } } } } /** the SAX document handler */ private final InternalLoader saxHandler; /** property resolver **/ private final PropertyResolver overridePropsResolver; /** the loaded configurations **/ private final Deque<DefaultConfiguration> configStack = new ArrayDeque<>(); /** the Configuration that is being built */ private Configuration configuration; /** flags if modules with the severity 'ignore' should be omitted. */ private final boolean omitIgnoredModules; /** * Creates a new <code>ConfigurationLoader</code> instance. * @param overrideProps resolver for overriding properties * @param omitIgnoredModules <code>true</code> if ignored modules should be * omitted * @throws ParserConfigurationException if an error occurs * @throws SAXException if an error occurs */ private ConfigurationLoader(final PropertyResolver overrideProps, final boolean omitIgnoredModules) throws ParserConfigurationException, SAXException { saxHandler = new InternalLoader(); overridePropsResolver = overrideProps; this.omitIgnoredModules = omitIgnoredModules; } /** * Creates mapping between local resources and dtd ids. * @return map between local resources and dtd ids. */ private static Map<String, String> createIdToResourceNameMap() { final Map<String, String> map = Maps.newHashMap(); map.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0); map.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); map.put(DTD_PUBLIC_ID_1_2, DTD_RESOURCE_NAME_1_2); map.put(DTD_PUBLIC_ID_1_3, DTD_RESOURCE_NAME_1_3); return map; } /** * Parses the specified input source loading the configuration information. * The stream wrapped inside the source, if any, is NOT * explicitely closed after parsing, it is the responsibility of * the caller to close the stream. * * @param source the source that contains the configuration data * @throws IOException if an error occurs * @throws SAXException if an error occurs */ private void parseInputSource(InputSource source) throws IOException, SAXException { saxHandler.parseInputSource(source); } /** * Returns the module configurations in a specified file. * @param config location of config file, can be either a URL or a filename * @param overridePropsResolver overriding properties * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(String config, PropertyResolver overridePropsResolver) throws CheckstyleException { return loadConfiguration(config, overridePropsResolver, false); } /** * Returns the module configurations in a specified file. * * @param config location of config file, can be either a URL or a filename * @param overridePropsResolver overriding properties * @param omitIgnoredModules <code>true</code> if modules with severity * 'ignore' should be omitted, <code>false</code> otherwise * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(String config, PropertyResolver overridePropsResolver, boolean omitIgnoredModules) throws CheckstyleException { try { // figure out if this is a File or a URL URI uri; try { final URL url = new URL(config); uri = url.toURI(); } catch (final MalformedURLException ex) { uri = null; } catch (final URISyntaxException ex) { // URL violating RFC 2396 uri = null; } if (uri == null) { final File file = new File(config); if (file.exists()) { uri = file.toURI(); } else { // check to see if the file is in the classpath try { final URL configUrl = ConfigurationLoader.class .getResource(config); if (configUrl == null) { throw new FileNotFoundException(config); } uri = configUrl.toURI(); } catch (final URISyntaxException e) { throw new FileNotFoundException(config); } } } final InputSource source = new InputSource(uri.toString()); return loadConfiguration(source, overridePropsResolver, omitIgnoredModules); } catch (final FileNotFoundException e) { throw new CheckstyleException("unable to find " + config, e); } catch (final CheckstyleException e) { //wrap again to add file name info throw new CheckstyleException("unable to read " + config + " - " + e.getMessage(), e); } } /** * Returns the module configurations from a specified input stream. * Note that clients are required to close the given stream by themselves * * @param configStream the input stream to the Checkstyle configuration * @param overridePropsResolver overriding properties * @param omitIgnoredModules <code>true</code> if modules with severity * 'ignore' should be omitted, <code>false</code> otherwise * @return the check configurations * @throws CheckstyleException if an error occurs * * @deprecated As this method does not provide a valid system ID, * preventing resolution of external entities, a * {@link #loadConfiguration(InputSource,PropertyResolver,boolean) * version using an InputSource} * should be used instead */ @Deprecated public static Configuration loadConfiguration(InputStream configStream, PropertyResolver overridePropsResolver, boolean omitIgnoredModules) throws CheckstyleException { return loadConfiguration(new InputSource(configStream), overridePropsResolver, omitIgnoredModules); } /** * Returns the module configurations from a specified input source. * Note that if the source does wrap an open byte or character * stream, clients are required to close that stream by themselves * * @param configSource the input stream to the Checkstyle configuration * @param overridePropsResolver overriding properties * @param omitIgnoredModules <code>true</code> if modules with severity * 'ignore' should be omitted, <code>false</code> otherwise * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(InputSource configSource, PropertyResolver overridePropsResolver, boolean omitIgnoredModules) throws CheckstyleException { try { final ConfigurationLoader loader = new ConfigurationLoader(overridePropsResolver, omitIgnoredModules); loader.parseInputSource(configSource); return loader.getConfiguration(); } catch (final ParserConfigurationException e) { throw new CheckstyleException( "unable to parse configuration stream", e); } catch (final SAXParseException e) { throw new CheckstyleException("unable to parse configuration stream" + " - " + e.getMessage() + ":" + e.getLineNumber() + ":" + e.getColumnNumber(), e); } catch (final SAXException e) { throw new CheckstyleException("unable to parse configuration stream" + " - " + e.getMessage(), e); } catch (final IOException e) { throw new CheckstyleException("unable to read from stream", e); } } /** * Returns the configuration in the last file parsed. * @return Configuration object */ private Configuration getConfiguration() { return configuration; } /** * Replaces <code>${xxx}</code> style constructions in the given value * with the string value of the corresponding data types. * * The method is package visible to facilitate testing. * * @param value The string to be scanned for property references. * May be <code>null</code>, in which case this * method returns immediately with no effect. * @param props Mapping (String to String) of property names to their * values. Must not be <code>null</code>. * @param defaultValue default to use if one of the properties in value * cannot be resolved from props. * * @return the original string with the properties replaced, or * <code>null</code> if the original string is <code>null</code>. * @throws CheckstyleException if the string contains an opening * <code>${</code> without a closing * <code>}</code> * * Code copied from ant - * http://cvs.apache.org/viewcvs/jakarta-ant/src/main/org/apache/tools/ant/ProjectHelper.java */ // Package visible for testing purposes static String replaceProperties( String value, PropertyResolver props, String defaultValue) throws CheckstyleException { if (value == null) { return null; } final List<String> fragments = Lists.newArrayList(); final List<String> propertyRefs = Lists.newArrayList(); parsePropertyString(value, fragments, propertyRefs); final StringBuilder sb = new StringBuilder(); final Iterator<String> i = fragments.iterator(); final Iterator<String> j = propertyRefs.iterator(); while (i.hasNext()) { String fragment = i.next(); if (fragment == null) { final String propertyName = j.next(); fragment = props.resolve(propertyName); if (fragment == null) { if (defaultValue != null) { return defaultValue; } throw new CheckstyleException( "Property ${" + propertyName + "} has not been set"); } } sb.append(fragment); } return sb.toString(); } /** * Parses a string containing <code>${xxx}</code> style property * references into two lists. The first list is a collection * of text fragments, while the other is a set of string property names. * <code>null</code> entries in the first list indicate a property * reference from the second list. * * @param value Text to parse. Must not be <code>null</code>. * @param fragments List to add text fragments to. * Must not be <code>null</code>. * @param propertyRefs List to add property names to. * Must not be <code>null</code>. * * @throws CheckstyleException if the string contains an opening * <code>${</code> without a closing * <code>}</code> * Code copied from ant - * http://cvs.apache.org/viewcvs/jakarta-ant/src/main/org/apache/tools/ant/ProjectHelper.java */ private static void parsePropertyString(String value, List<String> fragments, List<String> propertyRefs) throws CheckstyleException { int prev = 0; //search for the next instance of $ from the 'prev' position int pos = value.indexOf('$', prev); while (pos >= 0) { //if there was any text before this, add it as a fragment if (pos > 0) { fragments.add(value.substring(prev, pos)); } //if we are at the end of the string, we tack on a $ //then move past it if (pos == value.length() - 1) { fragments.add("$"); prev = pos + 1; } else if (value.charAt(pos + 1) != '{') { //peek ahead to see if the next char is a property or not //not a property: insert the char as a literal /* fragments.addElement(value.substring(pos + 1, pos + 2)); prev = pos + 2; */ if (value.charAt(pos + 1) == '$') { //backwards compatibility two $ map to one mode fragments.add("$"); prev = pos + 2; } else { //new behaviour: $X maps to $X for all values of X!='$' fragments.add(value.substring(pos, pos + 2)); prev = pos + 2; } } else { //property found, extract its name or bail on a typo final int endName = value.indexOf('}', pos); if (endName < 0) { throw new CheckstyleException("Syntax error in property: " + value); } final String propertyName = value.substring(pos + 2, endName); fragments.add(null); propertyRefs.add(propertyName); prev = endName + 1; } //search for the next instance of $ from the 'prev' position pos = value.indexOf('$', prev); } //no more $ signs found //if there is any tail to the file, append it if (prev < value.length()) { fragments.add(value.substring(prev)); } } }
4108d76511501757496f551599de54e641365d4e
e7861c0ed1b49224b6c4ccf6dbfc63be61a026e5
/JAVA/12월 17일 스트림끝 컬렉션시작 set ArrayList/차주님/testCollectionProject/src/test/list/TestPersonArrayList.java
093db420cf08d15cd31b07642d44c4fbf1677857
[]
no_license
kdw912001/kh
7d7610b4ddaab286714131d1c9108373f6c920a9
73c511db0723e0bc49258d8d146ba6f8ee9db762
refs/heads/master
2020-04-06T10:19:58.220792
2019-05-03T18:41:57
2019-05-03T18:41:57
157,376,594
1
0
null
null
null
null
UTF-8
Java
false
false
719
java
package test.list; import java.util.*; public class TestPersonArrayList { public static void main(String[] args) { // Person 저장용 ArrayList 사용 ArrayList list = new ArrayList(); list.add(new Person("홍길동", 25, 1537.5)); list.add(new Person("이순신", 49, 15789.0)); list.add(new Person("신사임당", 55, 34567.4)); System.out.println(list); for(Object obj : list) { System.out.println(obj); } //각 객체가 가진 포인트 값의 합계를 구함 double totalPoint = 0.; for(int i = 0; i < list.size(); i++) { Person p = (Person)list.get(i); totalPoint += p.getPoint(); } System.out.println("포인트 총합 : " + totalPoint); } }
aedc1f034a64eda691d9ca989aff167a42a622b0
372a2654cd32a36711b4d3391c57d191d4b857ab
/Algorithms/Algorithms/src/educative/extras/EducativeExtras.java
c2304e2e39c48940f469b1463a8298b493b53a36
[]
no_license
Abhinav11M/LeetCode
77365b262d9cdb84ab2fdaf7566db47403e6ef6d
1c37d8bd616fb51fc63b22a220bd9ccbeea241a4
refs/heads/master
2021-09-01T21:48:29.270740
2021-08-10T14:44:19
2021-08-10T14:44:19
201,512,337
0
0
null
2021-03-31T21:46:19
2019-08-09T17:23:57
Java
UTF-8
Java
false
false
1,084
java
package educative.extras; import java.util.ArrayList; import java.util.List; public class EducativeExtras { public static List<List<Integer>> findSubarrays(int[] arr, int target) { List<List<Integer>> result = new ArrayList<>(); for(int i = 0; i < arr.length; ++i) { List<Integer> list = new ArrayList<>(); list.add(arr[i]); findSubArrays(arr, target, i+1, result, list, arr[i]); } return result; } private static void findSubArrays(int[] arr, int target, int index, List<List<Integer>> result, List<Integer> list, int product) { if(product >= target || index >= arr.length) { return; } if(product < target) { result.add(new ArrayList<Integer>(list)); } list.add(arr[index]); product = product * arr[index]; findSubArrays(arr, target, index+1, result, list, product); } public boolean subsetSumExists(int[] num, int sum) { boolean[] dp = new boolean[sum+1]; // Sum 0 can be achieved by not choosing anything dp[0] = true; for(int i = 0; i <= sum; ++i) { // dp[i] = dp[] } return false; } }
bc31b2791a04c4437c841c8ee4a8765bcdd7b269
266a0d256916312b6b6c6830a873a54b70f93028
/springboot-shiro/src/main/java/com/xiaopengwei/sprngboot/shiro/web/HomeController.java
af6b8283ce31610781769891c91ba7ae1c71af6e
[ "MIT" ]
permissive
xpwi/springboot-multi-example
625216d35f8e7f86474be718abde5818d0829e8a
db58146036daf1a2c0d01c9b6ed83fb663104f78
refs/heads/master
2023-07-22T22:20:18.664489
2023-07-20T15:37:13
2023-07-20T15:37:13
182,486,524
12
10
MIT
2023-07-18T20:52:21
2019-04-21T03:45:07
Java
UTF-8
Java
false
false
2,483
java
package com.xiaopengwei.sprngboot.shiro.web; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * <p> * 前置控制器 * </p> * * @author github.com/xpwi * @since 2019-04-21 */ @Controller public class HomeController { /** * 索引 * * @return java.lang.String * @author github.com/xpwi */ @RequestMapping({"/", "/index"}) public String index() { return "/index"; } /** * 登录 * * @param request * @param map * @return java.lang.String * @author github.com/xpwi */ @RequestMapping("/login") public String login(HttpServletRequest request, Map<String, Object> map) throws Exception { System.out.println("HomeController.login()"); // 登录失败从 request 中获取 shiro 处理的异常信息. // shiroLoginFailure: 就是 shiro 异常类的全类名. String exception = (String) request.getAttribute("shiroLoginFailure"); System.out.println("exception=" + exception); String msg = ""; if (exception != null) { if (UnknownAccountException.class.getName().equals(exception)) { System.out.println("UnknownAccountException -- > 账号不存在:"); msg = "UnknownAccountException -- > 账号不存在:"; } else if (IncorrectCredentialsException.class.getName().equals(exception)) { System.out.println("IncorrectCredentialsException -- > 密码不正确:"); msg = "IncorrectCredentialsException -- > 密码不正确:"; } else if ("kaptchaValidateFailed".equals(exception)) { System.out.println("kaptchaValidateFailed -- > 验证码错误"); msg = "kaptchaValidateFailed -- > 验证码错误"; } else { msg = "else >> " + exception; System.out.println("else -- >" + exception); } } map.put("msg", msg); // 此方法不处理登录成功,由 shiro 进行处理 return "/login"; } @RequestMapping("/403") public String unauthorizedRole() { System.out.println("------没有权限-------"); return "403"; } }
5be2479b35ab32cc36ad8ed069bbfca125a9d7a4
33d6261fb8d118a965434deb9f588d601ccfe61e
/SpagoBICockpitEngine/src/it/eng/spagobi/engine/cockpit/api/crosstable/FieldOptions.java
45c9f4e1d3143cf36212524390868a7a6c3ae873
[]
no_license
svn2github/SpagoBI-V4x
8980656ec888782ea2ffb5a06ffa60b5c91849ee
b6cb536106644e446de2d974837ff909bfa73b58
refs/heads/master
2020-05-28T02:52:31.002963
2015-01-16T11:17:54
2015-01-16T11:17:54
10,394,712
3
6
null
null
null
null
UTF-8
Java
false
false
889
java
/* SpagoBI, the Open Source Business Intelligence suite * Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice. * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package it.eng.spagobi.engine.cockpit.api.crosstable; import java.util.List; public class FieldOptions { protected Field field = null; private List<FieldOption> options = null; public List<FieldOption> getOptions() { return options; } public void setOptions(List<FieldOption> options) { this.options = options; } public Field getField() { return field; } public void setField(Field field) { this.field = field; } }
[ "aalagna@99afaf0d-6903-0410-885a-c66a8bbb5f81" ]
aalagna@99afaf0d-6903-0410-885a-c66a8bbb5f81
9e28ccfd8fd992d8da67c00441070bcd0b0f9468
2628171d098a7f404cd2c6e194032b688d03c49d
/app/src/main/java/com/example/second_assignment/models/User.java
8b3a2d7a7573e6de0c3c568d89e9e8249055c82f
[]
no_license
bibektamang873/Second_Assignment
5965e5797e9e9abcfd6c7ce99df2c1c976d17cdb
9d12d1cae9b88d0bcef73f5bdd22f1c55f6cfe38
refs/heads/master
2020-09-09T08:36:41.110918
2020-01-27T05:07:26
2020-01-27T05:07:26
221,401,795
0
0
null
null
null
null
UTF-8
Java
false
false
975
java
package com.example.second_assignment.models; import java.io.Serializable; public class User implements Serializable { private String fullName, gender,dob, country, email, contact; private int image; public User(String fullName, String gender, String dob, String country, String email, String contact, int image) { this.fullName = fullName; this.gender = gender; this.dob = dob; this.country = country; this.email = email; this.contact = contact; this.image = image; } public String getFullName() { return fullName; } public String getGender() { return gender; } public String getDob() { return dob; } public String getCountry() { return country; } public String getEmail() { return email; } public String getContact() { return contact; } public int getImage() { return image; } }
0f02284e36dd514b3857f174e45b69c07902052d
fdae1f3cdb8009a335c682bbe42fce50d4ef684d
/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/RestSqlStatsAction.java
8f5d75008c9db69dda5213b9decaa15f2eaf8baa
[ "Elastic-2.0", "LicenseRef-scancode-elastic-license-2018", "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-other-permissive" ]
permissive
hackery/elasticsearch
6239e18223c6b8481fd618eea8fa471802418395
4e392e118fcc4f6c0058294d07ac89913e9945ac
refs/heads/master
2021-06-03T21:46:57.381022
2019-06-12T13:54:28
2019-06-12T13:54:28
79,211,925
0
0
Apache-2.0
2019-06-12T14:29:02
2017-01-17T09:37:11
Java
UTF-8
Java
false
false
1,780
java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.sql.plugin; import org.apache.logging.log4j.LogManager; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestActions; import org.elasticsearch.xpack.sql.proto.Protocol; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; public class RestSqlStatsAction extends BaseRestHandler { private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(RestSqlStatsAction.class)); protected RestSqlStatsAction(Settings settings, RestController controller) { super(settings); // TODO: remove deprecated endpoint in 8.0.0 controller.registerWithDeprecatedHandler( GET, Protocol.SQL_STATS_REST_ENDPOINT, this, GET, Protocol.SQL_STATS_DEPRECATED_REST_ENDPOINT, deprecationLogger); } @Override public String getName() { return "sql_stats"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { SqlStatsRequest request = new SqlStatsRequest(); return channel -> client.execute(SqlStatsAction.INSTANCE, request, new RestActions.NodesResponseRestListener<>(channel)); } }
3aa07e667a6e67b065a730c04689cc0523426e7f
5ae9f92bfc06a35f803574a33b1bbf4678d703fe
/src/main/java/com/leti/social_net/services/servicesImpl/NetworkPlaceholder.java
d4e979b2090dbf327fe67adfb60c501ef7cc120b
[]
no_license
ussernamenikita/Java_lessons
e808fc2c1a01ebdab04fe9d7cd0f3bae18d2d7f8
f6ca7ced131ef50b060a34f936fb499792685668
refs/heads/master
2021-08-31T00:10:14.094318
2017-12-19T23:12:29
2017-12-19T23:12:29
110,440,934
0
0
null
null
null
null
UTF-8
Java
false
false
4,871
java
package com.leti.social_net.services.servicesImpl; import com.leti.social_net.dao.FriendsDao; import com.leti.social_net.dao.MessagesDao; import com.leti.social_net.dao.PostsDao; import com.leti.social_net.dao.UserDao; import com.leti.social_net.models.Message; import com.leti.social_net.models.Post; import com.leti.social_net.models.Token; import com.leti.social_net.models.User; import com.leti.social_net.services.NetworkService; import javafx.util.Pair; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Interface implementation * for work with network */ @Service public class NetworkPlaceholder implements NetworkService { /** * Standard logger */ private static Logger Log = Logger.getLogger(NetworkPlaceholder.class); @Autowired UserDao userDao; @Autowired FriendsDao friendsDao; @Autowired MessagesDao messagesDao; @Autowired PostsDao postsDao; @Override public String getToken(String userName, String password) { String t = Token.getToken(userName, password); Integer value = Token.getIdFromToken(t, this); if (value == null || value == -1) { return null; } return t; } private User findUserById(int id) { return userDao.getParticularUser(id); } @Override public void sendMessage(Message msg) { messagesDao.putMessage(msg); } @Override public void addUserToFriend(String token, int userId) { Integer i = Token.getIdFromToken(token,this); if(i == null) { return; } if(isFriends(i,userId)) { return; } User currentUser = findUserById(i); User newFriend = findUserById(userId); if (currentUser != null && newFriend != null) { friendsDao.addFriends(currentUser,newFriend); } } @Override public Pair<Long, List<Post>> getMyRecentPosts(String token, long offset, int limit) { Integer id = Token.getIdFromToken(token,this);; if(id == null) return null; User user = userDao.getParticularUser(id); List<Post> posts = postsDao.getRecentPosts(user,offset,limit); Long newV = (long) (posts != null ? posts.size() : 0); newV= newV+offset-1; return new Pair<>(newV, posts) ; } @Override public Pair<Long, List<Post>> getRecentPosts(long offset, int limit) { List<Post> posts = postsDao.getRecentPosts(offset,limit); Long newV = (long) (posts != null ? posts.size() : 0); newV= newV+offset-1; return new Pair<Long,List<Post>>(newV,posts) ; } @Override public int getFriendsCount(String token) { Integer id = Token.getIdFromToken(token,this);; if(id == null) return 0; User user = new User(); user.setId(id); List<User> list = friendsDao.getFriends(user); return list == null ? 0 : list.size(); } @Override public List<User> getUserFriends(String token, int limit, int offset) { Integer id = Token.getIdFromToken(token,this);; if(id != null) { User u = new User(); u.setId(id); return friendsDao.getFriends(u,limit,offset); } return null; } @Override public boolean isFriends(Integer userId, Integer userTo) { User u1 = new User(); u1.setId(userId); User u2 = new User(); u2.setId(userTo); List<User> list = friendsDao.getFriends(u1); return list != null && list.contains(u2); } @Override public boolean isFriends(String token, Integer secondUsrId) { Integer integer = Token.getIdFromToken(token,this);; return isFriends(integer,secondUsrId); } @Override public List<Message> getMessgaes(User userTo, User userFrom) { List<Message> msg = messagesDao.getMessages(userFrom,userTo); msg.sort((o1, o2) -> (int) (o1.getSendTimestamp() - o2.getSendTimestamp())); return msg; } @Override public User getUserByLoginAndPassword(String login, String password) { return userDao.getUserByLoginAndPassword(login,password); } @Override public boolean userExist(String username) { User user = userDao.getUserByLogin(username); return user != null; } @Override public User getUser(Integer id) { if(id == null) return null; return userDao.getParticularUser(id); } @Override public void post(Post post) { postsDao.insertPost(post); } @Override public int addUser(User user) { return userDao.insertOrUpdate(user); } }
1b52bc9bbb30bf2a346d5e556b508ad81b00d1e4
d2877a344523e465c4a111f905fb7e065d8cea48
/Aula_Invertida_MarcusV/src/aula_threads/ThreadRacer.java
5bc94b4639f02d408e92e919f7341513ed4edb64
[]
no_license
MarcusVLMA/sistemasDistribuidos
9e396277b8199529b273e53e2d9e489fd564d4f4
fc833cdee385e266458591147a29af4f4022755a
refs/heads/master
2020-03-27T03:17:21.312342
2018-09-18T12:41:08
2018-09-18T12:41:08
145,851,327
0
0
null
null
null
null
UTF-8
Java
false
false
412
java
package aula_threads; public class ThreadRacer extends Thread { private String i; public ThreadRacer(String i) { this.i = i; } public void run() { while(true) { System.out.println("[Thread] O corredor " + i + " está correndo. Vrruuuummmm"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
4913765f4f796d09960f19d174e7462cc6828810
b5d06b06fdd7ccc1598d6a130fa68ec737698d15
/src/com/briup/ch05/ModifySuper.java
37f579678b3238d3f4fbe2bac7c69c41fd11da72
[]
no_license
larrybriup/coreJava
9d8ce75f4bc08eac47ccf3e20825e60b3d5acf6e
f4d43f90a4055cb5eb999f368b888dc9544a7788
refs/heads/master
2020-05-20T05:36:26.526630
2015-07-12T06:43:13
2015-07-12T06:43:13
38,557,615
0
0
null
null
null
null
UTF-8
Java
false
false
456
java
package com.briup.ch05; public class ModifySuper{ protected int num; String msg; public String desc; private boolean tags; } class ModifyTest{ int i; public void show(){ ModifySuper modify = new ModifySuper(); // modify.tags = true;//同包不同类私有无法调 modify.msg = "msg"; modify.num = 0; modify.desc = "desc"; } public static void main(String[] args){ ModifyTest mt = new ModifyTest(); mt.i = 100; mt.show(); } }
54ee424fe9352895a5e79f3c23e7c9b4423b142f
c993df52a3285f1cae76ad1d8af3f9ffeb3bc1e7
/src/main/java/com/bocs/sys/model/DecorationDegree.java
de21af701f123826641d87045564926c8845204e
[]
no_license
SongQi1/kbcrm
b06deda299c8b1c2ffffc61e4bb4a434024ccd82
81a4963738114e1d48649ca5caad37f0b2016182
refs/heads/master
2021-05-04T21:53:00.485855
2018-02-02T13:04:16
2018-02-02T13:04:16
119,980,253
1
0
null
null
null
null
UTF-8
Java
false
false
479
java
package com.bocs.sys.model; import com.baomidou.mybatisplus.annotations.TableName; import com.bocs.core.base.BaseModel; import java.io.Serializable; /** * <p> * 装修程度 * </p> * * @author SongQi * @since 2017-09-09 */ @TableName("sys_decoration_degree") @SuppressWarnings("serial") public class DecorationDegree extends BaseModel { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
30487495ec6025518272624e014f81357fa2ec38
97984bff4c1257db1f56a2621de8cb61c651eeb3
/app/src/main/java/com/example/schedulemai/lesson/UnknownLesson.java
3ad17614ddd228ac72971d2bf1ae74d5fe2e1782
[]
no_license
ilyanovv/schedule-app
1de3235ccbd6a9fecbe78707d4c02c1b66bc9284
46f72a6df7530291cdb77d6f24dad465c11f98ab
refs/heads/master
2021-01-24T02:59:58.517642
2018-06-11T16:54:00
2018-06-11T16:54:00
122,872,266
0
0
null
null
null
null
UTF-8
Java
false
false
625
java
package com.example.schedulemai.lesson; import com.example.schedulemai.R; /** * Created by IO.Novikov on 01.04.2018. */ public class UnknownLesson extends Lesson { public UnknownLesson(String recordId, String name, String teacher, String lessonType, String timeBegin, String timeEnd, String classroom, String lessonDate, String groupNumber) { super(recordId, name, teacher, LessonType.UNKNOWN.getName(), timeBegin, timeEnd, classroom, lessonDate, groupNumber); } @Override public int getBackgroundStyle() { return R.drawable.lab_back; } }
f4edce8f562c5053c11ee83bbf5596c52d33dcad
7dd73504d783c7ebb0c2e51fa98dea2b25c37a11
/eaglercraft-main/eaglercraft-main/sp-server/src/main/java/net/minecraft/src/GenLayerShore.java
6e5f4fe26bd802a5ea9ed01f1150efa524361c1e
[ "CC-BY-NC-4.0" ]
permissive
bagel-man/bagel-man.github.io
32813dd7ef0b95045f53718a74ae1319dae8c31e
eaccb6c00aa89c449c56a842052b4e24f15a8869
refs/heads/master
2023-04-05T10:27:26.743162
2023-03-16T04:24:32
2023-03-16T04:24:32
220,102,442
3
21
MIT
2022-12-14T18:44:43
2019-11-06T22:29:24
C++
UTF-8
Java
false
false
2,889
java
package net.minecraft.src; public class GenLayerShore extends GenLayer { public GenLayerShore(long par1, GenLayer par3GenLayer) { super(par1); this.parent = par3GenLayer; } /** * Returns a list of integer values generated by this layer. These may be * interpreted as temperatures, rainfall amounts, or biomeList[] indices based * on the particular GenLayer subclass. */ public int[] getInts(int par1, int par2, int par3, int par4) { int[] var5 = this.parent.getInts(par1 - 1, par2 - 1, par3 + 2, par4 + 2); int[] var6 = IntCache.getIntCache(par3 * par4); for (int var7 = 0; var7 < par4; ++var7) { for (int var8 = 0; var8 < par3; ++var8) { this.initChunkSeed((long) (var8 + par1), (long) (var7 + par2)); int var9 = var5[var8 + 1 + (var7 + 1) * (par3 + 2)]; int var10; int var11; int var12; int var13; if (var9 == BiomeGenBase.mushroomIsland.biomeID) { var10 = var5[var8 + 1 + (var7 + 1 - 1) * (par3 + 2)]; var11 = var5[var8 + 1 + 1 + (var7 + 1) * (par3 + 2)]; var12 = var5[var8 + 1 - 1 + (var7 + 1) * (par3 + 2)]; var13 = var5[var8 + 1 + (var7 + 1 + 1) * (par3 + 2)]; if (var10 != BiomeGenBase.ocean.biomeID && var11 != BiomeGenBase.ocean.biomeID && var12 != BiomeGenBase.ocean.biomeID && var13 != BiomeGenBase.ocean.biomeID) { var6[var8 + var7 * par3] = var9; } else { var6[var8 + var7 * par3] = BiomeGenBase.mushroomIslandShore.biomeID; } } else if (var9 != BiomeGenBase.ocean.biomeID && var9 != BiomeGenBase.river.biomeID && var9 != BiomeGenBase.swampland.biomeID && var9 != BiomeGenBase.extremeHills.biomeID) { var10 = var5[var8 + 1 + (var7 + 1 - 1) * (par3 + 2)]; var11 = var5[var8 + 1 + 1 + (var7 + 1) * (par3 + 2)]; var12 = var5[var8 + 1 - 1 + (var7 + 1) * (par3 + 2)]; var13 = var5[var8 + 1 + (var7 + 1 + 1) * (par3 + 2)]; if (var10 != BiomeGenBase.ocean.biomeID && var11 != BiomeGenBase.ocean.biomeID && var12 != BiomeGenBase.ocean.biomeID && var13 != BiomeGenBase.ocean.biomeID) { var6[var8 + var7 * par3] = var9; } else { var6[var8 + var7 * par3] = BiomeGenBase.beach.biomeID; } } else if (var9 == BiomeGenBase.extremeHills.biomeID) { var10 = var5[var8 + 1 + (var7 + 1 - 1) * (par3 + 2)]; var11 = var5[var8 + 1 + 1 + (var7 + 1) * (par3 + 2)]; var12 = var5[var8 + 1 - 1 + (var7 + 1) * (par3 + 2)]; var13 = var5[var8 + 1 + (var7 + 1 + 1) * (par3 + 2)]; if (var10 == BiomeGenBase.extremeHills.biomeID && var11 == BiomeGenBase.extremeHills.biomeID && var12 == BiomeGenBase.extremeHills.biomeID && var13 == BiomeGenBase.extremeHills.biomeID) { var6[var8 + var7 * par3] = var9; } else { var6[var8 + var7 * par3] = BiomeGenBase.extremeHillsEdge.biomeID; } } else { var6[var8 + var7 * par3] = var9; } } } return var6; } }
e9692c7132f6afe03aa733790ed51425d0027835
148a1c077eaf30f68e0afb271d3f444150f6d9c1
/drools-spring-app/src/main/java/sbnz/integracija/example/util/JwtUtil.java
71fa9cb3defda13e67b69346f3a7a2447c6a7863
[]
no_license
anja-meseldzic/SBNZ-projekat
c086b575009467af916a1387828ddd7b601bbb85
7cb08a815ee52c4db7e8659d45d907c720853860
refs/heads/main
2023-08-16T14:48:39.208386
2021-09-12T20:19:49
2021-09-12T20:19:49
357,122,253
0
0
null
null
null
null
UTF-8
Java
false
false
2,389
java
package sbnz.integracija.example.util; import java.util.Date; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JwtUtil { private final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS512; private final int EXPIRES_IN = 3000000; @Value("juubi") private String secret; private final String AUTH_HEADER = "Authorization"; public String generateJwt(UserClaims claims) { JwtBuilder builder = Jwts.builder(); builder.setIssuedAt(new Date()) .setExpiration(generateExpirationDate()) .signWith(SIGNATURE_ALGORITHM, this.secret); for(String claim : claims.getClaims()) builder.claim(claim, claims.getClaimValue(claim)); return builder.compact(); } public UserClaims decodeJwt(String jwt, Set<String> claims) { Claims allClaims = getAllClaimsFromToken(jwt); UserClaims userClaims = new UserClaims(); for(String claim : claims) userClaims.setClaimValue(claim, allClaims.get(claim).toString()); return userClaims; } public boolean expired(String jwt) { Date expires = getExpirationDate(jwt); if(expires != null) return expires.before(new Date()); else return true; } public String getJwtFromRequest(HttpServletRequest request) { String authHeader = getAuthHeaderFromHeader(request); if (authHeader != null && authHeader.startsWith("Bearer ")) { return authHeader.substring(7); } return null; } private String getAuthHeaderFromHeader(HttpServletRequest request) { return request.getHeader(AUTH_HEADER); } private Date generateExpirationDate() { return new Date(new Date().getTime() + EXPIRES_IN); } private Claims getAllClaimsFromToken(String jwt) { Claims claims; try { claims = Jwts.parser() .setSigningKey(this.secret) .parseClaimsJws(jwt) .getBody(); } catch (Exception e) { claims = null; } return claims; } private Date getExpirationDate(String jwt) { Date expiration; try { final Claims claims = this.getAllClaimsFromToken(jwt); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; } }
258a5b217707166f1af8245084bcf16731afc02b
5c8df724ac5e7417dbd8b64dc22e773a42a743a5
/src/main/java/fr/uga/miage/miageBartender/Drink.java
a6697bfbd72d5faf550af16c2f9ce9d34928326c
[]
no_license
Jeremy38100/PatternChainOfResponsibility
977d5fe0e49b868be1d8fab757ddd4925f39eaaf
c7fc37786d214e91816666ee6e7bbead0878143b
refs/heads/master
2021-08-30T03:17:17.841587
2017-12-15T21:06:10
2017-12-15T21:06:10
114,231,856
0
0
null
null
null
null
UTF-8
Java
false
false
612
java
package fr.uga.miage.miageBartender; public class Drink { private String name; private EnumDrinkType type; public Drink(String name, EnumDrinkType type) { this.name = name; this.type = type; } public String getName() { return name; } public EnumDrinkType getType() { return type; } public boolean isAbleToDrink(double gramsAlcoholPerLiter) { if (this.type == EnumDrinkType.Medium) return gramsAlcoholPerLiter < 1; else if (this.type == EnumDrinkType.Strong) return gramsAlcoholPerLiter < 0.5; return true; } }
47450d0fef510c66044aa24dbf63b157d2b966ee
30a1020318980e7e3353372f91a592e39fa64d78
/payment-chen-offline/src/main/java/com/payment/entity/groupwormhole/AuthRoleResource.java
8b76766ed406780f8e08b522502b7f1da6214ef8
[]
no_license
shiyanga/payment-chen-love
e71ffabba7ea8c770d548e78e4dde8fa38e7bb98
ad19e80a4a420b2f2f5fe7230e0e5ebcdff7c74f
refs/heads/master
2021-01-18T15:40:43.830760
2017-08-16T10:30:47
2017-08-16T10:30:47
100,187,522
0
0
null
null
null
null
UTF-8
Java
false
false
689
java
package com.payment.entity.groupwormhole; import com.payment.entity.publicenitty.Entity; /** * Created by shi_y on 2017/1/23. */ public class AuthRoleResource extends Entity { private Integer id; private AuthRole role; private AuthResource resource; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public AuthRole getRole() { return role; } public void setRole(AuthRole role) { this.role = role; } public AuthResource getResource() { return resource; } public void setResource(AuthResource resource) { this.resource = resource; } }
9216f0faf7ef234cd981095b059b8e3dc00c446e
b0d44ff0d3a5d76cc08a4812f1f226bf055cbf1a
/algafood-api/src/main/java/com/algaworks/algafood/api/controller/TesteController.java
3ab4be4dd80b2d8b38e095b212bed56507f877a6
[]
no_license
julio0345/AlgaFood
56403e4ed8c9001bd66cb37fe8491b02d2057135
4b518f8dcc4a1d0a9ace93119538a348737db4bd
refs/heads/master
2023-06-02T18:27:35.547124
2021-06-15T10:46:07
2021-06-15T10:46:07
350,522,138
0
0
null
null
null
null
UTF-8
Java
false
false
1,828
java
package com.algaworks.algafood.api.controller; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.algaworks.algafood.domain.model.Kitchen; import com.algaworks.algafood.domain.model.Restaurant; import com.algaworks.algafood.domain.repository.KitchenRepository; import com.algaworks.algafood.domain.repository.RestaurantRepository; import com.algaworks.algafood.infrastructure.repository.spec.RestaurantFreeDelivery; import com.algaworks.algafood.infrastructure.repository.spec.RestaurantSimilarName; @RestController @RequestMapping("/testes") public class TesteController { @Autowired private KitchenRepository repository; @Autowired private RestaurantRepository repositoryRestaurant; @GetMapping public List<Kitchen> findByName(@RequestParam String name, @RequestParam BigDecimal inicial, @RequestParam BigDecimal finalV){ List<Kitchen> listKitchens = repository.findByName(name); Optional<Kitchen> opKitchen = repository.findById(2L); listKitchens = repository.meuMetodo("Japonesa"); listKitchens = repository.getKitchensByNameContaining("a"); List<Restaurant> listRestaurants = repositoryRestaurant.buscarTudo("Japonesa", inicial ,finalV); var freeDevilery = new RestaurantFreeDelivery(); var similarA = new RestaurantSimilarName("a"); listRestaurants = repositoryRestaurant.findAll(freeDevilery.and(similarA)); Optional<Restaurant> rest = repositoryRestaurant.getFirst(); return null; } }
a351fcac4b81da9c920a74911d78ff098f895221
0230d49f7488ee549693b9f2c1ebe6170c9e7619
/src/main/java/com/bt/creditappservices/service/DivisionsService.java
fe28ab8c0265d21f96e8d833b1a88412f636caac
[]
no_license
msundara1/test
0cdefdf2f593f0164976dedc496d4dae43d23da3
4a9430a41d27c987527dbfa7c68f970b46de2604
refs/heads/master
2020-03-27T18:59:42.104552
2018-09-03T03:18:46
2018-09-03T03:18:46
146,958,604
0
0
null
null
null
null
UTF-8
Java
false
false
599
java
package com.bt.creditappservices.service; import com.bt.creditappservices.model.DivisionEntity; import com.bt.creditappservices.model.request.DivisionsRequest; import java.util.List; import java.util.UUID; /** * @author msundara */ public interface DivisionsService { List<DivisionEntity> getAllDivisions(); List<DivisionEntity> getAllTenantDivisions(String tenantId); DivisionEntity getDivision(UUID divisionId); String createDivision(DivisionsRequest request); DivisionEntity updateDivision(UUID divisionId, DivisionsRequest request); void deleteDivision(UUID divisionId); }
c8b660a7697ac3e9881beeaa1d21409c1a47927c
72279284a121720a403ee232ae8aca9492212a7b
/jpa-test/src/main/java/course/spring/jpatest/service/impl/ShampooServiceImpl.java
49f07d9a6b8bbb265158eb730d2bb3b94529c34a
[]
no_license
VTheodore/spring5-course
d0354aee7c96fa14b9ab5a7cb3a1aa80a17ecb94
ed369e57211f963af5fe7861754fc5f771d3860c
refs/heads/main
2023-03-14T15:48:50.176580
2021-03-10T11:47:08
2021-03-10T11:47:08
316,708,831
0
0
null
null
null
null
UTF-8
Java
false
false
1,433
java
package course.spring.jpatest.service.impl; import course.spring.jpatest.dao.ShampooRepository; import course.spring.jpatest.entity.Ingredient; import course.spring.jpatest.entity.Shampoo; import course.spring.jpatest.service.ShampooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional(readOnly = true) public class ShampooServiceImpl implements ShampooService { private final ShampooRepository shampooRepository; @Autowired public ShampooServiceImpl(ShampooRepository shampooRepository) { this.shampooRepository = shampooRepository; } @Override public List<Shampoo> findShampoosBySize(int size) { return this.shampooRepository.findAllBySize(size); } @Override public List<Shampoo> findShampoosByPriceGreaterThan(double price) { return this.shampooRepository.findAllByPriceGreaterThan(price); } @Override public List<Shampoo> findShampoosByPriceBetween(double lowerBound, double upperBound) { return this.shampooRepository.findAllByPriceBetween(lowerBound, upperBound); } @Override public List<Shampoo> findShampoosByIngredientsContaining(Ingredient ingredient) { return this.shampooRepository.findAllByIngredientsContaining(ingredient); } }
047b7c99ee6e7b60b16e34812af38fa6af418f3f
08651bae8390c31fa2870d2ae76457500cf7f218
/src/test/java/guru/springframework/sfgdi/comtrollers/SetterInjectedControllerTest.java
01e0206bbbb1fbc4306afceaa096491c728dea3d
[]
no_license
UshaGBadebgowda/springframeworktutorial
92dcb91669aa164acd757be34a001421d3459834
7bb14d58c3cc9f7a2fd29d4e2ff00facf772411f
refs/heads/master
2022-12-04T08:54:02.470610
2020-08-26T16:55:02
2020-08-26T16:55:02
285,832,218
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package guru.springframework.sfgdi.comtrollers; import guru.springframework.sfgdi.services.ConstructorGreetingServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SetterInjectedControllerTest { SetterInjectedController setterInjectedController; @Test void getGreetingService() { System.out.println(setterInjectedController.getGreetingService()); } @BeforeEach void setUp() { setterInjectedController = new SetterInjectedController(); setterInjectedController.setGreetingService(new ConstructorGreetingServiceImpl()); } }
45901f89038c9849eea3d3135179a05d699d1c5f
3069cf8f5ee7ffa3b8ee630849c9ea37366fc92c
/src/main/java/com/stancforma/dxf/DxfInsert.java
a0c22ab032683e5881667a5038d4888f3eaac423
[ "MIT" ]
permissive
tyson925/stancforma-nest
ab9973b6e326c2029c046aea78761b47ba9c9dc5
298d2465c30245c770291fae3075e9530fb1b6d7
refs/heads/master
2022-05-28T02:11:35.640778
2019-08-09T12:42:15
2019-08-09T12:42:15
148,758,847
1
0
MIT
2022-05-20T20:46:25
2018-09-14T08:24:37
Java
UTF-8
Java
false
false
1,233
java
package com.stancforma.dxf; import java.util.List; public class DxfInsert extends DxfEntity { DxfValue _blockName; DxfValue _bpx; DxfValue _bpy; DxfValue _bpz; DxfInsert(DxfEntity entity) throws Exception { super(entity._container); List<DxfValue> attributes = _container.getAttributes(); if (!entity.type().equals("INSERT")) { throw new Exception("Entity must be an insert"); } _blockName = Util.mapValue(attributes, 2); _bpx = Util.mapValue(attributes, 10); _bpy = Util.mapValue(attributes, 20); _bpz = Util.mapValue(attributes, 30, 0); } // block name void blockName(String value) { _blockName.set(value); } String blockName() { return _blockName.asString(); } // base point x void bpx(double value) { _bpx.set(value); } double bpx() { return _bpx.asDouble(); } // base point y void bpy(double value) { _bpy.set(value); } double bpy() { return _bpy.asDouble(); } // base point z void bpz(double value) { _bpz.set(value); } double bpz() { return _bpz.asDouble(); } }
f93085a9e96fda855ac73e2165d4535697e2cb6c
2414e933e0319f028a95491cb1dd810a9c497007
/src/main/java/emotionfox/emomod/biome/gen/EmotionGenPine.java
04b5627ca838d7470ed06f3853cde25f204b461e
[]
no_license
EmotionFox/EmotionMod
c14e9015db6fc8a0452f45df88e16632c006cc1a
7695319ca6e86240d067e56847cb28e1ce3f7cf1
refs/heads/master
2021-01-23T00:20:18.287196
2017-10-09T20:44:49
2017-10-09T20:44:49
85,717,282
2
0
null
null
null
null
UTF-8
Java
false
false
4,350
java
package emotionfox.emomod.biome.gen; import java.util.Random; import emotionfox.emomod.block.EmotionNewLeaves; import emotionfox.emomod.block.EmotionNewLog; import emotionfox.emomod.block.EmotionPlanks; import emotionfox.emomod.block.EmotionSapling; import emotionfox.emomod.init.EmotionBlock; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; public class EmotionGenPine extends WorldGenerator { private EmotionSapling sapling = (EmotionSapling) EmotionBlock.SAPLING; @Override public boolean generate(World world, Random rand, BlockPos pos) { int height = 6 + rand.nextInt(4); IBlockState logs = EmotionBlock.NEW_LOG.getDefaultState().withProperty(EmotionNewLog.VARIANT, EmotionPlanks.EnumType.PINE); IBlockState leaves = EmotionBlock.NEW_LEAVES.getDefaultState().withProperty(EmotionNewLeaves.VARIANT, EmotionPlanks.EnumType.PINE); if (this.sapling.canBlockStay(world, pos, sapling.getDefaultState().withProperty(EmotionSapling.TYPE, EmotionPlanks.EnumType.PINE)) && world.isAirBlock(pos) && pos.getY() < 200 && (pos.getY() > 80 || rand.nextInt(10) == 0)) { for (int x = -1; x <= 1; ++x) { for (int z = -1; z <= 1; ++z) { if (world.isAirBlock(pos.add(x, height + 1, 0))) world.setBlockState(pos.add(x, height + 1, 0), leaves); if (world.isAirBlock(pos.add(0, height + 1, z))) world.setBlockState(pos.add(0, height + 1, z), leaves); if (world.isAirBlock(pos.add(x, height, z))) world.setBlockState(pos.add(x, height, z), leaves); if (world.isAirBlock(pos.add(x, height - 1, z))) world.setBlockState(pos.add(x, height - 1, z), leaves); } } for (int x = -2; x <= 2; ++x) { for (int z = -2; z <= 2; ++z) { if (world.isAirBlock(pos.add(x, height - 1, 0))) world.setBlockState(pos.add(x, height - 1, 0), leaves); if (world.isAirBlock(pos.add(0, height - 1, z))) world.setBlockState(pos.add(0, height - 1, z), leaves); } } for (int x = -2; x <= 2; ++x) { for (int z = -1; z <= 1; ++z) { if (world.isAirBlock(pos.add(x, height - 2, z))) world.setBlockState(pos.add(x, height - 2, z), leaves); if (world.isAirBlock(pos.add(z, height - 2, x))) world.setBlockState(pos.add(z, height - 2, x), leaves); } } for (int z = -3; z <= 3; z++) { for (int x = -1; x <= 1; x++) { if (world.isAirBlock(pos.add(x, height - 3, z))) world.setBlockState(pos.add(x, height - 3, z), leaves); if (world.isAirBlock(pos.add(z, height - 3, x))) world.setBlockState(pos.add(z, height - 3, x), leaves); } } for (int x = -2; x <= 2; x++) { for (int z = -2; z <= 2; z++) { if (world.isAirBlock(pos.add(x, height - 3, z))) world.setBlockState(pos.add(x, height - 3, z), leaves); } } for (int y = 0; y <= height; ++y) { world.setBlockState(pos.add(0, y, 0), logs); } world.setBlockState(pos.add(0, height + 2, 0), leaves); return true; } else if (this.sapling.canBlockStay(world, pos, sapling.getDefaultState().withProperty(EmotionSapling.TYPE, EmotionPlanks.EnumType.PINE)) && world.isAirBlock(pos) && pos.getY() < 81) { for (int x = -2; x <= 2; x++) { for (int z = -1; z <= 1; z++) { if (world.isAirBlock(pos.add(x, 2, 0))) world.setBlockState(pos.add(x, 2, 0), leaves); if (world.isAirBlock(pos.add(0, 2, x))) world.setBlockState(pos.add(0, 2, x), leaves); if (world.isAirBlock(pos.add(z, 2, -1))) world.setBlockState(pos.add(z, 2, -1), leaves); if (world.isAirBlock(pos.add(z, 2, 1))) world.setBlockState(pos.add(z, 2, 1), leaves); if (world.isAirBlock(pos.add(-1, 2, z))) world.setBlockState(pos.add(-1, 2, z), leaves); if (world.isAirBlock(pos.add(1, 2, z))) world.setBlockState(pos.add(1, 2, z), leaves); if (world.isAirBlock(pos.add(z, 3, 0))) world.setBlockState(pos.add(z, 3, 0), leaves); if (world.isAirBlock(pos.add(0, 3, z))) world.setBlockState(pos.add(0, 3, z), leaves); } } for (int y = 0; y <= 4; y++) { world.setBlockState(pos.add(0, y, 0), logs); } world.setBlockState(pos.add(0, 4, 0), leaves); return true; } return false; } }
87ce055d04c98e4b758a29a413332a4f03c25bfd
55cf7e6960239e2bfcac6f13875f0fdfed4cedca
/HibernateDemoAppComplete/src/main/java/com/mphasis/training/hibernate/RealtionShipRetrivalDemo.java
b2f9661a278e624f6ce9dd56fa668ae6962d6ba1
[]
no_license
Shwetha31Anil/171demos
8f3c841fcf6253a606e6d93ba519d698bc261879
325dcb1283a2fa996dc722a3e9bb0041412fed0a
refs/heads/master
2022-12-22T22:01:35.294704
2019-10-23T05:34:04
2019-10-23T05:34:04
211,767,492
0
0
null
2022-12-16T08:03:07
2019-09-30T03:26:19
Rich Text Format
UTF-8
Java
false
false
947
java
package com.mphasis.training.hibernate; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import com.mphasis.training.hibernate.pojos.MOrder; import com.mphasis.training.hibernate.pojos.Product; import com.mphasis.training.hibernate.util.HibernateUtil; public class RealtionShipRetrivalDemo { public static void main(String[] args) { // TODO Auto-generated method stub SessionFactory sf=HibernateUtil.getSessionFactory(); Session session=sf.openSession(); MOrder order=(MOrder)session.get(MOrder.class, 123); /* * Criteria cr=session.createCriteria(Product.class); * cr.add(Restrictions.eq("order", order)); List<Product> products=cr.list(); * * products.forEach((ps1)->System.out.println(ps1)); */ System.out.println(order); session.close(); } }
a89c6b186ea9c7cddf7324f664a1cf93ac366703
02ec27dd237257e18b2e3b33049e30725287ba4d
/kinesis-demo-consumer/src/main/java/gov/va/vba/vbms/sirius/kinesis/aggregator/prototype/demo/config/KinesisExampleConfiguration.java
4905cedaecda2016af96ea3f893806f03a6701af
[]
no_license
bah-atimes/kinesis-demo
cfed3d6e15c6d49cfab3be6356a4d2a5587f03b8
0cf7b382387940f3e88333a7a1d75f00c62893fe
refs/heads/master
2022-11-10T01:07:19.881224
2020-07-02T19:42:11
2020-07-02T19:42:11
276,187,609
0
0
null
null
null
null
UTF-8
Java
false
false
867
java
package gov.va.vba.vbms.sirius.kinesis.aggregator.prototype.demo.config; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.kinesis.AmazonKinesis; import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration to make localstack work for the KPL and Kinesis Binder */ @Configuration public class KinesisExampleConfiguration { private final static String AWS_REGION = "us-east-1"; private final static String URL = "https://localhost:4568"; @Bean public AmazonKinesis amazonKinesis() { return AmazonKinesisClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(URL, AWS_REGION)) .build(); } }
09cdd712a45b47269cf5aaf70aac8c61e08a4874
07ce083e35d0d489597856a10c8942a9a935e449
/reservation_service/src/main/java/xml_bsep/reservation_service/model/ReservationStatus.java
0f65b9e52924f9d4d69f27632fbec28bde5234e2
[]
no_license
dejandoder/XML-BSEP
b2a1ca0413412aaec19ffd9b3c2d87e679ecdc6a
a0bdbbb726cd0e3ff410c43f2f6139f3e0d3606e
refs/heads/master
2023-01-09T02:40:42.275195
2019-06-29T19:13:30
2019-06-29T19:13:30
174,406,914
1
1
null
2023-01-07T06:17:10
2019-03-07T19:27:14
TSQL
UTF-8
Java
false
false
241
java
package xml_bsep.reservation_service.model; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; @XmlType(name = "ReservationStatus") @XmlEnum public enum ReservationStatus { PENDING, APPROVED, CONFIRMED; }
f93f99b8f06e7be6ffa675d4e761a8fb1a2ed50f
55458281690eec712560e18181ad705f3504ee8a
/kodilla-patterns2/src/main/java/com/kodilla/patterns2/observer/homework/Student.java
6515ed45f14c0355d102ec29064f58c8dec96618
[]
no_license
szymonpp2016/szymon-pp-2016-kodilla
5a99be5a71a9a47488975477e6861b7d88a7e4f4
908c1462536fd05b97ff09e6486d9c18eee2de19
refs/heads/master
2021-05-14T19:07:29.258186
2018-10-10T11:36:10
2018-10-10T11:36:10
116,100,342
0
0
null
2018-01-22T14:27:51
2018-01-03T06:27:57
Java
UTF-8
Java
false
false
280
java
package com.kodilla.patterns2.observer.homework; import lombok.Getter; @Getter class Student { private String userName; private String kursKode; Student(String userName, String kursKode) { this.userName = userName; this.kursKode = kursKode; } }
7566045a42ba6ad88b6d17c8ed733cd4085f8ea0
890eb6ad18df958de0d33a12ed45659bbcb2783e
/Android_Quirk_Locater/app/src/main/java/com/sps/android_quirk_locater/particleInfo.java
3797576f24d9db32ed91b0464754f02fe8d57132
[]
no_license
tomasvr/sps-particle-filtering
0167dfdae90380938afa941667ce87f75a7ca4e3
6499f18443fcfbf31b11be8ce65ac69b15c802ac
refs/heads/master
2022-12-23T19:57:55.195633
2020-06-24T13:59:25
2020-06-24T13:59:25
272,694,805
0
0
null
null
null
null
UTF-8
Java
false
false
810
java
package com.sps.android_quirk_locater; import android.graphics.drawable.ShapeDrawable; import java.util.ArrayList; public class particleInfo { private ShapeDrawable shape; private ArrayList<Integer> cell; public particleInfo(ShapeDrawable coordinates, ArrayList<Integer> cell) { this.shape = coordinates; this.cell = cell; } public particleInfo(ShapeDrawable coordinates) { this.shape = coordinates; this.cell = new ArrayList<>(); } public ShapeDrawable getShape() { return this.shape; } public ArrayList<Integer> getCell() { return this.cell; } public void setShape(ShapeDrawable shape) { this.shape = shape; } public void setCell(ArrayList<Integer> cell) { this.cell = cell; } }
adee7def1e27e2f3a40318b652559dfa20b29e7c
cba543b732a9a5ad73ddb2e9b20125159f0e1b2e
/sikuli_ide/src/main/java/org/jdesktop/swingx/package-info.java
2232f7e6d513c6427e1ec2cbf60264a3f705087b
[]
no_license
wsh231314/IntelligentOperation
e6266e1ae79fe93f132d8900ee484a4db0da3b24
a12aca5c5c67e6a2dddcd2d8420ca8a64af476f2
refs/heads/master
2020-04-05T13:31:55.376669
2017-07-28T05:59:05
2017-07-28T05:59:05
94,863,918
1
2
null
2017-07-27T02:44:17
2017-06-20T07:45:10
Java
UTF-8
Java
false
false
6,121
java
/* * $Id: package-info.java 3933 2011-03-02 19:02:29Z kschaefe $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ /** * Contains extensions to the Swing GUI toolkit, including new and enhanced * components that provide functionality commonly required by rich, * data-centric client applications. Many of these features will eventually * be incorporated into the Swing toolkit, although API compatibility will * not be guaranteed. * <p> * <p> * <h2>New or Enhanced Functionality</h2> * <p> * <h3>Auto-completion for TextFields and ComboBoxes</h3> * <p> * For more information, see the * <a href="autocomplete/package.html">AutoComplete</a> documentation. * <p> * <h3>Enhanced Rendering Support for Collection Components</h3> * <p> * <h3>Built-In Search Support for Collection Components and JXEditorPane</h3> * <p> * <h3>Login/Authentication Framework</h3> * <p> * <h3>Painter-Enabled Components</h3> * <p> * Components that use painters for background rendering alter the functionality * of how {@link java.awt.Component#setBackground(java.awt.Color)} works. * Setting the background color of a painter-enabled component effectively sets * the background painter to paint the requested color. * <p> * Look and Feel implementors should note that setting a * {@link java.swing.plaf.UIResource} to {@code setBackground} will cause a * {@code Painter} {@code UIResource} to be installed. This means that * implementors should set the background before setting the painter as the last * one set wins. * <p> * <h2>New and Enhanced components</h2> * <p> * <h3>Buttons and Labels</h3> * <ul> * <li> {@link org.jdesktop.swingx.JXButton} * <li> {@link org.jdesktop.swingx.JXHyperlink Hyperlink} * <li> {@link org.jdesktop.swingx.JXLabel} * <li> {@link org.jdesktop.swingx.JXBusyLabel} * <li> {@link org.jdesktop.swingx.JXRadioGroup} * </ul> * <p> * <p> * <h3>Collection Components</h3> * <p> * These are sortable/filterable (with the exception of hierarchical * components) with consistent and uniform SwingX rendering, highlighting, * searching and rollover support. * <ul> * <li> {@link org.jdesktop.swingx.JXTable Table} uses the enhanced * {@link org.jdesktop.swingx.JXTableHeader TableHeader} * <li> {@link org.jdesktop.swingx.JXList List} - rollover and sort/filter * functionality is disabled by default * <li> {@link org.jdesktop.swingx.JXTree Tree} * <li> {@link org.jdesktop.swingx.JXTreeTable TreeTable} - a new * hierarchical component with support of tabular node properties * </ul> * <p> * <h3>Top-level Windows, General and Special Purpose Containers</h3> * <ul> * <li>Enhanced {@link org.jdesktop.swingx.JXFrame Frame} using an extended * {@link org.jdesktop.swingx.JXRootPane RootPane RootPane} to support a * {@link org.jdesktop.swingx.JXStatusBar StatusBar} * <li> {@link org.jdesktop.swingx.JXDialog Dialog} * <li> {@link org.jdesktop.swingx.JXPanel Panel} * <li> {@link org.jdesktop.swingx.JXErrorPane ErrorPane} * <li> {@link org.jdesktop.swingx.JXLoginPane LoginPane} * <p> * <li>Search components: {@link org.jdesktop.swingx.JXFindBar FindBar} used * for incremental search (similar to FireFox), * {@link org.jdesktop.swingx.JXFindPanel FindPanel} used in a find dialog, * and {@link org.jdesktop.swingx.JXSearchPanel SearchPanel} used for what * was it? * <li>Nested SplitPane {@link org.jdesktop.swingx.JXMultiSplitPane * MultiSplitPane} * <li>Vertical collapsing/expansion functionality is provided by a * {@link org.jdesktop.swingx.JXCollapsiblePane CollapsiblePane}. A special * purpose collapsible is the {@link org.jdesktop.swingx.JXTaskPane * TaskPane} which typically is used to group buttons/hyperlinks which * perform related tasks. A special * {@link org.jdesktop.swingx.JXTaskPaneContainer TaskPaneContainer} is * responsible for the layout of several TaskPanes. * <li>Easily configurable {@link org.jdesktop.swingx.JXTipOfTheDay * TipOfTheDay} * <li> {@link org.jdesktop.swingx.JXTitledPanel TitledPanel} * <p> * </ul> * <p> * <h3>Miscellaneous Components</h3> * <p> * <ul> * <li>New calendar components: the {@link org.jdesktop.swingx.JXDatePicker * DatePicker} allows to select a single Date and a * {@link org.jdesktop.swingx.JXMonthView MonthView} showing the overview of * one or more months. * <p> * <li> {@link org.jdesktop.swingx.JXHeader Header} * <li> {@link org.jdesktop.swingx.JXTitledSeparator TitledSeparator} * <p> * <li> {@link org.jdesktop.swingx.JXColorSelectionButton} * <li> {@link org.jdesktop.swingx.JXEditorPane} * <li> {@link org.jdesktop.swingx.JXGradientChooser} * <li> {@link org.jdesktop.swingx.JXGraph} * <li>Image containers {@link org.jdesktop.swingx.JXImageView ImageView} * and {@link org.jdesktop.swingx.JXImagePanel ImagePanel} (PENDING JW: * merge/remove one?) * <li> {@link org.jdesktop.swingx.JXMultiThumbSlider MultiThumbSlider} * <p> * </ul> * <p> * <h2>External Information Sources</h2> * <p> * <a href="http://wiki.java.net/bin/view/Javadesktop/SwingX">SwingX Twiki</a> * <a href="http://wiki.java.net/bin/view/Javadesktop/SwingXChanges">Change History</a> * <a href="http://forums.java.net/jive/forum.jspa?forumID=73">SwingLabs User and * Developer Discussion Forum</a> */ package org.jdesktop.swingx;