blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
64942a39183abfad5bd68a21dd2b10f04bf445ee | 420,906,806,668 | f293e2cf15453d1489cba4f7577bf1cb98a020aa | /app/src/main/java/com/iflytek/demo/httpdemo/NetActivity.java | 8e5799aed5f4327bb7b5644cdcc3fea84bbb669b | [] | no_license | jiang666/MyApplication | https://github.com/jiang666/MyApplication | 504d2ad3eadbf8bae34bbb4fae1bbc6f8f1e698c | 7069e204bd2e7e1d7b0445c88c53507d39963481 | refs/heads/master | 2021-12-27T19:33:11.238000 | 2021-12-15T09:53:00 | 2021-12-15T09:53:00 | 76,636,304 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iflytek.demo.httpdemo;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.iflytek.demo.R;
import com.iflytek.demo.database.DBOpenHelper;
import com.iflytek.demo.util.ACache;
import com.squareup.picasso.Transformation;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
/**
* Created by jianglei on 2017/3/15.
*/
public class NetActivity extends Activity{
private TextView tv_nethttp;
private TextView tv_title;
private Toolbar mToolbar;
private ACache aCache;
private ImageView targetImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.net_activity);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tv_title = (TextView)findViewById(R.id.tv_title);
tv_title.setText("网络");
mToolbar.setNavigationIcon(R.drawable.back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NetActivity.this.finish();
}
});
tv_nethttp = (TextView) findViewById(R.id.tv_nethttp);
targetImageView = (ImageView) findViewById(R.id.vi_nethttp);
aCache = ACache.get(NetActivity.this);
/*String internetUrl = "http://192.168.1.145/sousou.png";
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_default)
.showImageForEmptyUri(R.drawable.ic_default)
.showImageOnFail(R.drawable.ic_default)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
ImageLoader.getInstance().displayImage(internetUrl, targetImageView, options);*/
/*Picasso.with(this)
.load(internetUrl)
.transform(new CropSquareTransformation())
.into(targetImageView);*/
ObjectAnimator animator = ObjectAnimator.ofFloat(targetImageView, "scaleX", 1f, 2f, 1f);
animator.setDuration(2000);
//animator.setRepeatCount(-1);
animator.start();
//透明度起始为1,结束时为0
ObjectAnimator animator1 = ObjectAnimator.ofFloat(targetImageView, "alpha", 0.5f, 1f);
animator1.setDuration(1000);//时间1s
animator1.start();
/*targetImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
// 获取当前触摸点的x,y坐标
x = (int) event.getX();
y = (int) event.getY();
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});*/
targetImageView.setOnClickListener(new myButtonListener());
findViewById(R.id.btn_down).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
new Thread(new Runnable() {
@Override
public void run() {
download();
}
}).start();
}
});
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
String path = NetActivity.this.getExternalFilesDir(null) + File.separator + "ooooooo.apk";
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
NetActivity.this.startActivity(intent);
/*String file = Environment.getExternalStorageState() + File.separator;
new FileUtil().deleteFolderFile(file,true);
*//*File file6 = new File(file);
if(file6.isFile()) {
file6.delete();
}*/
}
}).start();
}
});
findViewById(R.id.btn_adddata).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBOpenHelper helper = new DBOpenHelper(NetActivity.this);
// 调用 getWritableDatabase()或者 getReadableDatabase()其中一个方法将数据库建立
SQLiteDatabase db = helper.getWritableDatabase(); //得到的是SQLiteDatabase对象
//插入数据SQL语句
String stu_sql="insert into person(name,address) values('xiaoming','01005')";
//执行SQL语句
db.execSQL(stu_sql);
}
});
findViewById(R.id.btn_netcall).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//EventBus.getDefault().post(new MessageEven(353246));
/*String string = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = string + "/a.xml";
File file = new File(path);
parser(file);
setNet("0000");*/
/*String hh = aCache.getAsString("2222");
if(hh==null){
new Thread(new Runnable() {
@Override
public void run() {
try {
getWeather();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}else {
setNet(hh);
}*/
}
});
}
private void download() {
Log.e("","");
AppClient.ApiStores apiStores = AppClient.retrofit().create(AppClient.ApiStores.class);
//Observable<ResponseBody> call = apiStores.downloadFile("bd.mp4"); //note1
Observable<ResponseBody> call = apiStores.downloadFile("bt/api/touchsys/program/getMaterial?id=65379c0a051a4a379c0f51ba414ef7c0&cstmId=1d9757c68dbd46c1808b59370ed3d8a1"); //note1
Subscription subscription = call.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException)e;
int code = response.code();
}
}
@Override
public void onNext(ResponseBody user) {
String path = Environment.getExternalStorageDirectory().getPath() + "/touch/bd.mp4";
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = user.contentLength();
long fileSizeDownloaded = 0;
inputStream = user.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
//EventBus.getDefault().post(new MessageEven(fileSizeDownloaded*100/fileSize));
Log.e("========", "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
} catch (IOException e) {
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
}
}
});
}
public void parser(File resFile) {
FileInputStream is = null;
try {
is = new FileInputStream(resFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//获取xmlpull解析器
XmlPullParser xp = Xml.newPullParser();
try {
//初始化
xp.setInput(is, "utf-8");
//获取当前节点的事件类型
int type = xp.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
//获取当前节点的名字
if ("configs".equals(xp.getName())) {
} else if ("program".equals(xp.getName())) {
String name = xp.getAttributeValue(null,"name");
Log.e("name",name);
String programType = xp.getAttributeValue(null,"type");
Log.e("type",programType);
String version = xp.getAttributeValue(null,"version");
Log.e("version",version);
}
break;
case XmlPullParser.END_TAG:
if ("configs".equals(xp.getName())) {
}
break;
}
//把指针移动至下一个节点,并返回该节点的事件类型
type = xp.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private void getWeather() {
AppClient.ApiStores apiStores = AppClient.retrofit().create(AppClient.ApiStores.class);
Call<JsonDemo> call = apiStores.getWeather("json");
call.enqueue(new Callback<JsonDemo>() {
@Override
public void onResponse(Call<JsonDemo> call, Response<JsonDemo> response) {
Log.i("wxl", "getWeatherinfo=" + response.body().getApiInfo().getApiName());
try {
String string = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = string + "/a.xml";
Log.e("---path---",path);
FileOutputStream outStream = new FileOutputStream(path);
String apiinfo = new Gson().toJson(response.body().getApiInfo());
try {
aCache.put("2222",response.body().getApiInfo().getApiKey());
}catch (Exception e){
}
outStream.write(apiinfo.getBytes());
outStream.close();
//Toast.makeText(NetActivity.this,"Saved_"+ string,Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
return;
}
catch (IOException e){
return ;
}
setNet(response.body().getApiInfo().getApiName());
}
@Override
public void onFailure(Call<JsonDemo> call, Throwable t) {
setNet("null");
}
});
}
public void setNet(String str){
tv_nethttp.setText(str);
/*final int drawableRes = R.drawable.login;
Observable.create(new Observable.OnSubscribe<Drawable>() {
@Override
public void call(Subscriber<? super Drawable> subscriber) {
Drawable drawable = getTheme().getDrawable(drawableRes);
subscriber.onNext(drawable);
subscriber.onCompleted();
}
}).subscribe(new Observer<Drawable>() {
@Override
public void onNext(Drawable drawable) {
targetImageView.setImageDrawable(drawable);
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Toast.makeText(NetActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});*/
/*String[] names = {"1","2","3"};
Observable.from(names)
.observeOn(Schedulers.io())
.subscribe(new Action1<String>() {
@Override
public void call(String name) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String date=sdf.format(new java.util.Date());
Log.d("-------------", name+ date);
try {
Thread.sleep(20000);
Log.d("============", "Observable thread is : " + Thread.currentThread().getName());
}catch (Exception e){
}
}
});*/
}
public class myButtonListener implements View.OnClickListener{
@Override
public void onClick(View view) {
final ValueAnimator animator = ValueAnimator.ofInt(1, 100);
animator.setDuration(5000);
animator.setInterpolator(new BounceInterpolator());//线性效果变化
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
Integer integer = (Integer) animator.getAnimatedValue();
tv_nethttp.setText("" + integer);
tv_nethttp.setHeight(integer);
}
});
animator.start();
}
}
public class CropSquareTransformation implements Transformation {
@Override public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if (result != source) {
source.recycle();
}
return result;
}
@Override public String key() { return "square()"; }
}
}
| UTF-8 | Java | 17,308 | java | NetActivity.java | Java | [
{
"context": "mport rx.schedulers.Schedulers;\n\n/**\n * Created by jianglei on 2017/3/15.\n */\n\npublic class NetActivity exten",
"end": 1270,
"score": 0.9990424513816833,
"start": 1262,
"tag": "USERNAME",
"value": "jianglei"
},
{
"context": "ity.this);\n /*String internetUrl = \"http://192.168.1.145/sousou.png\";\n DisplayImageOptions options ",
"end": 2295,
"score": 0.9995024800300598,
"start": 2282,
"tag": "IP_ADDRESS",
"value": "192.168.1.145"
},
{
"context": "}\n @Override public String key() { return \"square()\"; }\n }\n}\n",
"end": 17067,
"score": 0.9914814233779907,
"start": 17059,
"tag": "KEY",
"value": "square()"
}
] | null | [] | package com.iflytek.demo.httpdemo;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.iflytek.demo.R;
import com.iflytek.demo.database.DBOpenHelper;
import com.iflytek.demo.util.ACache;
import com.squareup.picasso.Transformation;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
/**
* Created by jianglei on 2017/3/15.
*/
public class NetActivity extends Activity{
private TextView tv_nethttp;
private TextView tv_title;
private Toolbar mToolbar;
private ACache aCache;
private ImageView targetImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.net_activity);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tv_title = (TextView)findViewById(R.id.tv_title);
tv_title.setText("网络");
mToolbar.setNavigationIcon(R.drawable.back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NetActivity.this.finish();
}
});
tv_nethttp = (TextView) findViewById(R.id.tv_nethttp);
targetImageView = (ImageView) findViewById(R.id.vi_nethttp);
aCache = ACache.get(NetActivity.this);
/*String internetUrl = "http://192.168.1.145/sousou.png";
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_default)
.showImageForEmptyUri(R.drawable.ic_default)
.showImageOnFail(R.drawable.ic_default)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
ImageLoader.getInstance().displayImage(internetUrl, targetImageView, options);*/
/*Picasso.with(this)
.load(internetUrl)
.transform(new CropSquareTransformation())
.into(targetImageView);*/
ObjectAnimator animator = ObjectAnimator.ofFloat(targetImageView, "scaleX", 1f, 2f, 1f);
animator.setDuration(2000);
//animator.setRepeatCount(-1);
animator.start();
//透明度起始为1,结束时为0
ObjectAnimator animator1 = ObjectAnimator.ofFloat(targetImageView, "alpha", 0.5f, 1f);
animator1.setDuration(1000);//时间1s
animator1.start();
/*targetImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
// 获取当前触摸点的x,y坐标
x = (int) event.getX();
y = (int) event.getY();
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});*/
targetImageView.setOnClickListener(new myButtonListener());
findViewById(R.id.btn_down).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
new Thread(new Runnable() {
@Override
public void run() {
download();
}
}).start();
}
});
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
String path = NetActivity.this.getExternalFilesDir(null) + File.separator + "ooooooo.apk";
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
NetActivity.this.startActivity(intent);
/*String file = Environment.getExternalStorageState() + File.separator;
new FileUtil().deleteFolderFile(file,true);
*//*File file6 = new File(file);
if(file6.isFile()) {
file6.delete();
}*/
}
}).start();
}
});
findViewById(R.id.btn_adddata).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBOpenHelper helper = new DBOpenHelper(NetActivity.this);
// 调用 getWritableDatabase()或者 getReadableDatabase()其中一个方法将数据库建立
SQLiteDatabase db = helper.getWritableDatabase(); //得到的是SQLiteDatabase对象
//插入数据SQL语句
String stu_sql="insert into person(name,address) values('xiaoming','01005')";
//执行SQL语句
db.execSQL(stu_sql);
}
});
findViewById(R.id.btn_netcall).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//EventBus.getDefault().post(new MessageEven(353246));
/*String string = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = string + "/a.xml";
File file = new File(path);
parser(file);
setNet("0000");*/
/*String hh = aCache.getAsString("2222");
if(hh==null){
new Thread(new Runnable() {
@Override
public void run() {
try {
getWeather();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}else {
setNet(hh);
}*/
}
});
}
private void download() {
Log.e("","");
AppClient.ApiStores apiStores = AppClient.retrofit().create(AppClient.ApiStores.class);
//Observable<ResponseBody> call = apiStores.downloadFile("bd.mp4"); //note1
Observable<ResponseBody> call = apiStores.downloadFile("bt/api/touchsys/program/getMaterial?id=65379c0a051a4a379c0f51ba414ef7c0&cstmId=1d9757c68dbd46c1808b59370ed3d8a1"); //note1
Subscription subscription = call.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException)e;
int code = response.code();
}
}
@Override
public void onNext(ResponseBody user) {
String path = Environment.getExternalStorageDirectory().getPath() + "/touch/bd.mp4";
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = user.contentLength();
long fileSizeDownloaded = 0;
inputStream = user.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
//EventBus.getDefault().post(new MessageEven(fileSizeDownloaded*100/fileSize));
Log.e("========", "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
} catch (IOException e) {
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
}
}
});
}
public void parser(File resFile) {
FileInputStream is = null;
try {
is = new FileInputStream(resFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//获取xmlpull解析器
XmlPullParser xp = Xml.newPullParser();
try {
//初始化
xp.setInput(is, "utf-8");
//获取当前节点的事件类型
int type = xp.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
//获取当前节点的名字
if ("configs".equals(xp.getName())) {
} else if ("program".equals(xp.getName())) {
String name = xp.getAttributeValue(null,"name");
Log.e("name",name);
String programType = xp.getAttributeValue(null,"type");
Log.e("type",programType);
String version = xp.getAttributeValue(null,"version");
Log.e("version",version);
}
break;
case XmlPullParser.END_TAG:
if ("configs".equals(xp.getName())) {
}
break;
}
//把指针移动至下一个节点,并返回该节点的事件类型
type = xp.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private void getWeather() {
AppClient.ApiStores apiStores = AppClient.retrofit().create(AppClient.ApiStores.class);
Call<JsonDemo> call = apiStores.getWeather("json");
call.enqueue(new Callback<JsonDemo>() {
@Override
public void onResponse(Call<JsonDemo> call, Response<JsonDemo> response) {
Log.i("wxl", "getWeatherinfo=" + response.body().getApiInfo().getApiName());
try {
String string = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = string + "/a.xml";
Log.e("---path---",path);
FileOutputStream outStream = new FileOutputStream(path);
String apiinfo = new Gson().toJson(response.body().getApiInfo());
try {
aCache.put("2222",response.body().getApiInfo().getApiKey());
}catch (Exception e){
}
outStream.write(apiinfo.getBytes());
outStream.close();
//Toast.makeText(NetActivity.this,"Saved_"+ string,Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
return;
}
catch (IOException e){
return ;
}
setNet(response.body().getApiInfo().getApiName());
}
@Override
public void onFailure(Call<JsonDemo> call, Throwable t) {
setNet("null");
}
});
}
public void setNet(String str){
tv_nethttp.setText(str);
/*final int drawableRes = R.drawable.login;
Observable.create(new Observable.OnSubscribe<Drawable>() {
@Override
public void call(Subscriber<? super Drawable> subscriber) {
Drawable drawable = getTheme().getDrawable(drawableRes);
subscriber.onNext(drawable);
subscriber.onCompleted();
}
}).subscribe(new Observer<Drawable>() {
@Override
public void onNext(Drawable drawable) {
targetImageView.setImageDrawable(drawable);
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Toast.makeText(NetActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});*/
/*String[] names = {"1","2","3"};
Observable.from(names)
.observeOn(Schedulers.io())
.subscribe(new Action1<String>() {
@Override
public void call(String name) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String date=sdf.format(new java.util.Date());
Log.d("-------------", name+ date);
try {
Thread.sleep(20000);
Log.d("============", "Observable thread is : " + Thread.currentThread().getName());
}catch (Exception e){
}
}
});*/
}
public class myButtonListener implements View.OnClickListener{
@Override
public void onClick(View view) {
final ValueAnimator animator = ValueAnimator.ofInt(1, 100);
animator.setDuration(5000);
animator.setInterpolator(new BounceInterpolator());//线性效果变化
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
Integer integer = (Integer) animator.getAnimatedValue();
tv_nethttp.setText("" + integer);
tv_nethttp.setHeight(integer);
}
});
animator.start();
}
}
public class CropSquareTransformation implements Transformation {
@Override public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if (result != source) {
source.recycle();
}
return result;
}
@Override public String key() { return "square()"; }
}
}
| 17,308 | 0.503044 | 0.494087 | 419 | 39.763721 | 26.129 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.572792 | false | false | 9 |
00bb0fea7f52d9fb7c06aaead0204e078cef3477 | 17,403,207,517,371 | 280df17caa641d61741dd3cadf1fec2ff7c81834 | /theL_android/app/src/main/java/com/thel/network/api/AllApi.java | 4054be78892d9a16e8fb86313c47ee628735d0d3 | [] | no_license | dingzhenkai/rela | https://github.com/dingzhenkai/rela | 14f635ad39fd463d5b17c1aa785c369ea54a39d7 | 2d8a972e6fcebf650e5797c004c2b97b8e94baea | refs/heads/master | 2020-07-02T16:18:18.873000 | 2018-12-04T05:49:43 | 2018-12-04T05:49:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.thel.network.api;
import com.thel.base.BaseDataBean;
import com.thel.bean.AdBean;
import com.thel.bean.AdListBean;
import com.thel.bean.BasicInfoBean;
import com.thel.bean.BasicInfoNetBean;
import com.thel.bean.BlackListBean;
import com.thel.bean.CheckUserNameBean;
import com.thel.bean.ContactsListBean;
import com.thel.bean.FavoritesBean;
import com.thel.bean.FirstHotTopicBean;
import com.thel.bean.FriendListBean;
import com.thel.bean.FriendRecommendListBean;
import com.thel.bean.GoogleIapNotifyResultBean;
import com.thel.bean.HiddenLoveBean;
import com.thel.bean.InitRecommendUserListBean;
import com.thel.bean.LikeListBean;
import com.thel.bean.LikeResultBean;
import com.thel.bean.LiveClassificationBean;
import com.thel.bean.PayOrderBean;
import com.thel.bean.RecentAndHotTopicsBean;
import com.thel.bean.RechargeRecordListBeanNew;
import com.thel.bean.ReleaseMomentSucceedBean;
import com.thel.bean.ReleasedCommentBeanNew;
import com.thel.bean.ReleasedCommentReplyBeanNew;
import com.thel.bean.ResultBean;
import com.thel.bean.SearchUsersListBean;
import com.thel.bean.StickerPackListNetBean;
import com.thel.bean.StickerPackNetBean;
import com.thel.bean.ThemeCommentListBeanNew;
import com.thel.bean.TopicListBean;
import com.thel.bean.TrendingTagsBean;
import com.thel.bean.UploadVideoAlbumBean;
import com.thel.bean.VersionBean;
import com.thel.bean.WhoSeenMeListBean;
import com.thel.bean.comment.CommentListBeanNew;
import com.thel.bean.comment.CommentReplyListBeanNew;
import com.thel.bean.gift.WinkCommentListBean;
import com.thel.bean.gift.WinkListBean;
import com.thel.bean.live.LiveFollowingUsersBeanNew;
import com.thel.bean.me.MyCircleFriendListBean;
import com.thel.bean.me.MyCircleRequestListBean;
import com.thel.bean.me.MyWinkListBean;
import com.thel.bean.moments.MomentsBean;
import com.thel.bean.moments.MomentsBeanNew;
import com.thel.bean.moments.MomentsListBean;
import com.thel.bean.moments.MomentsMsgsListBean;
import com.thel.bean.recommend.RecommendedStickerListNetBean;
import com.thel.bean.theme.ThemeListBean;
import com.thel.bean.topic.TopicFollowerListBean;
import com.thel.bean.topic.TopicMainPageBean;
import com.thel.bean.user.BlackMomentListBean;
import com.thel.bean.user.BlockListBean;
import com.thel.bean.user.BlockListBeanNew;
import com.thel.bean.user.LocationNameBean;
import com.thel.bean.user.MatchQuestionBean;
import com.thel.bean.user.MyImagesListBean;
import com.thel.bean.user.NearUserBean;
import com.thel.bean.user.NearUserListNetBean;
import com.thel.bean.user.UploadTokenBean;
import com.thel.bean.user.UserInfoBean;
import com.thel.bean.video.VideoListBeanNew;
import com.thel.modules.live.bean.SoftMoneyListBean;
import com.thel.modules.main.me.bean.FriendsListBean;
import com.thel.modules.main.me.bean.IncomeRecordListBean;
import com.thel.modules.main.me.bean.MatchListBean;
import com.thel.modules.main.me.bean.MyInfoNetBean;
import com.thel.modules.main.me.bean.VipListBean;
import com.thel.modules.main.me.bean.WalletBean;
import com.thel.modules.main.settings.bean.PushSwitchTypeBean;
import com.thel.modules.main.userinfo.bean.FollowersListBean;
import com.thel.network.RequestConstants;
import java.util.Map;
import io.reactivex.Flowable;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Created by liuyun on 2017/9/25.
*/
public interface AllApi {
/**
* 获取一些基本的必要信息接口,如'我'是否是会员、是否有续播的直播
*
* @return
*/
@GET(RequestConstants.GET_BASIC_INFO)
Flowable<BasicInfoNetBean> getBasicInfo();
/**
* 获取自己是否有主播权限
*
* @param userId
* @return
*/
@GET(RequestConstants.GET_LIVE_PERMIT)
Flowable<BaseDataBean> getLivePermit(@Query("userId") String userId);
/**
* 上传设备id,主要是个推的id
*
* @param type
* @param token
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.UPLOAD_DEVICE_TOKEN)
Flowable<BasicInfoBean> uploadDeviceToken(@Field("type") String type, @Field("token") String token);
/**
* 显示欢迎消息
*
* @return
*/
@GET(RequestConstants.SHOW_WELCOME_MSG)
Flowable<BaseDataBean> showWelcomeMsg();
/**
* 通过服务器获取短信验证码,目前仅支持国内区域86
*
* @param cell
* @param zone
* @return
*/
@GET(RequestConstants.SEND_CODE)
Flowable<BaseDataBean> sendCode(@Query("cell") String cell, @Query("zone") String zone);
/**
* 获取上传视频文件到七牛的token
*
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.GET_UPLOAD_TOKEN)
Flowable<UploadTokenBean> getVideoUploadToken(@FieldMap Map<String, String> map);
/**
* 检查电话号码是否被注册过了
*
* @param cell
* @param zone
* @return
*/
@GET(RequestConstants.CHECK_PHONE_NUMBER)
Flowable<BaseDataBean> checkPhoneNumber(@Query("cell") String cell, @Query("zone") String zone);
/**
* 获取黑名单
*
* @return
*/
@GET(RequestConstants.BLACK_LIST)
Flowable<BlackListBean> blackList();
/**
* 手机号、微信、fb绑定
*
* @param map
* @return
*/
@GET(RequestConstants.REBIND)
Flowable<BaseDataBean> rebind(@QueryMap Map<String, String> map);
/**
* 检查用户名是否重复
*
* @param userName
* @return
*/
@GET(RequestConstants.CHECK_USERNAME)
Flowable<CheckUserNameBean> checkUserName(@Query("userName") String userName);
/**
* 找回密码
*
* @param email
* @return
*/
@GET(RequestConstants.FIND_BACK_PASSWORD)
Flowable<BaseDataBean> findBackPassword(@Query("email") String email);
/**
* 用户推出
*
* @return
*/
@POST(RequestConstants.USER_LOGOUT)
@FormUrlEncoded
Flowable<BaseDataBean> loadUserLogout(@FieldMap Map<String, String> map);
/**
* 获取附近用户列表(已登录)参数
*
* @param map
* @return
*/
@GET(RequestConstants.NEAR_BY_SIMPLE_LIST)
Flowable<NearUserBean> getNearbySimpleList(@QueryMap Map<String, String> map);
/**
* 获取附近用户列表(已登录)参数
*
* @param map
* @return
*/
@GET(RequestConstants.GET_ACTIVE_USERS)
Flowable<NearUserListNetBean> getActiveUsers(@QueryMap Map<String, String> map);
/**
* 世界功能
*
* @param map
* @return
*/
@GET(RequestConstants.WORLD_LIST)
Flowable<NearUserListNetBean> getWorldUsers(@QueryMap Map<String, String> map);
/**
* 读取其他用户个人信息
*
* @param userId
* @return
*/
@GET(RequestConstants.USER_INFO)
Flowable<UserInfoBean> getUserInfo(@Query("userId") String userId);
/**
* 读取我的信息
*
* @return
*/
@GET(RequestConstants.MY_INFO)
Flowable<MyInfoNetBean> getMyInfo();
/**
* 更新个人信息
*
* @param body
* @return
*/
@POST(RequestConstants.UPDATE_USER_INFO)
Flowable<BaseDataBean> updateUserInfo(@Body RequestBody body);
/**
* 更新个人信息
*
* @param map
* @return
*/
@POST(RequestConstants.UPDATE_USER_INFO)
@FormUrlEncoded
Flowable<BaseDataBean> updateUserInfo(@FieldMap Map<String, String> map);
/**
* 初始化个人信息,只需要填写昵称、thelID和头像
*
* @param userName
* @param avatarURL
* @param nickName
* @return
*/
@GET(RequestConstants.INIT_USER_INFO)
Flowable<BaseDataBean> updateUserInfo(@Query("userName") String userName, @Query("avatarURL") String avatarURL, @Query("nickName") String nickName);
/**
* 获取朋友列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FRIENDS)
Flowable<FriendsListBean> getFriendsList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取朋友列表(简易,只包含头像、名字、id)
*
* @return
*/
@GET(RequestConstants.GET__CONTACTS)
Flowable<ContactsListBean> getContactsList();
/**
* 获取关注列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FOLLOW)
Flowable<FriendsListBean> getFollowList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取粉丝列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FANS)
Flowable<FriendsListBean> getFansList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取点赞列表
*
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_LIKED)
Flowable<LikeListBean> getLikedList(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 搜索我的朋友
*
* @return
*/
@GET(RequestConstants.SEARCH_MY_FRIENDS)
Flowable<FriendsListBean> searchMyFriends(@QueryMap Map<String, String> map);
/**
* 上传相册图片(最终url)
*
* @return
*/
@POST(RequestConstants.UPLOAD_IMAGE)
Flowable<BaseDataBean> uploadImageUrl(@Body RequestBody body);
/**
* 上传相册图片(最终url)
*
* @return
*/
@POST(RequestConstants.UPLOAD_IMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> uploadImageUrl(@FieldMap Map<String, String> map);
/**
* 上传视频
*
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.UPLOAD_ALBUM_VIDEO)
Flowable<UploadVideoAlbumBean> uploadAlbumVideoUrl(@FieldMap Map<String, String> map);
/**
* 获取我的照片列表
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.MY_IMAGES_LIST)
Flowable<MyImagesListBean> getMyImagesList(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 删除照片
*
* @return
*/
@POST(RequestConstants.DELETE_IMAGE)
Flowable<BaseDataBean> deleteImage(@Body RequestBody body);
/**
* 删除照片
*
* @return
*/
@POST(RequestConstants.DELETE_IMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteImage(@FieldMap Map<String, String> map);
/**
* 设为隐私照片
*
* @return
*/
@POST(RequestConstants.SET_PRIVATE_STATUS)
Flowable<BaseDataBean> setPrivateStatus(@Body RequestBody body);
/**
* 设为隐私照片
*
* @return
*/
@POST(RequestConstants.SET_PRIVATE_STATUS)
@FormUrlEncoded
Flowable<BaseDataBean> setPrivateStatus(@FieldMap Map<String, String> map);
/**
* 设为封面照片
*
* @return
*/
@POST(RequestConstants.SET_COVER)
Flowable<BaseDataBean> setCover(@Body RequestBody body);
/**
* 设为封面照片
*
* @return
*/
@POST(RequestConstants.SET_COVER)
@FormUrlEncoded
Flowable<BaseDataBean> setCover(@FieldMap Map<String, String> map);
/**
* 搜索好友
*
* @param picId
* @param curPage
* @return
*/
@GET(RequestConstants.SEARCH_NICKNAME)
Flowable<SearchUsersListBean> searchNickname(@Query(RequestConstants.I_KEYWORD) String picId, @Query(RequestConstants.I_CURPAGE) String curPage);
/**
* 谁来看过我
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.CHEACK_VIEW)
Flowable<WhoSeenMeListBean> checkView(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 我看过谁
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.I_VIEW)
Flowable<WhoSeenMeListBean> iView(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 我的黑名单列表
*
* @return
*/
@GET(RequestConstants.GET_USER_BLACK_LIST)
Flowable<BlockListBean> getUserBlackList(@QueryMap Map<String, String> map);
@GET(RequestConstants.GET_USER_BLACK_LIST)
Flowable<BlockListBeanNew> getUserBlackList(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 解除黑名单
*
* @return
*/
@POST(RequestConstants.REMOVE_FROM_BLACKLIST)
Flowable<BaseDataBean> removeFromBlackList(@Body RequestBody body);
/**
* 解除黑名单
*
* @return
*/
@POST(RequestConstants.REMOVE_FROM_BLACKLIST)
@FormUrlEncoded
Flowable<BaseDataBean> removeFromBlackList(@FieldMap Map<String, String> map);
/**
* @param userId
* @return
*/
@GET(RequestConstants.SEND_HIDDEN_LOVE)
Flowable<HiddenLoveBean> sendHiddenLove(@Query("userId") String userId);
/**
* 传情
*
* @param userId
* @param type
* @return
*/
@GET(RequestConstants.SEND_WINK_CREATE)
Flowable<BaseDataBean> sendWink(@Query("userId") String userId, @Query("type") String type);
/**
* 关注
*
* @return
*/
@POST(RequestConstants.FOLLOW_USER)
Flowable<ResultBean> followUser(@Body RequestBody body);
@POST(RequestConstants.FOLLOW_USER)
@FormUrlEncoded
Flowable<ResultBean> followUser(@FieldMap Map<String, String> map);
@POST(RequestConstants.FOLLOW_USER_BATCH)
Flowable<ResultBean> followUserBatch(@Body RequestBody body);
@POST(RequestConstants.FOLLOW_USER_BATCH)
@FormUrlEncoded
Flowable<ResultBean> followUserBatch(@FieldMap Map<String, String> map);
/**
* 修改密码
*
* @return
*/
@POST(RequestConstants.MODIFY_PASSWORD)
Flowable<BaseDataBean> modifyPassword(@Body RequestBody body);
/**
* 修改密码
*
* @return
*/
@POST(RequestConstants.MODIFY_PASSWORD)
@FormUrlEncoded
Flowable<BaseDataBean> modifyPassword(@FieldMap Map<String, String> map);
/**
* 获取用户的粉丝列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_USER_FOLLOWERS_LIST)
Flowable<FollowersListBean> getUserFollowersList(@Query("userId") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 我的黑名单列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_USER_WINK_LIST)
Flowable<WinkListBean> getUserWinkList(@Query("userId") String userId, @Query("cursor") String curPage, @Query("pageSize") String pageSize);
/**
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_MY_WINK_LIST)
Flowable<MyWinkListBean> getMyWinkList(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* theL广告
*
* @return
*/
@GET(RequestConstants.GET_MAIN_ADVERT)
Flowable<AdListBean> getAd();
/**
* 消息的push 由客户端发出
*
* @param message
* @param nickName
* @param userId
* @param token
* @return
*/
@GET(RequestConstants.APP_PUSH)
Flowable<BaseDataBean> messagePushByClient(@Query("message") String message, @Query("nickName") String nickName, @Query("userId") String userId, @Query("token") String token);
/**
* 获取我的密友请求
*
* @return
*/
@GET(RequestConstants.GET_MY_CIRCLE_DATA)
Flowable<MyCircleFriendListBean> getMyCircleData();
/**
* 获取我的密友数据
*
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_MY_CIRCLE_REQUESTS)
Flowable<MyCircleRequestListBean> getMyCircleRequestData(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 发送一条密友请求
*
* @return
*/
@POST(RequestConstants.SEND_CIRCLE_REQUEST)
@FormUrlEncoded
Flowable<MyCircleRequestListBean> sendCircleRequest(@FieldMap Map<String, String> map);
/**
* 取消我发出的密友圈请求
*
* @return
*/
@POST(RequestConstants.CANCEL_CIRCLE_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> cancelRequest(@FieldMap Map<String, String> map);
/**
* 接受密友圈请求
*
* @return
*/
@POST(RequestConstants.ACCEPT_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> acceptRequest(@FieldMap Map<String, String> map);
/**
* 拒绝密友圈请求
*
* @return
*/
@POST(RequestConstants.REFUSE_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> refuseRequest(@FieldMap Map<String, String> map);
/**
* 移除密友圈朋友
*
* @return
*/
@POST(RequestConstants.REMOVE_CIRCLE_FRIEND)
Flowable<BaseDataBean> removeCircleFriend(@Body RequestBody body);
/**
* 移除密友圈朋友
*
* @return
*/
@POST(RequestConstants.REMOVE_CIRCLE_FRIEND)
@FormUrlEncoded
Flowable<BaseDataBean> removeCircleFriend(@FieldMap Map<String, String> map);
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@GET(RequestConstants.MATCH_LIST)
Flowable<MatchListBean> getMatchList();
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@POST(RequestConstants.MATCH_ROLLBACK)
Flowable<BaseDataBean> matchRollback(@Body RequestBody body);
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@POST(RequestConstants.MATCH_ROLLBACK)
@FormUrlEncoded
Flowable<BaseDataBean> matchRollback(@FieldMap Map<String, String> map);
/**
* 获取我的匹配问题
*
* @return
*/
@GET(RequestConstants.MY_QUESTIONS)
Flowable<MatchQuestionBean> getMyQuestions();
/**
* setMyQuestions
*
* @return
*/
@POST(RequestConstants.SET_QUESTIONS)
@FormUrlEncoded
Flowable<BaseDataBean> setMyQuestions(@FieldMap Map<String, String> map);
/**
* 喜欢或者不喜欢对方,或取消喜欢对方
*
* @return
*/
@POST(RequestConstants.LIKE_OR_NOT)
Flowable<LikeResultBean> likeOrNot(@Body RequestBody body);
/**
* 喜欢或者不喜欢对方,或取消喜欢对方
*
* @return
*/
@POST(RequestConstants.LIKE_OR_NOT)
@FormUrlEncoded
Flowable<LikeResultBean> likeOrNot(@FieldMap Map<String, String> map);
/**
* 获取表情商店首页-更多表情包
*
* @param vipfree
* @return
*/
@GET(RequestConstants.STICKER_STORE_RECOMMENDED)
Flowable<RecommendedStickerListNetBean> getStickerStoreRecommended(@Query("vipfree") String vipfree);
/**
* 表情包列表
*
* @return
*/
@GET(RequestConstants.STICKER_STORE_MORE)
Flowable<StickerPackListNetBean> getStickerStoreMore(@QueryMap Map<String, String> map);
/**
* 获取我已购买过的表情包
*
* @return
*/
@GET(RequestConstants.PURCHAESED_STICKER_PACKS)
Flowable<StickerPackListNetBean> getPurchasedStickerPacks();
/**
* 获取表情包详情
*
* @return
*/
@GET(RequestConstants.STICKER_PACK_DETAIL)
Flowable<StickerPackNetBean> getStickerPackDetail(@QueryMap Map<String, String> map);
/**
* 从服务端获取生成支付订单的必要数据
*
* @return
*/
@POST(RequestConstants.CREATE_STICKER_PACK_ORDER)
Flowable<PayOrderBean> createStickerPackOrder(@Body RequestBody body);
/**
* 从服务端获取生成支付订单的必要数据
*
* @return
*/
@POST(RequestConstants.CREATE_STICKER_PACK_ORDER)
@FormUrlEncoded
Flowable<PayOrderBean> createStickerPackOrder(@FieldMap Map<String, String> map);
/**
* @param userId 用户id。这个是可选参数,如果有,则是查看某个用户(也可以看自己)的朋友圈信息列表。如果没有这个参数( 或者这个参数传递一个空值),则查看“我能看到的所有的”朋友圈信息列表
* @param mainType 接受 3 种值:空,moments,popular:“空”和“moments”代表:“关注的 日志列表”, 或者是“某个人发的 日志列表”;"popular"代表:热门
* @param pageSize 每页显示多少条数据
* @param curPage 当前页码
* @return
*/
@GET(RequestConstants.MOMENTS_LIST)
Flowable<MomentsListBean> getMomentsList(@Query("userId") String userId, @Query("mainType") String mainType, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取最近5个参与的话题,加上 15个热门的话题
*/
@GET(RequestConstants.MOMENTS_GET_RECENT_AND_HOT_TOPICS)
Flowable<RecentAndHotTopicsBean> getRecentAndHotTopics();
/**
* 搜索话题列表
*/
@GET(RequestConstants.MOMENTS_SEARCH_TOPICS)
Flowable<TopicListBean> searchTopics(@Query(RequestConstants.I_TOPIC_NAME) String topicName, @Query(RequestConstants.I_CURPAGE) int curPage);
/**
* 用户昵称修改时间验证(30天内只能修改一次昵称)
**/
@GET(RequestConstants.GET_NICKNAME_TIMEVERIFY)
Flowable<BaseDataBean> getNickNameTimeVerify(@Query("nickname") String nickname);
/**
* 获取最热门的标签
*/
@GET(RequestConstants.GET_FIRST_HOT_TOPIC)
Flowable<FirstHotTopicBean> getFirstHotTopic();
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
Flowable<ReleaseMomentSucceedBean> releaseMoment(@Body RequestBody body);
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
@FormUrlEncoded
Flowable<ReleaseMomentSucceedBean> releaseMoment(@FieldMap Map<String, String> map);
@POST(RequestConstants.GET_UPLOAD_TOKEN)
Flowable<UploadTokenBean> getUploadToken(@Body RequestBody body);
@POST(RequestConstants.GET_UPLOAD_TOKEN)
@FormUrlEncoded
Flowable<UploadTokenBean> getUploadToken(@FieldMap Map<String, String> map);
/**
* 我的钱包数据
*/
@GET(RequestConstants.GET_WALLET_DATA)
Flowable<WalletBean> getWalletData();
@GET(RequestConstants.GET_HOTTHEME_LIST)
Flowable<ThemeListBean> getHotThemeList(@Query(RequestConstants.I_CURSOR) String page, @Query(RequestConstants.I_LIMIT) String limit);
@GET(RequestConstants.GET_THEMES_LIST)
Flowable<ThemeListBean> getThemesList(@Query(RequestConstants.I_CURSOR) String page, @Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_THEMECLASS) String themeClass);
@GET(RequestConstants.GET_MAIN_ADVERT)
Flowable<AdBean> getAd(@Query(RequestConstants.I_CLIENT) String client);
/**
* 收益或提现记录
*/
@GET(RequestConstants.GET_INCOME_OR_WITHDRAW_RECORD)
Flowable<IncomeRecordListBean> getIncomeOrWithdrawRecord(@QueryMap Map<String, String> map);
/**
* 获取朋友圈消息
*
* @param pageSize
* @param curPage
*/
@GET(RequestConstants.MOMENTS_GET_MSGS)
Flowable<MomentsMsgsListBean> getMomentsMsgsList(@Query("pageSize") int pageSize, @Query("curPage") int curPage);
// /**
// * 获取moment的评论列表
// *
// * @param id 朋友圈消息id
// * @param limit 每页显示多少条数据
// * @param cursor 数据库游标
// * @return
// */
// @GET(RequestConstants.GET_COMMENT_LIST)
// Flowable<MomentCommentBean> getCommentList(@Query("id") String id, @Query("limit") String limit, @Query("cursor") String cursor);
@GET(RequestConstants.GET_TRENDING_TAGS)
Flowable<TrendingTagsBean> getTrendingTags();
@POST(RequestConstants.INIT_USER_INFO)
Flowable<BaseDataBean> initUserInfo(@Body RequestBody body);
@POST(RequestConstants.INIT_USER_INFO)
@FormUrlEncoded
Flowable<BaseDataBean> initUserInfo(@FieldMap Map<String, String> map);
/**
* 获取购买vip页面的列表
*/
@GET(RequestConstants.BUY_VIP_LIST)
Flowable<VipListBean> getBuyVipList();
/**
* 获取地理名
*/
@GET(RequestConstants.GET_LOC_NAME)
Flowable<LocationNameBean> getLocationName(@QueryMap Map<String, String> map);
/**
* google wallet 购买成功后提交服务端验证
*/
@POST(RequestConstants.IAP_NOTIFY)
Flowable<GoogleIapNotifyResultBean> iapNotify(@Body RequestBody body);
/**
* google wallet 购买成功后提交服务端验证
*/
@POST(RequestConstants.IAP_NOTIFY)
@FormUrlEncoded
Flowable<GoogleIapNotifyResultBean> iapNotify(@FieldMap Map<String, String> map);
/**
* 获取点赞列表
*
* @param id
* @param cursor
* @param limit
*/
@GET(RequestConstants.MOMENTS_GET_LIKES)
Flowable<WinkCommentListBean> getWinkComments(@Query("id") String id, @Query("limit") String limit, @Query("cursor") String cursor);
/**
* Gold购买/赠送商品(会员)
*/
@POST(RequestConstants.BUY_WITH_GOLD)
Flowable<BaseDataBean> buyWithGold(@Body RequestBody body);
/**
* Gold购买/赠送商品(会员)
*/
@POST(RequestConstants.BUY_WITH_GOLD)
@FormUrlEncoded
Flowable<BaseDataBean> buyWithGold(@FieldMap Map<String, String> map);
/**
* 话题主页面(热门日志)
*
* @param topicName
* @param curPage
* @param pageSize
*/
@GET(RequestConstants.MOMENTS_TOPIC_MAINPAGE_HOT)
Flowable<TopicMainPageBean> getTopicMainPageHot(@Query("topicName") String topicName, @Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 获取moment详情,带评论、wink等等所有信息
*
* @param momentsId 朋友圈消息id
* @param pageSize 当前页码
* @param curPage 每页显示多少条数据
*/
@GET(RequestConstants.MOMENTS_GET_MOMENT_INFO)
Flowable<MomentsBean> getMomentInfo(@Query("momentsId") String momentsId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 4.1.0 话题回复
*
* @param map 要回复的话题bean
*/
@POST(RequestConstants.THEMES_COMMENT_ADD)
@FormUrlEncoded
Flowable<BaseDataBean> releaseThemesComment(@FieldMap Map<String, String> map);
/**
* 发布一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_RELEASE_COMMENT)
@FormUrlEncoded
Flowable<ReleasedCommentBeanNew> releaseComment(@FieldMap Map<String, String> map);
/**
* 获取被推荐的日志详情
*
* @param momentId
*/
@GET(RequestConstants.GET_FRIEND_RECOMMEND_DETAIL)
Flowable<MomentsBean> getFriendRecommendDetail(@Query("id") String momentId);
/**
* 推荐的日志列表的日志详情
*
* @param momentId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_MOMENTS_FRIEND_RECOMMEND_LIST)
Flowable<FriendRecommendListBean> getMomentsFriendRecommendList(@Query("id") String momentId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 发布一条推荐用户日志
*
* @param map
*/
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
@FormUrlEncoded
Flowable<ReleaseMomentSucceedBean> releaseUserCardMoment(@FieldMap Map<String, String> map);
/**
* 查看指定用户的视频列表
*
* @param userId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_MOMENTS_VIDEO_USER_LIST)
Flowable<VideoListBeanNew> getVideoListData(@Query("userId") String userId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 视频播放次数上报
*
* @param map
* @return
*/
@POST(RequestConstants.POST_VIDEO_PLAY_COUNT_UPLOAD)
@FormUrlEncoded
Flowable<BaseDataBean> postVideoPlayCountUpload(@FieldMap Map<String, String> map);
/**
* 获取开关列表
*/
@GET(RequestConstants.PUSH_SWITCH)
Flowable<PushSwitchTypeBean> getPushSwitchList();
/**
* 获取屏蔽日志的用户列表
*/
@GET(RequestConstants.GET_BLOCK_USER_LIST_FOR_MOMENTS)
Flowable<BlackMomentListBean> getBlockUserListForMoments();
/**
* 屏蔽某人的日志(从屏蔽黑名单中移除)
*/
@POST(RequestConstants.CANCEL_BLOCK_USER_MOMENTS)
Flowable<BaseDataBean> cancelBlockUserMoments(@Body RequestBody body);
/**
* 屏蔽某人的日志(从屏蔽黑名单中移除)
*/
@POST(RequestConstants.CANCEL_BLOCK_USER_MOMENTS)
@FormUrlEncoded
Flowable<BaseDataBean> cancelBlockUserMoments(@FieldMap Map<String, String> map);
/**
* 推送开关
*/
@POST(RequestConstants.PUSH_CONFIG)
Flowable<BaseDataBean> pushConfig(@Body RequestBody body);
/**
* 推送开关
*/
@POST(RequestConstants.PUSH_CONFIG)
@FormUrlEncoded
Flowable<BaseDataBean> pushConfig(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_COLLECTION_LIST)
Flowable<FavoritesBean> getFavoriteList(@Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_CURSOR) String cursor);
@POST(RequestConstants.POST_COLLECTION_DELETE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteFavoriteMoment(@Field(RequestConstants.FAVORITE_ID) String favoriteId, @Field(RequestConstants.FAVORITE_COUNT) String momentsId, @Field(RequestConstants.FAVORITE_TYPE) String favoriteType);
@POST(RequestConstants.POST_COLLECTION_DELETE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteFavoriteMoment(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_GOLD_LIST)
Flowable<SoftMoneyListBean> getGoldListData();
/**
* 获取正在直播的用户列表
*
* @return
*/
@GET(RequestConstants.GET_FOLLOWING_USERS)
Flowable<LiveFollowingUsersBeanNew> getFollowingUsers();
/**
* 获取评论的回复列表
*
* @param commentId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_COMMENT_REPLY_LIST)
Flowable<CommentReplyListBeanNew> getCommentReplyList(@Query("id") String commentId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 回复一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.REPLY_COMMENT)
@FormUrlEncoded
Flowable<ReleasedCommentReplyBeanNew> replyComment(@FieldMap Map<String, String> map);
/**
* 删除一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_DELETE_COMMENT)
@FormUrlEncoded
Flowable<BaseDataBean> deleteComment(@FieldMap Map<String, String> map);
/**
* 删除一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.DELETE_COMMENT_REPLY)
@FormUrlEncoded
Flowable<BaseDataBean> deleteCommentReply(@FieldMap Map<String, String> map);
/**
* 举报一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_REPORT_COMMENT)
@FormUrlEncoded
Flowable<BaseDataBean> reportComment(@FieldMap Map<String, String> map);
/**
* 获取moment详情,2.20.0版本后用在MomentCommentActivity页面
*
* @param id 日志id
* @return
*/
@GET(RequestConstants.GET_MOMENT_DETAIL)
Flowable<MomentsBeanNew> getMomentInfoV2(@Query("id") String id);
/**
* 获取moment的评论列表
*
* @param commentId
* @param limit
* @param cursor
* @return
*/
@GET(RequestConstants.GET_COMMENT_LIST)
Flowable<CommentListBeanNew> getCommentList(@Query("id") String commentId, @Query("limit") String limit, @Query("cursor") String cursor);
/**
* @param momentsId
* @param reasonType
* @return
*/
@GET(RequestConstants.BLOCK_THIS_MOMENT)
Flowable<BaseDataBean> blockThisMoment(@Query("momentsId") String momentsId, @Query("reasonType") String reasonType);
/**
* 举报一条日志
*
* @param momentsId
* @param reasonType
* @param reasonContent
* @return
*/
@GET(RequestConstants.MOMENTS_REPORT_MOMENT)
Flowable<BaseDataBean> reportMoment(@Query("momentsId") String momentsId, @Query("reasonType") String reasonType, @Query("reasonContent") String reasonContent);
/**
* 举报用户
*
* @param userId
* @param reasonType
* @param imageUrlList
* @param reasonContent
* @return
*/
@GET(RequestConstants.REPORT_USER)
Flowable<BaseDataBean> reportUser(@Query("userId") String userId, @Query("reasonType") String reasonType, @Query("imageUrlList") String imageUrlList, @Query("reasonContent") String reasonContent);
/**
* 举报用户
*
* @param feedBackType
* @param imageUrlList
* @param feedBackContent
* @return
*/
@GET(RequestConstants.BUG_FEEDBACK)
Flowable<BaseDataBean> bugFeedback(@Query("feedBackType") String feedBackType, @Query("imageUrlList") String imageUrlList, @Query("feedBackContent") String feedBackContent);
/**
* 2.22.0
* 举报用户(观众或者主播)
*
* @param map
* @return
*/
@POST(RequestConstants.POST_REPORT_LIVESHOW_USER)
@FormUrlEncoded
Flowable<BaseDataBean> postReportLiveShowUser(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_RECHARGE_RECORD)
Flowable<RechargeRecordListBeanNew> getRechargeRecord(@Query(RequestConstants.I_CURSOR) String cursor, @Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_FILTER) String filter);
@POST(RequestConstants.SEND_WINK_CREATE)
@FormUrlEncoded
Flowable<BaseDataBean> sendWink(@FieldMap Map<String, String> map);
/**
* 新注册用户获取推荐关注用户列表
*
* @param curPage
*/
@GET(RequestConstants.GET_INIT_RECOMMEND_USERS)
Flowable<InitRecommendUserListBean> getInitRecommendUsers(@Query("curPage") String curPage);
/**
* 4.1.0 获取热门话题回复
* 获取moment的评论列表
*
* @param momentsId 朋友圈消息id
* @param pageSize 当前页码
* @param curPage 每页显示多少条数据
*/
@GET(RequestConstants.THEMES_COMMENT_LIST)
Flowable<ThemeCommentListBeanNew> getThemeCommentList(@Query("cursor") String curPage, @Query("limit") String pageSize, @Query("id") String momentsId);
@POST(RequestConstants.POST_REPORT_USER_ORIMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> postReportImageOrUser(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_USERS_RELATION)
Flowable<FriendListBean> getUsersRelation(@Query(RequestConstants.I_TYPE) String type);
@POST(RequestConstants.UPLOAD_DEVICE_TOKEN)
@FormUrlEncoded
Flowable<BaseDataBean> uploadDeviceToken(@FieldMap Map<String, String> map);
@GET(RequestConstants.MOMENTS_MENTIONED_LIST)
Flowable<TopicFollowerListBean> getMomentMentionedList(@Query("momentsId") String momentsId);
@GET(RequestConstants.GET_LIVE_CLASSIFICATION)
Flowable<LiveClassificationBean> getLiveType();
@GET(RequestConstants.CHECK_UPDATE)
Flowable<VersionBean> checkUpdate(@QueryMap Map<String, String> map);
@POST(RequestConstants.SUBMIT_VIDEO_REPORT)
@FormUrlEncoded
Flowable<BaseDataBean> submitVideoReport(@FieldMap Map<String, String> map);
}
| UTF-8 | Java | 36,098 | java | AllApi.java | Java | [
{
"context": "import retrofit2.http.QueryMap;\n\n/**\n * Created by liuyun on 2017/9/25.\n */\n\npublic interface AllApi {\n\n ",
"end": 3525,
"score": 0.9993667602539062,
"start": 3519,
"tag": "USERNAME",
"value": "liuyun"
},
{
"context": "p);\n\n /**\n * 检查用户名是否重复\n *\n * @param userName\n * @return\n */\n @GET(RequestConstants.",
"end": 5417,
"score": 0.8329430818557739,
"start": 5409,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " * 初始化个人信息,只需要填写昵称、thelID和头像\n *\n * @param userName\n * @param avatarURL\n * @param nickName\n ",
"end": 7342,
"score": 0.9788501858711243,
"start": 7334,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " Flowable<BaseDataBean> updateUserInfo(@Query(\"userName\") String userName, @Query(\"avatarURL\") String ava",
"end": 7513,
"score": 0.6048275232315063,
"start": 7505,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "DataBean> updateUserInfo(@Query(\"userName\") String userName, @Query(\"avatarURL\") String avatarURL, @Query(\"ni",
"end": 7531,
"score": 0.9638113379478455,
"start": 7523,
"tag": "USERNAME",
"value": "userName"
}
] | null | [] | package com.thel.network.api;
import com.thel.base.BaseDataBean;
import com.thel.bean.AdBean;
import com.thel.bean.AdListBean;
import com.thel.bean.BasicInfoBean;
import com.thel.bean.BasicInfoNetBean;
import com.thel.bean.BlackListBean;
import com.thel.bean.CheckUserNameBean;
import com.thel.bean.ContactsListBean;
import com.thel.bean.FavoritesBean;
import com.thel.bean.FirstHotTopicBean;
import com.thel.bean.FriendListBean;
import com.thel.bean.FriendRecommendListBean;
import com.thel.bean.GoogleIapNotifyResultBean;
import com.thel.bean.HiddenLoveBean;
import com.thel.bean.InitRecommendUserListBean;
import com.thel.bean.LikeListBean;
import com.thel.bean.LikeResultBean;
import com.thel.bean.LiveClassificationBean;
import com.thel.bean.PayOrderBean;
import com.thel.bean.RecentAndHotTopicsBean;
import com.thel.bean.RechargeRecordListBeanNew;
import com.thel.bean.ReleaseMomentSucceedBean;
import com.thel.bean.ReleasedCommentBeanNew;
import com.thel.bean.ReleasedCommentReplyBeanNew;
import com.thel.bean.ResultBean;
import com.thel.bean.SearchUsersListBean;
import com.thel.bean.StickerPackListNetBean;
import com.thel.bean.StickerPackNetBean;
import com.thel.bean.ThemeCommentListBeanNew;
import com.thel.bean.TopicListBean;
import com.thel.bean.TrendingTagsBean;
import com.thel.bean.UploadVideoAlbumBean;
import com.thel.bean.VersionBean;
import com.thel.bean.WhoSeenMeListBean;
import com.thel.bean.comment.CommentListBeanNew;
import com.thel.bean.comment.CommentReplyListBeanNew;
import com.thel.bean.gift.WinkCommentListBean;
import com.thel.bean.gift.WinkListBean;
import com.thel.bean.live.LiveFollowingUsersBeanNew;
import com.thel.bean.me.MyCircleFriendListBean;
import com.thel.bean.me.MyCircleRequestListBean;
import com.thel.bean.me.MyWinkListBean;
import com.thel.bean.moments.MomentsBean;
import com.thel.bean.moments.MomentsBeanNew;
import com.thel.bean.moments.MomentsListBean;
import com.thel.bean.moments.MomentsMsgsListBean;
import com.thel.bean.recommend.RecommendedStickerListNetBean;
import com.thel.bean.theme.ThemeListBean;
import com.thel.bean.topic.TopicFollowerListBean;
import com.thel.bean.topic.TopicMainPageBean;
import com.thel.bean.user.BlackMomentListBean;
import com.thel.bean.user.BlockListBean;
import com.thel.bean.user.BlockListBeanNew;
import com.thel.bean.user.LocationNameBean;
import com.thel.bean.user.MatchQuestionBean;
import com.thel.bean.user.MyImagesListBean;
import com.thel.bean.user.NearUserBean;
import com.thel.bean.user.NearUserListNetBean;
import com.thel.bean.user.UploadTokenBean;
import com.thel.bean.user.UserInfoBean;
import com.thel.bean.video.VideoListBeanNew;
import com.thel.modules.live.bean.SoftMoneyListBean;
import com.thel.modules.main.me.bean.FriendsListBean;
import com.thel.modules.main.me.bean.IncomeRecordListBean;
import com.thel.modules.main.me.bean.MatchListBean;
import com.thel.modules.main.me.bean.MyInfoNetBean;
import com.thel.modules.main.me.bean.VipListBean;
import com.thel.modules.main.me.bean.WalletBean;
import com.thel.modules.main.settings.bean.PushSwitchTypeBean;
import com.thel.modules.main.userinfo.bean.FollowersListBean;
import com.thel.network.RequestConstants;
import java.util.Map;
import io.reactivex.Flowable;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Created by liuyun on 2017/9/25.
*/
public interface AllApi {
/**
* 获取一些基本的必要信息接口,如'我'是否是会员、是否有续播的直播
*
* @return
*/
@GET(RequestConstants.GET_BASIC_INFO)
Flowable<BasicInfoNetBean> getBasicInfo();
/**
* 获取自己是否有主播权限
*
* @param userId
* @return
*/
@GET(RequestConstants.GET_LIVE_PERMIT)
Flowable<BaseDataBean> getLivePermit(@Query("userId") String userId);
/**
* 上传设备id,主要是个推的id
*
* @param type
* @param token
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.UPLOAD_DEVICE_TOKEN)
Flowable<BasicInfoBean> uploadDeviceToken(@Field("type") String type, @Field("token") String token);
/**
* 显示欢迎消息
*
* @return
*/
@GET(RequestConstants.SHOW_WELCOME_MSG)
Flowable<BaseDataBean> showWelcomeMsg();
/**
* 通过服务器获取短信验证码,目前仅支持国内区域86
*
* @param cell
* @param zone
* @return
*/
@GET(RequestConstants.SEND_CODE)
Flowable<BaseDataBean> sendCode(@Query("cell") String cell, @Query("zone") String zone);
/**
* 获取上传视频文件到七牛的token
*
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.GET_UPLOAD_TOKEN)
Flowable<UploadTokenBean> getVideoUploadToken(@FieldMap Map<String, String> map);
/**
* 检查电话号码是否被注册过了
*
* @param cell
* @param zone
* @return
*/
@GET(RequestConstants.CHECK_PHONE_NUMBER)
Flowable<BaseDataBean> checkPhoneNumber(@Query("cell") String cell, @Query("zone") String zone);
/**
* 获取黑名单
*
* @return
*/
@GET(RequestConstants.BLACK_LIST)
Flowable<BlackListBean> blackList();
/**
* 手机号、微信、fb绑定
*
* @param map
* @return
*/
@GET(RequestConstants.REBIND)
Flowable<BaseDataBean> rebind(@QueryMap Map<String, String> map);
/**
* 检查用户名是否重复
*
* @param userName
* @return
*/
@GET(RequestConstants.CHECK_USERNAME)
Flowable<CheckUserNameBean> checkUserName(@Query("userName") String userName);
/**
* 找回密码
*
* @param email
* @return
*/
@GET(RequestConstants.FIND_BACK_PASSWORD)
Flowable<BaseDataBean> findBackPassword(@Query("email") String email);
/**
* 用户推出
*
* @return
*/
@POST(RequestConstants.USER_LOGOUT)
@FormUrlEncoded
Flowable<BaseDataBean> loadUserLogout(@FieldMap Map<String, String> map);
/**
* 获取附近用户列表(已登录)参数
*
* @param map
* @return
*/
@GET(RequestConstants.NEAR_BY_SIMPLE_LIST)
Flowable<NearUserBean> getNearbySimpleList(@QueryMap Map<String, String> map);
/**
* 获取附近用户列表(已登录)参数
*
* @param map
* @return
*/
@GET(RequestConstants.GET_ACTIVE_USERS)
Flowable<NearUserListNetBean> getActiveUsers(@QueryMap Map<String, String> map);
/**
* 世界功能
*
* @param map
* @return
*/
@GET(RequestConstants.WORLD_LIST)
Flowable<NearUserListNetBean> getWorldUsers(@QueryMap Map<String, String> map);
/**
* 读取其他用户个人信息
*
* @param userId
* @return
*/
@GET(RequestConstants.USER_INFO)
Flowable<UserInfoBean> getUserInfo(@Query("userId") String userId);
/**
* 读取我的信息
*
* @return
*/
@GET(RequestConstants.MY_INFO)
Flowable<MyInfoNetBean> getMyInfo();
/**
* 更新个人信息
*
* @param body
* @return
*/
@POST(RequestConstants.UPDATE_USER_INFO)
Flowable<BaseDataBean> updateUserInfo(@Body RequestBody body);
/**
* 更新个人信息
*
* @param map
* @return
*/
@POST(RequestConstants.UPDATE_USER_INFO)
@FormUrlEncoded
Flowable<BaseDataBean> updateUserInfo(@FieldMap Map<String, String> map);
/**
* 初始化个人信息,只需要填写昵称、thelID和头像
*
* @param userName
* @param avatarURL
* @param nickName
* @return
*/
@GET(RequestConstants.INIT_USER_INFO)
Flowable<BaseDataBean> updateUserInfo(@Query("userName") String userName, @Query("avatarURL") String avatarURL, @Query("nickName") String nickName);
/**
* 获取朋友列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FRIENDS)
Flowable<FriendsListBean> getFriendsList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取朋友列表(简易,只包含头像、名字、id)
*
* @return
*/
@GET(RequestConstants.GET__CONTACTS)
Flowable<ContactsListBean> getContactsList();
/**
* 获取关注列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FOLLOW)
Flowable<FriendsListBean> getFollowList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取粉丝列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET__FANS)
Flowable<FriendsListBean> getFansList(@Query("userid") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取点赞列表
*
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_LIKED)
Flowable<LikeListBean> getLikedList(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 搜索我的朋友
*
* @return
*/
@GET(RequestConstants.SEARCH_MY_FRIENDS)
Flowable<FriendsListBean> searchMyFriends(@QueryMap Map<String, String> map);
/**
* 上传相册图片(最终url)
*
* @return
*/
@POST(RequestConstants.UPLOAD_IMAGE)
Flowable<BaseDataBean> uploadImageUrl(@Body RequestBody body);
/**
* 上传相册图片(最终url)
*
* @return
*/
@POST(RequestConstants.UPLOAD_IMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> uploadImageUrl(@FieldMap Map<String, String> map);
/**
* 上传视频
*
* @return
*/
@FormUrlEncoded
@POST(RequestConstants.UPLOAD_ALBUM_VIDEO)
Flowable<UploadVideoAlbumBean> uploadAlbumVideoUrl(@FieldMap Map<String, String> map);
/**
* 获取我的照片列表
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.MY_IMAGES_LIST)
Flowable<MyImagesListBean> getMyImagesList(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 删除照片
*
* @return
*/
@POST(RequestConstants.DELETE_IMAGE)
Flowable<BaseDataBean> deleteImage(@Body RequestBody body);
/**
* 删除照片
*
* @return
*/
@POST(RequestConstants.DELETE_IMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteImage(@FieldMap Map<String, String> map);
/**
* 设为隐私照片
*
* @return
*/
@POST(RequestConstants.SET_PRIVATE_STATUS)
Flowable<BaseDataBean> setPrivateStatus(@Body RequestBody body);
/**
* 设为隐私照片
*
* @return
*/
@POST(RequestConstants.SET_PRIVATE_STATUS)
@FormUrlEncoded
Flowable<BaseDataBean> setPrivateStatus(@FieldMap Map<String, String> map);
/**
* 设为封面照片
*
* @return
*/
@POST(RequestConstants.SET_COVER)
Flowable<BaseDataBean> setCover(@Body RequestBody body);
/**
* 设为封面照片
*
* @return
*/
@POST(RequestConstants.SET_COVER)
@FormUrlEncoded
Flowable<BaseDataBean> setCover(@FieldMap Map<String, String> map);
/**
* 搜索好友
*
* @param picId
* @param curPage
* @return
*/
@GET(RequestConstants.SEARCH_NICKNAME)
Flowable<SearchUsersListBean> searchNickname(@Query(RequestConstants.I_KEYWORD) String picId, @Query(RequestConstants.I_CURPAGE) String curPage);
/**
* 谁来看过我
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.CHEACK_VIEW)
Flowable<WhoSeenMeListBean> checkView(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 我看过谁
*
* @param curPage
* @param pageSize
* @return
*/
@GET(RequestConstants.I_VIEW)
Flowable<WhoSeenMeListBean> iView(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 我的黑名单列表
*
* @return
*/
@GET(RequestConstants.GET_USER_BLACK_LIST)
Flowable<BlockListBean> getUserBlackList(@QueryMap Map<String, String> map);
@GET(RequestConstants.GET_USER_BLACK_LIST)
Flowable<BlockListBeanNew> getUserBlackList(@Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 解除黑名单
*
* @return
*/
@POST(RequestConstants.REMOVE_FROM_BLACKLIST)
Flowable<BaseDataBean> removeFromBlackList(@Body RequestBody body);
/**
* 解除黑名单
*
* @return
*/
@POST(RequestConstants.REMOVE_FROM_BLACKLIST)
@FormUrlEncoded
Flowable<BaseDataBean> removeFromBlackList(@FieldMap Map<String, String> map);
/**
* @param userId
* @return
*/
@GET(RequestConstants.SEND_HIDDEN_LOVE)
Flowable<HiddenLoveBean> sendHiddenLove(@Query("userId") String userId);
/**
* 传情
*
* @param userId
* @param type
* @return
*/
@GET(RequestConstants.SEND_WINK_CREATE)
Flowable<BaseDataBean> sendWink(@Query("userId") String userId, @Query("type") String type);
/**
* 关注
*
* @return
*/
@POST(RequestConstants.FOLLOW_USER)
Flowable<ResultBean> followUser(@Body RequestBody body);
@POST(RequestConstants.FOLLOW_USER)
@FormUrlEncoded
Flowable<ResultBean> followUser(@FieldMap Map<String, String> map);
@POST(RequestConstants.FOLLOW_USER_BATCH)
Flowable<ResultBean> followUserBatch(@Body RequestBody body);
@POST(RequestConstants.FOLLOW_USER_BATCH)
@FormUrlEncoded
Flowable<ResultBean> followUserBatch(@FieldMap Map<String, String> map);
/**
* 修改密码
*
* @return
*/
@POST(RequestConstants.MODIFY_PASSWORD)
Flowable<BaseDataBean> modifyPassword(@Body RequestBody body);
/**
* 修改密码
*
* @return
*/
@POST(RequestConstants.MODIFY_PASSWORD)
@FormUrlEncoded
Flowable<BaseDataBean> modifyPassword(@FieldMap Map<String, String> map);
/**
* 获取用户的粉丝列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_USER_FOLLOWERS_LIST)
Flowable<FollowersListBean> getUserFollowersList(@Query("userId") String userId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 我的黑名单列表
*
* @param userId
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_USER_WINK_LIST)
Flowable<WinkListBean> getUserWinkList(@Query("userId") String userId, @Query("cursor") String curPage, @Query("pageSize") String pageSize);
/**
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_MY_WINK_LIST)
Flowable<MyWinkListBean> getMyWinkList(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* theL广告
*
* @return
*/
@GET(RequestConstants.GET_MAIN_ADVERT)
Flowable<AdListBean> getAd();
/**
* 消息的push 由客户端发出
*
* @param message
* @param nickName
* @param userId
* @param token
* @return
*/
@GET(RequestConstants.APP_PUSH)
Flowable<BaseDataBean> messagePushByClient(@Query("message") String message, @Query("nickName") String nickName, @Query("userId") String userId, @Query("token") String token);
/**
* 获取我的密友请求
*
* @return
*/
@GET(RequestConstants.GET_MY_CIRCLE_DATA)
Flowable<MyCircleFriendListBean> getMyCircleData();
/**
* 获取我的密友数据
*
* @param pageSize
* @param curPage
* @return
*/
@GET(RequestConstants.GET_MY_CIRCLE_REQUESTS)
Flowable<MyCircleRequestListBean> getMyCircleRequestData(@Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 发送一条密友请求
*
* @return
*/
@POST(RequestConstants.SEND_CIRCLE_REQUEST)
@FormUrlEncoded
Flowable<MyCircleRequestListBean> sendCircleRequest(@FieldMap Map<String, String> map);
/**
* 取消我发出的密友圈请求
*
* @return
*/
@POST(RequestConstants.CANCEL_CIRCLE_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> cancelRequest(@FieldMap Map<String, String> map);
/**
* 接受密友圈请求
*
* @return
*/
@POST(RequestConstants.ACCEPT_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> acceptRequest(@FieldMap Map<String, String> map);
/**
* 拒绝密友圈请求
*
* @return
*/
@POST(RequestConstants.REFUSE_REQUEST)
@FormUrlEncoded
Flowable<BaseDataBean> refuseRequest(@FieldMap Map<String, String> map);
/**
* 移除密友圈朋友
*
* @return
*/
@POST(RequestConstants.REMOVE_CIRCLE_FRIEND)
Flowable<BaseDataBean> removeCircleFriend(@Body RequestBody body);
/**
* 移除密友圈朋友
*
* @return
*/
@POST(RequestConstants.REMOVE_CIRCLE_FRIEND)
@FormUrlEncoded
Flowable<BaseDataBean> removeCircleFriend(@FieldMap Map<String, String> map);
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@GET(RequestConstants.MATCH_LIST)
Flowable<MatchListBean> getMatchList();
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@POST(RequestConstants.MATCH_ROLLBACK)
Flowable<BaseDataBean> matchRollback(@Body RequestBody body);
/**
* 获取推荐的匹配用户列表
*
* @return
*/
@POST(RequestConstants.MATCH_ROLLBACK)
@FormUrlEncoded
Flowable<BaseDataBean> matchRollback(@FieldMap Map<String, String> map);
/**
* 获取我的匹配问题
*
* @return
*/
@GET(RequestConstants.MY_QUESTIONS)
Flowable<MatchQuestionBean> getMyQuestions();
/**
* setMyQuestions
*
* @return
*/
@POST(RequestConstants.SET_QUESTIONS)
@FormUrlEncoded
Flowable<BaseDataBean> setMyQuestions(@FieldMap Map<String, String> map);
/**
* 喜欢或者不喜欢对方,或取消喜欢对方
*
* @return
*/
@POST(RequestConstants.LIKE_OR_NOT)
Flowable<LikeResultBean> likeOrNot(@Body RequestBody body);
/**
* 喜欢或者不喜欢对方,或取消喜欢对方
*
* @return
*/
@POST(RequestConstants.LIKE_OR_NOT)
@FormUrlEncoded
Flowable<LikeResultBean> likeOrNot(@FieldMap Map<String, String> map);
/**
* 获取表情商店首页-更多表情包
*
* @param vipfree
* @return
*/
@GET(RequestConstants.STICKER_STORE_RECOMMENDED)
Flowable<RecommendedStickerListNetBean> getStickerStoreRecommended(@Query("vipfree") String vipfree);
/**
* 表情包列表
*
* @return
*/
@GET(RequestConstants.STICKER_STORE_MORE)
Flowable<StickerPackListNetBean> getStickerStoreMore(@QueryMap Map<String, String> map);
/**
* 获取我已购买过的表情包
*
* @return
*/
@GET(RequestConstants.PURCHAESED_STICKER_PACKS)
Flowable<StickerPackListNetBean> getPurchasedStickerPacks();
/**
* 获取表情包详情
*
* @return
*/
@GET(RequestConstants.STICKER_PACK_DETAIL)
Flowable<StickerPackNetBean> getStickerPackDetail(@QueryMap Map<String, String> map);
/**
* 从服务端获取生成支付订单的必要数据
*
* @return
*/
@POST(RequestConstants.CREATE_STICKER_PACK_ORDER)
Flowable<PayOrderBean> createStickerPackOrder(@Body RequestBody body);
/**
* 从服务端获取生成支付订单的必要数据
*
* @return
*/
@POST(RequestConstants.CREATE_STICKER_PACK_ORDER)
@FormUrlEncoded
Flowable<PayOrderBean> createStickerPackOrder(@FieldMap Map<String, String> map);
/**
* @param userId 用户id。这个是可选参数,如果有,则是查看某个用户(也可以看自己)的朋友圈信息列表。如果没有这个参数( 或者这个参数传递一个空值),则查看“我能看到的所有的”朋友圈信息列表
* @param mainType 接受 3 种值:空,moments,popular:“空”和“moments”代表:“关注的 日志列表”, 或者是“某个人发的 日志列表”;"popular"代表:热门
* @param pageSize 每页显示多少条数据
* @param curPage 当前页码
* @return
*/
@GET(RequestConstants.MOMENTS_LIST)
Flowable<MomentsListBean> getMomentsList(@Query("userId") String userId, @Query("mainType") String mainType, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 获取最近5个参与的话题,加上 15个热门的话题
*/
@GET(RequestConstants.MOMENTS_GET_RECENT_AND_HOT_TOPICS)
Flowable<RecentAndHotTopicsBean> getRecentAndHotTopics();
/**
* 搜索话题列表
*/
@GET(RequestConstants.MOMENTS_SEARCH_TOPICS)
Flowable<TopicListBean> searchTopics(@Query(RequestConstants.I_TOPIC_NAME) String topicName, @Query(RequestConstants.I_CURPAGE) int curPage);
/**
* 用户昵称修改时间验证(30天内只能修改一次昵称)
**/
@GET(RequestConstants.GET_NICKNAME_TIMEVERIFY)
Flowable<BaseDataBean> getNickNameTimeVerify(@Query("nickname") String nickname);
/**
* 获取最热门的标签
*/
@GET(RequestConstants.GET_FIRST_HOT_TOPIC)
Flowable<FirstHotTopicBean> getFirstHotTopic();
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
Flowable<ReleaseMomentSucceedBean> releaseMoment(@Body RequestBody body);
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
@FormUrlEncoded
Flowable<ReleaseMomentSucceedBean> releaseMoment(@FieldMap Map<String, String> map);
@POST(RequestConstants.GET_UPLOAD_TOKEN)
Flowable<UploadTokenBean> getUploadToken(@Body RequestBody body);
@POST(RequestConstants.GET_UPLOAD_TOKEN)
@FormUrlEncoded
Flowable<UploadTokenBean> getUploadToken(@FieldMap Map<String, String> map);
/**
* 我的钱包数据
*/
@GET(RequestConstants.GET_WALLET_DATA)
Flowable<WalletBean> getWalletData();
@GET(RequestConstants.GET_HOTTHEME_LIST)
Flowable<ThemeListBean> getHotThemeList(@Query(RequestConstants.I_CURSOR) String page, @Query(RequestConstants.I_LIMIT) String limit);
@GET(RequestConstants.GET_THEMES_LIST)
Flowable<ThemeListBean> getThemesList(@Query(RequestConstants.I_CURSOR) String page, @Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_THEMECLASS) String themeClass);
@GET(RequestConstants.GET_MAIN_ADVERT)
Flowable<AdBean> getAd(@Query(RequestConstants.I_CLIENT) String client);
/**
* 收益或提现记录
*/
@GET(RequestConstants.GET_INCOME_OR_WITHDRAW_RECORD)
Flowable<IncomeRecordListBean> getIncomeOrWithdrawRecord(@QueryMap Map<String, String> map);
/**
* 获取朋友圈消息
*
* @param pageSize
* @param curPage
*/
@GET(RequestConstants.MOMENTS_GET_MSGS)
Flowable<MomentsMsgsListBean> getMomentsMsgsList(@Query("pageSize") int pageSize, @Query("curPage") int curPage);
// /**
// * 获取moment的评论列表
// *
// * @param id 朋友圈消息id
// * @param limit 每页显示多少条数据
// * @param cursor 数据库游标
// * @return
// */
// @GET(RequestConstants.GET_COMMENT_LIST)
// Flowable<MomentCommentBean> getCommentList(@Query("id") String id, @Query("limit") String limit, @Query("cursor") String cursor);
@GET(RequestConstants.GET_TRENDING_TAGS)
Flowable<TrendingTagsBean> getTrendingTags();
@POST(RequestConstants.INIT_USER_INFO)
Flowable<BaseDataBean> initUserInfo(@Body RequestBody body);
@POST(RequestConstants.INIT_USER_INFO)
@FormUrlEncoded
Flowable<BaseDataBean> initUserInfo(@FieldMap Map<String, String> map);
/**
* 获取购买vip页面的列表
*/
@GET(RequestConstants.BUY_VIP_LIST)
Flowable<VipListBean> getBuyVipList();
/**
* 获取地理名
*/
@GET(RequestConstants.GET_LOC_NAME)
Flowable<LocationNameBean> getLocationName(@QueryMap Map<String, String> map);
/**
* google wallet 购买成功后提交服务端验证
*/
@POST(RequestConstants.IAP_NOTIFY)
Flowable<GoogleIapNotifyResultBean> iapNotify(@Body RequestBody body);
/**
* google wallet 购买成功后提交服务端验证
*/
@POST(RequestConstants.IAP_NOTIFY)
@FormUrlEncoded
Flowable<GoogleIapNotifyResultBean> iapNotify(@FieldMap Map<String, String> map);
/**
* 获取点赞列表
*
* @param id
* @param cursor
* @param limit
*/
@GET(RequestConstants.MOMENTS_GET_LIKES)
Flowable<WinkCommentListBean> getWinkComments(@Query("id") String id, @Query("limit") String limit, @Query("cursor") String cursor);
/**
* Gold购买/赠送商品(会员)
*/
@POST(RequestConstants.BUY_WITH_GOLD)
Flowable<BaseDataBean> buyWithGold(@Body RequestBody body);
/**
* Gold购买/赠送商品(会员)
*/
@POST(RequestConstants.BUY_WITH_GOLD)
@FormUrlEncoded
Flowable<BaseDataBean> buyWithGold(@FieldMap Map<String, String> map);
/**
* 话题主页面(热门日志)
*
* @param topicName
* @param curPage
* @param pageSize
*/
@GET(RequestConstants.MOMENTS_TOPIC_MAINPAGE_HOT)
Flowable<TopicMainPageBean> getTopicMainPageHot(@Query("topicName") String topicName, @Query("curPage") String curPage, @Query("pageSize") String pageSize);
/**
* 获取moment详情,带评论、wink等等所有信息
*
* @param momentsId 朋友圈消息id
* @param pageSize 当前页码
* @param curPage 每页显示多少条数据
*/
@GET(RequestConstants.MOMENTS_GET_MOMENT_INFO)
Flowable<MomentsBean> getMomentInfo(@Query("momentsId") String momentsId, @Query("pageSize") String pageSize, @Query("curPage") String curPage);
/**
* 4.1.0 话题回复
*
* @param map 要回复的话题bean
*/
@POST(RequestConstants.THEMES_COMMENT_ADD)
@FormUrlEncoded
Flowable<BaseDataBean> releaseThemesComment(@FieldMap Map<String, String> map);
/**
* 发布一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_RELEASE_COMMENT)
@FormUrlEncoded
Flowable<ReleasedCommentBeanNew> releaseComment(@FieldMap Map<String, String> map);
/**
* 获取被推荐的日志详情
*
* @param momentId
*/
@GET(RequestConstants.GET_FRIEND_RECOMMEND_DETAIL)
Flowable<MomentsBean> getFriendRecommendDetail(@Query("id") String momentId);
/**
* 推荐的日志列表的日志详情
*
* @param momentId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_MOMENTS_FRIEND_RECOMMEND_LIST)
Flowable<FriendRecommendListBean> getMomentsFriendRecommendList(@Query("id") String momentId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 发布一条推荐用户日志
*
* @param map
*/
@POST(RequestConstants.MOMENTS_RELEASE_MOMENT)
@FormUrlEncoded
Flowable<ReleaseMomentSucceedBean> releaseUserCardMoment(@FieldMap Map<String, String> map);
/**
* 查看指定用户的视频列表
*
* @param userId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_MOMENTS_VIDEO_USER_LIST)
Flowable<VideoListBeanNew> getVideoListData(@Query("userId") String userId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 视频播放次数上报
*
* @param map
* @return
*/
@POST(RequestConstants.POST_VIDEO_PLAY_COUNT_UPLOAD)
@FormUrlEncoded
Flowable<BaseDataBean> postVideoPlayCountUpload(@FieldMap Map<String, String> map);
/**
* 获取开关列表
*/
@GET(RequestConstants.PUSH_SWITCH)
Flowable<PushSwitchTypeBean> getPushSwitchList();
/**
* 获取屏蔽日志的用户列表
*/
@GET(RequestConstants.GET_BLOCK_USER_LIST_FOR_MOMENTS)
Flowable<BlackMomentListBean> getBlockUserListForMoments();
/**
* 屏蔽某人的日志(从屏蔽黑名单中移除)
*/
@POST(RequestConstants.CANCEL_BLOCK_USER_MOMENTS)
Flowable<BaseDataBean> cancelBlockUserMoments(@Body RequestBody body);
/**
* 屏蔽某人的日志(从屏蔽黑名单中移除)
*/
@POST(RequestConstants.CANCEL_BLOCK_USER_MOMENTS)
@FormUrlEncoded
Flowable<BaseDataBean> cancelBlockUserMoments(@FieldMap Map<String, String> map);
/**
* 推送开关
*/
@POST(RequestConstants.PUSH_CONFIG)
Flowable<BaseDataBean> pushConfig(@Body RequestBody body);
/**
* 推送开关
*/
@POST(RequestConstants.PUSH_CONFIG)
@FormUrlEncoded
Flowable<BaseDataBean> pushConfig(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_COLLECTION_LIST)
Flowable<FavoritesBean> getFavoriteList(@Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_CURSOR) String cursor);
@POST(RequestConstants.POST_COLLECTION_DELETE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteFavoriteMoment(@Field(RequestConstants.FAVORITE_ID) String favoriteId, @Field(RequestConstants.FAVORITE_COUNT) String momentsId, @Field(RequestConstants.FAVORITE_TYPE) String favoriteType);
@POST(RequestConstants.POST_COLLECTION_DELETE)
@FormUrlEncoded
Flowable<BaseDataBean> deleteFavoriteMoment(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_GOLD_LIST)
Flowable<SoftMoneyListBean> getGoldListData();
/**
* 获取正在直播的用户列表
*
* @return
*/
@GET(RequestConstants.GET_FOLLOWING_USERS)
Flowable<LiveFollowingUsersBeanNew> getFollowingUsers();
/**
* 获取评论的回复列表
*
* @param commentId
* @param cursor
* @param limit
* @return
*/
@GET(RequestConstants.GET_COMMENT_REPLY_LIST)
Flowable<CommentReplyListBeanNew> getCommentReplyList(@Query("id") String commentId, @Query("cursor") String cursor, @Query("limit") String limit);
/**
* 回复一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.REPLY_COMMENT)
@FormUrlEncoded
Flowable<ReleasedCommentReplyBeanNew> replyComment(@FieldMap Map<String, String> map);
/**
* 删除一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_DELETE_COMMENT)
@FormUrlEncoded
Flowable<BaseDataBean> deleteComment(@FieldMap Map<String, String> map);
/**
* 删除一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.DELETE_COMMENT_REPLY)
@FormUrlEncoded
Flowable<BaseDataBean> deleteCommentReply(@FieldMap Map<String, String> map);
/**
* 举报一条评论
*
* @param map
* @return
*/
@POST(RequestConstants.MOMENTS_REPORT_COMMENT)
@FormUrlEncoded
Flowable<BaseDataBean> reportComment(@FieldMap Map<String, String> map);
/**
* 获取moment详情,2.20.0版本后用在MomentCommentActivity页面
*
* @param id 日志id
* @return
*/
@GET(RequestConstants.GET_MOMENT_DETAIL)
Flowable<MomentsBeanNew> getMomentInfoV2(@Query("id") String id);
/**
* 获取moment的评论列表
*
* @param commentId
* @param limit
* @param cursor
* @return
*/
@GET(RequestConstants.GET_COMMENT_LIST)
Flowable<CommentListBeanNew> getCommentList(@Query("id") String commentId, @Query("limit") String limit, @Query("cursor") String cursor);
/**
* @param momentsId
* @param reasonType
* @return
*/
@GET(RequestConstants.BLOCK_THIS_MOMENT)
Flowable<BaseDataBean> blockThisMoment(@Query("momentsId") String momentsId, @Query("reasonType") String reasonType);
/**
* 举报一条日志
*
* @param momentsId
* @param reasonType
* @param reasonContent
* @return
*/
@GET(RequestConstants.MOMENTS_REPORT_MOMENT)
Flowable<BaseDataBean> reportMoment(@Query("momentsId") String momentsId, @Query("reasonType") String reasonType, @Query("reasonContent") String reasonContent);
/**
* 举报用户
*
* @param userId
* @param reasonType
* @param imageUrlList
* @param reasonContent
* @return
*/
@GET(RequestConstants.REPORT_USER)
Flowable<BaseDataBean> reportUser(@Query("userId") String userId, @Query("reasonType") String reasonType, @Query("imageUrlList") String imageUrlList, @Query("reasonContent") String reasonContent);
/**
* 举报用户
*
* @param feedBackType
* @param imageUrlList
* @param feedBackContent
* @return
*/
@GET(RequestConstants.BUG_FEEDBACK)
Flowable<BaseDataBean> bugFeedback(@Query("feedBackType") String feedBackType, @Query("imageUrlList") String imageUrlList, @Query("feedBackContent") String feedBackContent);
/**
* 2.22.0
* 举报用户(观众或者主播)
*
* @param map
* @return
*/
@POST(RequestConstants.POST_REPORT_LIVESHOW_USER)
@FormUrlEncoded
Flowable<BaseDataBean> postReportLiveShowUser(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_RECHARGE_RECORD)
Flowable<RechargeRecordListBeanNew> getRechargeRecord(@Query(RequestConstants.I_CURSOR) String cursor, @Query(RequestConstants.I_LIMIT) String limit, @Query(RequestConstants.I_FILTER) String filter);
@POST(RequestConstants.SEND_WINK_CREATE)
@FormUrlEncoded
Flowable<BaseDataBean> sendWink(@FieldMap Map<String, String> map);
/**
* 新注册用户获取推荐关注用户列表
*
* @param curPage
*/
@GET(RequestConstants.GET_INIT_RECOMMEND_USERS)
Flowable<InitRecommendUserListBean> getInitRecommendUsers(@Query("curPage") String curPage);
/**
* 4.1.0 获取热门话题回复
* 获取moment的评论列表
*
* @param momentsId 朋友圈消息id
* @param pageSize 当前页码
* @param curPage 每页显示多少条数据
*/
@GET(RequestConstants.THEMES_COMMENT_LIST)
Flowable<ThemeCommentListBeanNew> getThemeCommentList(@Query("cursor") String curPage, @Query("limit") String pageSize, @Query("id") String momentsId);
@POST(RequestConstants.POST_REPORT_USER_ORIMAGE)
@FormUrlEncoded
Flowable<BaseDataBean> postReportImageOrUser(@FieldMap Map<String, String> map);
@GET(RequestConstants.GET_USERS_RELATION)
Flowable<FriendListBean> getUsersRelation(@Query(RequestConstants.I_TYPE) String type);
@POST(RequestConstants.UPLOAD_DEVICE_TOKEN)
@FormUrlEncoded
Flowable<BaseDataBean> uploadDeviceToken(@FieldMap Map<String, String> map);
@GET(RequestConstants.MOMENTS_MENTIONED_LIST)
Flowable<TopicFollowerListBean> getMomentMentionedList(@Query("momentsId") String momentsId);
@GET(RequestConstants.GET_LIVE_CLASSIFICATION)
Flowable<LiveClassificationBean> getLiveType();
@GET(RequestConstants.CHECK_UPDATE)
Flowable<VersionBean> checkUpdate(@QueryMap Map<String, String> map);
@POST(RequestConstants.SUBMIT_VIDEO_REPORT)
@FormUrlEncoded
Flowable<BaseDataBean> submitVideoReport(@FieldMap Map<String, String> map);
}
| 36,098 | 0.665905 | 0.664746 | 1,237 | 26.223928 | 31.125648 | 222 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.282943 | false | false | 9 |
74bb86f8e6330541bf0ac2b6041d4ed1cfb4618b | 17,403,207,519,524 | 1f72619dd9970c3bd16e2c5c75a5dbd728a50b63 | /app/src/main/java/com/example/navendu/inventoryapp/data/InventoryContract.java | 73a1689cc05c44af089aa03082b27bb0685e528a | [] | no_license | navenduagarwal/inventoryapp | https://github.com/navenduagarwal/inventoryapp | 244f276bbb64d7fa8b9349c6fd03ecded5301ad5 | 5665bdf2686248e230a3669d79b06ac8f21a9640 | refs/heads/master | 2021-01-19T05:03:06.434000 | 2016-07-05T18:00:27 | 2016-07-05T18:00:27 | 62,638,412 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.navendu.inventoryapp.data;
import android.provider.BaseColumns;
/**
* Defines tables and columns required to maintain a product inventory
*/
public class InventoryContract {
/* Inner class that defines the table contents of table*/
public static final class ProductEntry implements BaseColumns {
public static final String TABLE_NAME = "product";
//Name , stored as String
public static final String COLUMN_NAME = "name";
//Image, stored as BLOB
public static final String COLUMN_IMAGE = "image";
//Short Description, stored as text
public static final String COLUMN_SHORT_DESC = "short_desc";
// Price per quantity for the product, stored as real;
public static final String COLUMN_PRICE = "price";
//quantity of items available in the inventory
public static final String COLUMN_QTY_AVL = "qty_avl";
//quantity of items sold from the store
public static final String COLUMN_QTY_SOLD = "qty_sold";
}
}
| UTF-8 | Java | 1,046 | java | InventoryContract.java | Java | [] | null | [] | package com.example.navendu.inventoryapp.data;
import android.provider.BaseColumns;
/**
* Defines tables and columns required to maintain a product inventory
*/
public class InventoryContract {
/* Inner class that defines the table contents of table*/
public static final class ProductEntry implements BaseColumns {
public static final String TABLE_NAME = "product";
//Name , stored as String
public static final String COLUMN_NAME = "name";
//Image, stored as BLOB
public static final String COLUMN_IMAGE = "image";
//Short Description, stored as text
public static final String COLUMN_SHORT_DESC = "short_desc";
// Price per quantity for the product, stored as real;
public static final String COLUMN_PRICE = "price";
//quantity of items available in the inventory
public static final String COLUMN_QTY_AVL = "qty_avl";
//quantity of items sold from the store
public static final String COLUMN_QTY_SOLD = "qty_sold";
}
}
| 1,046 | 0.683556 | 0.683556 | 28 | 36.357143 | 26.212339 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
961070ce6b4af81fdaf6bae63824c4925e41a416 | 28,389,733,843,356 | 70ec3d39a0668e181ac391ab850658b660477be8 | /10001StPrime/src/PrimeNumbersTest.java | 7ce36647206c49e69ecbe517ca0e91e8a2826eac | [] | no_license | akshathas/DailyPractice | https://github.com/akshathas/DailyPractice | 42a12047c4dca85ccdd450c08cae1b52190416a0 | 1889dda19289fb525a25823f11e7b054c8240d36 | refs/heads/master | 2016-09-11T02:02:46.376000 | 2011-02-17T06:06:31 | 2011-02-17T06:06:31 | 1,286,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import junit.framework.TestCase;
public class PrimeNumbersTest extends TestCase {
public void testShouldChecktherequiredPrimeNumber(){
assertEquals(104743, new PrimeNumbers().getTheRequiredPrimeNumber(10001));
}
}
| UTF-8 | Java | 221 | java | PrimeNumbersTest.java | Java | [] | null | [] | import junit.framework.TestCase;
public class PrimeNumbersTest extends TestCase {
public void testShouldChecktherequiredPrimeNumber(){
assertEquals(104743, new PrimeNumbers().getTheRequiredPrimeNumber(10001));
}
}
| 221 | 0.81448 | 0.764706 | 9 | 23.555555 | 27.737305 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 9 |
2cbb6c70f080463556fbcac6886132911552667f | 21,483,426,476,271 | 08c67c376da23af79a4aa79b02d6426c3356dfda | /src/main/java/org/dselent/scheduling/server/dao/RequestTermDao.java | b9d36a23d709c84c90b9260bfe071b8e467eac41 | [] | no_license | frcampanelli/CourseLoadScheduling | https://github.com/frcampanelli/CourseLoadScheduling | 3716d6787b64720b429510a2ee505b8a7dac785f | 3138456e3f61c092f595d9f0d0819080362b610b | refs/heads/master | 2020-03-07T01:02:21.725000 | 2018-02-26T12:59:12 | 2018-02-26T12:59:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dselent.scheduling.server.dao;
import org.dselent.scheduling.server.model.RequestTerm;
import org.springframework.stereotype.Repository;
@Repository
public interface RequestTermDao extends Dao<RequestTerm>
{
// add functions here as needed
}
| UTF-8 | Java | 257 | java | RequestTermDao.java | Java | [] | null | [] | package org.dselent.scheduling.server.dao;
import org.dselent.scheduling.server.model.RequestTerm;
import org.springframework.stereotype.Repository;
@Repository
public interface RequestTermDao extends Dao<RequestTerm>
{
// add functions here as needed
}
| 257 | 0.824903 | 0.824903 | 10 | 24.700001 | 23.177792 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
d9ee6663b545d40dfa445562005bcf030971c568 | 26,757,646,297,534 | 0e4807d8f493c69f88ed912c199a5e90fdef6445 | /csmall/promo-services/promo-provider/src/main/java/com/mall/promo/dal/entitys/PromoItem.java | 58c141927522c594c95834bd64edf71a92811798 | [
"Apache-2.0"
] | permissive | AnshengAriel/csmall | https://github.com/AnshengAriel/csmall | 579c333b4b0c20ba56dc75faf41c34e73e57fce0 | 85a9b5ecbc43d08be404be97c0c20563ec44b026 | refs/heads/master | 2022-12-29T03:04:48.853000 | 2020-10-20T09:52:05 | 2020-10-20T09:52:05 | 305,648,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mall.promo.dal.entitys;
import lombok.Data;
import lombok.ToString;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* @author: jia.xue
* @Email: xuejia@cskaoyan.onaliyun.com
* @Description
**/
@Data
@ToString
@Table(name = "tb_promo_item")
public class PromoItem {
// 主键id
private Integer id;
/**
* 秒杀场次主键id
* @see com.mall.promo.dal.entitys.PromoSession
*/
private Long psId;
// 商品id
private Long itemId;
//商品秒杀价格
private BigDecimal seckillPrice;
//商品秒杀库存
private Integer itemStock;
} | UTF-8 | Java | 630 | java | PromoItem.java | Java | [
{
"context": "ble;\nimport java.math.BigDecimal;\n\n/**\n * @author: jia.xue\n * @Email: xuejia@cskaoyan.onaliyun.com\n * @Descr",
"end": 167,
"score": 0.8136442303657532,
"start": 160,
"tag": "NAME",
"value": "jia.xue"
},
{
"context": "th.BigDecimal;\n\n/**\n * @author: jia.xue\n * @Email: xuejia@cskaoyan.onaliyun.com\n * @Description\n **/\n@Data\n@ToString\n@Table(name ",
"end": 207,
"score": 0.9999331831932068,
"start": 179,
"tag": "EMAIL",
"value": "xuejia@cskaoyan.onaliyun.com"
}
] | null | [] | package com.mall.promo.dal.entitys;
import lombok.Data;
import lombok.ToString;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* @author: jia.xue
* @Email: <EMAIL>
* @Description
**/
@Data
@ToString
@Table(name = "tb_promo_item")
public class PromoItem {
// 主键id
private Integer id;
/**
* 秒杀场次主键id
* @see com.mall.promo.dal.entitys.PromoSession
*/
private Long psId;
// 商品id
private Long itemId;
//商品秒杀价格
private BigDecimal seckillPrice;
//商品秒杀库存
private Integer itemStock;
} | 609 | 0.658703 | 0.658703 | 40 | 13.675 | 13.58195 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
bc611349dbe4d2657a5ba49a2cd6fd6b832cf6b9 | 31,327,491,464,159 | 9d2c1e64b5c300dc1c7a63e141841660968dc560 | /medical-health/medical-system/system-api/src/main/java/com/zrf/service/CheckItemService.java | de509e56ec29f07761c5a57808d6813579d8be69 | [] | no_license | funfage/MedicalHealth | https://github.com/funfage/MedicalHealth | bee06ab33ce811b720ccbbbb2e58974d94ed30d2 | bfe4ff52efcf68f228d1a5493b912a4c4605d3b0 | refs/heads/main | 2023-03-28T23:42:25.247000 | 2021-03-21T14:20:31 | 2021-03-21T14:20:31 | 339,968,590 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zrf.service;
import com.zrf.domain.CheckItem;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zrf.dto.CheckItemDto;
import com.zrf.vo.DataGridView;
import java.util.List;
public interface CheckItemService {
/**
* 分页查询
*
* @param checkItemDto
* @return
*/
DataGridView listCheckItemPage(CheckItemDto checkItemDto);
/**
* 根据ID查询
*
* @param checkItemId
* @return
*/
CheckItem getOne(Long checkItemId);
/**
* 添加
*
* @param checkItemDto
* @return
*/
int addCheckItem(CheckItemDto checkItemDto);
/**
* 修改
*
* @param checkItemDto
* @return
*/
int updateCheckItem(CheckItemDto checkItemDto);
/**
* 根据ID删除
*
* @param checkItemIds
* @return
*/
int deleteCheckItemByIds(Long[] checkItemIds);
/**
* 查询所有可用的检查项目
* @return
*/
List<CheckItem> queryAllCheckItems();
}
| UTF-8 | Java | 1,039 | java | CheckItemService.java | Java | [] | null | [] | package com.zrf.service;
import com.zrf.domain.CheckItem;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zrf.dto.CheckItemDto;
import com.zrf.vo.DataGridView;
import java.util.List;
public interface CheckItemService {
/**
* 分页查询
*
* @param checkItemDto
* @return
*/
DataGridView listCheckItemPage(CheckItemDto checkItemDto);
/**
* 根据ID查询
*
* @param checkItemId
* @return
*/
CheckItem getOne(Long checkItemId);
/**
* 添加
*
* @param checkItemDto
* @return
*/
int addCheckItem(CheckItemDto checkItemDto);
/**
* 修改
*
* @param checkItemDto
* @return
*/
int updateCheckItem(CheckItemDto checkItemDto);
/**
* 根据ID删除
*
* @param checkItemIds
* @return
*/
int deleteCheckItemByIds(Long[] checkItemIds);
/**
* 查询所有可用的检查项目
* @return
*/
List<CheckItem> queryAllCheckItems();
}
| 1,039 | 0.594924 | 0.594924 | 58 | 15.982759 | 15.881557 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.206897 | false | false | 9 |
89365904378fc65616486ba045685096d9095b99 | 5,299,989,645,807 | 8740f56e4b44cee91a2f371b52e32e9b0354b23f | /src/criancaesperanca/CriancaEsperanca.java | 6007f6e18f759ea2f06daa27b486318e004a2416 | [] | no_license | maikonhot/CriancaEsperanca | https://github.com/maikonhot/CriancaEsperanca | 9ead2fef27ced6225c6cd486e77b4682fc778908 | 7c42cae357cd879aca11221fbb5737a950c2743e | refs/heads/master | 2020-03-28T04:57:00.105000 | 2018-09-07T00:02:59 | 2018-09-07T00:02:59 | 147,746,921 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package criancaesperanca;
import java.util.Scanner;
public class CriancaEsperanca {
public static void main(String[] args) {
int doacao, valor;
Scanner leia = new Scanner(System.in);
System.out.println("Digite a doação desejada");
doacao=leia.nextInt();
switch(doacao){
case 10:
System.out.println("Obrigado Você Doou R$10 Reais");
break;
case 15:
System.out.println("Obrigado Você Doou R$15 Reais");
break;
case 20:
System.out.println("Obrigado Você Doou R$20 Reais");
break;
case 40:
System.out.println("Obrigado Você Doou R$40 Reais");
break;
case 5:
System.out.println("Digite o Valor Desejado");
valor = leia.nextInt();
System.out.println("Sua doação foi de R$"+valor);
System.out.println("Obrigado Sua Doação é Muito Importante");
break;
default:
System.out.println("Você Cancelou a Doação");
}
}
}
| UTF-8 | Java | 1,220 | java | CriancaEsperanca.java | Java | [] | null | [] |
package criancaesperanca;
import java.util.Scanner;
public class CriancaEsperanca {
public static void main(String[] args) {
int doacao, valor;
Scanner leia = new Scanner(System.in);
System.out.println("Digite a doação desejada");
doacao=leia.nextInt();
switch(doacao){
case 10:
System.out.println("Obrigado Você Doou R$10 Reais");
break;
case 15:
System.out.println("Obrigado Você Doou R$15 Reais");
break;
case 20:
System.out.println("Obrigado Você Doou R$20 Reais");
break;
case 40:
System.out.println("Obrigado Você Doou R$40 Reais");
break;
case 5:
System.out.println("Digite o Valor Desejado");
valor = leia.nextInt();
System.out.println("Sua doação foi de R$"+valor);
System.out.println("Obrigado Sua Doação é Muito Importante");
break;
default:
System.out.println("Você Cancelou a Doação");
}
}
}
| 1,220 | 0.5 | 0.485904 | 40 | 27.75 | 22.087044 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 9 |
4b6bf3a9f109f0840bfd256846bea1975858de96 | 14,697,378,116,099 | 88ac09da198e5ba0060804678a3133bcdd2d18b1 | /library/src/main/java/company/tap/gosellapi/open/models/TopupPost.java | 68da934aa0156c307a18929e9a8e2c13fd3d094c | [
"MIT"
] | permissive | Tap-Payments/goSellSDK-Android | https://github.com/Tap-Payments/goSellSDK-Android | f95ee91fd3d0442d0ec04f0978b2eaf08be99c80 | e7c6d1161d29754a14127b1260984cdebc762905 | refs/heads/master | 2023-08-18T03:49:56.276000 | 2023-08-16T09:58:37 | 2023-08-16T09:58:37 | 122,467,714 | 17 | 13 | MIT | false | 2022-03-06T15:09:59 | 2018-02-22T11:05:57 | 2021-12-18T11:53:55 | 2022-03-06T08:26:17 | 4,804 | 12 | 10 | 6 | Java | false | false | package company.tap.gosellapi.open.models;
import android.support.annotation.Nullable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* Created by AhlaamK on 7/7/21.
* <p>
* Copyright (c) 2021 Tap Payments.
* All rights reserved.
**/
public class TopupPost implements Serializable {
@SerializedName("url")
@Expose
@Nullable
private String url;
public TopupPost(String url ){
this.url = url;
}
public String getUrl() {
return url;
}
}
| UTF-8 | Java | 605 | java | TopupPost.java | Java | [
{
"context": "e;\nimport java.math.BigDecimal;\n\n/**\n * Created by AhlaamK on 7/7/21.\n * <p>\n * Copyright (c) 2021 Tap Pa",
"end": 268,
"score": 0.991158127784729,
"start": 261,
"tag": "USERNAME",
"value": "AhlaamK"
}
] | null | [] | package company.tap.gosellapi.open.models;
import android.support.annotation.Nullable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* Created by AhlaamK on 7/7/21.
* <p>
* Copyright (c) 2021 Tap Payments.
* All rights reserved.
**/
public class TopupPost implements Serializable {
@SerializedName("url")
@Expose
@Nullable
private String url;
public TopupPost(String url ){
this.url = url;
}
public String getUrl() {
return url;
}
}
| 605 | 0.689256 | 0.676033 | 30 | 19.166666 | 16.494612 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
5ac696482ffe389d9ffe27e6ba75d51ec6a38543 | 32,195,074,871,442 | a7246e9b0d69b29f656ccc12103fce4365a3f0db | /sources/com/facebook/ads/redexgen/X/HV.java | caa1f3bcc0d1b61fa4de87df777803273886f566 | [] | no_license | dungnguyenBKA/app1-decompile | https://github.com/dungnguyenBKA/app1-decompile | e1343b0505bfc8532409f5a51ddc9ac7ad439e04 | 5b9aadc0fb75d6f276e7f8ed912b430896989b15 | refs/heads/master | 2023-07-26T01:41:47.981000 | 2021-09-10T13:24:12 | 2021-09-10T13:24:12 | 405,087,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.ads.redexgen.X;
import java.io.IOException;
public interface HV {
void A3z();
void A8I() throws IOException, InterruptedException;
}
| UTF-8 | Java | 165 | java | HV.java | Java | [] | null | [] | package com.facebook.ads.redexgen.X;
import java.io.IOException;
public interface HV {
void A3z();
void A8I() throws IOException, InterruptedException;
}
| 165 | 0.733333 | 0.721212 | 9 | 17.333334 | 18.630919 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
f11afd2b0f478fe8feabb114def76ba075c89401 | 14,886,356,710,012 | ccdc52a6a64d9fb0698ae9dcf36c150f2f2b747d | /com/android/server/connectivity/nano/DnsEvent.java | 140ea2ba4bbd4b9c8015e04a7c723dc49715bfa0 | [
"Apache-2.0"
] | permissive | headuck/SM-9750-TGY-Oct20-Network | https://github.com/headuck/SM-9750-TGY-Oct20-Network | 192e6f8e66963de15ba83a52992c618f5a26f4fa | a0a85132d2f18be8fe44b8b3142e0ecd287d7930 | refs/heads/main | 2022-12-30T20:49:13.209000 | 2020-10-17T15:38:34 | 2020-10-17T15:38:34 | 304,911,332 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.server.connectivity.nano;
import com.google.protobuf.nano.CodedOutputByteBufferNano;
import com.google.protobuf.nano.MessageNano;
import com.google.protobuf.nano.WireFormatNano;
import java.io.IOException;
public final class DnsEvent extends MessageNano {
public int[] dnsReturnCode;
public long[] dnsTime;
public DnsEvent() {
clear();
}
public DnsEvent clear() {
this.dnsReturnCode = WireFormatNano.EMPTY_INT_ARRAY;
this.dnsTime = WireFormatNano.EMPTY_LONG_ARRAY;
this.cachedSize = -1;
return this;
}
@Override // com.google.protobuf.nano.MessageNano
public void writeTo(CodedOutputByteBufferNano codedOutputByteBufferNano) throws IOException {
int[] iArr = this.dnsReturnCode;
int i = 0;
if (iArr != null && iArr.length > 0) {
int i2 = 0;
while (true) {
int[] iArr2 = this.dnsReturnCode;
if (i2 >= iArr2.length) {
break;
}
codedOutputByteBufferNano.writeInt32(1, iArr2[i2]);
i2++;
}
}
long[] jArr = this.dnsTime;
if (jArr != null && jArr.length > 0) {
while (true) {
long[] jArr2 = this.dnsTime;
if (i >= jArr2.length) {
break;
}
codedOutputByteBufferNano.writeInt64(2, jArr2[i]);
i++;
}
}
super.writeTo(codedOutputByteBufferNano);
}
/* access modifiers changed from: protected */
@Override // com.google.protobuf.nano.MessageNano
public int computeSerializedSize() {
int[] iArr;
int computeSerializedSize = super.computeSerializedSize();
int[] iArr2 = this.dnsReturnCode;
int i = 0;
if (iArr2 != null && iArr2.length > 0) {
int i2 = 0;
int i3 = 0;
while (true) {
iArr = this.dnsReturnCode;
if (i2 >= iArr.length) {
break;
}
i3 += CodedOutputByteBufferNano.computeInt32SizeNoTag(iArr[i2]);
i2++;
}
computeSerializedSize = computeSerializedSize + i3 + (iArr.length * 1);
}
long[] jArr = this.dnsTime;
if (jArr == null || jArr.length <= 0) {
return computeSerializedSize;
}
int i4 = 0;
while (true) {
long[] jArr2 = this.dnsTime;
if (i >= jArr2.length) {
return computeSerializedSize + i4 + (jArr2.length * 1);
}
i4 += CodedOutputByteBufferNano.computeInt64SizeNoTag(jArr2[i]);
i++;
}
}
}
| UTF-8 | Java | 2,775 | java | DnsEvent.java | Java | [] | null | [] | package com.android.server.connectivity.nano;
import com.google.protobuf.nano.CodedOutputByteBufferNano;
import com.google.protobuf.nano.MessageNano;
import com.google.protobuf.nano.WireFormatNano;
import java.io.IOException;
public final class DnsEvent extends MessageNano {
public int[] dnsReturnCode;
public long[] dnsTime;
public DnsEvent() {
clear();
}
public DnsEvent clear() {
this.dnsReturnCode = WireFormatNano.EMPTY_INT_ARRAY;
this.dnsTime = WireFormatNano.EMPTY_LONG_ARRAY;
this.cachedSize = -1;
return this;
}
@Override // com.google.protobuf.nano.MessageNano
public void writeTo(CodedOutputByteBufferNano codedOutputByteBufferNano) throws IOException {
int[] iArr = this.dnsReturnCode;
int i = 0;
if (iArr != null && iArr.length > 0) {
int i2 = 0;
while (true) {
int[] iArr2 = this.dnsReturnCode;
if (i2 >= iArr2.length) {
break;
}
codedOutputByteBufferNano.writeInt32(1, iArr2[i2]);
i2++;
}
}
long[] jArr = this.dnsTime;
if (jArr != null && jArr.length > 0) {
while (true) {
long[] jArr2 = this.dnsTime;
if (i >= jArr2.length) {
break;
}
codedOutputByteBufferNano.writeInt64(2, jArr2[i]);
i++;
}
}
super.writeTo(codedOutputByteBufferNano);
}
/* access modifiers changed from: protected */
@Override // com.google.protobuf.nano.MessageNano
public int computeSerializedSize() {
int[] iArr;
int computeSerializedSize = super.computeSerializedSize();
int[] iArr2 = this.dnsReturnCode;
int i = 0;
if (iArr2 != null && iArr2.length > 0) {
int i2 = 0;
int i3 = 0;
while (true) {
iArr = this.dnsReturnCode;
if (i2 >= iArr.length) {
break;
}
i3 += CodedOutputByteBufferNano.computeInt32SizeNoTag(iArr[i2]);
i2++;
}
computeSerializedSize = computeSerializedSize + i3 + (iArr.length * 1);
}
long[] jArr = this.dnsTime;
if (jArr == null || jArr.length <= 0) {
return computeSerializedSize;
}
int i4 = 0;
while (true) {
long[] jArr2 = this.dnsTime;
if (i >= jArr2.length) {
return computeSerializedSize + i4 + (jArr2.length * 1);
}
i4 += CodedOutputByteBufferNano.computeInt64SizeNoTag(jArr2[i]);
i++;
}
}
}
| 2,775 | 0.528288 | 0.51027 | 86 | 31.267443 | 21.477097 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546512 | false | false | 9 |
b3f1e76c536d5f65af71c6cfee6d1b6aae37c1fb | 29,265,907,177,150 | 854d06932d1ad8b6f58f03a1a3fae2b6e30594a0 | /Aula08Livraria_Livro_Editora/src/teste/TesteDaoMysql.java | 4f9b3dab54980f116b0532b4cd662c3bc1ad182d | [] | no_license | viniciusdenovaes/Unip202ALPOOdiurno | https://github.com/viniciusdenovaes/Unip202ALPOOdiurno | baf5a82f2fbcf01a1853882aed77f43ad55f2ec6 | 723378d60193f1c4755f308acf6c554d4d3e54d7 | refs/heads/master | 2023-01-09T14:01:33.244000 | 2020-11-06T12:49:48 | 2020-11-06T12:49:48 | 288,170,869 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teste;
import java.util.Collection;
import java.util.Map;
import entidades.Editora;
import entidades.Livro;
import model.dao.Dao;
import model.dao.mysql.DaoMySql;
public class TesteDaoMysql {
public static void main(String[] args) {
Dao dao = new DaoMySql();
// Collection<Livro> livros = dao.getLivros("Art");
//
// for(Livro l: livros) {
// System.out.println(l);
// }
Map<Editora, Collection<Livro>> editoras = dao.getEditoras("so");
for(Editora e: editoras.keySet()) {
System.out.println(e);
Collection<Livro> livros = editoras.get(e);
for(Livro l: livros) {
System.out.println("\t" + l);
}
}
}
}
| UTF-8 | Java | 651 | java | TesteDaoMysql.java | Java | [] | null | [] | package teste;
import java.util.Collection;
import java.util.Map;
import entidades.Editora;
import entidades.Livro;
import model.dao.Dao;
import model.dao.mysql.DaoMySql;
public class TesteDaoMysql {
public static void main(String[] args) {
Dao dao = new DaoMySql();
// Collection<Livro> livros = dao.getLivros("Art");
//
// for(Livro l: livros) {
// System.out.println(l);
// }
Map<Editora, Collection<Livro>> editoras = dao.getEditoras("so");
for(Editora e: editoras.keySet()) {
System.out.println(e);
Collection<Livro> livros = editoras.get(e);
for(Livro l: livros) {
System.out.println("\t" + l);
}
}
}
}
| 651 | 0.668203 | 0.668203 | 31 | 20 | 17.350281 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.774194 | false | false | 9 |
7442f9b5123041f29bc738ed2bf5f81ba6cfea7b | 20,023,137,583,938 | 5e129fe0e1b744bddfb7b544dcbf05f03cb74649 | /src/main/java/by/tms/featuric/service/impl/AnswerServiceImpl.java | 94cd4ac12124d4d32de207b22085a699f1499952 | [] | no_license | KrisRadchikova/featuric | https://github.com/KrisRadchikova/featuric | 3cecf8ef46687ee2c9e034cb62c2a9b0727ea446 | d4349f9abb22ea9304d7aed64fbb088e5af9f05a | refs/heads/master | 2023-04-11T17:53:19.232000 | 2021-05-03T19:59:10 | 2021-05-03T19:59:10 | 353,645,143 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.tms.featuric.service.impl;
import by.tms.featuric.entity.FtrcAnswer;
import by.tms.featuric.exception.ExistsException;
import by.tms.featuric.exception.IndexOutOfBoundsException;
import by.tms.featuric.exception.NotFoundException;
import by.tms.featuric.repository.FtrcAnswerRepository;
import by.tms.featuric.service.interfaces.AnswerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
@Slf4j
@Service
public class AnswerServiceImpl implements AnswerService {
private final FtrcAnswerRepository ftrcAnswerRepository;
@Autowired
public AnswerServiceImpl(FtrcAnswerRepository ftrcAnswerRepository) {
this.ftrcAnswerRepository = ftrcAnswerRepository;
}
@Override
public FtrcAnswer save(FtrcAnswer ftrcAnswer) {
log.info("Method - save answer");
if (ftrcAnswerRepository.findByDescription(ftrcAnswer.getDescription()) != null) {
throw new ExistsException("Answer exists");
}
return ftrcAnswerRepository.save(ftrcAnswer);
}
@Override
public FtrcAnswer update(BigInteger id, FtrcAnswer ftrcAnswerRequest) {
log.info("Method - update answer");
ftrcAnswerRepository.findById(id).map(ftrcAnswer -> {
ftrcAnswer.setDescription(ftrcAnswerRequest.getDescription());
ftrcAnswer.setRightAnswer(ftrcAnswerRequest.isRightAnswer());
ftrcAnswer.setQuestion(ftrcAnswerRequest.getQuestion());
return ftrcAnswerRepository.save(ftrcAnswer);
});
return ftrcAnswerRequest;
}
@Override
public void deleteAnswerById(BigInteger id) {
log.info("Method - delete answer by ID");
if (ftrcAnswerRepository.findById(id).isPresent()) {
ftrcAnswerRepository.deleteById(id);
} else {
throw new NotFoundException("Answer with id " + id + " not found");
}
}
@Override
public FtrcAnswer findAnswerById(BigInteger id) {
log.info("Method - find answer by ID");
return ftrcAnswerRepository.findById(id).orElseThrow(IndexOutOfBoundsException::new);
}
}
| UTF-8 | Java | 2,230 | java | AnswerServiceImpl.java | Java | [] | null | [] | package by.tms.featuric.service.impl;
import by.tms.featuric.entity.FtrcAnswer;
import by.tms.featuric.exception.ExistsException;
import by.tms.featuric.exception.IndexOutOfBoundsException;
import by.tms.featuric.exception.NotFoundException;
import by.tms.featuric.repository.FtrcAnswerRepository;
import by.tms.featuric.service.interfaces.AnswerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
@Slf4j
@Service
public class AnswerServiceImpl implements AnswerService {
private final FtrcAnswerRepository ftrcAnswerRepository;
@Autowired
public AnswerServiceImpl(FtrcAnswerRepository ftrcAnswerRepository) {
this.ftrcAnswerRepository = ftrcAnswerRepository;
}
@Override
public FtrcAnswer save(FtrcAnswer ftrcAnswer) {
log.info("Method - save answer");
if (ftrcAnswerRepository.findByDescription(ftrcAnswer.getDescription()) != null) {
throw new ExistsException("Answer exists");
}
return ftrcAnswerRepository.save(ftrcAnswer);
}
@Override
public FtrcAnswer update(BigInteger id, FtrcAnswer ftrcAnswerRequest) {
log.info("Method - update answer");
ftrcAnswerRepository.findById(id).map(ftrcAnswer -> {
ftrcAnswer.setDescription(ftrcAnswerRequest.getDescription());
ftrcAnswer.setRightAnswer(ftrcAnswerRequest.isRightAnswer());
ftrcAnswer.setQuestion(ftrcAnswerRequest.getQuestion());
return ftrcAnswerRepository.save(ftrcAnswer);
});
return ftrcAnswerRequest;
}
@Override
public void deleteAnswerById(BigInteger id) {
log.info("Method - delete answer by ID");
if (ftrcAnswerRepository.findById(id).isPresent()) {
ftrcAnswerRepository.deleteById(id);
} else {
throw new NotFoundException("Answer with id " + id + " not found");
}
}
@Override
public FtrcAnswer findAnswerById(BigInteger id) {
log.info("Method - find answer by ID");
return ftrcAnswerRepository.findById(id).orElseThrow(IndexOutOfBoundsException::new);
}
}
| 2,230 | 0.720179 | 0.718834 | 63 | 34.396824 | 27.558043 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460317 | false | false | 9 |
e0a07b6b891c2cd56f64795651622c3e557f9283 | 22,204,980,953,472 | a269dd8989dcf825388ec3c1fc4e1c48154e9353 | /src/main/java/GraphsAndTrees/createMinimalBST.java | f73e8ea33d715674ef04c9f5f4e0e05b93dc3e60 | [] | no_license | venkat1013/ctci | https://github.com/venkat1013/ctci | 8d90fa31b624f880ec326f9b47f7389ca1e6ff09 | 0356cb51a952e502ae51b16cf54161a3a13d295f | refs/heads/master | 2020-04-07T20:03:46.302000 | 2018-11-22T09:41:15 | 2018-11-22T09:41:15 | 158,673,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package GraphsAndTrees;
public class createMinimalBST {
TreeNode createMinimalBST(int[] array) {
return constructMinimalBST(array, 0, array.length - 1);
}
public TreeNode constructMinimalBST(int[] array, int begin, int end) {
return null;
}
public TreeNode addToTree(int arr[],int begin,int end){
if(begin > end){
return null;
}
int mid = (begin + end)/2;
TreeNode treeNode = new TreeNode(mid);
treeNode.left = addToTree(arr,begin,mid-1);
treeNode.right = addToTree(arr,mid+1,end);
return treeNode;
}
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
}
| UTF-8 | Java | 841 | java | createMinimalBST.java | Java | [] | null | [] | package GraphsAndTrees;
public class createMinimalBST {
TreeNode createMinimalBST(int[] array) {
return constructMinimalBST(array, 0, array.length - 1);
}
public TreeNode constructMinimalBST(int[] array, int begin, int end) {
return null;
}
public TreeNode addToTree(int arr[],int begin,int end){
if(begin > end){
return null;
}
int mid = (begin + end)/2;
TreeNode treeNode = new TreeNode(mid);
treeNode.left = addToTree(arr,begin,mid-1);
treeNode.right = addToTree(arr,mid+1,end);
return treeNode;
}
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
}
| 841 | 0.561237 | 0.555291 | 33 | 24.484848 | 19.493776 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.757576 | false | false | 9 |
d5fa4f4d47013be5943c801adcfd6f8680f0204f | 22,874,995,856,024 | 7bee6674e6d3317a61f5f2bbbeaeef8b3ff3df03 | /springbootapi-master/src/main/java/br/com/treinaweb/springbootapi/repository/ReceptorRepository.java | aab70b18cb4df9a5b07f30f4ecd7b5007c9da04b | [] | no_license | Wes-Ley-Cor-Ean-O39/FMU | https://github.com/Wes-Ley-Cor-Ean-O39/FMU | 502627b795823e20949652ed973f7e1a3c2fe624 | 7995323c0d91d02b460c0ccd151c007d1f6ce9d4 | refs/heads/master | 2022-12-20T11:05:28.459000 | 2021-10-28T03:13:13 | 2021-10-28T03:13:13 | 151,197,525 | 2 | 0 | null | false | 2022-12-16T04:25:12 | 2018-10-02T03:55:01 | 2021-10-28T03:14:01 | 2022-12-16T04:25:09 | 143,467 | 1 | 0 | 10 | Roff | false | false | package br.com.treinaweb.springbootapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.treinaweb.springbootapi.entity.Receptor;
@Repository
public interface ReceptorRepository extends JpaRepository<Receptor, Long>{
}
| UTF-8 | Java | 311 | java | ReceptorRepository.java | Java | [] | null | [] | package br.com.treinaweb.springbootapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.treinaweb.springbootapi.entity.Receptor;
@Repository
public interface ReceptorRepository extends JpaRepository<Receptor, Long>{
}
| 311 | 0.848875 | 0.848875 | 11 | 27.272728 | 28.530975 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
a85b82a844330e29aa5ce928c0d501d0cad7ee7c | 31,379,031,106,569 | f7a574735cea550968515ce6d76abbd7407f96c5 | /src/main/java/org/openepics/discs/names/service/v1/NameElement.java | 470836ab7e48a3080d6bf087ca44a7ac5eacf55f | [] | no_license | imranau/names | https://github.com/imranau/names | e7ebe99b39b8b7bf977588bbee97a614e4040c06 | 6961b4dafff47223565fd5a18541efe17e75b443 | refs/heads/master | 2020-12-23T22:26:57.497000 | 2016-09-30T19:30:25 | 2016-09-30T19:30:25 | 237,295,231 | 0 | 0 | null | true | 2020-01-30T20:04:30 | 2020-01-30T20:04:29 | 2019-02-15T20:12:17 | 2019-02-15T20:42:24 | 3,918 | 0 | 0 | 0 | null | false | false | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.openepics.discs.names.service.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Vasu V <vuppala@frib.msu.org>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NameElement {
private String id;
private String code;
private String description;
private String category;
private String status;
NameElement() {
}
NameElement(String id, String code, String category, String desc, String status) {
this.id = id;
this.code = code;
this.category = category;
this.description = desc;
this.status = status;
}
public void setId(String id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setDescription(String description) {
this.description = description;
}
public void setCategory(String category) {
this.category = category;
}
public void setStatus(String status) {
this.status = status;
}
}
| UTF-8 | Java | 1,258 | java | NameElement.java | Java | [
{
"context": "bind.annotation.XmlRootElement;\n\n/**\n *\n * @author Vasu V <vuppala@frib.msu.org>\n */\n@XmlRootElement\n@XmlAc",
"end": 319,
"score": 0.9997450113296509,
"start": 313,
"tag": "NAME",
"value": "Vasu V"
},
{
"context": "tation.XmlRootElement;\n\n/**\n *\n * @author Vasu V <vuppala@frib.msu.org>\n */\n@XmlRootElement\n@XmlAccessorType(XmlAccessTy",
"end": 341,
"score": 0.9999354481697083,
"start": 321,
"tag": "EMAIL",
"value": "vuppala@frib.msu.org"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.openepics.discs.names.service.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <NAME> <<EMAIL>>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NameElement {
private String id;
private String code;
private String description;
private String category;
private String status;
NameElement() {
}
NameElement(String id, String code, String category, String desc, String status) {
this.id = id;
this.code = code;
this.category = category;
this.description = desc;
this.status = status;
}
public void setId(String id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setDescription(String description) {
this.description = description;
}
public void setCategory(String category) {
this.category = category;
}
public void setStatus(String status) {
this.status = status;
}
}
| 1,245 | 0.648649 | 0.647854 | 55 | 21.872726 | 19.201378 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
38b4177fb33aec2c9cf12f757568213e99cf67ad | 14,731,737,869,446 | d5d3ff3359c234c010ae84ff40755394b209724e | /Clients/RCP/Core/plugins/gov.pnnl.velo.abc/src/abc/table/ABCTableModel.java | 1e7f71455b42e7b64ced132256e4832ce3687c93 | [] | no_license | purohitsumit/velo | https://github.com/purohitsumit/velo | 59f58f60f926d22af270e14c6362b26d9a3b3d59 | bd5ee6b395b2f48e1d8db613d92f567c55f9e736 | refs/heads/master | 2020-05-03T05:36:07.610000 | 2018-10-31T22:14:43 | 2018-10-31T22:14:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package abc.table;
import javax.swing.table.DefaultTableModel;
import abc.validation.ABCDataItem;
public class ABCTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
private ABCTable table;
public ABCTableModel(ABCTable table) {
this.table = table;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public int getRowCount() {
int rowCount = 0;
if(table == null)
return rowCount;
// Otherwise count them up
for(ABCTableRow row: table.getRows()) {
if(row.isVisible()) // Will be visible if it has no parent or its parent is selected and visible
rowCount += row.rowSpan;
}
return rowCount;
}
@Override public Object getValueAt(int row, int column) { return null; }
@Override
public void setValueAt(Object aValue, int row, int column) {
/*
ABCTableRow aBCTableRow = table.getRowModel(row);
if(aBCTableRow != null && aBCTableRow.hasChildren()) {
// updateChildren(aBCTableRow, row, aValue);
aBCTableRow.setPreviousSelection((ABCDataItem)aValue); // Update this
}
*/
}
/*
public void updateChildren(ABCTableRow tableRow, int row, Object aValue) {
int modifiedRows = 0;
System.out.println("Comparing: " + aValue + " to " + tableRow.getPreviousSelection());
if(tableRow.hasChildren() && !aValue.equals(tableRow.getPreviousSelection())) {
int previousChildren = tableRow.getChildRows((ABCDataItem)tableRow.getPreviousSelection());
int newChildren = tableRow.getChildRows((ABCDataItem)aValue);
if(newChildren != previousChildren)
System.out.println("Previous children: " + previousChildren + ", new children: " + newChildren);
modifiedRows = newChildren;
if(previousChildren > newChildren) {
fireTableRowsDeleted(row + 1 + previousChildren - (previousChildren - newChildren), row + previousChildren);
} else if(newChildren > previousChildren) {
fireTableRowsInserted(row + 1 + previousChildren, row + newChildren);
modifiedRows -= newChildren - previousChildren; // Don't need to modified the inserted rows
}
fireTableRowsUpdated(row, row + modifiedRows);
}
}
*/
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return table.getRowModel(rowIndex).getCell(columnIndex).isEditable();
}
}
| UTF-8 | Java | 2,474 | java | ABCTableModel.java | Java | [] | null | [] | package abc.table;
import javax.swing.table.DefaultTableModel;
import abc.validation.ABCDataItem;
public class ABCTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
private ABCTable table;
public ABCTableModel(ABCTable table) {
this.table = table;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public int getRowCount() {
int rowCount = 0;
if(table == null)
return rowCount;
// Otherwise count them up
for(ABCTableRow row: table.getRows()) {
if(row.isVisible()) // Will be visible if it has no parent or its parent is selected and visible
rowCount += row.rowSpan;
}
return rowCount;
}
@Override public Object getValueAt(int row, int column) { return null; }
@Override
public void setValueAt(Object aValue, int row, int column) {
/*
ABCTableRow aBCTableRow = table.getRowModel(row);
if(aBCTableRow != null && aBCTableRow.hasChildren()) {
// updateChildren(aBCTableRow, row, aValue);
aBCTableRow.setPreviousSelection((ABCDataItem)aValue); // Update this
}
*/
}
/*
public void updateChildren(ABCTableRow tableRow, int row, Object aValue) {
int modifiedRows = 0;
System.out.println("Comparing: " + aValue + " to " + tableRow.getPreviousSelection());
if(tableRow.hasChildren() && !aValue.equals(tableRow.getPreviousSelection())) {
int previousChildren = tableRow.getChildRows((ABCDataItem)tableRow.getPreviousSelection());
int newChildren = tableRow.getChildRows((ABCDataItem)aValue);
if(newChildren != previousChildren)
System.out.println("Previous children: " + previousChildren + ", new children: " + newChildren);
modifiedRows = newChildren;
if(previousChildren > newChildren) {
fireTableRowsDeleted(row + 1 + previousChildren - (previousChildren - newChildren), row + previousChildren);
} else if(newChildren > previousChildren) {
fireTableRowsInserted(row + 1 + previousChildren, row + newChildren);
modifiedRows -= newChildren - previousChildren; // Don't need to modified the inserted rows
}
fireTableRowsUpdated(row, row + modifiedRows);
}
}
*/
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return table.getRowModel(rowIndex).getCell(columnIndex).isEditable();
}
}
| 2,474 | 0.669766 | 0.66734 | 71 | 32.84507 | 32.103111 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774648 | false | false | 9 |
353685445f3f2b58f434db2c76dbd983db2614fd | 1,443,109,056,513 | 3cebe34e77438831007c598fe9a8e6109df765ed | /src/com/algoritmusistemos/gvdis/web/delegators/UtilDelegator.java | dfa0b48301f1bcd19c337e80a1c396aa497b7221 | [] | no_license | pauvil/test | https://github.com/pauvil/test | b0be7a5fef6177ccf6aace3974151f290a1738fa | 138d9a5d21d823560bb1de4e6b23e6e50b91cf3e | refs/heads/master | 2021-04-15T12:55:38.790000 | 2018-03-21T11:42:56 | 2018-03-21T11:42:56 | 126,167,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.algoritmusistemos.gvdis.web.delegators;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.hibernate.Session;
import com.algoritmusistemos.gvdis.web.exceptions.ObjectNotFoundException;
import com.algoritmusistemos.gvdis.web.persistence.Istaiga;
import com.algoritmusistemos.gvdis.web.persistence.Valstybe;
import com.algoritmusistemos.gvdis.web.persistence.Zinynas;
import com.algoritmusistemos.gvdis.web.persistence.ZinynoReiksme;
import com.algoritmusistemos.gvdis.web.utils.HibernateUtils;
public class UtilDelegator
{
private static UtilDelegator instance;
public static UtilDelegator getInstance()
{
if (instance == null){
instance = new UtilDelegator();
}
return instance;
}
public static void setError(String error,ActionErrors errors,HttpServletRequest request)
{
errors.add("title", new ActionMessage(error));
request.setAttribute(error, "");
}
public static String trim(String string, int length)
{
if (string == null){
return null;
}
else if (length >= string.length()){
return string;
}
else {
return string.substring(0, length);
}
}
public List getValstybes(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v order by v.pavadinimas").list();
return l;
}
public List getValstybesBeLietuvos(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v where lower(v.pavadinimas) not like 'lietuva' order by v.pavadinimas").list();
return l;
}
public List getPilietybes(HttpServletRequest request)
{
List l = getPilietybesBeNull(request);
Valstybe v = new Valstybe();
v.setKodas("-1");
v.setPavadinimas("");
v.setPilietybe("");
l.add(0, v);
return l;
}
public List getPilietybesBeNull(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v where v.pilietybe is not null order by v.pilietybe").list();
return l;
}
public Valstybe getValstybe(String id,HttpServletRequest request)
{
Valstybe v = (Valstybe)HibernateUtils.currentSession(request).load(Valstybe.class,id);
return v;
}
public Valstybe getValstybe(String id,Session session)
{
Valstybe v = (Valstybe)session.load(Valstybe.class,id);
return v;
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public ZinynoReiksme getZinynoReiksme(long id,HttpServletRequest request)
{
return (ZinynoReiksme)HibernateUtils.currentSession(request).load(ZinynoReiksme.class, new Long(id));
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public Set getZinynoReiksmes(String name,HttpServletRequest request)
throws ObjectNotFoundException
{
Zinynas zin = (Zinynas)HibernateUtils.currentSession(request).createQuery(
"from Zinynas zin where zin.kodas = :kodas").setString("kodas", name).uniqueResult();
if (zin == null){
throw new ObjectNotFoundException("�inynas su kodu " + name + " neregistruotas sistemoje");
}
if (zin == null)return null;
return zin.getZinynoReiksmes();
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public ZinynoReiksme getZinynoReiksme(String value,HttpServletRequest request)
throws ObjectNotFoundException
{
ZinynoReiksme zr = (ZinynoReiksme)HibernateUtils.currentSession(request).createQuery(
"from ZinynoReiksme zr where zr.pavadinimas = :value").setString("value", value).uniqueResult();
if(null != zr) return zr;
else throw new ObjectNotFoundException("ZinynoReiksme su pavadinimu " + value + " neregistruotas sistemoje");
}
public List getIstaigos(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Istaiga i order by i.pavadinimas").list();
return l;
}
public Istaiga getIstaiga(long id,HttpServletRequest request)
{
Istaiga l = (Istaiga)HibernateUtils.currentSession(request).createQuery(
"from Istaiga ist where ist.id = :id").setLong("id", id).uniqueResult();
return l;
}
}
| UTF-8 | Java | 4,561 | java | UtilDelegator.java | Java | [] | null | [] | package com.algoritmusistemos.gvdis.web.delegators;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.hibernate.Session;
import com.algoritmusistemos.gvdis.web.exceptions.ObjectNotFoundException;
import com.algoritmusistemos.gvdis.web.persistence.Istaiga;
import com.algoritmusistemos.gvdis.web.persistence.Valstybe;
import com.algoritmusistemos.gvdis.web.persistence.Zinynas;
import com.algoritmusistemos.gvdis.web.persistence.ZinynoReiksme;
import com.algoritmusistemos.gvdis.web.utils.HibernateUtils;
public class UtilDelegator
{
private static UtilDelegator instance;
public static UtilDelegator getInstance()
{
if (instance == null){
instance = new UtilDelegator();
}
return instance;
}
public static void setError(String error,ActionErrors errors,HttpServletRequest request)
{
errors.add("title", new ActionMessage(error));
request.setAttribute(error, "");
}
public static String trim(String string, int length)
{
if (string == null){
return null;
}
else if (length >= string.length()){
return string;
}
else {
return string.substring(0, length);
}
}
public List getValstybes(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v order by v.pavadinimas").list();
return l;
}
public List getValstybesBeLietuvos(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v where lower(v.pavadinimas) not like 'lietuva' order by v.pavadinimas").list();
return l;
}
public List getPilietybes(HttpServletRequest request)
{
List l = getPilietybesBeNull(request);
Valstybe v = new Valstybe();
v.setKodas("-1");
v.setPavadinimas("");
v.setPilietybe("");
l.add(0, v);
return l;
}
public List getPilietybesBeNull(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Valstybe v where v.pilietybe is not null order by v.pilietybe").list();
return l;
}
public Valstybe getValstybe(String id,HttpServletRequest request)
{
Valstybe v = (Valstybe)HibernateUtils.currentSession(request).load(Valstybe.class,id);
return v;
}
public Valstybe getValstybe(String id,Session session)
{
Valstybe v = (Valstybe)session.load(Valstybe.class,id);
return v;
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public ZinynoReiksme getZinynoReiksme(long id,HttpServletRequest request)
{
return (ZinynoReiksme)HibernateUtils.currentSession(request).load(ZinynoReiksme.class, new Long(id));
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public Set getZinynoReiksmes(String name,HttpServletRequest request)
throws ObjectNotFoundException
{
Zinynas zin = (Zinynas)HibernateUtils.currentSession(request).createQuery(
"from Zinynas zin where zin.kodas = :kodas").setString("kodas", name).uniqueResult();
if (zin == null){
throw new ObjectNotFoundException("�inynas su kodu " + name + " neregistruotas sistemoje");
}
if (zin == null)return null;
return zin.getZinynoReiksmes();
}
/**
* Gra�ina �inyno reik�m� su duotu ID
* @param id - rei�m�s ID
* @throws DocumentNotFoundException - jei n�ra tokios reik�m�s
*/
public ZinynoReiksme getZinynoReiksme(String value,HttpServletRequest request)
throws ObjectNotFoundException
{
ZinynoReiksme zr = (ZinynoReiksme)HibernateUtils.currentSession(request).createQuery(
"from ZinynoReiksme zr where zr.pavadinimas = :value").setString("value", value).uniqueResult();
if(null != zr) return zr;
else throw new ObjectNotFoundException("ZinynoReiksme su pavadinimu " + value + " neregistruotas sistemoje");
}
public List getIstaigos(HttpServletRequest request)
{
List l = HibernateUtils.currentSession(request).createQuery("from Istaiga i order by i.pavadinimas").list();
return l;
}
public Istaiga getIstaiga(long id,HttpServletRequest request)
{
Istaiga l = (Istaiga)HibernateUtils.currentSession(request).createQuery(
"from Istaiga ist where ist.id = :id").setLong("id", id).uniqueResult();
return l;
}
}
| 4,561 | 0.726082 | 0.725416 | 140 | 31.178572 | 33.436352 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.471429 | false | false | 9 |
529fb283558d74deb70fa6c3ad6bb342c7012f58 | 32,590,211,873,634 | 5be812bdf1909a47312823fdf9dcce3849d673cd | /chapter_006/db_tracker/src/main/java/ru/elazarev/exceptions/package-info.java | ec56fecc8eb9b4cd22d8256be01d8b08e1c75ea3 | [
"Apache-2.0"
] | permissive | helycopternicht/elazarev | https://github.com/helycopternicht/elazarev | 284e43eee0705d40d0faeb73475594d5048dd8be | 0a2a3ce40fb8d02237001314fae7c967c256d297 | refs/heads/master | 2021-01-12T09:32:43.081000 | 2018-02-08T15:07:58 | 2018-02-08T15:07:58 | 76,188,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Pacckage fro exceptions fro tracker app.
* @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
* @since 14.04.17
*/
package ru.elazarev.exceptions; | UTF-8 | Java | 163 | java | package-info.java | Java | [
{
"context": "acckage fro exceptions fro tracker app.\n * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)\n * @since 14.0",
"end": 73,
"score": 0.9998936653137207,
"start": 59,
"tag": "NAME",
"value": "Eugene Lazarev"
},
{
"context": "fro tracker app.\n * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)\n * @since 14.04.17\n */\npackage ru.elazarev.excep",
"end": 107,
"score": 0.9999338984489441,
"start": 81,
"tag": "EMAIL",
"value": "helycopternicht@rambler.ru"
}
] | null | [] | /**
* Pacckage fro exceptions fro tracker app.
* @author <NAME> mailto(<EMAIL>)
* @since 14.04.17
*/
package ru.elazarev.exceptions; | 136 | 0.742331 | 0.705521 | 6 | 26.333334 | 20.781937 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 9 |
05b968966b5d2cad29f6682b98a61cf02ca86f1f | 3,264,175,168,619 | a75a894657aa70b0f3c5bfac15994820cd855840 | /5.semester/Programming_in_Java/Solutions/8/Panel.java | f562f3182f72b7dee39b82477237a6b6436ad90e | [] | no_license | triggor/uni_assignments | https://github.com/triggor/uni_assignments | 16faefd1b178783588d3b57a6af8ec8c5850a6b5 | ac2460b412f2f0a65a7fe8cea49ccba999b24f91 | refs/heads/master | 2022-06-03T03:12:41.100000 | 2022-04-03T22:15:57 | 2022-04-03T22:15:57 | 69,769,910 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mikolaj;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class Panel extends JPanel{
public static final int FIELDSIZE = 50;
private Santa santa;
protected Frame frame;
final Child[] children;
public Panel(Frame frame)
{
this.frame = frame;
this.addKeyListener(upKeyListener);
this.addKeyListener(downKeyListener);
this.addKeyListener(leftKeyListener);
this.addKeyListener(rightKeyListener);
this.addKeyListener(giftKeyListener);
this.addKeyListener(exitKeyListener);
santa = new Santa(this);
children = new Child[frame.mikolaj.kidsNum];
for(int i=0; i<frame.mikolaj.kidsNum; i++){
children[i] = new Child(this, i, santa);
}
}
public KeyListener upKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_W){
santa.move("UP");
}
}
};
public KeyListener downKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_S){
santa.move("DOWN");
}
}
};
public KeyListener leftKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_A){
santa.move("LEFT");
}
}
};
public KeyListener rightKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_D){
santa.move("RIGHT");
}
}
};
public KeyListener exitKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
System.exit(0);//czemu nie dziala po pojawianiu sie komunikatu JLabel???????????????????????
}
}
};
public KeyListener giftKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_SPACE){
frame.mikolaj.setGift(santa.x, santa.y);//Santa standing and Gift is set
//System.out.println("Gift is set at " + santa.x + ", " + santa.y);
}
}
};
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
drawSanta(g);
drawKids(g);
drawGifts(g);
}
private void drawSanta(Graphics g){
g.drawImage(santa.santaImage, santa.x*FIELDSIZE, santa.y*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
private void drawKids(Graphics g){
for(int i=0; i<Mikolaj.N; i++){
for(int j=0; j<Mikolaj.M; j++){
if(frame.mikolaj.checkAwakeChild(j,i)){//Child is standing
g.drawImage(Child.childImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkSleepChild(j,i)){//Child is sleeping
g.drawImage(Child.sleepImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkHappyChild(j,i)){//Child is happy
g.drawImage(Child.happyImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkJumpingChild(j,i)){//Child is happy
g.drawImage(Child.childImage, j*FIELDSIZE, i*FIELDSIZE-10, FIELDSIZE, FIELDSIZE, this);
}
}
}
}
private void drawGifts(Graphics g){
for(int i=0; i<Mikolaj.N; i++){
for(int j=0; j<Mikolaj.M; j++){
if(frame.mikolaj.checkGift(j, i)){//Gift is set
g.drawImage(santa.giftImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
}
}
}
}
| UTF-8 | Java | 4,300 | java | Panel.java | Java | [] | null | [] | package mikolaj;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class Panel extends JPanel{
public static final int FIELDSIZE = 50;
private Santa santa;
protected Frame frame;
final Child[] children;
public Panel(Frame frame)
{
this.frame = frame;
this.addKeyListener(upKeyListener);
this.addKeyListener(downKeyListener);
this.addKeyListener(leftKeyListener);
this.addKeyListener(rightKeyListener);
this.addKeyListener(giftKeyListener);
this.addKeyListener(exitKeyListener);
santa = new Santa(this);
children = new Child[frame.mikolaj.kidsNum];
for(int i=0; i<frame.mikolaj.kidsNum; i++){
children[i] = new Child(this, i, santa);
}
}
public KeyListener upKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_W){
santa.move("UP");
}
}
};
public KeyListener downKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_S){
santa.move("DOWN");
}
}
};
public KeyListener leftKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_A){
santa.move("LEFT");
}
}
};
public KeyListener rightKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_D){
santa.move("RIGHT");
}
}
};
public KeyListener exitKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
System.exit(0);//czemu nie dziala po pojawianiu sie komunikatu JLabel???????????????????????
}
}
};
public KeyListener giftKeyListener = new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_SPACE){
frame.mikolaj.setGift(santa.x, santa.y);//Santa standing and Gift is set
//System.out.println("Gift is set at " + santa.x + ", " + santa.y);
}
}
};
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
drawSanta(g);
drawKids(g);
drawGifts(g);
}
private void drawSanta(Graphics g){
g.drawImage(santa.santaImage, santa.x*FIELDSIZE, santa.y*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
private void drawKids(Graphics g){
for(int i=0; i<Mikolaj.N; i++){
for(int j=0; j<Mikolaj.M; j++){
if(frame.mikolaj.checkAwakeChild(j,i)){//Child is standing
g.drawImage(Child.childImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkSleepChild(j,i)){//Child is sleeping
g.drawImage(Child.sleepImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkHappyChild(j,i)){//Child is happy
g.drawImage(Child.happyImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
else if(frame.mikolaj.checkJumpingChild(j,i)){//Child is happy
g.drawImage(Child.childImage, j*FIELDSIZE, i*FIELDSIZE-10, FIELDSIZE, FIELDSIZE, this);
}
}
}
}
private void drawGifts(Graphics g){
for(int i=0; i<Mikolaj.N; i++){
for(int j=0; j<Mikolaj.M; j++){
if(frame.mikolaj.checkGift(j, i)){//Gift is set
g.drawImage(santa.giftImage, j*FIELDSIZE, i*FIELDSIZE, FIELDSIZE, FIELDSIZE, this);
}
}
}
}
}
| 4,300 | 0.541163 | 0.538837 | 126 | 32.111111 | 27.33572 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730159 | false | false | 9 |
ae26e6c0bcaef873ae1030a1dc05466369e3d0d2 | 21,698,174,799,016 | e159c3610a12029f2dc192521e5d92fc92a5bcb2 | /app/src/main/java/com/example/isharaj/contactportal/MainActivity.java | 9dad94862b227363a9645bd66a7a4892503bdf66 | [] | no_license | ishara-upalaksha/ContactsPortal | https://github.com/ishara-upalaksha/ContactsPortal | 2aeef54286b965873eed3bafbe3aa5b22775129b | cdb1056ca0f433644f0bb94f01b9cf3938b430c0 | refs/heads/master | 2020-04-20T14:57:41.473000 | 2019-02-03T05:57:41 | 2019-02-03T05:57:41 | 168,914,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.isharaj.contactportal;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.example.isharaj.contactportal.entities.Person;
import com.example.isharaj.contactportal.services.DatabaseHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Person> people = new ArrayList<>();
DatabaseHelper mDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
mDatabaseHelper = new DatabaseHelper(this);
getContacts();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,people);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void goToAddContactActivity(View view){
Intent addContactIntent = new Intent(this,AddContactActivity.class);
startActivity(addContactIntent);
}
public void getContacts() {
people.clear();
Cursor contacts = mDatabaseHelper.getData();
while(contacts.moveToNext()){
people.add(new Person(contacts.getString(1),
contacts.getString(2),
contacts.getString(3)));
}
Collections.sort(people);
}
}
| UTF-8 | Java | 1,821 | java | MainActivity.java | Java | [] | null | [] | package com.example.isharaj.contactportal;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.example.isharaj.contactportal.entities.Person;
import com.example.isharaj.contactportal.services.DatabaseHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Person> people = new ArrayList<>();
DatabaseHelper mDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
mDatabaseHelper = new DatabaseHelper(this);
getContacts();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,people);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void goToAddContactActivity(View view){
Intent addContactIntent = new Intent(this,AddContactActivity.class);
startActivity(addContactIntent);
}
public void getContacts() {
people.clear();
Cursor contacts = mDatabaseHelper.getData();
while(contacts.moveToNext()){
people.add(new Person(contacts.getString(1),
contacts.getString(2),
contacts.getString(3)));
}
Collections.sort(people);
}
}
| 1,821 | 0.714443 | 0.711148 | 57 | 30.947369 | 22.121214 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 9 |
a880f84a9535b460e1ce10a97bc750a8132edd9c | 6,648,609,429,462 | a408709446aad522776133f6ce7515c336ec0ce1 | /RapidJS/src/org/mycholan/rapidjs/meta/dao/Rapid_MetaDataAccessObject.java | 1e476ab2ccc2704b732c0ed60fc7aec48cf13352 | [] | no_license | mycholan/RapidJS | https://github.com/mycholan/RapidJS | 0c2022a6add7ac6b70e637b3098d5a33c5349b27 | 79923365606155880ff74300883cce1f0eda6eb4 | refs/heads/master | 2021-01-19T08:46:23.207000 | 2013-11-24T18:19:53 | 2013-11-24T18:19:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.mycholan.rapidjs.meta.dao;
import java.util.ArrayList;
import java.util.Iterator;
import net.sf.json.JSONArray;
import org.mycholan.rapidjs.loader.Rapid_Initializer;
import org.mycholan.rapidjs.model.Rapid_ApplicationMetaData;
import org.mycholan.rapidjs.model.Rapid_FactoryMetaData;
import org.mycholan.rapidjs.model.Rapid_RowValueModel;
import org.mycholan.rapidjs.session.RapidContext;
public class Rapid_MetaDataAccessObject {
private RapidContext rContext = null;
Rapid_FactoryMetaData FactoryMetaObj = null;
Rapid_ApplicationMetaData AppMetaData = null;
JSONArray jArray = null;
public Rapid_MetaDataAccessObject(RapidContext rcontext) {
rContext = rcontext;
FactoryMetaObj = Rapid_Initializer.LoadFactoryMeta();
AppMetaData = Rapid_Initializer.LoadApplicationMeta();
}
public String doGetMetaData() {
if(rContext.getRequestModel().getTable().equals("BASE")) {
/*return all the table which will be to create tabs in factory page*/
jArray = JSONArray.fromObject(FactoryMetaObj.getFactoryTab());
}else if(rContext.getRequestModel().getTable().equals("SUBTAB")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(FactoryMetaObj.getFactorySubTab());
}else if(rContext.getRequestModel().getTable().equals("ACTION")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("STYLE")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("DATA")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("DEVICE")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else{
/*return column list of particular table */
for(int i = 0; i < AppMetaData.getAppMetaData().size(); i++) {
if(AppMetaData.getAppMetaData().get(i).getTablename().equals(rContext.getRequestModel().getTable())) {
jArray = JSONArray.fromObject(AppMetaData.getAppMetaData().get(i).getColumn());
}
}
}
if(jArray != null) {
return jArray.toString();
}
return "{\"status\":\"Table not found\", \"info\":\"\"}";
}
private String getSubTabPanelMeta(String table, String subtab) {
ArrayList<ArrayList<String>> rowList = new ArrayList<ArrayList<String>>();
for(int i = 0; i < FactoryMetaObj.getFactoryInitValue().size(); i++) {
if(FactoryMetaObj.getFactoryInitValue().get(i).getTableName().equals("FACTORY_META_CONTROL")) {
for(int j = 0; j < FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().size(); j++) {
for(int k = 0; k < FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue().size(); k++) {
if(FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue().get(k).toLowerCase().equals("rj_"+rContext.getRequestModel().getTable().toLowerCase())) {
rowList.add(FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue());
break;
}
}
}
}
}
jArray = JSONArray.fromObject(rowList);
return jArray.toString();
}
}
| UTF-8 | Java | 3,539 | java | Rapid_MetaDataAccessObject.java | Java | [] | null | [] | package org.mycholan.rapidjs.meta.dao;
import java.util.ArrayList;
import java.util.Iterator;
import net.sf.json.JSONArray;
import org.mycholan.rapidjs.loader.Rapid_Initializer;
import org.mycholan.rapidjs.model.Rapid_ApplicationMetaData;
import org.mycholan.rapidjs.model.Rapid_FactoryMetaData;
import org.mycholan.rapidjs.model.Rapid_RowValueModel;
import org.mycholan.rapidjs.session.RapidContext;
public class Rapid_MetaDataAccessObject {
private RapidContext rContext = null;
Rapid_FactoryMetaData FactoryMetaObj = null;
Rapid_ApplicationMetaData AppMetaData = null;
JSONArray jArray = null;
public Rapid_MetaDataAccessObject(RapidContext rcontext) {
rContext = rcontext;
FactoryMetaObj = Rapid_Initializer.LoadFactoryMeta();
AppMetaData = Rapid_Initializer.LoadApplicationMeta();
}
public String doGetMetaData() {
if(rContext.getRequestModel().getTable().equals("BASE")) {
/*return all the table which will be to create tabs in factory page*/
jArray = JSONArray.fromObject(FactoryMetaObj.getFactoryTab());
}else if(rContext.getRequestModel().getTable().equals("SUBTAB")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(FactoryMetaObj.getFactorySubTab());
}else if(rContext.getRequestModel().getTable().equals("ACTION")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("STYLE")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("DATA")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else if(rContext.getRequestModel().getTable().equals("DEVICE")) {
/*return meta tab which will be used to create sub tabs*/
jArray = JSONArray.fromObject(getSubTabPanelMeta("", rContext.getRequestModel().getTable()));
}else{
/*return column list of particular table */
for(int i = 0; i < AppMetaData.getAppMetaData().size(); i++) {
if(AppMetaData.getAppMetaData().get(i).getTablename().equals(rContext.getRequestModel().getTable())) {
jArray = JSONArray.fromObject(AppMetaData.getAppMetaData().get(i).getColumn());
}
}
}
if(jArray != null) {
return jArray.toString();
}
return "{\"status\":\"Table not found\", \"info\":\"\"}";
}
private String getSubTabPanelMeta(String table, String subtab) {
ArrayList<ArrayList<String>> rowList = new ArrayList<ArrayList<String>>();
for(int i = 0; i < FactoryMetaObj.getFactoryInitValue().size(); i++) {
if(FactoryMetaObj.getFactoryInitValue().get(i).getTableName().equals("FACTORY_META_CONTROL")) {
for(int j = 0; j < FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().size(); j++) {
for(int k = 0; k < FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue().size(); k++) {
if(FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue().get(k).toLowerCase().equals("rj_"+rContext.getRequestModel().getTable().toLowerCase())) {
rowList.add(FactoryMetaObj.getFactoryInitValue().get(i).getTableValue().get(j).getTvalue());
break;
}
}
}
}
}
jArray = JSONArray.fromObject(rowList);
return jArray.toString();
}
}
| 3,539 | 0.722238 | 0.721108 | 78 | 44.371796 | 36.024605 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.820513 | false | false | 9 |
2085f491b88ea5741c7dd4e58eefdd8c616e8df1 | 17,377,437,699,590 | 26bfac7852409146ccc2e480a253ec427de67598 | /arch-isomer/src/main/java/com/freshjuice/isomer/security/multi/rep/AuthenticationRepConfigurer.java | 3f942856f0bb051366dfeef39cc08d4b425fd776 | [] | no_license | freshlml/Arch | https://github.com/freshlml/Arch | f5e590c95030e77caa9b5f85eec7a81877060a5f | dec092cc9032dfa8b3bc1b959680da3c6ba491b4 | refs/heads/master | 2023-08-28T08:08:23.801000 | 2021-09-03T03:06:21 | 2021-09-03T03:06:21 | 388,678,768 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.freshjuice.isomer.security.multi.rep;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.freshjuice.isomer.security.multi.rep.resolver.AuthenticationResolver;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.http.HttpServletRequest;
public class AuthenticationRepConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<AuthenticationRepConfigurer<H>, H> {
//private SessionAuthenticationStrategy sessionAuthenticationStrategy;
//private RememberMeServices rememberMeServices;
//private AuthenticationManager authenticationManager;
//private MessageSourceAccessor messages;
//private boolean continueChainBeforeSuccessfulAuthentication = false;
//private boolean allowSessionCreation = true;
//private ApplicationEventPublisher eventPublisher;
//private boolean permitAll;
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private ObjectMapper objectMapper;
private String defaultFilterProcessesUrl = "/login";
private AuthenticationFailureHandler failureHandler;
private AuthenticationSuccessHandler successHandler;
private AuthenticationSuccessHandler alreadyAuthHandler;
private AuthenticationResolver authenticationTokenResolver;
public AuthenticationRepConfigurer<H> alreadyAuthHandler(AuthenticationSuccessHandler alreadyAuthHandler) {
this.alreadyAuthHandler = alreadyAuthHandler;
return this;
}
public AuthenticationRepConfigurer<H> authenticationTokenResolver(AuthenticationResolver authenticationTokenResolver) {
this.authenticationTokenResolver = authenticationTokenResolver;
return this;
}
public AuthenticationRepConfigurer<H> objectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public AuthenticationRepConfigurer<H> loginProcessesUrl(String defaultFilterProcessesUrl) {
this.defaultFilterProcessesUrl = defaultFilterProcessesUrl;
return this;
}
public AuthenticationRepConfigurer<H> successHandler(AuthenticationSuccessHandler successHandler) {
this.successHandler = successHandler;
return this;
}
public AuthenticationRepConfigurer<H> failureHandler(AuthenticationFailureHandler failureHandler) {
this.failureHandler = failureHandler;
return this;
}
public AuthenticationRepConfigurer<H> authenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
this.authenticationDetailsSource = authenticationDetailsSource;
return this;
}
/*public FlAuthenticationRepConfigurer<H> permitAll() {
return permitAll(true);
}
public FlAuthenticationRepConfigurer<H> permitAll(boolean permitAll) {
this.permitAll = permitAll;
return this;
}*/
@Override
public void init(H http) throws Exception {
//rememberMeServices = http.getSharedObject(RememberMeServices.class);
//sessionAuthenticationStrategy = http.getSharedObject(SessionAuthenticationStrategy.class);
//authenticationManager = http.getSharedObject(AuthenticationManager.class);
}
@Override
public void configure(H http) throws Exception {
AuthenticationRepFilter authenticationRepFilter = new AuthenticationRepFilter(defaultFilterProcessesUrl);
authenticationRepFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
authenticationRepFilter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class));
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
authenticationRepFilter.setRememberMeServices(rememberMeServices);
authenticationRepFilter.setAuthenticationSuccessHandler(successHandler);
authenticationRepFilter.setAuthenticationFailureHandler(failureHandler);
authenticationRepFilter.setAlreadyAuthHandler(alreadyAuthHandler);
authenticationRepFilter.setObjectMapper(objectMapper);
if(authenticationTokenResolver != null) {
authenticationRepFilter.setAuthenticationTokenResolver(authenticationTokenResolver);
}
if(authenticationDetailsSource != null) {
authenticationRepFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
}
if(rememberMeServices != null && rememberMeServices instanceof AbstractRememberMeServices) {
AbstractRememberMeServices abRemember = (AbstractRememberMeServices) rememberMeServices;
authenticationRepFilter.setRememberMeParameter(abRemember.getParameter());
}
authenticationRepFilter = postProcess(authenticationRepFilter);
//Filter的顺序实在HttpSecurity的FilterComparator中定义
http.addFilterBefore(authenticationRepFilter, UsernamePasswordAuthenticationFilter.class);
RepRequestParamsFilter repRequestParamsFilter = new RepRequestParamsFilter();
repRequestParamsFilter.setRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
http.addFilterBefore(repRequestParamsFilter, AuthenticationRepFilter.class);
}
}
| UTF-8 | Java | 6,162 | java | AuthenticationRepConfigurer.java | Java | [] | null | [] | package com.freshjuice.isomer.security.multi.rep;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.freshjuice.isomer.security.multi.rep.resolver.AuthenticationResolver;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.http.HttpServletRequest;
public class AuthenticationRepConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<AuthenticationRepConfigurer<H>, H> {
//private SessionAuthenticationStrategy sessionAuthenticationStrategy;
//private RememberMeServices rememberMeServices;
//private AuthenticationManager authenticationManager;
//private MessageSourceAccessor messages;
//private boolean continueChainBeforeSuccessfulAuthentication = false;
//private boolean allowSessionCreation = true;
//private ApplicationEventPublisher eventPublisher;
//private boolean permitAll;
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private ObjectMapper objectMapper;
private String defaultFilterProcessesUrl = "/login";
private AuthenticationFailureHandler failureHandler;
private AuthenticationSuccessHandler successHandler;
private AuthenticationSuccessHandler alreadyAuthHandler;
private AuthenticationResolver authenticationTokenResolver;
public AuthenticationRepConfigurer<H> alreadyAuthHandler(AuthenticationSuccessHandler alreadyAuthHandler) {
this.alreadyAuthHandler = alreadyAuthHandler;
return this;
}
public AuthenticationRepConfigurer<H> authenticationTokenResolver(AuthenticationResolver authenticationTokenResolver) {
this.authenticationTokenResolver = authenticationTokenResolver;
return this;
}
public AuthenticationRepConfigurer<H> objectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public AuthenticationRepConfigurer<H> loginProcessesUrl(String defaultFilterProcessesUrl) {
this.defaultFilterProcessesUrl = defaultFilterProcessesUrl;
return this;
}
public AuthenticationRepConfigurer<H> successHandler(AuthenticationSuccessHandler successHandler) {
this.successHandler = successHandler;
return this;
}
public AuthenticationRepConfigurer<H> failureHandler(AuthenticationFailureHandler failureHandler) {
this.failureHandler = failureHandler;
return this;
}
public AuthenticationRepConfigurer<H> authenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
this.authenticationDetailsSource = authenticationDetailsSource;
return this;
}
/*public FlAuthenticationRepConfigurer<H> permitAll() {
return permitAll(true);
}
public FlAuthenticationRepConfigurer<H> permitAll(boolean permitAll) {
this.permitAll = permitAll;
return this;
}*/
@Override
public void init(H http) throws Exception {
//rememberMeServices = http.getSharedObject(RememberMeServices.class);
//sessionAuthenticationStrategy = http.getSharedObject(SessionAuthenticationStrategy.class);
//authenticationManager = http.getSharedObject(AuthenticationManager.class);
}
@Override
public void configure(H http) throws Exception {
AuthenticationRepFilter authenticationRepFilter = new AuthenticationRepFilter(defaultFilterProcessesUrl);
authenticationRepFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
authenticationRepFilter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class));
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
authenticationRepFilter.setRememberMeServices(rememberMeServices);
authenticationRepFilter.setAuthenticationSuccessHandler(successHandler);
authenticationRepFilter.setAuthenticationFailureHandler(failureHandler);
authenticationRepFilter.setAlreadyAuthHandler(alreadyAuthHandler);
authenticationRepFilter.setObjectMapper(objectMapper);
if(authenticationTokenResolver != null) {
authenticationRepFilter.setAuthenticationTokenResolver(authenticationTokenResolver);
}
if(authenticationDetailsSource != null) {
authenticationRepFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
}
if(rememberMeServices != null && rememberMeServices instanceof AbstractRememberMeServices) {
AbstractRememberMeServices abRemember = (AbstractRememberMeServices) rememberMeServices;
authenticationRepFilter.setRememberMeParameter(abRemember.getParameter());
}
authenticationRepFilter = postProcess(authenticationRepFilter);
//Filter的顺序实在HttpSecurity的FilterComparator中定义
http.addFilterBefore(authenticationRepFilter, UsernamePasswordAuthenticationFilter.class);
RepRequestParamsFilter repRequestParamsFilter = new RepRequestParamsFilter();
repRequestParamsFilter.setRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
http.addFilterBefore(repRequestParamsFilter, AuthenticationRepFilter.class);
}
}
| 6,162 | 0.801595 | 0.801595 | 126 | 47.761906 | 39.732124 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.579365 | false | false | 9 |
68463eb874bca21e88825d237cd30199f840e0c8 | 7,636,451,879,295 | 4f9e971939f240b899849c40923036d1f67981ef | /server/src/main/java/com/softserve/academy/Tips4Trips/dto/converter/PostConverter.java | 13c861aeab10bce43511c49a6e2eb3caf1cafab6 | [
"Apache-2.0"
] | permissive | kolyasalubov/Lv-393.Java.Tips4Trips | https://github.com/kolyasalubov/Lv-393.Java.Tips4Trips | 2cea4e3bae0004143c2461732e90b350b0176f41 | 95b111bd3fd2fd1e6411b0743362dcd5e3fae060 | refs/heads/master | 2023-01-22T07:29:20.743000 | 2019-05-29T10:19:00 | 2019-05-29T10:19:00 | 179,278,645 | 6 | 3 | Apache-2.0 | false | 2023-01-07T04:25:12 | 2019-04-03T11:46:23 | 2022-11-14T22:52:09 | 2023-01-07T04:25:11 | 21,191 | 5 | 0 | 32 | CSS | false | false | package com.softserve.academy.Tips4Trips.dto.converter;
import com.softserve.academy.Tips4Trips.dto.Page;
import com.softserve.academy.Tips4Trips.dto.details.PostDetailsDTO;
import com.softserve.academy.Tips4Trips.dto.info.PostInfoDTO;
import com.softserve.academy.Tips4Trips.entity.Route;
import com.softserve.academy.Tips4Trips.entity.blog.Post;
import com.softserve.academy.Tips4Trips.service.AccountService;
import com.softserve.academy.Tips4Trips.service.RouteService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Date;
@Component
public class PostConverter implements Converter<Post, PostDetailsDTO> {
private AccountService accountService;
private RouteService routeService;
private RouteConverter routeConverter;
private AccountConverter accountConverter;
private ImageConverter imageConverter;
private ModelMapper modelMapper;
@Autowired
public PostConverter(AccountService accountService,
RouteService routeService,
RouteConverter routeConverter,
AccountConverter accountConverter,
ImageConverter imageConverter,
ModelMapper modelMapper) {
this.accountService = accountService;
this.routeService = routeService;
this.routeConverter = routeConverter;
this.accountConverter = accountConverter;
this.imageConverter = imageConverter;
this.modelMapper = modelMapper;
}
// @PostConstruct
// private void post(){
// modelMapper.createTypeMap(Post.class, PostDetailsDTO.class)
// .setPostConverter(converter -> {
// PostDetailsDTO postDetailsDTO = converter.getDestination();
// Post source = converter.getSource();
// Route route = source.getRoute();
// modelMapper.createTypeMap(Route.class, RouteInfoDTO.class)
// .setPostConverter(converter1 -> {
// RouteInfoDTO routeInfoDTO = converter1.getDestination();
//
// return routeInfoDTO;
// });
// postDetailsDTO.setRouteInfo(modelMapper.map(route, RouteInfoDTO.class));
//
// postDetailsDTO.setLikes(ControllerLinkBuilder
// .linkTo(ControllerLinkBuilder
// .methodOn(LikeController.class)
// .getAccounts(source.getId()))
// .withRel("likes").getHref());
// postDetailsDTO.setComments(ControllerLinkBuilder
// .linkTo(ControllerLinkBuilder
// .methodOn(CommentController.class)
// .findByPostId(source.getId()))
// .withRel("comments").getHref());
// return postDetailsDTO;
//
// });
// }
@Override
public Post convertToEntity(PostDetailsDTO postDetailsDTO) {
Post post = new Post();
post.setId(postDetailsDTO.getId());
post.setName(postDetailsDTO.getName());
post.setContent(postDetailsDTO.getContent());
post.setCreationDate(new Date());
post.setImages(imageConverter.convertToEntity(postDetailsDTO.getImages()));
// post.setCreationDate(postDetailsDTO.getCreationDate());
Route route = routeService.findById(
postDetailsDTO.getRouteInfo().getId());
post.setRoute(route);
post.setAuthor(accountService.findById(postDetailsDTO.getAuthor().getId()));
return post;
}
public Page<PostInfoDTO> convertToInfoDTO(final Page<Post> postPage) {
List<PostInfoDTO> dtos = postPage.getContent().stream()
.map(post -> modelMapper.map(post, PostInfoDTO.class))
.collect(Collectors.toList());
return new Page<>(dtos, postPage.getNumber(), postPage.getTotalPages());
}
@Override
public PostDetailsDTO convertToDTO(Post post) {
return modelMapper.map(post, PostDetailsDTO.class);
}
}
| UTF-8 | Java | 4,376 | java | PostConverter.java | Java | [] | null | [] | package com.softserve.academy.Tips4Trips.dto.converter;
import com.softserve.academy.Tips4Trips.dto.Page;
import com.softserve.academy.Tips4Trips.dto.details.PostDetailsDTO;
import com.softserve.academy.Tips4Trips.dto.info.PostInfoDTO;
import com.softserve.academy.Tips4Trips.entity.Route;
import com.softserve.academy.Tips4Trips.entity.blog.Post;
import com.softserve.academy.Tips4Trips.service.AccountService;
import com.softserve.academy.Tips4Trips.service.RouteService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Date;
@Component
public class PostConverter implements Converter<Post, PostDetailsDTO> {
private AccountService accountService;
private RouteService routeService;
private RouteConverter routeConverter;
private AccountConverter accountConverter;
private ImageConverter imageConverter;
private ModelMapper modelMapper;
@Autowired
public PostConverter(AccountService accountService,
RouteService routeService,
RouteConverter routeConverter,
AccountConverter accountConverter,
ImageConverter imageConverter,
ModelMapper modelMapper) {
this.accountService = accountService;
this.routeService = routeService;
this.routeConverter = routeConverter;
this.accountConverter = accountConverter;
this.imageConverter = imageConverter;
this.modelMapper = modelMapper;
}
// @PostConstruct
// private void post(){
// modelMapper.createTypeMap(Post.class, PostDetailsDTO.class)
// .setPostConverter(converter -> {
// PostDetailsDTO postDetailsDTO = converter.getDestination();
// Post source = converter.getSource();
// Route route = source.getRoute();
// modelMapper.createTypeMap(Route.class, RouteInfoDTO.class)
// .setPostConverter(converter1 -> {
// RouteInfoDTO routeInfoDTO = converter1.getDestination();
//
// return routeInfoDTO;
// });
// postDetailsDTO.setRouteInfo(modelMapper.map(route, RouteInfoDTO.class));
//
// postDetailsDTO.setLikes(ControllerLinkBuilder
// .linkTo(ControllerLinkBuilder
// .methodOn(LikeController.class)
// .getAccounts(source.getId()))
// .withRel("likes").getHref());
// postDetailsDTO.setComments(ControllerLinkBuilder
// .linkTo(ControllerLinkBuilder
// .methodOn(CommentController.class)
// .findByPostId(source.getId()))
// .withRel("comments").getHref());
// return postDetailsDTO;
//
// });
// }
@Override
public Post convertToEntity(PostDetailsDTO postDetailsDTO) {
Post post = new Post();
post.setId(postDetailsDTO.getId());
post.setName(postDetailsDTO.getName());
post.setContent(postDetailsDTO.getContent());
post.setCreationDate(new Date());
post.setImages(imageConverter.convertToEntity(postDetailsDTO.getImages()));
// post.setCreationDate(postDetailsDTO.getCreationDate());
Route route = routeService.findById(
postDetailsDTO.getRouteInfo().getId());
post.setRoute(route);
post.setAuthor(accountService.findById(postDetailsDTO.getAuthor().getId()));
return post;
}
public Page<PostInfoDTO> convertToInfoDTO(final Page<Post> postPage) {
List<PostInfoDTO> dtos = postPage.getContent().stream()
.map(post -> modelMapper.map(post, PostInfoDTO.class))
.collect(Collectors.toList());
return new Page<>(dtos, postPage.getNumber(), postPage.getTotalPages());
}
@Override
public PostDetailsDTO convertToDTO(Post post) {
return modelMapper.map(post, PostDetailsDTO.class);
}
}
| 4,376 | 0.627514 | 0.625229 | 103 | 41.485435 | 26.023464 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621359 | false | false | 9 |
dc03042f864bfbead25773fb0e62a40d88e964d8 | 29,368,986,422,410 | f712654dd0a5b6b1c5f575ccbaecf807b7df97b2 | /AlphaJava/src/UserInput.java | 68390c65ce9e9a6fe6fe858db12bbb887b7f8389 | [] | no_license | blinsy/Java-Projects | https://github.com/blinsy/Java-Projects | 69958c6c6f27995778ebc9a0424c88240884b1ca | 7e3359badf502ba20105076d0b098d7da716876c | refs/heads/master | 2020-04-12T14:08:24.459000 | 2018-12-20T07:43:11 | 2018-12-20T07:43:11 | 162,543,510 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class UserInput {
public static void main(String[] args){
//Accept input from the user
//Take the user's input and calculate the square
int userInput,square;
Scanner input;
System.out.println("Please enter a number to find its square");
input = new Scanner(System.in);
userInput = input.nextInt();
square = userInput*userInput;
System.out.println("The square of the inputed number is "+square);
}
}
| UTF-8 | Java | 514 | java | UserInput.java | Java | [] | null | [] | import java.util.Scanner;
public class UserInput {
public static void main(String[] args){
//Accept input from the user
//Take the user's input and calculate the square
int userInput,square;
Scanner input;
System.out.println("Please enter a number to find its square");
input = new Scanner(System.in);
userInput = input.nextInt();
square = userInput*userInput;
System.out.println("The square of the inputed number is "+square);
}
}
| 514 | 0.640078 | 0.640078 | 16 | 31.125 | 22.410585 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 9 |
db20b5d310bcb5d4b1009f69f23c27bd143eec32 | 32,409,823,234,949 | fa734f2c358f48b0020b2cd1a7792eebc027b685 | /src/main/java/com/vachiShop/service/IFeedbackService.java | 19a3f2cd560cc8b77a887f549c3a20081dd53987 | [] | no_license | pdchinh/vachiShop | https://github.com/pdchinh/vachiShop | dbfe0da99c2c319dc75f101c004928307c0a8e6a | d0fd83a42b51472712bd4d82676439eb9b613e33 | refs/heads/master | 2023-05-13T00:23:14.664000 | 2023-03-24T09:47:01 | 2023-03-24T09:47:01 | 360,794,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vachiShop.service;
import java.util.List;
public interface IFeedbackService {
float rateAvg(long id);
}
| UTF-8 | Java | 119 | java | IFeedbackService.java | Java | [] | null | [] | package com.vachiShop.service;
import java.util.List;
public interface IFeedbackService {
float rateAvg(long id);
}
| 119 | 0.781513 | 0.781513 | 7 | 16 | 14.111798 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
ac3cf7ef13e6cd99534f76e0ec1f83c34bae7c02 | 16,947,941,006,633 | 0129f50ca73d9e8c669b1381c50aee589c5e827c | /arc/test/java/xml/xpath/expression/RelativePathExpressionTest.java | c6f7844e3036829dbe4f6de4a7d903d823a9266d | [] | no_license | blackjava/EasyXPath | https://github.com/blackjava/EasyXPath | cb19ffcb6b6015ebefcf4c58bb525a77358a6016 | b3d142cb6762ed9ff5126038bfdac04bb6341176 | refs/heads/master | 2020-05-19T21:44:36.854000 | 2014-10-31T12:47:39 | 2014-10-31T12:47:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xml.xpath.expression;
import org.junit.Test;
import static org.junit.Assert.*;
public class RelativePathExpressionTest {
@Test
public void relative_path_expression_containing_current_node_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("."));
}
@Test
public void relative_path_expression_containing_single_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node"));
}
@Test
public void relative_path_expression_containing_nested_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node/child"));
}
@Test
public void relative_path_expression_containing_search_for_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node//child"));
}
@Test
public void absolute_path_expression_containing_single_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("/node"));
}
@Test
public void absolute_path_expression_containing_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("/node/child"));
}
@Test
public void search_path_expression_containing_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("//node/child"));
}
@Test
public void path_expression_containing_illegal_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("2node"));
}
@Test
public void path_expression_containing_illegal_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("node/2child"));
}
@Test
public void path_expression_containing_backslash_character_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("node\\2child"));
}
}
| UTF-8 | Java | 2,014 | java | RelativePathExpressionTest.java | Java | [] | null | [] | package xml.xpath.expression;
import org.junit.Test;
import static org.junit.Assert.*;
public class RelativePathExpressionTest {
@Test
public void relative_path_expression_containing_current_node_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("."));
}
@Test
public void relative_path_expression_containing_single_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node"));
}
@Test
public void relative_path_expression_containing_nested_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node/child"));
}
@Test
public void relative_path_expression_containing_search_for_node_name_is_recognized() {
assertTrue(RelativePathExpression.isRelativePathExpression("node//child"));
}
@Test
public void absolute_path_expression_containing_single_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("/node"));
}
@Test
public void absolute_path_expression_containing_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("/node/child"));
}
@Test
public void search_path_expression_containing_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("//node/child"));
}
@Test
public void path_expression_containing_illegal_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("2node"));
}
@Test
public void path_expression_containing_illegal_nested_node_name_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("node/2child"));
}
@Test
public void path_expression_containing_backslash_character_is_not_recognized() {
assertFalse(RelativePathExpression.isRelativePathExpression("node\\2child"));
}
}
| 2,014 | 0.727408 | 0.725919 | 57 | 34.333332 | 37.166924 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.22807 | false | false | 9 |
52b6ce2d576bb420962d2b14a76ad9ea7172700f | 16,947,941,004,961 | c60a999d7c4c00cc7e8b54281bb59c476f53aaad | /src/main/java/io/confluent/consumer/offsets/mirror/service/MirrorMakerService.java | 30992e209d7ab5a7746ba6a17548526fcd48d634 | [] | no_license | ph1lm/kafka-consumer-offsets | https://github.com/ph1lm/kafka-consumer-offsets | 1801dee630eeee56cd409e0db53030af330cbabe | 6ddbac1e1f8c796722bc86d7829a39821d351a98 | refs/heads/master | 2021-01-01T19:41:07.042000 | 2018-02-21T16:01:11 | 2018-02-21T16:01:11 | 98,649,316 | 2 | 3 | null | false | 2018-02-21T16:01:12 | 2017-07-28T12:53:30 | 2018-01-15T12:52:16 | 2018-02-21T16:01:12 | 104 | 1 | 2 | 0 | Java | false | null | package io.confluent.consumer.offsets.mirror.service;
import com.google.common.base.Preconditions;
import io.confluent.consumer.offsets.mirror.MirrorMakerHandlerContext;
import io.confluent.consumer.offsets.mirror.MirrorMakerStateStore;
import io.confluent.consumer.offsets.mirror.entity.MirrorMaker;
import io.confluent.consumer.offsets.mirror.entity.MirrorMakerCounts;
import io.confluent.consumer.offsets.mirror.entity.MirrorMakerTimestamps;
import io.confluent.consumer.offsets.mirror.entity.TopicStats;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class MirrorMakerService {
private static final MirrorMakerService INSTANCE = new MirrorMakerService();
private static final ThreadLocal<SimpleDateFormat> DATE_FORMATTER = ThreadLocal.withInitial(() -> new SimpleDateFormat("dd-MM-yyyy hh:mm:ss SSS"));
private final MirrorMakerStateStore mirrorStateStore;
private MirrorMakerService() {
final MirrorMakerHandlerContext context = MirrorMakerHandlerContext.getInstance();
this.mirrorStateStore = context.getMirrorStateStore();
}
public static MirrorMakerService getInstance() {
return INSTANCE;
}
public MirrorMaker getMirrorMakerState() {
return new MirrorMaker(this.mirrorStateStore.getState());
}
public List<TopicStats> getTopicStats() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.map(entry ->
TopicStats.builder()
.name(entry.getKey().getTopic())
.partition(entry.getKey().getPartition())
.offset(entry.getValue().getOffset())
.count(entry.getValue().getCount())
.date(entry.getValue().getDate())
.build())
.sorted()
.collect(Collectors.toList());
}
public List<TopicStats> getTopicStats(String topicName) {
Preconditions.checkArgument(topicName != null);
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.filter(entry -> entry.getKey().getTopic().equals(topicName))
.map(entry ->
TopicStats.builder()
.name(entry.getKey().getTopic())
.partition(entry.getKey().getPartition())
.offset(entry.getValue().getOffset())
.count(entry.getValue().getCount())
.date(entry.getValue().getDate())
.build())
.sorted()
.collect(Collectors.toList());
}
public List<MirrorMakerCounts> getMirrorMakerCounts() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.collect(Collectors.groupingBy(entry -> entry.getKey().getTopic(),
Collectors.summingLong(entry -> entry.getValue().getCount())))
.entrySet()
.stream()
.map(entry -> new MirrorMakerCounts(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
public List<MirrorMakerTimestamps> getMirrorMakerTimestamps() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.collect(Collectors.groupingBy(entry -> entry.getKey().getTopic(),
Collectors.mapping(entry -> entry.getValue().getDate(), Collectors.collectingAndThen(
Collectors.maxBy(Date::compareTo), optional -> optional.get()))))
.entrySet()
.stream().map(entry -> new MirrorMakerTimestamps(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
}
| UTF-8 | Java | 3,559 | java | MirrorMakerService.java | Java | [] | null | [] | package io.confluent.consumer.offsets.mirror.service;
import com.google.common.base.Preconditions;
import io.confluent.consumer.offsets.mirror.MirrorMakerHandlerContext;
import io.confluent.consumer.offsets.mirror.MirrorMakerStateStore;
import io.confluent.consumer.offsets.mirror.entity.MirrorMaker;
import io.confluent.consumer.offsets.mirror.entity.MirrorMakerCounts;
import io.confluent.consumer.offsets.mirror.entity.MirrorMakerTimestamps;
import io.confluent.consumer.offsets.mirror.entity.TopicStats;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class MirrorMakerService {
private static final MirrorMakerService INSTANCE = new MirrorMakerService();
private static final ThreadLocal<SimpleDateFormat> DATE_FORMATTER = ThreadLocal.withInitial(() -> new SimpleDateFormat("dd-MM-yyyy hh:mm:ss SSS"));
private final MirrorMakerStateStore mirrorStateStore;
private MirrorMakerService() {
final MirrorMakerHandlerContext context = MirrorMakerHandlerContext.getInstance();
this.mirrorStateStore = context.getMirrorStateStore();
}
public static MirrorMakerService getInstance() {
return INSTANCE;
}
public MirrorMaker getMirrorMakerState() {
return new MirrorMaker(this.mirrorStateStore.getState());
}
public List<TopicStats> getTopicStats() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.map(entry ->
TopicStats.builder()
.name(entry.getKey().getTopic())
.partition(entry.getKey().getPartition())
.offset(entry.getValue().getOffset())
.count(entry.getValue().getCount())
.date(entry.getValue().getDate())
.build())
.sorted()
.collect(Collectors.toList());
}
public List<TopicStats> getTopicStats(String topicName) {
Preconditions.checkArgument(topicName != null);
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.filter(entry -> entry.getKey().getTopic().equals(topicName))
.map(entry ->
TopicStats.builder()
.name(entry.getKey().getTopic())
.partition(entry.getKey().getPartition())
.offset(entry.getValue().getOffset())
.count(entry.getValue().getCount())
.date(entry.getValue().getDate())
.build())
.sorted()
.collect(Collectors.toList());
}
public List<MirrorMakerCounts> getMirrorMakerCounts() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.collect(Collectors.groupingBy(entry -> entry.getKey().getTopic(),
Collectors.summingLong(entry -> entry.getValue().getCount())))
.entrySet()
.stream()
.map(entry -> new MirrorMakerCounts(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
public List<MirrorMakerTimestamps> getMirrorMakerTimestamps() {
return this.mirrorStateStore.getTopicsStats()
.entrySet()
.stream()
.collect(Collectors.groupingBy(entry -> entry.getKey().getTopic(),
Collectors.mapping(entry -> entry.getValue().getDate(), Collectors.collectingAndThen(
Collectors.maxBy(Date::compareTo), optional -> optional.get()))))
.entrySet()
.stream().map(entry -> new MirrorMakerTimestamps(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
}
| 3,559 | 0.67238 | 0.67238 | 92 | 37.684784 | 28.515797 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326087 | false | false | 9 |
1b48a4f8bd33c6e17eb3e91f9ed27242367d69fe | 25,469,156,103,601 | 1b1b4e4a8fc394121229bed44d1addc450170966 | /Biolipsis 1.2/src/motor/Juego.java | 511d29e69e52728c78b8ed0046899d07decb0954 | [] | no_license | 6xhhs/biolipsis | https://github.com/6xhhs/biolipsis | 27f8b23321d3fbfb710c6502fce98bc1b8316df8 | 2e376033858b8aceafb4251de88961e6f2375863 | refs/heads/master | 2021-01-25T08:37:39.964000 | 2010-05-14T16:52:50 | 2010-05-14T16:52:50 | 41,024,873 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package motor;
//import elementos.AnimalCinco;
import java.util.Random;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import menu.Menu;
import personajes.Enemigos;
import personajes.Heroes;
//import personajes.ZombieMoviles;
public class Juego extends GameCanvas implements Animable {
private AdministradorJuego admin;
private AnimadorJuego animador;
private boolean bandera = false;
private Graphics g;
public int ANCHO;
private int ALTO;
private Biolipsis midlet;
private boolean banderaDisparo = false;
private boolean banderaMovimientoZombie;
private boolean banderaColisionDano;
private int banderaNumeroZombie;
private boolean banderaDireccion;
private boolean banderaBala;
private boolean banderaMorir;
private boolean banderaVirus;
private boolean banderaVirus1;
private boolean banderaVirus2;
private boolean banderaParpadeo;
private Menu menu;
private Random random;
public Juego(Biolipsis midlet, boolean seleccionPersonaje) throws Exception {
super(true);
setFullScreenMode(true);
g = getGraphics();
ANCHO = getWidth();
ALTO = getHeight();
this.midlet = midlet;
if(!midlet.estaReproduciendo()){
midlet.reproducir("Menu.mid");
}
banderaMovimientoZombie = false;
banderaColisionDano = false;
banderaDireccion=false;
banderaNumeroZombie = 0;
banderaBala=false;
banderaMorir=false;
banderaVirus = false;
banderaVirus1 = false;
banderaVirus2 = false;
banderaParpadeo = false;
random = new Random();
admin = new AdministradorJuego(ANCHO, ALTO, seleccionPersonaje);
animador = new AnimadorJuego(this);
animador.iniciar();
}
public void dibujar() {
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
admin.paint(g);
g.setColor(0x00FF00);
g.drawString("D-Salir", ANCHO / 2, ALTO, Graphics.BOTTOM | Graphics.HCENTER);
flushGraphics();
}
public void actualizar() {
int tecla = getKeyStates();
if (tecla == 0 && !banderaDisparo) {
if (!banderaDisparo) {
admin.personaje.setFrameSequence(admin.personaje.getSecuencia());
bandera = false;
}
bandera = false;
}
int x = admin.personaje.getX();
int y = admin.personaje.getY();
if ((tecla & RIGHT_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverDerecha();
if(!banderaBala){
banderaDireccion=false;
}
} else if ((tecla & LEFT_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverIzquierda();
if(!banderaBala){
banderaDireccion=true;
}
}
if ((tecla & FIRE_PRESSED) != 0 && !bandera) {
bandera = true;
banderaDisparo = true;
banderaBala=true;
if(!banderaDireccion){
admin.bala.setPosition(x+Heroes.ancho,y+(Heroes.alto/2));
}else{
admin.bala.setPosition(x,y+(Heroes.alto/2));
}
admin.personaje.setFrameSequence(Heroes.getSecuenciaDisparo());
}
if ((tecla & UP_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverArriba();
}
if ((tecla & DOWN_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverAbajo();
}
if ((tecla & GAME_D_PRESSED) != 0) {
midlet.notifyPaused();
System.out.println("Me han pausado");
} else if ((tecla & GAME_A_PRESSED) != 0) {
midlet.resumeRequest();
}
if (admin.personaje.collidesWith(admin.mapa1, false)) {
admin.personaje.setPosition(x, y);
}
if (banderaDisparo) {
admin.personaje.disparo(this);
}
if(banderaBala){
admin.bala.movimiento(admin.mapa1, (Enemigos) admin.zombie1, (Enemigos)admin.zombie2, (Enemigos)admin.zombie3, this, admin, banderaDireccion);
}
if(admin.zombie1.collidesWith(admin.bala, true)){
admin.zombie1.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento()-10, -10);
}
if(admin.zombie1.getVida()<=0){
banderaMorir=true;
admin.zombie1.morir(this, admin);
if(!banderaMorir){
admin.zombie1.restaurarVida();
}
}
if(admin.zombie1.getVida()>0){
admin.zombie1.mover(this, banderaMovimientoZombie, admin.mapa1, admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 1;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && !banderaColisionDano && banderaNumeroZombie == 1) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && banderaNumeroZombie == 1) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
if(admin.zombie2.collidesWith(admin.bala, true)){
admin.zombie2.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento(), 0);
}
if(admin.zombie2.getVida()<=0){
banderaMorir=true;
admin.zombie2.morir(this, admin);
if(!banderaMorir){
admin.zombie2.restaurarVida();
}
}
if(admin.zombie2.getVida()>0){
admin.zombie2.mover(this, banderaMovimientoZombie, admin.mapa1,admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 2;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && !banderaColisionDano && banderaNumeroZombie == 2) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && banderaNumeroZombie == 2) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
if(admin.zombie3.collidesWith(admin.bala, true)){
admin.zombie3.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento(), 0);
}
if(admin.zombie3.getVida()<=0){
banderaMorir=true;
admin.zombie3.morir(this, admin);
if(!banderaMorir) {
admin.zombie3.restaurarVida();
}
}
if(admin.zombie3.getVida()>0){
admin.zombie3.mover(this, banderaMovimientoZombie, admin.mapa1,admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 3;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && !banderaColisionDano && banderaNumeroZombie == 3) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && banderaNumeroZombie == 3) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
// Actualizacion y colisiones de primer nivel
if( admin.lancha.getX()>=1900) {
admin.lancha.setPosition(-30, 75);
}
if(admin.personaje.getX()>=650 && admin.personaje.getX()<=700) {
admin.agua.setPosition(760, 90);
}
if(admin.personaje.getX()>=1410 && admin.personaje.getX()<=1460) {
admin.agua.setPosition(1520, 90);
}
if(admin.personaje.getX()>=440 && admin.personaje.getX()<=490) {
admin.agua.setPosition(0, 90);
}
if(admin.personaje.getX()>=1200 && admin.personaje.getX()<=1250) {
admin.agua.setPosition(760, 90);
}
if(admin.personaje.getX()>=1030 && admin.personaje.getX()<=1080) {
admin.agua1.setPosition(1140, 90);
}
if(admin.personaje.getX()>=700 && admin.personaje.getX()<=790) {
admin.agua1.setPosition(380, 90);
}
admin.nativoUno.mover(-2);
admin.lancha.mover(2);
admin.animalUno.mover(-1);
admin.animalDos.mover(-1);
admin.animalCinco.mover(-1);
admin.animalSeis.mover(-1);
admin.animalUno.actualizar();
admin.animalDos.actualizar();
admin.animalTres.actualizar();
admin.animalCuatro.actualizar();
admin.animalCinco.actualizar();
admin.animalSeis.actualizar();
admin.nativoUno.actualizar();
admin.nativoDos.actualizar();
admin.nativoTres.actualizar();
admin.lancha.actualizar();
admin.agua.actualizar();
admin.agua1.actualizar();
if(admin.personaje.collidesWith(admin.vida, true)) {
admin.vida.setPosition(admin.personaje.getX()+700, 80);
admin.personaje.calcularRecuperacion();
System.out.println("Subi a " + Heroes.vida + " de vida");
} else if (admin.personaje.getX()>admin.vida.getX()+180) {
admin.vida.setPosition(admin.personaje.getX()+700, 80);
}
admin.vida.actualizar();
// Actualizacion y colisiones de segundo nivel
/*if(admin.personaje.collidesWith(admin.virus, true) && !banderaVirus && !banderaParpadeo) {
banderaVirus = true;
if(banderaVirus) {
banderaParpadeo = true;
admin.personaje.setFrameSequence(admin.personaje.getSecuenciaHerido());
admin.personaje.calcularDano();
}
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus, true)) {
admin.personaje.herido(this);
}
if(admin.personaje.collidesWith(admin.virus1, true) && !banderaVirus1) {
banderaVirus1 = true;
admin.personaje.calcularDano();
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus1, true)) {
banderaVirus1 = false;
}
if(admin.personaje.collidesWith(admin.virus2, true) && !banderaVirus2) {
banderaVirus2 = true;
admin.personaje.calcularDano();
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus2, true)) {
banderaVirus2 = false;
}
if(admin.personaje.getX()>admin.virus.getX()+180) {
admin.virus.setPosition(random.nextInt(1900), admin.virus.getY());
} else if (admin.personaje.getX()<admin.virus.getX()-180) {
admin.virus.setPosition(random.nextInt(1900), admin.virus.getY());
System.out.println("Soy virus y cambie mi posicion a " + admin.virus.getX());
}
if(admin.personaje.getX()>admin.virus1.getX()+180) {
admin.virus1.setPosition(random.nextInt(1900), admin.virus1.getY());
} else if (admin.personaje.getX()<admin.virus1.getX()-180) {
admin.virus1.setPosition(random.nextInt(1900), admin.virus1.getY());
System.out.println("Soy virus1 y cambie mi posicion a " + admin.virus1.getX());
}
if(admin.personaje.getX()>admin.virus2.getX()+180) {
admin.virus2.setPosition(random.nextInt(1900), admin.virus2.getY());
} else if (admin.personaje.getX()<admin.virus2.getX()-180) {
admin.virus2.setPosition(random.nextInt(1900), admin.virus2.getY());
System.out.println("Soy virus2 y cambie mi posicion a " + admin.virus2.getX());
}
admin.virus.actualizar();
admin.virus1.actualizar();
admin.virus2.actualizar();
if( admin.tren.getX()>=1550) {
admin.tren.setPosition(-200, 55);
}
admin.tren.mover(6);
admin.tren.actualizar();
if(admin.personaje.getX()>admin.flecha.getX()+190) {
admin.flecha.setPosition(admin.personaje.getX()+190, 20);
}
if(admin.personaje.getX()<admin.flecha.getX()-190) {
admin.flecha.setPosition(admin.personaje.getX()-190, 20);
}
admin.flecha.actualizar();
// Actualizacion y colisiones de tercer nivel
admin.rayo.actualizar();
if(admin.personaje.collidesWith(admin.auto, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.autoDos, true)) {
admin.personaje.setPosition(x, y);
}
admin.autoDos.actualizar();
admin.personajeExtra.mover(-1);
if(admin.personaje.collidesWith(admin.autoUno, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.destruido, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.taxi, true)) {
admin.personaje.setPosition(x, y);
}
*/
}
public void setBanderaMoviemientoZombie(boolean banderaMoviemientoZombie) {
this.banderaMovimientoZombie = banderaMoviemientoZombie;
}
public void setBandera(boolean bandera) {
this.bandera = bandera;
}
public void setBanderaColisionDano(boolean banderaColisionDano) {
this.banderaColisionDano = banderaColisionDano;
}
public void setBanderaDisparo(boolean banderaDisparo) {
this.banderaDisparo = banderaDisparo;
}
public void setBanderaBala(boolean banderaBala) {
this.banderaBala = banderaBala;
}
public void setBanderaMorir(boolean banderaMorir) {
this.banderaMorir = banderaMorir;
}
public void setBanderaParpadeo(boolean banderaParpadeo) {
this.banderaParpadeo = banderaParpadeo;
}
public void setBanderaVirus(boolean banderaVirus) {
this.banderaVirus = banderaVirus;
}
public void terminar() {
animador.terminar();
midlet.terminar();
}
}
| UTF-8 | Java | 14,816 | java | Juego.java | Java | [] | null | [] | package motor;
//import elementos.AnimalCinco;
import java.util.Random;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import menu.Menu;
import personajes.Enemigos;
import personajes.Heroes;
//import personajes.ZombieMoviles;
public class Juego extends GameCanvas implements Animable {
private AdministradorJuego admin;
private AnimadorJuego animador;
private boolean bandera = false;
private Graphics g;
public int ANCHO;
private int ALTO;
private Biolipsis midlet;
private boolean banderaDisparo = false;
private boolean banderaMovimientoZombie;
private boolean banderaColisionDano;
private int banderaNumeroZombie;
private boolean banderaDireccion;
private boolean banderaBala;
private boolean banderaMorir;
private boolean banderaVirus;
private boolean banderaVirus1;
private boolean banderaVirus2;
private boolean banderaParpadeo;
private Menu menu;
private Random random;
public Juego(Biolipsis midlet, boolean seleccionPersonaje) throws Exception {
super(true);
setFullScreenMode(true);
g = getGraphics();
ANCHO = getWidth();
ALTO = getHeight();
this.midlet = midlet;
if(!midlet.estaReproduciendo()){
midlet.reproducir("Menu.mid");
}
banderaMovimientoZombie = false;
banderaColisionDano = false;
banderaDireccion=false;
banderaNumeroZombie = 0;
banderaBala=false;
banderaMorir=false;
banderaVirus = false;
banderaVirus1 = false;
banderaVirus2 = false;
banderaParpadeo = false;
random = new Random();
admin = new AdministradorJuego(ANCHO, ALTO, seleccionPersonaje);
animador = new AnimadorJuego(this);
animador.iniciar();
}
public void dibujar() {
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
admin.paint(g);
g.setColor(0x00FF00);
g.drawString("D-Salir", ANCHO / 2, ALTO, Graphics.BOTTOM | Graphics.HCENTER);
flushGraphics();
}
public void actualizar() {
int tecla = getKeyStates();
if (tecla == 0 && !banderaDisparo) {
if (!banderaDisparo) {
admin.personaje.setFrameSequence(admin.personaje.getSecuencia());
bandera = false;
}
bandera = false;
}
int x = admin.personaje.getX();
int y = admin.personaje.getY();
if ((tecla & RIGHT_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverDerecha();
if(!banderaBala){
banderaDireccion=false;
}
} else if ((tecla & LEFT_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverIzquierda();
if(!banderaBala){
banderaDireccion=true;
}
}
if ((tecla & FIRE_PRESSED) != 0 && !bandera) {
bandera = true;
banderaDisparo = true;
banderaBala=true;
if(!banderaDireccion){
admin.bala.setPosition(x+Heroes.ancho,y+(Heroes.alto/2));
}else{
admin.bala.setPosition(x,y+(Heroes.alto/2));
}
admin.personaje.setFrameSequence(Heroes.getSecuenciaDisparo());
}
if ((tecla & UP_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverArriba();
}
if ((tecla & DOWN_PRESSED) != 0 && !banderaDisparo) {
admin.personaje.moverAbajo();
}
if ((tecla & GAME_D_PRESSED) != 0) {
midlet.notifyPaused();
System.out.println("Me han pausado");
} else if ((tecla & GAME_A_PRESSED) != 0) {
midlet.resumeRequest();
}
if (admin.personaje.collidesWith(admin.mapa1, false)) {
admin.personaje.setPosition(x, y);
}
if (banderaDisparo) {
admin.personaje.disparo(this);
}
if(banderaBala){
admin.bala.movimiento(admin.mapa1, (Enemigos) admin.zombie1, (Enemigos)admin.zombie2, (Enemigos)admin.zombie3, this, admin, banderaDireccion);
}
if(admin.zombie1.collidesWith(admin.bala, true)){
admin.zombie1.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento()-10, -10);
}
if(admin.zombie1.getVida()<=0){
banderaMorir=true;
admin.zombie1.morir(this, admin);
if(!banderaMorir){
admin.zombie1.restaurarVida();
}
}
if(admin.zombie1.getVida()>0){
admin.zombie1.mover(this, banderaMovimientoZombie, admin.mapa1, admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 1;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && !banderaColisionDano && banderaNumeroZombie == 1) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie1, true) && banderaNumeroZombie == 1) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
if(admin.zombie2.collidesWith(admin.bala, true)){
admin.zombie2.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento(), 0);
}
if(admin.zombie2.getVida()<=0){
banderaMorir=true;
admin.zombie2.morir(this, admin);
if(!banderaMorir){
admin.zombie2.restaurarVida();
}
}
if(admin.zombie2.getVida()>0){
admin.zombie2.mover(this, banderaMovimientoZombie, admin.mapa1,admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 2;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && !banderaColisionDano && banderaNumeroZombie == 2) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie2, true) && banderaNumeroZombie == 2) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
if(admin.zombie3.collidesWith(admin.bala, true)){
admin.zombie3.calcularDanio();
admin.bala.setPosition(admin.getDesplazamiento(), 0);
}
if(admin.zombie3.getVida()<=0){
banderaMorir=true;
admin.zombie3.morir(this, admin);
if(!banderaMorir) {
admin.zombie3.restaurarVida();
}
}
if(admin.zombie3.getVida()>0){
admin.zombie3.mover(this, banderaMovimientoZombie, admin.mapa1,admin.personaje);
if (admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && (banderaNumeroZombie == 0)) {
banderaNumeroZombie = 3;
}
if (admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && !banderaColisionDano && banderaNumeroZombie == 3) {
banderaColisionDano = true;
admin.personaje.calcularDano();
System.out.println("tienes " + Heroes.vida + " vidas");
}
if (!admin.personaje.collidesWith((Enemigos)admin.zombie3, true) && banderaNumeroZombie == 3) {
banderaColisionDano = false;
banderaNumeroZombie = 0;
}
}
// Actualizacion y colisiones de primer nivel
if( admin.lancha.getX()>=1900) {
admin.lancha.setPosition(-30, 75);
}
if(admin.personaje.getX()>=650 && admin.personaje.getX()<=700) {
admin.agua.setPosition(760, 90);
}
if(admin.personaje.getX()>=1410 && admin.personaje.getX()<=1460) {
admin.agua.setPosition(1520, 90);
}
if(admin.personaje.getX()>=440 && admin.personaje.getX()<=490) {
admin.agua.setPosition(0, 90);
}
if(admin.personaje.getX()>=1200 && admin.personaje.getX()<=1250) {
admin.agua.setPosition(760, 90);
}
if(admin.personaje.getX()>=1030 && admin.personaje.getX()<=1080) {
admin.agua1.setPosition(1140, 90);
}
if(admin.personaje.getX()>=700 && admin.personaje.getX()<=790) {
admin.agua1.setPosition(380, 90);
}
admin.nativoUno.mover(-2);
admin.lancha.mover(2);
admin.animalUno.mover(-1);
admin.animalDos.mover(-1);
admin.animalCinco.mover(-1);
admin.animalSeis.mover(-1);
admin.animalUno.actualizar();
admin.animalDos.actualizar();
admin.animalTres.actualizar();
admin.animalCuatro.actualizar();
admin.animalCinco.actualizar();
admin.animalSeis.actualizar();
admin.nativoUno.actualizar();
admin.nativoDos.actualizar();
admin.nativoTres.actualizar();
admin.lancha.actualizar();
admin.agua.actualizar();
admin.agua1.actualizar();
if(admin.personaje.collidesWith(admin.vida, true)) {
admin.vida.setPosition(admin.personaje.getX()+700, 80);
admin.personaje.calcularRecuperacion();
System.out.println("Subi a " + Heroes.vida + " de vida");
} else if (admin.personaje.getX()>admin.vida.getX()+180) {
admin.vida.setPosition(admin.personaje.getX()+700, 80);
}
admin.vida.actualizar();
// Actualizacion y colisiones de segundo nivel
/*if(admin.personaje.collidesWith(admin.virus, true) && !banderaVirus && !banderaParpadeo) {
banderaVirus = true;
if(banderaVirus) {
banderaParpadeo = true;
admin.personaje.setFrameSequence(admin.personaje.getSecuenciaHerido());
admin.personaje.calcularDano();
}
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus, true)) {
admin.personaje.herido(this);
}
if(admin.personaje.collidesWith(admin.virus1, true) && !banderaVirus1) {
banderaVirus1 = true;
admin.personaje.calcularDano();
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus1, true)) {
banderaVirus1 = false;
}
if(admin.personaje.collidesWith(admin.virus2, true) && !banderaVirus2) {
banderaVirus2 = true;
admin.personaje.calcularDano();
System.out.println("El virus me ha hecho danio y baje mi vida a " + Heroes.vida);
} if (!admin.personaje.collidesWith(admin.virus2, true)) {
banderaVirus2 = false;
}
if(admin.personaje.getX()>admin.virus.getX()+180) {
admin.virus.setPosition(random.nextInt(1900), admin.virus.getY());
} else if (admin.personaje.getX()<admin.virus.getX()-180) {
admin.virus.setPosition(random.nextInt(1900), admin.virus.getY());
System.out.println("Soy virus y cambie mi posicion a " + admin.virus.getX());
}
if(admin.personaje.getX()>admin.virus1.getX()+180) {
admin.virus1.setPosition(random.nextInt(1900), admin.virus1.getY());
} else if (admin.personaje.getX()<admin.virus1.getX()-180) {
admin.virus1.setPosition(random.nextInt(1900), admin.virus1.getY());
System.out.println("Soy virus1 y cambie mi posicion a " + admin.virus1.getX());
}
if(admin.personaje.getX()>admin.virus2.getX()+180) {
admin.virus2.setPosition(random.nextInt(1900), admin.virus2.getY());
} else if (admin.personaje.getX()<admin.virus2.getX()-180) {
admin.virus2.setPosition(random.nextInt(1900), admin.virus2.getY());
System.out.println("Soy virus2 y cambie mi posicion a " + admin.virus2.getX());
}
admin.virus.actualizar();
admin.virus1.actualizar();
admin.virus2.actualizar();
if( admin.tren.getX()>=1550) {
admin.tren.setPosition(-200, 55);
}
admin.tren.mover(6);
admin.tren.actualizar();
if(admin.personaje.getX()>admin.flecha.getX()+190) {
admin.flecha.setPosition(admin.personaje.getX()+190, 20);
}
if(admin.personaje.getX()<admin.flecha.getX()-190) {
admin.flecha.setPosition(admin.personaje.getX()-190, 20);
}
admin.flecha.actualizar();
// Actualizacion y colisiones de tercer nivel
admin.rayo.actualizar();
if(admin.personaje.collidesWith(admin.auto, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.autoDos, true)) {
admin.personaje.setPosition(x, y);
}
admin.autoDos.actualizar();
admin.personajeExtra.mover(-1);
if(admin.personaje.collidesWith(admin.autoUno, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.destruido, true)) {
admin.personaje.setPosition(x, y);
}
if(admin.personaje.collidesWith(admin.taxi, true)) {
admin.personaje.setPosition(x, y);
}
*/
}
public void setBanderaMoviemientoZombie(boolean banderaMoviemientoZombie) {
this.banderaMovimientoZombie = banderaMoviemientoZombie;
}
public void setBandera(boolean bandera) {
this.bandera = bandera;
}
public void setBanderaColisionDano(boolean banderaColisionDano) {
this.banderaColisionDano = banderaColisionDano;
}
public void setBanderaDisparo(boolean banderaDisparo) {
this.banderaDisparo = banderaDisparo;
}
public void setBanderaBala(boolean banderaBala) {
this.banderaBala = banderaBala;
}
public void setBanderaMorir(boolean banderaMorir) {
this.banderaMorir = banderaMorir;
}
public void setBanderaParpadeo(boolean banderaParpadeo) {
this.banderaParpadeo = banderaParpadeo;
}
public void setBanderaVirus(boolean banderaVirus) {
this.banderaVirus = banderaVirus;
}
public void terminar() {
animador.terminar();
midlet.terminar();
}
}
| 14,816 | 0.59159 | 0.572152 | 393 | 36.699745 | 27.412436 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707379 | false | false | 9 |
472a1182c20df6583ea56a7e96c804a5754881de | 23,450,521,465,089 | 45da4a5a3cef7694ad8533d3a14f4f13ffa54ed8 | /core/src/main/java/com/lovcreate/core/views/support/BaseActivity.java | 79b98bef84e6b6714f532c795631888d5c7db117 | [] | no_license | LengM/MyVideo | https://github.com/LengM/MyVideo | 4cea773d53c15fb8fa0487942dc3e6d3b57e7b6c | 0255f214c77e3abb0874fce446234d2662923f25 | refs/heads/master | 2021-01-22T10:41:26.370000 | 2017-09-04T08:33:31 | 2017-09-04T08:33:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lovcreate.core.views.support;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.lovcreate.core.utils.CoverLayerDialog;
import com.lovcreate.core.utils.Logcat;
import java.util.LinkedList;
import java.util.List;
import butterknife.ButterKnife;
/**
* 向上兼容的基本Activity
* 向上兼容低版本的Fragment,替代FragmentActivity.
* 同时向上兼容低版本的ActionBar(由ToolBar替代),替代ActionBarActivity
* <p/>
* 当前BaseActivity已经实现的公用特性:
* <p/>
* 1,沉浸式状态栏
* 使用:在继承此BaseActivity的Activity中重写setStatusBar()方法.
* 一,如果要改变沉浸式状态栏颜色,使用StatusBarUtil.setColor();
* 二,如果根布局有背景图片,使用StatusBarUtil.setTranslucent();例如WelcomeActivity
* 三,如果根布局下为头部是ImageView的界面设置状态栏透明,使用StatusBarUtil.setTranslucentForImageView()方法;例如LoginActivity
* <p/>
* 2,EditView点击空白区域隐藏输入法软键盘
* 借鉴于 http://blog.csdn.net/djl461260911/article/details/45893451
* <p/>
* 3,遮盖框
* 将与BaseActivity共生,这样当网络要求打开多个BaseActivity时,每一个BaseActivity打开的遮盖框将不会互相影响(工具类CoverLayerDialog打开的遮盖框是共享的)
* <p/>
* 4,关闭App
* 每次创建Activity时在这里进行记录,当要进去退出时,finish所有的activity实现退出
* <p/>
* Created by Peter.Pan on 2016/3/24.
* Update by Albert.Ma on 2017/5/18.
*/
public class BaseActivity extends AppCompatActivity {
protected Context baContext;//上下文
protected FragmentManager baFragmentManger;
protected static List<BaseActivity> baAllActivity = new LinkedList<>();//保存每个Activity
/**
* 遮盖框
*/
protected ProgressDialog bfDialog;
/**
* 创建时
*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
baAllActivity.add(this);//每次创建时,加入到activity容器中
baContext = this;
baFragmentManger = getSupportFragmentManager();
Logcat.i(this.toString() + " - ==> onCreate...");
}
/**
* 重写setContentView(int)方法,添加初始化ButterKnife控件
*/
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
//初始化ButterKnife
ButterKnife.bind(this);
//设置沉浸式状态栏
setStatusBar();
}
/**
* 开始时
*/
@Override
protected void onStart() {
super.onStart();
Logcat.i(this.toString() + " - ==> onStart...");
}
@Override
protected void onResume() {
super.onResume();
Logcat.i(this.toString() + " - ==> onResume...");
}
@Override
protected void onPause() {
super.onPause();
Logcat.i(this.toString() + " - ==> onPause...");
}
/**
* 结束时
*/
@Override
protected void onStop() {
super.onStop();
Logcat.i(this.toString() + " - ==> onStop...");
}
/**
* 销毁时
*/
@Override
protected void onDestroy() {
super.onDestroy();
Logcat.i(this.toString() + " - ==> onDestroy...");
}
////////////////////////////// 沉浸式状态栏 //////////////////////////////
/**
* 重写此方法可自定义沉浸式状态栏
*/
protected void setStatusBar() {
}
////////////////////////////// EditView点击空白区域隐藏输入法软键盘 //////////////////////////////
/**
* EditView点击空白区域隐藏输入法软键盘
*
* @param ev
* @return
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, ev)) {
hideKeyboard(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
/**
* EditView点击空白区域隐藏输入法软键盘:
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*
* @param v
* @param event
* @return
*/
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击EditText的事件,忽略它
return false;
} else {
return true;
}
}
// 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
return false;
}
/**
* EditView点击空白区域隐藏输入法软键盘:获取InputMethodManager隐藏软键盘
*
* @param token
*/
private void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/////////////////////////////////// 遮盖框 ////////////////////////////////////
/**
* 打开一个 内容为message 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, null, ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
}
/**
* 打开一个 内容为message 有取消监听 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
* @param onCancelListener 取消监听
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable, DialogInterface.OnCancelListener onCancelListener) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, onCancelListener, ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
}
/**
* 打开一个 内容为message 有取消监听 主题为theme 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
* @param onCancelListener 取消监听
* @param theme 主题
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable, DialogInterface.OnCancelListener onCancelListener, int theme) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, onCancelListener, theme);
}
/**
* 关闭遮盖层
*/
public void closeProgressDialog() {
if (bfDialog != null) {
bfDialog.dismiss();//关闭
}
}
/**
* 进度条遮盖层,设置进度
*
* @param max 最大进度
* @param progress 当前进度
*/
public void setProgress(long max, long progress) {
bfDialog.setMax(100);
int progressPercent = (int) (progress / (float) max * 100);
bfDialog.setProgress(progressPercent);
}
////////////////////////////// 关闭App //////////////////////////////
public void shutDownApp(){
try {
for (BaseActivity activity: baAllActivity) {
if (activity != null)
activity.finish();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
/////////////////////////////////// 日志 ////////////////////////////////////
/**
* 用于日志输出,仅打印类名
*/
@Override
public String toString() {
String packageClazz = super.getClass().getName();
return packageClazz.substring(packageClazz.lastIndexOf(".") + 1, packageClazz.length());
}
}
| UTF-8 | Java | 9,058 | java | BaseActivity.java | Java | [
{
"context": "ditView点击空白区域隐藏输入法软键盘\n * 借鉴于 http://blog.csdn.net/djl461260911/article/details/45893451\n * <p/>\n * 3,遮盖框\n * 将与Ba",
"end": 1179,
"score": 0.9993824362754822,
"start": 1167,
"tag": "USERNAME",
"value": "djl461260911"
},
{
"context": "要进去退出时,finish所有的activity实现退出\n * <p/>\n * Created by Peter.Pan on 2016/3/24.\n * Update by Albert.Ma on 2017/5/18",
"end": 1431,
"score": 0.996912956237793,
"start": 1422,
"tag": "NAME",
"value": "Peter.Pan"
},
{
"context": " * Created by Peter.Pan on 2016/3/24.\n * Update by Albert.Ma on 2017/5/18.\n */\npublic class BaseActivity exten",
"end": 1468,
"score": 0.9946811199188232,
"start": 1459,
"tag": "NAME",
"value": "Albert.Ma"
}
] | null | [] | package com.lovcreate.core.views.support;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.lovcreate.core.utils.CoverLayerDialog;
import com.lovcreate.core.utils.Logcat;
import java.util.LinkedList;
import java.util.List;
import butterknife.ButterKnife;
/**
* 向上兼容的基本Activity
* 向上兼容低版本的Fragment,替代FragmentActivity.
* 同时向上兼容低版本的ActionBar(由ToolBar替代),替代ActionBarActivity
* <p/>
* 当前BaseActivity已经实现的公用特性:
* <p/>
* 1,沉浸式状态栏
* 使用:在继承此BaseActivity的Activity中重写setStatusBar()方法.
* 一,如果要改变沉浸式状态栏颜色,使用StatusBarUtil.setColor();
* 二,如果根布局有背景图片,使用StatusBarUtil.setTranslucent();例如WelcomeActivity
* 三,如果根布局下为头部是ImageView的界面设置状态栏透明,使用StatusBarUtil.setTranslucentForImageView()方法;例如LoginActivity
* <p/>
* 2,EditView点击空白区域隐藏输入法软键盘
* 借鉴于 http://blog.csdn.net/djl461260911/article/details/45893451
* <p/>
* 3,遮盖框
* 将与BaseActivity共生,这样当网络要求打开多个BaseActivity时,每一个BaseActivity打开的遮盖框将不会互相影响(工具类CoverLayerDialog打开的遮盖框是共享的)
* <p/>
* 4,关闭App
* 每次创建Activity时在这里进行记录,当要进去退出时,finish所有的activity实现退出
* <p/>
* Created by Peter.Pan on 2016/3/24.
* Update by Albert.Ma on 2017/5/18.
*/
public class BaseActivity extends AppCompatActivity {
protected Context baContext;//上下文
protected FragmentManager baFragmentManger;
protected static List<BaseActivity> baAllActivity = new LinkedList<>();//保存每个Activity
/**
* 遮盖框
*/
protected ProgressDialog bfDialog;
/**
* 创建时
*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
baAllActivity.add(this);//每次创建时,加入到activity容器中
baContext = this;
baFragmentManger = getSupportFragmentManager();
Logcat.i(this.toString() + " - ==> onCreate...");
}
/**
* 重写setContentView(int)方法,添加初始化ButterKnife控件
*/
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
//初始化ButterKnife
ButterKnife.bind(this);
//设置沉浸式状态栏
setStatusBar();
}
/**
* 开始时
*/
@Override
protected void onStart() {
super.onStart();
Logcat.i(this.toString() + " - ==> onStart...");
}
@Override
protected void onResume() {
super.onResume();
Logcat.i(this.toString() + " - ==> onResume...");
}
@Override
protected void onPause() {
super.onPause();
Logcat.i(this.toString() + " - ==> onPause...");
}
/**
* 结束时
*/
@Override
protected void onStop() {
super.onStop();
Logcat.i(this.toString() + " - ==> onStop...");
}
/**
* 销毁时
*/
@Override
protected void onDestroy() {
super.onDestroy();
Logcat.i(this.toString() + " - ==> onDestroy...");
}
////////////////////////////// 沉浸式状态栏 //////////////////////////////
/**
* 重写此方法可自定义沉浸式状态栏
*/
protected void setStatusBar() {
}
////////////////////////////// EditView点击空白区域隐藏输入法软键盘 //////////////////////////////
/**
* EditView点击空白区域隐藏输入法软键盘
*
* @param ev
* @return
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, ev)) {
hideKeyboard(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
/**
* EditView点击空白区域隐藏输入法软键盘:
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*
* @param v
* @param event
* @return
*/
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击EditText的事件,忽略它
return false;
} else {
return true;
}
}
// 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
return false;
}
/**
* EditView点击空白区域隐藏输入法软键盘:获取InputMethodManager隐藏软键盘
*
* @param token
*/
private void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/////////////////////////////////// 遮盖框 ////////////////////////////////////
/**
* 打开一个 内容为message 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, null, ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
}
/**
* 打开一个 内容为message 有取消监听 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
* @param onCancelListener 取消监听
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable, DialogInterface.OnCancelListener onCancelListener) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, onCancelListener, ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
}
/**
* 打开一个 内容为message 有取消监听 主题为theme 的遮盖层
*
* @param context 上下文
* @param message 遮盖层显示的内容
* @param cancelable 是否可以撤销
* @param onCancelListener 取消监听
* @param theme 主题
*/
public void openProgressDialogForLoading(Context context, String message, boolean cancelable, DialogInterface.OnCancelListener onCancelListener, int theme) {
bfDialog = CoverLayerDialog.openProgressDialogForLoading(context, message, cancelable, onCancelListener, theme);
}
/**
* 关闭遮盖层
*/
public void closeProgressDialog() {
if (bfDialog != null) {
bfDialog.dismiss();//关闭
}
}
/**
* 进度条遮盖层,设置进度
*
* @param max 最大进度
* @param progress 当前进度
*/
public void setProgress(long max, long progress) {
bfDialog.setMax(100);
int progressPercent = (int) (progress / (float) max * 100);
bfDialog.setProgress(progressPercent);
}
////////////////////////////// 关闭App //////////////////////////////
public void shutDownApp(){
try {
for (BaseActivity activity: baAllActivity) {
if (activity != null)
activity.finish();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
/////////////////////////////////// 日志 ////////////////////////////////////
/**
* 用于日志输出,仅打印类名
*/
@Override
public String toString() {
String packageClazz = super.getClass().getName();
return packageClazz.substring(packageClazz.lastIndexOf(".") + 1, packageClazz.length());
}
}
| 9,058 | 0.587592 | 0.581363 | 277 | 27.397112 | 28.250832 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418773 | false | false | 9 |
3fd275f1e1dbdf19af5313817ae34a68e24a4df0 | 27,513,560,503,417 | d0d6693164ef7e91bda1e90ebf3a9deff0ff809f | /src/com/tq/requisition/test/infrastructure/repository/TestFml.java | a5cd526748300b0aa645013dc1969aaca52ab99e | [
"Apache-2.0"
] | permissive | bellmit/requisition_land | https://github.com/bellmit/requisition_land | d013cee1cd2b7c1dcbe21ad0f63d3a063f64fdc6 | 51fbb1d63a6a9483384ea818757e9fa085a9a4f2 | refs/heads/master | 2021-12-20T11:20:13.216000 | 2016-09-19T07:56:41 | 2016-09-19T07:56:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tq.requisition.test.infrastructure.repository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import com.tq.requisition.domain.model.familyMember.FamilyItem;
import com.tq.requisition.domain.model.removeFamily.Family;
import com.tq.requisition.domain.model.removeFamily.IFamilyRepository;
import com.tq.requisition.domain.model.share.Gender;
import com.tq.requisition.infrastructure.serviceLocator.ServiceLocator;
public class TestFml {
private IFamilyRepository repository;
@Before
public void init() {
repository = ServiceLocator.instance().getService("fmlRepository", IFamilyRepository.class);
}
@Test
public void add() {
List<FamilyItem> list = new ArrayList<FamilyItem>();
list.add(FamilyItem.obtain(//
"name",//
"id number2",//
new Date(),//
Gender.MALE, //
"only child",//
true, //
"address", //
"relationship str",//
"household str", //
"social str",//
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(),//
UUID.randomUUID(),//
"pro name"));
Family fml = Family.obtain(//
"户主名字",//
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
"address",//
12,//
1.6f,//
1.6f,//
"des", //
"deal", //
"union", //
"remark", //
"path", //
list,//
"pro name",//
null,//
"path",null,null,null);
repository.context().beginTransaction();
Family f = repository.addFamily(fml);
repository.context().commit();
System.out.println(f);
}
@Test
public void query() {
repository.context().beginTransaction();
Family fml = repository.getByKey(Family.class, UUID.fromString("1bc05f79-67b2-43cb-804d-2d9cd0b5d7c7"));
System.out.println(fml.getAddress());
}
@Test
public void queryFuzzy() {
// repository.context().beginTransaction();
// FamilyQueryModel queryModel = new FamilyQueryModel();
// queryModel.setCommunityId(null);
// queryModel.setIdNumber(null);
// queryModel.setProId(null);
// queryModel.setStreetId(null);
//
// PageModel pageModel = new PageModel();
// pageModel.pageIndex = 1;
// pageModel.pageSize = 3;
// List<Family> fmls = repository.getListByFuzzy(queryModel, pageModel);
// for (Family family : fmls) {
// System.out.println(family.getAddress());
// }
}
@Test
public void getByIds() {
List<Family> list = repository.getFml4Print("'08c785aa-2db4-4a5c-96e4-48e4e57078a8','787531b0-b2c7-4888-97b6-6fca1754f5a5'");
for (Family family : list) {
System.out.println(family.getHeadName());
}
}
}
| UTF-8 | Java | 2,755 | java | TestFml.java | Java | [] | null | [] | package com.tq.requisition.test.infrastructure.repository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import com.tq.requisition.domain.model.familyMember.FamilyItem;
import com.tq.requisition.domain.model.removeFamily.Family;
import com.tq.requisition.domain.model.removeFamily.IFamilyRepository;
import com.tq.requisition.domain.model.share.Gender;
import com.tq.requisition.infrastructure.serviceLocator.ServiceLocator;
public class TestFml {
private IFamilyRepository repository;
@Before
public void init() {
repository = ServiceLocator.instance().getService("fmlRepository", IFamilyRepository.class);
}
@Test
public void add() {
List<FamilyItem> list = new ArrayList<FamilyItem>();
list.add(FamilyItem.obtain(//
"name",//
"id number2",//
new Date(),//
Gender.MALE, //
"only child",//
true, //
"address", //
"relationship str",//
"household str", //
"social str",//
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(),//
UUID.randomUUID(),//
"pro name"));
Family fml = Family.obtain(//
"户主名字",//
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
UUID.randomUUID(), //
"address",//
12,//
1.6f,//
1.6f,//
"des", //
"deal", //
"union", //
"remark", //
"path", //
list,//
"pro name",//
null,//
"path",null,null,null);
repository.context().beginTransaction();
Family f = repository.addFamily(fml);
repository.context().commit();
System.out.println(f);
}
@Test
public void query() {
repository.context().beginTransaction();
Family fml = repository.getByKey(Family.class, UUID.fromString("1bc05f79-67b2-43cb-804d-2d9cd0b5d7c7"));
System.out.println(fml.getAddress());
}
@Test
public void queryFuzzy() {
// repository.context().beginTransaction();
// FamilyQueryModel queryModel = new FamilyQueryModel();
// queryModel.setCommunityId(null);
// queryModel.setIdNumber(null);
// queryModel.setProId(null);
// queryModel.setStreetId(null);
//
// PageModel pageModel = new PageModel();
// pageModel.pageIndex = 1;
// pageModel.pageSize = 3;
// List<Family> fmls = repository.getListByFuzzy(queryModel, pageModel);
// for (Family family : fmls) {
// System.out.println(family.getAddress());
// }
}
@Test
public void getByIds() {
List<Family> list = repository.getFml4Print("'08c785aa-2db4-4a5c-96e4-48e4e57078a8','787531b0-b2c7-4888-97b6-6fca1754f5a5'");
for (Family family : list) {
System.out.println(family.getHeadName());
}
}
}
| 2,755 | 0.666302 | 0.639709 | 106 | 24.896227 | 22.377098 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.90566 | false | false | 9 |
54860f3fbe20244f13d83ac7055a523a8ed657f4 | 14,791,867,420,093 | f2671d48696ec14590d7306f9f53207366ba631d | /pinot-spi/src/main/java/org/apache/pinot/spi/utils/ByteArray.java | 6eefcadeae3741727f67b9f88a59a241bf816e22 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"NAIST-2003",
"bzip2-1.0.6",
"OpenSSL",
"CC-BY-2.5",
"CC-BY-SA-3.0",
"CDDL-1.0",
"MIT",
"CPL-1.0",
"LicenseRef-scancode-public-domain",
"CDDL-1.1",
"EPL-1.0",
"CC-BY-4.0",
"WTFPL",
"EPL-2.0",
"ISC",
"BSD-2-Clause"
] | permissive | mcvsubbu/incubator-pinot | https://github.com/mcvsubbu/incubator-pinot | 5602f1bc925aec6f400f93f53915d1ca10d1f217 | dc3b6fd3192b9301017e91a564241479e67727b9 | refs/heads/master | 2023-07-13T13:34:05.824000 | 2023-05-14T01:28:55 | 2023-05-14T01:28:55 | 175,093,979 | 2 | 0 | Apache-2.0 | true | 2019-03-11T22:33:11 | 2019-03-11T22:33:11 | 2019-03-11T21:28:37 | 2019-03-11T21:34:10 | 165,772 | 0 | 0 | 0 | null | false | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.spi.utils;
import java.io.Serializable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Wrapper around byte[] that provides additional features such as:
* <ul>
* <li>Implements comparable interface, so comparison and sorting can be performed</li>
* <li>Implements equals() and hashCode(), so it can be used as key for HashMap/Set</li>
* <li>Caches the hash code of the byte[]</li>
* </ul>
*/
public class ByteArray implements Comparable<ByteArray>, Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(ByteArray.class);
private static final MethodHandle COMPARE_UNSIGNED;
static {
MethodHandle compareUnsigned = null;
try {
compareUnsigned = MethodHandles.publicLookup().findStatic(Arrays.class, "compareUnsigned",
MethodType.methodType(int.class, byte[].class, int.class, int.class, byte[].class, int.class, int.class));
} catch (Exception ignored) {
LOGGER.warn("Arrays.compareUnsigned unavailable - this may have a performance impact (are you using JDK8?)");
}
COMPARE_UNSIGNED = compareUnsigned;
}
private final byte[] _bytes;
// Hash for empty ByteArray is 1
private int _hash = 1;
public ByteArray(byte[] bytes) {
_bytes = bytes;
}
public byte[] getBytes() {
return _bytes;
}
public int length() {
return _bytes.length;
}
public String toHexString() {
return BytesUtils.toHexString(_bytes);
}
@Override
public String toString() {
return toHexString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ByteArray bytes = (ByteArray) o;
return Arrays.equals(_bytes, bytes._bytes);
}
@Override
public int hashCode() {
int hash = _hash;
if (hash == 1 && _bytes.length > 0) {
int i = 0;
for (; i + 7 < _bytes.length; i += 8) {
hash = -1807454463 * hash
+ 1742810335 * _bytes[i]
+ 887503681 * _bytes[i + 1]
+ 28629151 * _bytes[i + 2]
+ 923521 * _bytes[i + 3]
+ 29791 * _bytes[i + 4]
+ 961 * _bytes[i + 5]
+ 31 * _bytes[i + 6]
+ _bytes[i + 7];
}
for (; i < _bytes.length; i++) {
hash = 31 * hash + _bytes[i];
}
_hash = hash;
}
return hash;
}
@Override
public int compareTo(ByteArray that) {
if (this == that) {
return 0;
}
return compare(_bytes, that._bytes);
}
/**
* Compares two byte[] values. The comparison performed is on unsigned value for each byte.
* Returns:
* <ul>
* <li> 0 if both values are identical. </li>
* <li> -ve integer if first value is smaller than the second. </li>
* <li> +ve integer if first value is larger than the second. </li>
* </ul>
*
* @param left First byte[] to compare.
* @param right Second byte[] to compare.
* @return Result of comparison as stated above.
*/
public static int compare(byte[] left, byte[] right) {
return compare(left, 0, left.length, right, 0, right.length);
}
/**
* Compares two byte[] values. The comparison performed is on unsigned value for each byte.
* Returns:
* <ul>
* <li> 0 if both values are identical. </li>
* <li> -ve integer if first value is smaller than the second. </li>
* <li> +ve integer if first value is larger than the second. </li>
* </ul>
*
* @param left First byte[] to compare.
* @param leftFromIndex inclusive index of first byte to compare in left
* @param leftToIndex exclusive index of last byte to compare in left
* @param right Second byte[] to compare.
* @param rightFromIndex inclusive index of first byte to compare in right
* @param rightToIndex exclusive index of last byte to compare in right
* @return Result of comparison as stated above.
*/
public static int compare(byte[] left, int leftFromIndex, int leftToIndex, byte[] right, int rightFromIndex,
int rightToIndex) {
if (COMPARE_UNSIGNED != null) {
try {
return (int) COMPARE_UNSIGNED.invokeExact(left, leftFromIndex, leftToIndex, right, rightFromIndex,
rightToIndex);
} catch (ArrayIndexOutOfBoundsException outOfBounds) {
throw outOfBounds;
} catch (Throwable ignore) {
}
}
return compareFallback(left, leftFromIndex, leftToIndex, right, rightFromIndex, rightToIndex);
}
private static int compareFallback(byte[] left, int leftFromIndex, int leftToIndex, byte[] right, int rightFromIndex,
int rightToIndex) {
int len1 = leftToIndex - leftFromIndex;
int len2 = rightToIndex - rightFromIndex;
int lim = Math.min(len1, len2);
for (int k = 0; k < lim; k++) {
// Java byte is always signed, but we need to perform unsigned comparison.
int ai = Byte.toUnsignedInt(left[k + leftFromIndex]);
int bi = Byte.toUnsignedInt(right[k + rightFromIndex]);
if (ai != bi) {
return ai - bi;
}
}
return len1 - len2;
}
}
| UTF-8 | Java | 6,072 | java | ByteArray.java | Java | [] | null | [] | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.spi.utils;
import java.io.Serializable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Wrapper around byte[] that provides additional features such as:
* <ul>
* <li>Implements comparable interface, so comparison and sorting can be performed</li>
* <li>Implements equals() and hashCode(), so it can be used as key for HashMap/Set</li>
* <li>Caches the hash code of the byte[]</li>
* </ul>
*/
public class ByteArray implements Comparable<ByteArray>, Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(ByteArray.class);
private static final MethodHandle COMPARE_UNSIGNED;
static {
MethodHandle compareUnsigned = null;
try {
compareUnsigned = MethodHandles.publicLookup().findStatic(Arrays.class, "compareUnsigned",
MethodType.methodType(int.class, byte[].class, int.class, int.class, byte[].class, int.class, int.class));
} catch (Exception ignored) {
LOGGER.warn("Arrays.compareUnsigned unavailable - this may have a performance impact (are you using JDK8?)");
}
COMPARE_UNSIGNED = compareUnsigned;
}
private final byte[] _bytes;
// Hash for empty ByteArray is 1
private int _hash = 1;
public ByteArray(byte[] bytes) {
_bytes = bytes;
}
public byte[] getBytes() {
return _bytes;
}
public int length() {
return _bytes.length;
}
public String toHexString() {
return BytesUtils.toHexString(_bytes);
}
@Override
public String toString() {
return toHexString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ByteArray bytes = (ByteArray) o;
return Arrays.equals(_bytes, bytes._bytes);
}
@Override
public int hashCode() {
int hash = _hash;
if (hash == 1 && _bytes.length > 0) {
int i = 0;
for (; i + 7 < _bytes.length; i += 8) {
hash = -1807454463 * hash
+ 1742810335 * _bytes[i]
+ 887503681 * _bytes[i + 1]
+ 28629151 * _bytes[i + 2]
+ 923521 * _bytes[i + 3]
+ 29791 * _bytes[i + 4]
+ 961 * _bytes[i + 5]
+ 31 * _bytes[i + 6]
+ _bytes[i + 7];
}
for (; i < _bytes.length; i++) {
hash = 31 * hash + _bytes[i];
}
_hash = hash;
}
return hash;
}
@Override
public int compareTo(ByteArray that) {
if (this == that) {
return 0;
}
return compare(_bytes, that._bytes);
}
/**
* Compares two byte[] values. The comparison performed is on unsigned value for each byte.
* Returns:
* <ul>
* <li> 0 if both values are identical. </li>
* <li> -ve integer if first value is smaller than the second. </li>
* <li> +ve integer if first value is larger than the second. </li>
* </ul>
*
* @param left First byte[] to compare.
* @param right Second byte[] to compare.
* @return Result of comparison as stated above.
*/
public static int compare(byte[] left, byte[] right) {
return compare(left, 0, left.length, right, 0, right.length);
}
/**
* Compares two byte[] values. The comparison performed is on unsigned value for each byte.
* Returns:
* <ul>
* <li> 0 if both values are identical. </li>
* <li> -ve integer if first value is smaller than the second. </li>
* <li> +ve integer if first value is larger than the second. </li>
* </ul>
*
* @param left First byte[] to compare.
* @param leftFromIndex inclusive index of first byte to compare in left
* @param leftToIndex exclusive index of last byte to compare in left
* @param right Second byte[] to compare.
* @param rightFromIndex inclusive index of first byte to compare in right
* @param rightToIndex exclusive index of last byte to compare in right
* @return Result of comparison as stated above.
*/
public static int compare(byte[] left, int leftFromIndex, int leftToIndex, byte[] right, int rightFromIndex,
int rightToIndex) {
if (COMPARE_UNSIGNED != null) {
try {
return (int) COMPARE_UNSIGNED.invokeExact(left, leftFromIndex, leftToIndex, right, rightFromIndex,
rightToIndex);
} catch (ArrayIndexOutOfBoundsException outOfBounds) {
throw outOfBounds;
} catch (Throwable ignore) {
}
}
return compareFallback(left, leftFromIndex, leftToIndex, right, rightFromIndex, rightToIndex);
}
private static int compareFallback(byte[] left, int leftFromIndex, int leftToIndex, byte[] right, int rightFromIndex,
int rightToIndex) {
int len1 = leftToIndex - leftFromIndex;
int len2 = rightToIndex - rightFromIndex;
int lim = Math.min(len1, len2);
for (int k = 0; k < lim; k++) {
// Java byte is always signed, but we need to perform unsigned comparison.
int ai = Byte.toUnsignedInt(left[k + leftFromIndex]);
int bi = Byte.toUnsignedInt(right[k + rightFromIndex]);
if (ai != bi) {
return ai - bi;
}
}
return len1 - len2;
}
}
| 6,072 | 0.648057 | 0.633564 | 191 | 30.790575 | 28.429174 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513089 | false | false | 9 |
a7903e7f80f828293552cf7101f55c04b1cffee2 | 8,847,632,689,409 | ee64b825239f1934043f7faed06ec8d51ae01ef4 | /DP/FrogJump.java | 8ea33877fe58cebcfd2eeba4892fc31c5d0f61f9 | [] | no_license | JiaxingTIAN/Leetcode | https://github.com/JiaxingTIAN/Leetcode | 5aacba20da09cd5045eb0f5e0840d51cd9f94a9d | e4cff0d9196adc318562184e4704795cfcfb6566 | refs/heads/master | 2020-05-22T06:35:21.830000 | 2017-03-22T18:12:30 | 2017-03-22T18:12:30 | 65,645,071 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Solution {
public boolean canCross(int[] stones) {
if(stones == null || stones.length == 0){
return false;
}
return dfs(stones, 0, 1);
}
//Baise DFS solution each time 3 steps => O(3^n)
public boolean dfs(int[] stones, int idx, int step){
if(idx == stones.length-1){
return true;
}
int i = idx + 1;
boolean flag = false;
for(i=idx+1; i<stones.length; i++){
if(stones[i] == stones[idx] + step)
if(dfs(stones, i, step-1) || dfs(stones, i, step) || dfs(stones, i, step+1))
return true;
}
return false;
}
}
//DP solution store the stone location and step => Worset Case O(n^2)
public class Solution {
public boolean canCross(int[] stones) {
if(stones == null || stones.length == 0){
return false;
}
int n = stones.length;
Map<Integer, Set<Integer>> map = new HashMap<>(); //Store the stone location and step pair
for(int stone:stones){
map.put(stone, new HashSet<>()); //Initialize stone location
}
map.get(0).add(1); //first step start at 0 with 1
for(int i=0; i<n-1; i++){ //No need to calculate for last stone
for(int step:map.get(stones[i])){ //try each step from stone
int reach = stones[i] + step;
if(reach == stones[n-1]) //See if reach final location
return true;
if(map.get(reach) == null) //If not a stone continue
continue;
for(int s = step+1; s>0 && s>=step-1; s--){
map.get(reach).add(s); //Add steps for reachable stone
}
}
}
return false;
}
}
| UTF-8 | Java | 1,837 | java | FrogJump.java | Java | [] | null | [] | public class Solution {
public boolean canCross(int[] stones) {
if(stones == null || stones.length == 0){
return false;
}
return dfs(stones, 0, 1);
}
//Baise DFS solution each time 3 steps => O(3^n)
public boolean dfs(int[] stones, int idx, int step){
if(idx == stones.length-1){
return true;
}
int i = idx + 1;
boolean flag = false;
for(i=idx+1; i<stones.length; i++){
if(stones[i] == stones[idx] + step)
if(dfs(stones, i, step-1) || dfs(stones, i, step) || dfs(stones, i, step+1))
return true;
}
return false;
}
}
//DP solution store the stone location and step => Worset Case O(n^2)
public class Solution {
public boolean canCross(int[] stones) {
if(stones == null || stones.length == 0){
return false;
}
int n = stones.length;
Map<Integer, Set<Integer>> map = new HashMap<>(); //Store the stone location and step pair
for(int stone:stones){
map.put(stone, new HashSet<>()); //Initialize stone location
}
map.get(0).add(1); //first step start at 0 with 1
for(int i=0; i<n-1; i++){ //No need to calculate for last stone
for(int step:map.get(stones[i])){ //try each step from stone
int reach = stones[i] + step;
if(reach == stones[n-1]) //See if reach final location
return true;
if(map.get(reach) == null) //If not a stone continue
continue;
for(int s = step+1; s>0 && s>=step-1; s--){
map.get(reach).add(s); //Add steps for reachable stone
}
}
}
return false;
}
}
| 1,837 | 0.49755 | 0.485574 | 51 | 35.019608 | 25.599089 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.843137 | false | false | 9 |
f062a50ed3a2f036f8d1db5c75a27c32becdedae | 6,442,450,996,235 | be1463bbe0d505d558a942d20f286f908c64d609 | /002ClassesAndObject/src/com/cg/date/constructor/TestConstructor.java | 485c977cfeeee303f3c77217e5eb844e2646e489 | [
"MIT"
] | permissive | brijeshsmita/base | https://github.com/brijeshsmita/base | b0f5d9e39c256ed320e94d0cca98ee456ac8e3ad | e013b471574566f4e0bbb99d86126a112abffa15 | refs/heads/master | 2021-01-17T12:07:35.208000 | 2016-03-11T12:27:19 | 2016-03-11T12:27:19 | 39,211,449 | 0 | 0 | null | true | 2015-07-16T17:42:40 | 2015-07-16T17:42:40 | 2015-05-27T22:43:30 | 2013-12-26T15:18:20 | 174 | 0 | 0 | 0 | null | null | null | package com.cg.date.constructor;
public class TestConstructor {
public static void main(String[] args) {
/*MyDate dob = new MyDate();
System.out.println("=======Priting DOB information=====");
dob.print();
System.out.println("===================================");*/
/*System.out.println("=======Priting DOJ information======");*/
MyDate doj = new MyDate(29,12,2015);
System.out.println("======DOJ======\n"+doj);
//doj.setDate(29,12, 2015);
//doj.print();
System.out.println("===================================");
}
}
| UTF-8 | Java | 557 | java | TestConstructor.java | Java | [] | null | [] | package com.cg.date.constructor;
public class TestConstructor {
public static void main(String[] args) {
/*MyDate dob = new MyDate();
System.out.println("=======Priting DOB information=====");
dob.print();
System.out.println("===================================");*/
/*System.out.println("=======Priting DOJ information======");*/
MyDate doj = new MyDate(29,12,2015);
System.out.println("======DOJ======\n"+doj);
//doj.setDate(29,12, 2015);
//doj.print();
System.out.println("===================================");
}
}
| 557 | 0.520646 | 0.491921 | 15 | 35.133335 | 20.330164 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.533333 | false | false | 9 |
8257f9762734b4519fa72434583c811299318c22 | 14,078,902,831,252 | 8b804e40a947da52968162ece71af1e9e9f32da6 | /project/ParallelExecute/src/main/java/org/para/distributed/util/SystemUtil.java | e6c7ea8ffe09768e4ad8efeb01f4be39fc3b89b3 | [
"Apache-2.0"
] | permissive | suhuanzheng7784877/ParallelExecute | https://github.com/suhuanzheng7784877/ParallelExecute | 7028f7c7642953c40763b8ab0b3f8ca97f8e5910 | 1f7bb182cd7a4cd43b8f07b0cee37d0118c18e7e | refs/heads/master | 2021-01-01T05:51:26.854000 | 2015-02-01T12:44:37 | 2015-02-01T12:44:37 | 14,553,962 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.para.distributed.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.para.distributed.dto.WorkerNode;
import org.para.distributed.task.DistributedParallelTask;
import org.para.util.PropertiesUtil;
import org.para.util.StringUtil;
import com.sun.management.OperatingSystemMXBean;
/**
* 获取系统信息相关的辅助方法
*
* @author liuyan
* @Email:suhuanzheng7784877@163.com
* @version 0.1
* @Date: 2013-12-18
* @Copyright: 2013 story All rights reserved.
*/
public final class SystemUtil {
private static Logger logger = Logger.getLogger(SystemUtil.class);
/**
* 系统的classpath
*/
private static String java_class_path = System
.getProperty("java.class.path");
/**
* 本机node的ip地址
*/
public volatile static String localIP = null;
/**
* 查询CPU使用率的命令
*/
public final static String cpuUseCommandTop = "top -b -n 1";
/**
* 查看CPU使用率命令
*/
public final static String cpuUseCommandVmstat = "vmstat -n 1 -a 2";
/**
* 查询内存的命令
*/
public final static String memoryCommand = "cat /proc/meminfo";
/**
* 上一次的CPU空闲率
*/
public volatile static float lastCPURate = 0.0F;
/**
* 以mb为单位的分母
*/
public static final int mb = 1024 * 1024;
/**
* 操作系统相关的MBean
*/
public static final OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
/**
* 结点机器上可用磁盘根路径
*/
final static String NODE_ROOT_PATH = PropertiesUtil
.getValue("nodeagent.downloadfile.freeDisk");
static {
try {
localIP = getIP();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/**
* 获取结点硬件信息
*
* @param isRegister
* @return
* @throws UnknownHostException
*/
public static WorkerNode getWorkerNode(boolean isRegister)
throws UnknownHostException {
WorkerNode workerNode = WorkerNode.getSingle();
// CPU空闲率
float cpuFreeRate;
// 注册时间
long registerTime = System.currentTimeMillis();
if (isRegister) {
// [1]-是注册的逻辑
workerNode.setCreatetime(registerTime);
// cpu的闲置率
cpuFreeRate = getCpuFreeRateForRegister();
// 构建节点上的应用实例信息
// buildNodeWebAppInstences(workerNode);
} else {
// [2]-心跳的逻辑
// cpu的闲置率
cpuFreeRate = getCpuFreeRateForLinuxHeartbeat();
}
// 本机器空余硬盘
long freeDisk = getFreeDisk();
// 本机器空余内存
long freeMemroy = getRealFreeMemory();
// 物理总内存
long physicalTotal = getPhysicalTotal();
// 本机器CPU核数
int cpuProcessors = getCPUProcessors();
// 内存空闲率
float memroyFreeRate = Float.parseFloat(String.valueOf(freeMemroy))
/ Float.parseFloat(String.valueOf(physicalTotal));
logger.info("node-ip:" + localIP);
logger.info("freeDisk:" + freeDisk);
logger.info("freeMemroy:" + freeMemroy);
logger.info("cpuProcessors:" + cpuProcessors);
logger.info("cpuFreeRate:" + cpuFreeRate);
logger.info("physicalTotal:" + physicalTotal);
logger.info("memroyFreeRate:" + memroyFreeRate);
logger.info("registerTime:" + registerTime);
workerNode.setCpufreerate(cpuFreeRate);
workerNode.setWorkerIp(localIP);
workerNode.setFreedisk(freeDisk);
workerNode.setFreememroy(freeMemroy);
workerNode.setLasthearttime(registerTime);
return workerNode;
}
/**
* 构建节点上的应用实例信息 TODO:暂时不发送节点上的任务信息,暂时由总master进行调度
*
* @param nodeInfo
*/
// public static void buildNodeWebAppInstences(WorkerNode workerNode) {
// // 应用实例Map集合
// Map<String, WebAppInstence> webAppInstenceMaps =
// GlobalMemroyStore.WebAppInstencePool;
// WebAppInstence webAppInstence = null;
// List<WebAppInstence> webAppInstenceList = new ArrayList<WebAppInstence>(
// 16);
// for (String webAppInstenceKey : webAppInstenceMaps.keySet()) {
//
// webAppInstence = webAppInstenceMaps.get(webAppInstenceKey);
// webAppInstenceList.add(webAppInstence);
// }
// nodeInfo.setWebAppInstences(webAppInstenceList);
// }
/**
* 检查附着在结点上的所有应用实例情况2.9.3
*
* @return
*/
public static List<DistributedParallelTask> getParallelTasks() {
return null;
}
/**
* 获取本机IP
*
* @return
* @throws UnknownHostException
*/
public static String getIP() throws UnknownHostException {
if (localIP == null) {
try {
if (StringUtil.OSisLinux()) {// linux获取ip
Enumeration<NetworkInterface> e1 = NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = e1.nextElement();
if (ni.getName().startsWith("eth0")
|| ni.getName().startsWith("eth1")) {
Enumeration<InetAddress> e2 = ni.getInetAddresses();
InetAddress ia = null;
while (e2.hasMoreElements()) {
ia = e2.nextElement();
if (ia != null && ia instanceof Inet4Address) {
localIP = ia.getHostAddress();
if (localIP != null
&& !"".equals(localIP.trim())) {
return localIP;
}
}
}
}
}
} else {// windows获取ip
localIP = InetAddress.getLocalHost().getHostAddress();
return localIP;
}
} catch (SocketException e) {
logger.error("error", e);
} catch (Exception e) {
logger.error("error", e);
}
}
logger.info("[local ip is " + localIP + "]");
return localIP;
}
/**
* 获取剩余硬盘信息
*
* @return
*/
public static long getFreeDisk() {
File fileRoot = new File(NODE_ROOT_PATH);
// 如果不存在,则直接创建。
if (!fileRoot.exists()) {
fileRoot.mkdir();
}
long freeSpaceB = fileRoot.getFreeSpace();
long freeSpaceMB = freeSpaceB / mb;
return freeSpaceMB;
}
/**
* 获取剩余内存,适用于windows
*
* @return
*/
public static long getFreeMemroy() {
// 空闲物理内存
long physicalFree = osmxb.getFreePhysicalMemorySize() / mb;
// 系统总物理内存
long physicalTotal = osmxb.getTotalPhysicalMemorySize() / mb;
// 已用的物理内存
long physicalUse = physicalTotal - physicalFree;
// 获取操作系统的版本
String os = System.getProperty("os.name");
logger.info("OS Version:" + os);
logger.info("physicalFree :" + physicalFree + "MB");
logger.info("physicalUse:" + physicalUse + "MB");
logger.info("physicalTotal:" + physicalTotal + "MB");
// 单位是mb
return physicalFree;
}
/**
* 获取剩余内存
*
* @return
*/
public static long getPhysicalTotal() {
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 系统总物理内存
long physicalTotal = osmxb.getTotalPhysicalMemorySize() / mb;
// 单位是mb
return physicalTotal;
}
/**
* 获取CPU核数
*
* @return
*/
public static int getCPUProcessors() {
return Runtime.getRuntime().availableProcessors();
}
/**
* 本机IP是否在该ips的List中
*
* @param ips
* @return
* @throws UnknownHostException
*/
public final static boolean ipIsWillWork(List<String> ips)
throws UnknownHostException {
if (ips == null || 0 == ips.size()) {
return false;
}
String localhostIp = getIP();
if (localhostIp == null || "".equals(localhostIp)) {
return false;
}
System.out.println("ips:" + ips);
// List列表是否包含本机的ip地址
return ips.contains(localhostIp);
}
/**
* 获取瞬时CPU空闲率, TODO:暂时只支持linux windows默认是50%
*
* @return
*/
public final static float getCpuFreeRateForRegister() {
// linux系统
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
try {
// CPU空闲率
Float cpuFreeFloat = readCPUFreeVMStatCommand(is, isr, brStat);
logger.info("cpuFreeFloat.floatValue():"
+ cpuFreeFloat.floatValue());
// 返回CPU空闲率
float cpuFreeRate = Float.parseFloat(String
.valueOf(cpuFreeFloat)) / 100;
// 记住此次的CPU空闲率
rememberLastCPUFreeRate(cpuFreeRate);
return cpuFreeRate;
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println(ioe.getMessage());
logger.error("error", ioe);
return 0.5F;
} catch (InterruptedException ee) {
ee.printStackTrace();
logger.error("error", ee);
return 0.5F;
} finally {
freeResource(is, isr, brStat);
}
} else {
return 0.5F;
}
}
/**
* 记住此次的CPU空闲率
*
* @param cpuFreeRate
*/
private static void rememberLastCPUFreeRate(float cpuFreeRate) {
lastCPURate = cpuFreeRate;
}
/**
* CPU平均空闲率
*
* @param currentCpuFreeRate
* @return
*/
private static float getAverageCPUFreeRate(float currentCpuFreeRate) {
float averageCPUFreeRate = (lastCPURate + currentCpuFreeRate) / 2;
return averageCPUFreeRate;
}
/**
* 获取CPU空闲率, TODO:暂时只支持linux
*
* @return
*/
public final static float getCpuFreeRateForLinuxHeartbeat() {
// linux系统
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
try {
// CPU空闲率
Float cpuFreeFloat = readCPUFreeVMStatCommand(is, isr, brStat);
logger.info("cpuFreeFloat.floatValue():"
+ cpuFreeFloat.floatValue());
// 返回CPU空闲率
float cpuFreeRate = Float.parseFloat(String
.valueOf(cpuFreeFloat)) / 100;
float averageCPUFreeRate = getAverageCPUFreeRate(cpuFreeRate);
// CPU的平均空闲率
logger.info("[averageCPUFreeRate]:" + averageCPUFreeRate);
// 记住此次的CPU空闲率
rememberLastCPUFreeRate(averageCPUFreeRate);
return averageCPUFreeRate;
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println(ioe.getMessage());
return 0.5F;
} catch (InterruptedException ee) {
ee.printStackTrace();
logger.error("error", ee);
return 0.5F;
} finally {
freeResource(is, isr, brStat);
}
} else {
return 0.5F;
}
}
/**
* 释放空闲IO资源
*
* @param is
* @param isr
* @param br
*/
private static void freeResource(InputStream is, InputStreamReader isr,
BufferedReader br) {
try {
if (is != null)
is.close();
is = null;
if (isr != null)
isr.close();
isr = null;
if (br != null)
br.close();
isr = null;
} catch (IOException ioe) {
ioe.printStackTrace();
logger.error("error", ioe);
}
}
/**
* 获取linux真正的内存:free+buffer+cache
*
* @return
*/
private static long getRealFreeMemory() {
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
Process process = null;
try {
process = Runtime.getRuntime().exec(memoryCommand);
} catch (IOException e) {
e.printStackTrace();
logger.error("error", e);
}
// 进程执行结果输入
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
// 第一行是总内存需要忽略
try {
brStat.readLine();
String memFreeStringLine = brStat.readLine();
logger.debug("memFreeStringLine:" + memFreeStringLine);
tokenStat = new StringTokenizer(memFreeStringLine);
tokenStat.nextToken();
String memFreeString = tokenStat.nextToken();
String buffersStringLine = brStat.readLine();
logger.debug("buffersStringLine:" + buffersStringLine);
tokenStat = new StringTokenizer(buffersStringLine);
tokenStat.nextToken();
String buffersString = tokenStat.nextToken();
String cachedStringLine = brStat.readLine();
logger.debug("cachedStringLine:" + cachedStringLine);
tokenStat = new StringTokenizer(cachedStringLine);
tokenStat.nextToken();
String cachedString = tokenStat.nextToken();
logger.debug("memFreeString:" + memFreeString);
logger.debug("buffersString:" + buffersString);
logger.debug("cachedString:" + cachedString);
long memFree = Long.parseLong(memFreeString);
long buffers = Long.parseLong(buffersString);
long cached = Long.parseLong(cachedString);
logger.info("memFree:" + memFree + "kb");
logger.info("buffers:" + buffers + "kb");
logger.info("cached:" + cached + "kb");
// 以mb为单位
long availableMem = (memFree + buffers + cached) / 1024;
logger.info("availableMem:" + availableMem + "mb");
return availableMem;
} catch (IOException e) {
e.printStackTrace();
logger.error("error", e);
} finally {
// 释放空闲IO资源
freeResource(is, isr, brStat);
}
return 0L;
} else {
// 适用于Windows
return getFreeMemroy();
}
}
/**
* 读取VMstat命令,获取CPU空闲率
*
* @return
* @throws IOException
* @throws InterruptedException
*/
private static Float readCPUFreeVMStatCommand(InputStream is,
InputStreamReader isr, BufferedReader brStat) throws IOException,
InterruptedException {
StringTokenizer tokenStat = null;
Process process = Runtime.getRuntime().exec(cpuUseCommandVmstat);
// 等待执行完毕
process.waitFor();
// 进程执行结果输入s
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
// 第一行是title需要忽略
brStat.readLine();
brStat.readLine();
brStat.readLine();
// 获取top命令执行结果
String resultString = brStat.readLine();
logger.info("----brStat----" + resultString);
tokenStat = new StringTokenizer(resultString);
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuFree = tokenStat.nextToken();
logger.info("CPU idle : " + cpuFree);
// CPU空闲率
Float cpuFreeFloat = new Float(cpuFree);
return cpuFreeFloat;
}
/**
* 获取系统的 classpath
*
* @return
*/
public static String getSystemClassPath() {
return java_class_path;
}
}
| UTF-8 | Java | 14,851 | java | SystemUtil.java | Java | [
{
"context": "SystemMXBean;\n\n/**\n * 获取系统信息相关的辅助方法\n * \n * @author liuyan\n * @Email:suhuanzheng7784877@163.com\n * @version ",
"end": 774,
"score": 0.9619486927986145,
"start": 768,
"tag": "USERNAME",
"value": "liuyan"
},
{
"context": "\n * 获取系统信息相关的辅助方法\n * \n * @author liuyan\n * @Email:suhuanzheng7784877@163.com\n * @version 0.1\n * @Date: 2013-12-18\n * @Copyrigh",
"end": 811,
"score": 0.9999144673347473,
"start": 785,
"tag": "EMAIL",
"value": "suhuanzheng7784877@163.com"
}
] | null | [] | package org.para.distributed.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.para.distributed.dto.WorkerNode;
import org.para.distributed.task.DistributedParallelTask;
import org.para.util.PropertiesUtil;
import org.para.util.StringUtil;
import com.sun.management.OperatingSystemMXBean;
/**
* 获取系统信息相关的辅助方法
*
* @author liuyan
* @Email:<EMAIL>
* @version 0.1
* @Date: 2013-12-18
* @Copyright: 2013 story All rights reserved.
*/
public final class SystemUtil {
private static Logger logger = Logger.getLogger(SystemUtil.class);
/**
* 系统的classpath
*/
private static String java_class_path = System
.getProperty("java.class.path");
/**
* 本机node的ip地址
*/
public volatile static String localIP = null;
/**
* 查询CPU使用率的命令
*/
public final static String cpuUseCommandTop = "top -b -n 1";
/**
* 查看CPU使用率命令
*/
public final static String cpuUseCommandVmstat = "vmstat -n 1 -a 2";
/**
* 查询内存的命令
*/
public final static String memoryCommand = "cat /proc/meminfo";
/**
* 上一次的CPU空闲率
*/
public volatile static float lastCPURate = 0.0F;
/**
* 以mb为单位的分母
*/
public static final int mb = 1024 * 1024;
/**
* 操作系统相关的MBean
*/
public static final OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
/**
* 结点机器上可用磁盘根路径
*/
final static String NODE_ROOT_PATH = PropertiesUtil
.getValue("nodeagent.downloadfile.freeDisk");
static {
try {
localIP = getIP();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/**
* 获取结点硬件信息
*
* @param isRegister
* @return
* @throws UnknownHostException
*/
public static WorkerNode getWorkerNode(boolean isRegister)
throws UnknownHostException {
WorkerNode workerNode = WorkerNode.getSingle();
// CPU空闲率
float cpuFreeRate;
// 注册时间
long registerTime = System.currentTimeMillis();
if (isRegister) {
// [1]-是注册的逻辑
workerNode.setCreatetime(registerTime);
// cpu的闲置率
cpuFreeRate = getCpuFreeRateForRegister();
// 构建节点上的应用实例信息
// buildNodeWebAppInstences(workerNode);
} else {
// [2]-心跳的逻辑
// cpu的闲置率
cpuFreeRate = getCpuFreeRateForLinuxHeartbeat();
}
// 本机器空余硬盘
long freeDisk = getFreeDisk();
// 本机器空余内存
long freeMemroy = getRealFreeMemory();
// 物理总内存
long physicalTotal = getPhysicalTotal();
// 本机器CPU核数
int cpuProcessors = getCPUProcessors();
// 内存空闲率
float memroyFreeRate = Float.parseFloat(String.valueOf(freeMemroy))
/ Float.parseFloat(String.valueOf(physicalTotal));
logger.info("node-ip:" + localIP);
logger.info("freeDisk:" + freeDisk);
logger.info("freeMemroy:" + freeMemroy);
logger.info("cpuProcessors:" + cpuProcessors);
logger.info("cpuFreeRate:" + cpuFreeRate);
logger.info("physicalTotal:" + physicalTotal);
logger.info("memroyFreeRate:" + memroyFreeRate);
logger.info("registerTime:" + registerTime);
workerNode.setCpufreerate(cpuFreeRate);
workerNode.setWorkerIp(localIP);
workerNode.setFreedisk(freeDisk);
workerNode.setFreememroy(freeMemroy);
workerNode.setLasthearttime(registerTime);
return workerNode;
}
/**
* 构建节点上的应用实例信息 TODO:暂时不发送节点上的任务信息,暂时由总master进行调度
*
* @param nodeInfo
*/
// public static void buildNodeWebAppInstences(WorkerNode workerNode) {
// // 应用实例Map集合
// Map<String, WebAppInstence> webAppInstenceMaps =
// GlobalMemroyStore.WebAppInstencePool;
// WebAppInstence webAppInstence = null;
// List<WebAppInstence> webAppInstenceList = new ArrayList<WebAppInstence>(
// 16);
// for (String webAppInstenceKey : webAppInstenceMaps.keySet()) {
//
// webAppInstence = webAppInstenceMaps.get(webAppInstenceKey);
// webAppInstenceList.add(webAppInstence);
// }
// nodeInfo.setWebAppInstences(webAppInstenceList);
// }
/**
* 检查附着在结点上的所有应用实例情况2.9.3
*
* @return
*/
public static List<DistributedParallelTask> getParallelTasks() {
return null;
}
/**
* 获取本机IP
*
* @return
* @throws UnknownHostException
*/
public static String getIP() throws UnknownHostException {
if (localIP == null) {
try {
if (StringUtil.OSisLinux()) {// linux获取ip
Enumeration<NetworkInterface> e1 = NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = e1.nextElement();
if (ni.getName().startsWith("eth0")
|| ni.getName().startsWith("eth1")) {
Enumeration<InetAddress> e2 = ni.getInetAddresses();
InetAddress ia = null;
while (e2.hasMoreElements()) {
ia = e2.nextElement();
if (ia != null && ia instanceof Inet4Address) {
localIP = ia.getHostAddress();
if (localIP != null
&& !"".equals(localIP.trim())) {
return localIP;
}
}
}
}
}
} else {// windows获取ip
localIP = InetAddress.getLocalHost().getHostAddress();
return localIP;
}
} catch (SocketException e) {
logger.error("error", e);
} catch (Exception e) {
logger.error("error", e);
}
}
logger.info("[local ip is " + localIP + "]");
return localIP;
}
/**
* 获取剩余硬盘信息
*
* @return
*/
public static long getFreeDisk() {
File fileRoot = new File(NODE_ROOT_PATH);
// 如果不存在,则直接创建。
if (!fileRoot.exists()) {
fileRoot.mkdir();
}
long freeSpaceB = fileRoot.getFreeSpace();
long freeSpaceMB = freeSpaceB / mb;
return freeSpaceMB;
}
/**
* 获取剩余内存,适用于windows
*
* @return
*/
public static long getFreeMemroy() {
// 空闲物理内存
long physicalFree = osmxb.getFreePhysicalMemorySize() / mb;
// 系统总物理内存
long physicalTotal = osmxb.getTotalPhysicalMemorySize() / mb;
// 已用的物理内存
long physicalUse = physicalTotal - physicalFree;
// 获取操作系统的版本
String os = System.getProperty("os.name");
logger.info("OS Version:" + os);
logger.info("physicalFree :" + physicalFree + "MB");
logger.info("physicalUse:" + physicalUse + "MB");
logger.info("physicalTotal:" + physicalTotal + "MB");
// 单位是mb
return physicalFree;
}
/**
* 获取剩余内存
*
* @return
*/
public static long getPhysicalTotal() {
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 系统总物理内存
long physicalTotal = osmxb.getTotalPhysicalMemorySize() / mb;
// 单位是mb
return physicalTotal;
}
/**
* 获取CPU核数
*
* @return
*/
public static int getCPUProcessors() {
return Runtime.getRuntime().availableProcessors();
}
/**
* 本机IP是否在该ips的List中
*
* @param ips
* @return
* @throws UnknownHostException
*/
public final static boolean ipIsWillWork(List<String> ips)
throws UnknownHostException {
if (ips == null || 0 == ips.size()) {
return false;
}
String localhostIp = getIP();
if (localhostIp == null || "".equals(localhostIp)) {
return false;
}
System.out.println("ips:" + ips);
// List列表是否包含本机的ip地址
return ips.contains(localhostIp);
}
/**
* 获取瞬时CPU空闲率, TODO:暂时只支持linux windows默认是50%
*
* @return
*/
public final static float getCpuFreeRateForRegister() {
// linux系统
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
try {
// CPU空闲率
Float cpuFreeFloat = readCPUFreeVMStatCommand(is, isr, brStat);
logger.info("cpuFreeFloat.floatValue():"
+ cpuFreeFloat.floatValue());
// 返回CPU空闲率
float cpuFreeRate = Float.parseFloat(String
.valueOf(cpuFreeFloat)) / 100;
// 记住此次的CPU空闲率
rememberLastCPUFreeRate(cpuFreeRate);
return cpuFreeRate;
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println(ioe.getMessage());
logger.error("error", ioe);
return 0.5F;
} catch (InterruptedException ee) {
ee.printStackTrace();
logger.error("error", ee);
return 0.5F;
} finally {
freeResource(is, isr, brStat);
}
} else {
return 0.5F;
}
}
/**
* 记住此次的CPU空闲率
*
* @param cpuFreeRate
*/
private static void rememberLastCPUFreeRate(float cpuFreeRate) {
lastCPURate = cpuFreeRate;
}
/**
* CPU平均空闲率
*
* @param currentCpuFreeRate
* @return
*/
private static float getAverageCPUFreeRate(float currentCpuFreeRate) {
float averageCPUFreeRate = (lastCPURate + currentCpuFreeRate) / 2;
return averageCPUFreeRate;
}
/**
* 获取CPU空闲率, TODO:暂时只支持linux
*
* @return
*/
public final static float getCpuFreeRateForLinuxHeartbeat() {
// linux系统
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
try {
// CPU空闲率
Float cpuFreeFloat = readCPUFreeVMStatCommand(is, isr, brStat);
logger.info("cpuFreeFloat.floatValue():"
+ cpuFreeFloat.floatValue());
// 返回CPU空闲率
float cpuFreeRate = Float.parseFloat(String
.valueOf(cpuFreeFloat)) / 100;
float averageCPUFreeRate = getAverageCPUFreeRate(cpuFreeRate);
// CPU的平均空闲率
logger.info("[averageCPUFreeRate]:" + averageCPUFreeRate);
// 记住此次的CPU空闲率
rememberLastCPUFreeRate(averageCPUFreeRate);
return averageCPUFreeRate;
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println(ioe.getMessage());
return 0.5F;
} catch (InterruptedException ee) {
ee.printStackTrace();
logger.error("error", ee);
return 0.5F;
} finally {
freeResource(is, isr, brStat);
}
} else {
return 0.5F;
}
}
/**
* 释放空闲IO资源
*
* @param is
* @param isr
* @param br
*/
private static void freeResource(InputStream is, InputStreamReader isr,
BufferedReader br) {
try {
if (is != null)
is.close();
is = null;
if (isr != null)
isr.close();
isr = null;
if (br != null)
br.close();
isr = null;
} catch (IOException ioe) {
ioe.printStackTrace();
logger.error("error", ioe);
}
}
/**
* 获取linux真正的内存:free+buffer+cache
*
* @return
*/
private static long getRealFreeMemory() {
if (StringUtil.OSisLinux()) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
Process process = null;
try {
process = Runtime.getRuntime().exec(memoryCommand);
} catch (IOException e) {
e.printStackTrace();
logger.error("error", e);
}
// 进程执行结果输入
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
// 第一行是总内存需要忽略
try {
brStat.readLine();
String memFreeStringLine = brStat.readLine();
logger.debug("memFreeStringLine:" + memFreeStringLine);
tokenStat = new StringTokenizer(memFreeStringLine);
tokenStat.nextToken();
String memFreeString = tokenStat.nextToken();
String buffersStringLine = brStat.readLine();
logger.debug("buffersStringLine:" + buffersStringLine);
tokenStat = new StringTokenizer(buffersStringLine);
tokenStat.nextToken();
String buffersString = tokenStat.nextToken();
String cachedStringLine = brStat.readLine();
logger.debug("cachedStringLine:" + cachedStringLine);
tokenStat = new StringTokenizer(cachedStringLine);
tokenStat.nextToken();
String cachedString = tokenStat.nextToken();
logger.debug("memFreeString:" + memFreeString);
logger.debug("buffersString:" + buffersString);
logger.debug("cachedString:" + cachedString);
long memFree = Long.parseLong(memFreeString);
long buffers = Long.parseLong(buffersString);
long cached = Long.parseLong(cachedString);
logger.info("memFree:" + memFree + "kb");
logger.info("buffers:" + buffers + "kb");
logger.info("cached:" + cached + "kb");
// 以mb为单位
long availableMem = (memFree + buffers + cached) / 1024;
logger.info("availableMem:" + availableMem + "mb");
return availableMem;
} catch (IOException e) {
e.printStackTrace();
logger.error("error", e);
} finally {
// 释放空闲IO资源
freeResource(is, isr, brStat);
}
return 0L;
} else {
// 适用于Windows
return getFreeMemroy();
}
}
/**
* 读取VMstat命令,获取CPU空闲率
*
* @return
* @throws IOException
* @throws InterruptedException
*/
private static Float readCPUFreeVMStatCommand(InputStream is,
InputStreamReader isr, BufferedReader brStat) throws IOException,
InterruptedException {
StringTokenizer tokenStat = null;
Process process = Runtime.getRuntime().exec(cpuUseCommandVmstat);
// 等待执行完毕
process.waitFor();
// 进程执行结果输入s
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
// 第一行是title需要忽略
brStat.readLine();
brStat.readLine();
brStat.readLine();
// 获取top命令执行结果
String resultString = brStat.readLine();
logger.info("----brStat----" + resultString);
tokenStat = new StringTokenizer(resultString);
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuFree = tokenStat.nextToken();
logger.info("CPU idle : " + cpuFree);
// CPU空闲率
Float cpuFreeFloat = new Float(cpuFree);
return cpuFreeFloat;
}
/**
* 获取系统的 classpath
*
* @return
*/
public static String getSystemClassPath() {
return java_class_path;
}
}
| 14,832 | 0.673639 | 0.667724 | 640 | 20.664063 | 19.611332 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.203125 | false | false | 9 |
2ae959039855e867cf3b92bd0bbb252be3d99d98 | 6,047,313,954,438 | 7224a3106edfb9ddc7d5d5d8a0a0d5a9c4b3e06f | /canalmate-api/src/main/java/com/ppdai/canalmate/api/controller/canal/server/CanalProcessController.java | a032fa1ca42963f9048ab9ab08588034db2be94d | [] | no_license | waters321/canal-manager | https://github.com/waters321/canal-manager | 5acb0536c74130bcdafedb71db33d0af0b475f22 | da3db461a33f1814079a652c9abb39ecd7cdfc64 | refs/heads/master | 2020-04-11T15:20:35.488000 | 2018-12-20T04:03:47 | 2018-12-20T04:03:47 | 161,888,623 | 0 | 1 | null | false | 2018-12-20T04:00:18 | 2018-12-15T09:11:00 | 2018-12-15T10:21:46 | 2018-12-20T03:53:13 | 263 | 0 | 1 | 0 | Java | false | null | package com.ppdai.canalmate.api.controller.canal.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ppdai.canalmate.api.core.BaseController;
import com.ppdai.canalmate.api.core.PageResult;
import com.ppdai.canalmate.api.core.Result;
import com.ppdai.canalmate.api.model.canal.server.CanalClientStatus;
import com.ppdai.canalmate.api.model.canal.server.CanalServerConfig;
import com.ppdai.canalmate.api.model.canal.server.CanalServerConfigShow;
import com.ppdai.canalmate.api.model.canal.server.CanalServerStatus;
import com.ppdai.canalmate.api.service.canal.ProcessMonitorService;
import com.ppdai.canalmate.common.cons.CanalConstants;
import com.ppdai.canalmate.common.model.ZKDestinationBean;
import com.ppdai.canalmate.common.model.ZKDestinationClusterNode;
import com.ppdai.canalmate.common.utils.CanalPropertyUtils;
import com.ppdai.canalmate.common.utils.CanalZKUtils;
import com.ppdai.canalmate.common.utils.ReponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(value = "CanalProcessController", description = "进程管理的接口类")
@RestController
@EnableAutoConfiguration
@RequestMapping("/processMonitor")
public class CanalProcessController extends BaseController {
Logger logger = LoggerFactory.getLogger(CanalProcessController.class);
@Qualifier(value = "processMonitorService")
@Autowired
private ProcessMonitorService processMonitorService;
@SuppressWarnings("unchecked")
@ApiOperation(value = "列出canal server config的列表", httpMethod = "GET", response = Result.class)
@RequestMapping(value = "/canalServerConfig/list", method = RequestMethod.GET)
public Result listCanalServerConfig(
@RequestParam(value = "canal_server_name", required = false) String canalServerName,
@RequestParam(value = "canal_server_host", required = false) String canalServerHost,
@RequestParam(value = "pageNum", required = false) String pageNum,
@RequestParam(value = "numberPerPage", required = false) String numberPerPage) {
List<CanalServerConfigShow> canalServerConfigShowList = new ArrayList<CanalServerConfigShow>();
Map<String, String> argsMap = new HashMap<String, String>();
if (StringUtils.isNotBlank(pageNum)) {
argsMap.put("pageNum", pageNum);
} else {
argsMap.put("pageNum", "1");
}
if (StringUtils.isNotBlank(numberPerPage)) {
argsMap.put("numberPerPage", numberPerPage);
} else {
argsMap.put("numberPerPage", "10");
}
if (StringUtils.isNotBlank(canalServerName)) {
argsMap.put("canal_server_name", canalServerName);
}
if (StringUtils.isNotBlank(canalServerHost)) {
argsMap.put("canal_server_host", canalServerHost);
}
Map<String, Object> map = processMonitorService.listCanalServerConfig(argsMap);
canalServerConfigShowList = (List<CanalServerConfigShow>) map.get("resultList");
// 重新封装从数据库中的这个list,根据zk的状态,填入状态信息
canalServerConfigShowList =
processMonitorService.getCanalServerStatusBeanList(canalServerConfigShowList);
Integer cnt = (Integer) map.get("cnt");
PageResult result = new PageResult();
result.setCode(ReponseEnum.SUCCEED.getResCode());
result.setMessage(ReponseEnum.SUCCEED.getResMsg());
result.setData(canalServerConfigShowList);
result.setTotalNum(String.valueOf(cnt));
return result;
}
@ApiOperation(value = "列出canal server 状态列表", httpMethod = "GET", response = Result.class)
@RequestMapping(value = "/canalServerstatus/list", method = RequestMethod.GET)
public Result listCanalServerStatus(@ApiParam(required = true,
value = "canal_server_config的主键") @RequestParam(value = "id", required = true) String id) {
// 根据server id ,从数据库取对应的server配置
CanalServerConfig canalServerConfig =
processMonitorService.selectCanalServerConfigByPrimaryKey(Long.valueOf(id));
String zkAddress = CanalPropertyUtils
.getPropertyValueByKey(canalServerConfig.getCanalServerConfiguration(), "canal.zkServers");
String canalServerName = canalServerConfig.getCanalServerName();
String canalServerHost = canalServerConfig.getCanalServerHost();
String canalServerPort = canalServerConfig.getCanalServerPort();
String standbyServerHost = canalServerConfig.getStandbyServerHost();
String standbyServerPort = canalServerConfig.getStandbyServerPort();
String canalServerHostPort = canalServerHost.trim() + ":" + canalServerPort.trim();
String standbyServerHostPort = standbyServerHost.trim() + ":" + standbyServerPort.trim();
Map<String, CanalServerStatus> map = new HashMap<String, CanalServerStatus>();
// 先从zk里面取该server下所有destination的状态信息,给后面的判断准备数据
List<ZKDestinationBean> zKDestinationBeanList =
CanalZKUtils.getZKDestinationBeanListFromZKAddress(zkAddress);
/*
* 判断canal server的状态,分2步
* 第一步:先循环zk取该server所有destination的数据,从destination判断所有的server,不从zk的/otter/canal/cluster 路径判断。
* 把从zk取的数据做比较基准,数据都是zk存在的。 若是active=true,即:zk存在,db存在。标绿,说明是正常运行,正常配置的active节点
* 若是active=true,即:zk存在,但db不存在,标黄,说明是正常运行,但DB里面错误配置的节点
* 若是active=false,即:zk存在,db存在,标灰,说明是standby运行,正常配置的standby节点
* 若是active=false,即:zk存在,但db不存在,标黄,说明是standby运行,但DB里面错误配置的节点
*
* 第二步:根据db的数据做比较基准 标红的情况:server在db有配置,但zk不存在
*
*/
// 第一步:先循环zk取的数据,在zk存在的情况下,判断是否与db里面匹配
// 循环每个destination
for (ZKDestinationBean zKDestinationBean : zKDestinationBeanList) {
if (zKDestinationBean.getIsStatusOK() == false) {
break;
}
String destinationName = zKDestinationBean.getDestinationName();
if (zKDestinationBean.getzKDestinationRunningNode() == null) {
logger.debug("destinationName:" + destinationName + "没有server运行它,不计算,直接跳过");
continue;
}
// map ,取出最开始的那个list,放到map,先不定义standby active
// 根据 ls /otter/canal/cluster,找到注册在集群上的canal server
List<String> ipAndPortList = CanalZKUtils.getZKCanalServerListFromZKAddress(zkAddress);
for (String addressPort : ipAndPortList) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GRAY);
status.setComment("该server:" + addressPort + "在zk中/otter/canal/cluster已注册,默认标志为GRAY");
map.put(addressPort, status);
}
// 从每个destination中取 cluster 节点的状态
List<ZKDestinationClusterNode> list = zKDestinationBean.getzKDestinationClusterNodeList();
for (ZKDestinationClusterNode node : list) {
String addressPort = node.getAddressPort();// 例如: xxxxx:11111,从zk获取
// 若/otter/canal/destinations/xxxxx/running 的节点与/otter/canal/destinations/xxxx/cluster
// 下相同,则该节点为active
Boolean active = node.getActive();
if (active) {// 若是active
if (addressPort.equals(canalServerHostPort)
|| addressPort.equals(standbyServerHostPort)) {// 若跟db的配置表中的相同
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GREEN);
status.setComment("该server:" + addressPort + "在zk中是active状态,且与数据库中的host字段一致");
map.put(addressPort, status);
} else {// zk与db配置的不匹配
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.YELLOW);
status.setComment("该server:" + addressPort + "在zk中是active状态,但数据库中没有配置该server的host信息");
map.put(addressPort, status);
}
} else {// 若是standby
if (addressPort.equals(canalServerHostPort)
|| addressPort.equals(standbyServerHostPort)) {// 若跟db的配置表中的相同
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GRAY);
status.setComment("该server:" + addressPort + "在zk中是standby状态,且与数据库中的host字段一致");
map.put(addressPort, status);
} else {// zk与db配置的不匹配
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.YELLOW);
status.setComment("该server:" + addressPort + "在zk中是standby状态,但数据库中没有配置该server的host信息");
map.put(addressPort, status);
}
}
}
}
// 第二步:根据db的数据做比较基准,若server在db有配置,但zk不存在,说明对应的server挂了
if (!map.containsKey(canalServerHostPort)) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(canalServerHostPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.RED);
status.setComment(
"该server:" + canalServerHostPort + "在zk中不存在,但数据库中有该host的记录。有可能该host挂掉,或者该host信息配置错误");
map.put(canalServerHostPort, status);
}
if (!map.containsKey(standbyServerHostPort)) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(standbyServerHostPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.RED);
status.setComment("该server:" + canalServerHostPort
+ "在zk中不存在,但数据库中有该host的记录。有可能该host挂掉,或者该host standby信息配置错误");
map.put(standbyServerHostPort, status);
}
// 加到list中
List<CanalServerStatus> canalServerStatusList = new ArrayList<CanalServerStatus>();
for (Map.Entry<String, CanalServerStatus> entry : map.entrySet()) {
CanalServerStatus canalServerStatus = entry.getValue();
canalServerStatusList.add(canalServerStatus);
}
// 判断canal client的状态
List<CanalClientStatus> canalClientStatusList =
processMonitorService.getCanalClientStatusBeanList(id, zKDestinationBeanList);
Map<String, Object> data = new HashMap<String, Object>();
data.put("canalServerStatusList", canalServerStatusList);
data.put("canalClientStatusList", canalClientStatusList);
Result result = new Result();
result.setCode(ReponseEnum.SUCCEED.getResCode());
result.setMessage(ReponseEnum.SUCCEED.getResMsg());
result.setData(data);
return result;
}
}
| UTF-8 | Java | 12,295 | java | CanalProcessController.java | Java | [] | null | [] | package com.ppdai.canalmate.api.controller.canal.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ppdai.canalmate.api.core.BaseController;
import com.ppdai.canalmate.api.core.PageResult;
import com.ppdai.canalmate.api.core.Result;
import com.ppdai.canalmate.api.model.canal.server.CanalClientStatus;
import com.ppdai.canalmate.api.model.canal.server.CanalServerConfig;
import com.ppdai.canalmate.api.model.canal.server.CanalServerConfigShow;
import com.ppdai.canalmate.api.model.canal.server.CanalServerStatus;
import com.ppdai.canalmate.api.service.canal.ProcessMonitorService;
import com.ppdai.canalmate.common.cons.CanalConstants;
import com.ppdai.canalmate.common.model.ZKDestinationBean;
import com.ppdai.canalmate.common.model.ZKDestinationClusterNode;
import com.ppdai.canalmate.common.utils.CanalPropertyUtils;
import com.ppdai.canalmate.common.utils.CanalZKUtils;
import com.ppdai.canalmate.common.utils.ReponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(value = "CanalProcessController", description = "进程管理的接口类")
@RestController
@EnableAutoConfiguration
@RequestMapping("/processMonitor")
public class CanalProcessController extends BaseController {
Logger logger = LoggerFactory.getLogger(CanalProcessController.class);
@Qualifier(value = "processMonitorService")
@Autowired
private ProcessMonitorService processMonitorService;
@SuppressWarnings("unchecked")
@ApiOperation(value = "列出canal server config的列表", httpMethod = "GET", response = Result.class)
@RequestMapping(value = "/canalServerConfig/list", method = RequestMethod.GET)
public Result listCanalServerConfig(
@RequestParam(value = "canal_server_name", required = false) String canalServerName,
@RequestParam(value = "canal_server_host", required = false) String canalServerHost,
@RequestParam(value = "pageNum", required = false) String pageNum,
@RequestParam(value = "numberPerPage", required = false) String numberPerPage) {
List<CanalServerConfigShow> canalServerConfigShowList = new ArrayList<CanalServerConfigShow>();
Map<String, String> argsMap = new HashMap<String, String>();
if (StringUtils.isNotBlank(pageNum)) {
argsMap.put("pageNum", pageNum);
} else {
argsMap.put("pageNum", "1");
}
if (StringUtils.isNotBlank(numberPerPage)) {
argsMap.put("numberPerPage", numberPerPage);
} else {
argsMap.put("numberPerPage", "10");
}
if (StringUtils.isNotBlank(canalServerName)) {
argsMap.put("canal_server_name", canalServerName);
}
if (StringUtils.isNotBlank(canalServerHost)) {
argsMap.put("canal_server_host", canalServerHost);
}
Map<String, Object> map = processMonitorService.listCanalServerConfig(argsMap);
canalServerConfigShowList = (List<CanalServerConfigShow>) map.get("resultList");
// 重新封装从数据库中的这个list,根据zk的状态,填入状态信息
canalServerConfigShowList =
processMonitorService.getCanalServerStatusBeanList(canalServerConfigShowList);
Integer cnt = (Integer) map.get("cnt");
PageResult result = new PageResult();
result.setCode(ReponseEnum.SUCCEED.getResCode());
result.setMessage(ReponseEnum.SUCCEED.getResMsg());
result.setData(canalServerConfigShowList);
result.setTotalNum(String.valueOf(cnt));
return result;
}
@ApiOperation(value = "列出canal server 状态列表", httpMethod = "GET", response = Result.class)
@RequestMapping(value = "/canalServerstatus/list", method = RequestMethod.GET)
public Result listCanalServerStatus(@ApiParam(required = true,
value = "canal_server_config的主键") @RequestParam(value = "id", required = true) String id) {
// 根据server id ,从数据库取对应的server配置
CanalServerConfig canalServerConfig =
processMonitorService.selectCanalServerConfigByPrimaryKey(Long.valueOf(id));
String zkAddress = CanalPropertyUtils
.getPropertyValueByKey(canalServerConfig.getCanalServerConfiguration(), "canal.zkServers");
String canalServerName = canalServerConfig.getCanalServerName();
String canalServerHost = canalServerConfig.getCanalServerHost();
String canalServerPort = canalServerConfig.getCanalServerPort();
String standbyServerHost = canalServerConfig.getStandbyServerHost();
String standbyServerPort = canalServerConfig.getStandbyServerPort();
String canalServerHostPort = canalServerHost.trim() + ":" + canalServerPort.trim();
String standbyServerHostPort = standbyServerHost.trim() + ":" + standbyServerPort.trim();
Map<String, CanalServerStatus> map = new HashMap<String, CanalServerStatus>();
// 先从zk里面取该server下所有destination的状态信息,给后面的判断准备数据
List<ZKDestinationBean> zKDestinationBeanList =
CanalZKUtils.getZKDestinationBeanListFromZKAddress(zkAddress);
/*
* 判断canal server的状态,分2步
* 第一步:先循环zk取该server所有destination的数据,从destination判断所有的server,不从zk的/otter/canal/cluster 路径判断。
* 把从zk取的数据做比较基准,数据都是zk存在的。 若是active=true,即:zk存在,db存在。标绿,说明是正常运行,正常配置的active节点
* 若是active=true,即:zk存在,但db不存在,标黄,说明是正常运行,但DB里面错误配置的节点
* 若是active=false,即:zk存在,db存在,标灰,说明是standby运行,正常配置的standby节点
* 若是active=false,即:zk存在,但db不存在,标黄,说明是standby运行,但DB里面错误配置的节点
*
* 第二步:根据db的数据做比较基准 标红的情况:server在db有配置,但zk不存在
*
*/
// 第一步:先循环zk取的数据,在zk存在的情况下,判断是否与db里面匹配
// 循环每个destination
for (ZKDestinationBean zKDestinationBean : zKDestinationBeanList) {
if (zKDestinationBean.getIsStatusOK() == false) {
break;
}
String destinationName = zKDestinationBean.getDestinationName();
if (zKDestinationBean.getzKDestinationRunningNode() == null) {
logger.debug("destinationName:" + destinationName + "没有server运行它,不计算,直接跳过");
continue;
}
// map ,取出最开始的那个list,放到map,先不定义standby active
// 根据 ls /otter/canal/cluster,找到注册在集群上的canal server
List<String> ipAndPortList = CanalZKUtils.getZKCanalServerListFromZKAddress(zkAddress);
for (String addressPort : ipAndPortList) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GRAY);
status.setComment("该server:" + addressPort + "在zk中/otter/canal/cluster已注册,默认标志为GRAY");
map.put(addressPort, status);
}
// 从每个destination中取 cluster 节点的状态
List<ZKDestinationClusterNode> list = zKDestinationBean.getzKDestinationClusterNodeList();
for (ZKDestinationClusterNode node : list) {
String addressPort = node.getAddressPort();// 例如: xxxxx:11111,从zk获取
// 若/otter/canal/destinations/xxxxx/running 的节点与/otter/canal/destinations/xxxx/cluster
// 下相同,则该节点为active
Boolean active = node.getActive();
if (active) {// 若是active
if (addressPort.equals(canalServerHostPort)
|| addressPort.equals(standbyServerHostPort)) {// 若跟db的配置表中的相同
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GREEN);
status.setComment("该server:" + addressPort + "在zk中是active状态,且与数据库中的host字段一致");
map.put(addressPort, status);
} else {// zk与db配置的不匹配
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.YELLOW);
status.setComment("该server:" + addressPort + "在zk中是active状态,但数据库中没有配置该server的host信息");
map.put(addressPort, status);
}
} else {// 若是standby
if (addressPort.equals(canalServerHostPort)
|| addressPort.equals(standbyServerHostPort)) {// 若跟db的配置表中的相同
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.GRAY);
status.setComment("该server:" + addressPort + "在zk中是standby状态,且与数据库中的host字段一致");
map.put(addressPort, status);
} else {// zk与db配置的不匹配
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(addressPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.YELLOW);
status.setComment("该server:" + addressPort + "在zk中是standby状态,但数据库中没有配置该server的host信息");
map.put(addressPort, status);
}
}
}
}
// 第二步:根据db的数据做比较基准,若server在db有配置,但zk不存在,说明对应的server挂了
if (!map.containsKey(canalServerHostPort)) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(canalServerHostPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.RED);
status.setComment(
"该server:" + canalServerHostPort + "在zk中不存在,但数据库中有该host的记录。有可能该host挂掉,或者该host信息配置错误");
map.put(canalServerHostPort, status);
}
if (!map.containsKey(standbyServerHostPort)) {
CanalServerStatus status = new CanalServerStatus();
status.setAddressPort(standbyServerHostPort);
status.setCanalServerName(canalServerName);
status.setColor(CanalConstants.RED);
status.setComment("该server:" + canalServerHostPort
+ "在zk中不存在,但数据库中有该host的记录。有可能该host挂掉,或者该host standby信息配置错误");
map.put(standbyServerHostPort, status);
}
// 加到list中
List<CanalServerStatus> canalServerStatusList = new ArrayList<CanalServerStatus>();
for (Map.Entry<String, CanalServerStatus> entry : map.entrySet()) {
CanalServerStatus canalServerStatus = entry.getValue();
canalServerStatusList.add(canalServerStatus);
}
// 判断canal client的状态
List<CanalClientStatus> canalClientStatusList =
processMonitorService.getCanalClientStatusBeanList(id, zKDestinationBeanList);
Map<String, Object> data = new HashMap<String, Object>();
data.put("canalServerStatusList", canalServerStatusList);
data.put("canalClientStatusList", canalClientStatusList);
Result result = new Result();
result.setCode(ReponseEnum.SUCCEED.getResCode());
result.setMessage(ReponseEnum.SUCCEED.getResMsg());
result.setData(data);
return result;
}
}
| 12,295 | 0.73375 | 0.732753 | 246 | 43.833332 | 28.55932 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711382 | false | false | 9 |
e54c99ecfba7e70137c9557e1bd635d4153bc3e6 | 2,757,369,063,698 | 66ececd172abd2826f32be5c15b6f0a92d695cfb | /src/slogo/backend/Changer.java | 401740f7f5585ecd42ac3d538203946aab40b3cf | [
"MIT"
] | permissive | samuel-thompsonn/slogo-parser-cs308 | https://github.com/samuel-thompsonn/slogo-parser-cs308 | db478cf889fcbfcfb41c77afaf06da66c9c4742d | c58cd759374cd71846fc2bd6c30cd45cc35731db | refs/heads/master | 2023-08-06T15:01:05.654000 | 2021-09-22T03:12:26 | 2021-09-22T03:12:26 | 409,048,432 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package slogo.backend;
interface Changer {
/**
* Modifies the given Interpreter in some way based on the type of Changer.
* @param backEnd The Interpreter to modify settings for.
*/
void doChanges(Interpreter backEnd);
}
| UTF-8 | Java | 236 | java | Changer.java | Java | [] | null | [] | package slogo.backend;
interface Changer {
/**
* Modifies the given Interpreter in some way based on the type of Changer.
* @param backEnd The Interpreter to modify settings for.
*/
void doChanges(Interpreter backEnd);
}
| 236 | 0.720339 | 0.720339 | 10 | 22.6 | 25.772854 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 9 |
43a2155a27d62caa4c3b594e4bf0b6ddb58f65a6 | 2,757,369,060,727 | fc6c869ee0228497e41bf357e2803713cdaed63e | /weixin6519android1140/src/sourcecode/com/tencent/mm/plugin/sns/ui/previewimageview/c.java | 97521dda2eb2c48784e25697261d82e87e6b76e6 | [] | no_license | hyb1234hi/reverse-wechat | https://github.com/hyb1234hi/reverse-wechat | cbd26658a667b0c498d2a26a403f93dbeb270b72 | 75d3fd35a2c8a0469dbb057cd16bca3b26c7e736 | refs/heads/master | 2020-09-26T10:12:47.484000 | 2017-11-16T06:54:20 | 2017-11-16T06:54:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.plugin.sns.ui.previewimageview;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.i.j;
import com.tencent.mm.plugin.sns.model.h;
import com.tencent.mm.sdk.platformtools.w;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public final class c
extends b
{
private HashMap<String, Bitmap> pVB;
boolean pVE;
private int qnq;
private boolean qnr;
private boolean qns;
a qnt;
public c(Context paramContext, List<?> paramList, int paramInt, boolean paramBoolean, a parama)
{
super(paramContext, 4);
GMTrace.i(15970030583808L, 118986);
this.pVB = new HashMap();
super.bI(bJ(paramList));
this.qnq = 9;
this.qnr = paramBoolean;
this.qnt = parama;
bpY();
bpZ();
GMTrace.o(15970030583808L, 118986);
}
private List<d> bJ(List<?> paramList)
{
GMTrace.i(15970164801536L, 118987);
ArrayList localArrayList = new ArrayList(paramList.size());
int i = 0;
paramList = paramList.iterator();
while (paramList.hasNext())
{
Object localObject = paramList.next();
d locald = new d();
locald.data = localObject;
locald.id = i;
localArrayList.add(locald);
i += 1;
}
GMTrace.o(15970164801536L, 118987);
return localArrayList;
}
private void bpY()
{
GMTrace.i(15970299019264L, 118988);
int i = 0;
while (i < this.qnp)
{
d locald = new d();
locald.data = "";
locald.id = getCount();
locald.id = getCount();
add(i, locald);
i += 1;
}
GMTrace.o(15970299019264L, 118988);
}
public final void bI(List<?> paramList)
{
GMTrace.i(15970701672448L, 118991);
super.bI(bJ(paramList));
bpY();
bpZ();
GMTrace.o(15970701672448L, 118991);
}
public final void bpZ()
{
GMTrace.i(15970433236992L, 118989);
w.v("DynamicGridAdapter", "showAddImg %s, getCount %d, getHeaderCount %d, maxShowCount %d, showing %s", new Object[] { Boolean.valueOf(this.qnr), Integer.valueOf(getCount()), Integer.valueOf(this.qnp), Integer.valueOf(this.qnq), Boolean.valueOf(this.qns) });
if ((this.qnr) && (bqa() < this.qnq))
{
if (!this.qns)
{
this.qns = true;
add("");
GMTrace.o(15970433236992L, 118989);
}
}
else {
this.qns = false;
}
GMTrace.o(15970433236992L, 118989);
}
public final int bqa()
{
GMTrace.i(15970835890176L, 118992);
int j = getCount();
int k = this.qnp;
if (this.qns) {}
for (int i = 1;; i = 0)
{
GMTrace.o(15970835890176L, 118992);
return j - k - i;
}
}
public final void clear()
{
GMTrace.i(15970567454720L, 118990);
super.clear();
this.qns = false;
GMTrace.o(15970567454720L, 118990);
}
public final void di(int paramInt1, int paramInt2)
{
GMTrace.i(15971372761088L, 118996);
super.di(paramInt1, paramInt2);
if (this.qnt != null) {
this.qnt.de(paramInt1 - this.qnp, paramInt2 - this.qnp);
}
GMTrace.o(15971372761088L, 118996);
}
public final int getItemViewType(int paramInt)
{
GMTrace.i(16275912785920L, 121265);
if (TextUtils.isEmpty(getItem(paramInt).toString()))
{
GMTrace.o(16275912785920L, 121265);
return 1;
}
GMTrace.o(16275912785920L, 121265);
return 0;
}
public final View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
GMTrace.i(15970970107904L, 118993);
String str;
ImageView localImageView;
if (paramView == null)
{
paramView = LayoutInflater.from(this.mContext).inflate(i.g.pgd, paramViewGroup, false);
paramViewGroup = new b(paramView);
paramView.setTag(i.f.paY, paramViewGroup);
str = getItem(paramInt).toString();
localImageView = paramViewGroup.eId;
if (!TextUtils.isEmpty(str)) {
break label196;
}
localImageView.setBackgroundColor(0);
localImageView.setBackgroundDrawable(null);
localImageView.setImageDrawable(null);
localImageView.setBackgroundResource(i.e.oYm);
localImageView.setContentDescription(paramViewGroup.eId.getContext().getString(i.j.piB));
if (paramInt <= 0) {
break label169;
}
paramViewGroup.view.setTag(Integer.valueOf(-1));
label129:
if (paramInt >= this.qnp) {
break label312;
}
paramViewGroup.eId.setVisibility(4);
}
for (;;)
{
GMTrace.o(15970970107904L, 118993);
return paramView;
paramViewGroup = (b)paramView.getTag(i.f.paY);
break;
label169:
if (paramInt >= paramViewGroup.qnu.qnp) {
break label129;
}
paramViewGroup.view.setTag(Integer.valueOf(Integer.MAX_VALUE));
break label129;
label196:
paramViewGroup.view.setTag(Integer.valueOf(paramInt - paramViewGroup.qnu.qnp));
localImageView.setBackgroundDrawable(null);
localImageView.setTag(str);
localImageView.setContentDescription(paramViewGroup.eId.getContext().getString(i.j.pjy));
Bitmap localBitmap = (Bitmap)paramViewGroup.qnu.pVB.get(str);
if (!i.m(localBitmap))
{
new c(paramViewGroup.qnu, localImageView, str).m(new String[] { "" });
break label129;
}
localImageView.setImageBitmap(localBitmap);
break label129;
label312:
paramViewGroup.eId.setVisibility(0);
paramView.setVisibility(0);
}
}
public final int getViewTypeCount()
{
GMTrace.i(16276047003648L, 121266);
GMTrace.o(16276047003648L, 121266);
return 2;
}
public final boolean vC(int paramInt)
{
GMTrace.i(15971104325632L, 118994);
if (paramInt < this.qnp)
{
GMTrace.o(15971104325632L, 118994);
return false;
}
if (this.qns)
{
if (paramInt != getCount() - 1)
{
GMTrace.o(15971104325632L, 118994);
return true;
}
GMTrace.o(15971104325632L, 118994);
return false;
}
boolean bool = super.vC(paramInt);
GMTrace.o(15971104325632L, 118994);
return bool;
}
public final boolean vD(int paramInt)
{
GMTrace.i(15971238543360L, 118995);
if (paramInt < this.qnp)
{
GMTrace.o(15971238543360L, 118995);
return false;
}
if (this.qns)
{
if (paramInt != getCount() - 1)
{
GMTrace.o(15971238543360L, 118995);
return true;
}
GMTrace.o(15971238543360L, 118995);
return false;
}
boolean bool = super.vD(paramInt);
GMTrace.o(15971238543360L, 118995);
return bool;
}
public static abstract interface a
{
public abstract void de(int paramInt1, int paramInt2);
public abstract void removeItem(int paramInt);
}
private final class b
{
public ImageView eId;
View view;
public b(View paramView)
{
GMTrace.i(15992847597568L, 119156);
this.view = paramView;
this.eId = ((ImageView)paramView.findViewById(i.f.pbc));
GMTrace.o(15992847597568L, 119156);
}
}
final class c
extends h<String, Integer, Boolean>
{
private ImageView eKZ;
private Bitmap gsp;
private String path;
public c(ImageView paramImageView, String paramString)
{
GMTrace.i(15992310726656L, 119152);
this.eKZ = paramImageView;
this.path = paramString;
GMTrace.o(15992310726656L, 119152);
}
public final com.tencent.mm.sdk.platformtools.ae biu()
{
GMTrace.i(15992444944384L, 119153);
com.tencent.mm.sdk.platformtools.ae localae = com.tencent.mm.plugin.sns.model.ae.biO();
GMTrace.o(15992444944384L, 119153);
return localae;
}
}
private final class d
{
public Object data;
public int id;
public d()
{
GMTrace.i(15991773855744L, 119148);
GMTrace.o(15991773855744L, 119148);
}
public final int hashCode()
{
GMTrace.i(15992042291200L, 119150);
int i = this.id;
GMTrace.o(15992042291200L, 119150);
return i;
}
public final String toString()
{
GMTrace.i(15991908073472L, 119149);
String str = this.data.toString();
GMTrace.o(15991908073472L, 119149);
return str;
}
}
}
/* Location: D:\tools\apktool\weixin6519android1140\jar\classes2-dex2jar.jar!\com\tencent\mm\plugin\sns\ui\previewimageview\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 8,902 | java | c.java | Java | [] | null | [] | package com.tencent.mm.plugin.sns.ui.previewimageview;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.i.j;
import com.tencent.mm.plugin.sns.model.h;
import com.tencent.mm.sdk.platformtools.w;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public final class c
extends b
{
private HashMap<String, Bitmap> pVB;
boolean pVE;
private int qnq;
private boolean qnr;
private boolean qns;
a qnt;
public c(Context paramContext, List<?> paramList, int paramInt, boolean paramBoolean, a parama)
{
super(paramContext, 4);
GMTrace.i(15970030583808L, 118986);
this.pVB = new HashMap();
super.bI(bJ(paramList));
this.qnq = 9;
this.qnr = paramBoolean;
this.qnt = parama;
bpY();
bpZ();
GMTrace.o(15970030583808L, 118986);
}
private List<d> bJ(List<?> paramList)
{
GMTrace.i(15970164801536L, 118987);
ArrayList localArrayList = new ArrayList(paramList.size());
int i = 0;
paramList = paramList.iterator();
while (paramList.hasNext())
{
Object localObject = paramList.next();
d locald = new d();
locald.data = localObject;
locald.id = i;
localArrayList.add(locald);
i += 1;
}
GMTrace.o(15970164801536L, 118987);
return localArrayList;
}
private void bpY()
{
GMTrace.i(15970299019264L, 118988);
int i = 0;
while (i < this.qnp)
{
d locald = new d();
locald.data = "";
locald.id = getCount();
locald.id = getCount();
add(i, locald);
i += 1;
}
GMTrace.o(15970299019264L, 118988);
}
public final void bI(List<?> paramList)
{
GMTrace.i(15970701672448L, 118991);
super.bI(bJ(paramList));
bpY();
bpZ();
GMTrace.o(15970701672448L, 118991);
}
public final void bpZ()
{
GMTrace.i(15970433236992L, 118989);
w.v("DynamicGridAdapter", "showAddImg %s, getCount %d, getHeaderCount %d, maxShowCount %d, showing %s", new Object[] { Boolean.valueOf(this.qnr), Integer.valueOf(getCount()), Integer.valueOf(this.qnp), Integer.valueOf(this.qnq), Boolean.valueOf(this.qns) });
if ((this.qnr) && (bqa() < this.qnq))
{
if (!this.qns)
{
this.qns = true;
add("");
GMTrace.o(15970433236992L, 118989);
}
}
else {
this.qns = false;
}
GMTrace.o(15970433236992L, 118989);
}
public final int bqa()
{
GMTrace.i(15970835890176L, 118992);
int j = getCount();
int k = this.qnp;
if (this.qns) {}
for (int i = 1;; i = 0)
{
GMTrace.o(15970835890176L, 118992);
return j - k - i;
}
}
public final void clear()
{
GMTrace.i(15970567454720L, 118990);
super.clear();
this.qns = false;
GMTrace.o(15970567454720L, 118990);
}
public final void di(int paramInt1, int paramInt2)
{
GMTrace.i(15971372761088L, 118996);
super.di(paramInt1, paramInt2);
if (this.qnt != null) {
this.qnt.de(paramInt1 - this.qnp, paramInt2 - this.qnp);
}
GMTrace.o(15971372761088L, 118996);
}
public final int getItemViewType(int paramInt)
{
GMTrace.i(16275912785920L, 121265);
if (TextUtils.isEmpty(getItem(paramInt).toString()))
{
GMTrace.o(16275912785920L, 121265);
return 1;
}
GMTrace.o(16275912785920L, 121265);
return 0;
}
public final View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
GMTrace.i(15970970107904L, 118993);
String str;
ImageView localImageView;
if (paramView == null)
{
paramView = LayoutInflater.from(this.mContext).inflate(i.g.pgd, paramViewGroup, false);
paramViewGroup = new b(paramView);
paramView.setTag(i.f.paY, paramViewGroup);
str = getItem(paramInt).toString();
localImageView = paramViewGroup.eId;
if (!TextUtils.isEmpty(str)) {
break label196;
}
localImageView.setBackgroundColor(0);
localImageView.setBackgroundDrawable(null);
localImageView.setImageDrawable(null);
localImageView.setBackgroundResource(i.e.oYm);
localImageView.setContentDescription(paramViewGroup.eId.getContext().getString(i.j.piB));
if (paramInt <= 0) {
break label169;
}
paramViewGroup.view.setTag(Integer.valueOf(-1));
label129:
if (paramInt >= this.qnp) {
break label312;
}
paramViewGroup.eId.setVisibility(4);
}
for (;;)
{
GMTrace.o(15970970107904L, 118993);
return paramView;
paramViewGroup = (b)paramView.getTag(i.f.paY);
break;
label169:
if (paramInt >= paramViewGroup.qnu.qnp) {
break label129;
}
paramViewGroup.view.setTag(Integer.valueOf(Integer.MAX_VALUE));
break label129;
label196:
paramViewGroup.view.setTag(Integer.valueOf(paramInt - paramViewGroup.qnu.qnp));
localImageView.setBackgroundDrawable(null);
localImageView.setTag(str);
localImageView.setContentDescription(paramViewGroup.eId.getContext().getString(i.j.pjy));
Bitmap localBitmap = (Bitmap)paramViewGroup.qnu.pVB.get(str);
if (!i.m(localBitmap))
{
new c(paramViewGroup.qnu, localImageView, str).m(new String[] { "" });
break label129;
}
localImageView.setImageBitmap(localBitmap);
break label129;
label312:
paramViewGroup.eId.setVisibility(0);
paramView.setVisibility(0);
}
}
public final int getViewTypeCount()
{
GMTrace.i(16276047003648L, 121266);
GMTrace.o(16276047003648L, 121266);
return 2;
}
public final boolean vC(int paramInt)
{
GMTrace.i(15971104325632L, 118994);
if (paramInt < this.qnp)
{
GMTrace.o(15971104325632L, 118994);
return false;
}
if (this.qns)
{
if (paramInt != getCount() - 1)
{
GMTrace.o(15971104325632L, 118994);
return true;
}
GMTrace.o(15971104325632L, 118994);
return false;
}
boolean bool = super.vC(paramInt);
GMTrace.o(15971104325632L, 118994);
return bool;
}
public final boolean vD(int paramInt)
{
GMTrace.i(15971238543360L, 118995);
if (paramInt < this.qnp)
{
GMTrace.o(15971238543360L, 118995);
return false;
}
if (this.qns)
{
if (paramInt != getCount() - 1)
{
GMTrace.o(15971238543360L, 118995);
return true;
}
GMTrace.o(15971238543360L, 118995);
return false;
}
boolean bool = super.vD(paramInt);
GMTrace.o(15971238543360L, 118995);
return bool;
}
public static abstract interface a
{
public abstract void de(int paramInt1, int paramInt2);
public abstract void removeItem(int paramInt);
}
private final class b
{
public ImageView eId;
View view;
public b(View paramView)
{
GMTrace.i(15992847597568L, 119156);
this.view = paramView;
this.eId = ((ImageView)paramView.findViewById(i.f.pbc));
GMTrace.o(15992847597568L, 119156);
}
}
final class c
extends h<String, Integer, Boolean>
{
private ImageView eKZ;
private Bitmap gsp;
private String path;
public c(ImageView paramImageView, String paramString)
{
GMTrace.i(15992310726656L, 119152);
this.eKZ = paramImageView;
this.path = paramString;
GMTrace.o(15992310726656L, 119152);
}
public final com.tencent.mm.sdk.platformtools.ae biu()
{
GMTrace.i(15992444944384L, 119153);
com.tencent.mm.sdk.platformtools.ae localae = com.tencent.mm.plugin.sns.model.ae.biO();
GMTrace.o(15992444944384L, 119153);
return localae;
}
}
private final class d
{
public Object data;
public int id;
public d()
{
GMTrace.i(15991773855744L, 119148);
GMTrace.o(15991773855744L, 119148);
}
public final int hashCode()
{
GMTrace.i(15992042291200L, 119150);
int i = this.id;
GMTrace.o(15992042291200L, 119150);
return i;
}
public final String toString()
{
GMTrace.i(15991908073472L, 119149);
String str = this.data.toString();
GMTrace.o(15991908073472L, 119149);
return str;
}
}
}
/* Location: D:\tools\apktool\weixin6519android1140\jar\classes2-dex2jar.jar!\com\tencent\mm\plugin\sns\ui\previewimageview\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 8,902 | 0.634944 | 0.522921 | 345 | 24.799999 | 23.996208 | 262 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.744928 | false | false | 9 |
a7764afc37c7e3d870a76c7ac98e0a87608b02fa | 20,194,936,295,722 | 8350af19ec48687f4669475fa0403a2f340bf748 | /com.tyrfing.games.id18/src/com/tyrfing/games/id18/model/unit/Unit.java | 6aa54c3152bfe84fcbdd7e34ff6b0c85e26867ba | [
"MIT"
] | permissive | TyrfingX/TyrLib | https://github.com/TyrfingX/TyrLib | cba252f507be5f0670e4b9bac79cf0f7e8d4ddae | f08e34f8cd9cc5514ba5297b5f69c692f8832099 | refs/heads/master | 2021-06-05T10:36:23.620000 | 2017-08-27T22:24:48 | 2017-08-27T22:24:48 | 5,216,810 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tyrfing.games.id18.model.unit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.tyrfing.games.id18.model.battle.Battle;
import com.tyrfing.games.id18.model.field.Field;
import com.tyrfing.games.id18.model.field.IFieldObject;
import com.tyrfing.games.id18.model.tag.Tag;
import com.tyrfing.games.tyrlib3.model.IUUID;
import com.tyrfing.games.tyrlib3.model.game.stats.IModifiable;
import com.tyrfing.games.tyrlib3.model.game.stats.IStatHolder;
import com.tyrfing.games.tyrlib3.model.game.stats.Stat;
import com.tyrfing.games.tyrlib3.model.math.Vector2I;
import com.tyrfing.games.tyrlib3.model.resource.ISaveable;
public class Unit implements IFieldObject, IStatHolder<Integer>, IModifiable<StatModifier>, ISaveable, IUUID {
/**
*
*/
private static final long serialVersionUID = 6202604217909313414L;
private Vector2I fieldPosition;
private Vector2I fieldOrientation;
private Field deployedField;
private Faction faction;
private List<StatModifier> modifiers;
private Map<Stat, Integer> stats;
private List<Arte> artes;
private UUID uuid;
public Unit() {
fieldPosition = new Vector2I();
fieldOrientation = new Vector2I();
modifiers = new ArrayList<StatModifier>();
stats = new HashMap<Stat, Integer>();
artes = new ArrayList<Arte>();
uuid = UUID.randomUUID();
for (StatType statType : StatType.values()) {
stats.put(statType, 0);
}
}
@Override
public UUID getUUID() {
return uuid;
}
@Override
public Vector2I getFieldPosition() {
return fieldPosition;
}
public void setFieldPosition(Vector2I fieldPosition) {
this.fieldPosition = fieldPosition;
}
public Vector2I getFieldOrientation() {
return fieldOrientation;
}
public void setFieldOrientation(Vector2I fieldOrientation) {
this.fieldOrientation = fieldOrientation;
}
public void setDeployedField(Field field) {
if (this.deployedField != null) {
this.deployedField.getObjects().remove(this);
}
this.deployedField = field;
if (this.deployedField != null) {
this.deployedField.getObjects().add(this);
}
}
public Field getDeployedField() {
return deployedField;
}
public Faction getFaction() {
return faction;
}
public void setFaction(Faction faction) {
this.faction = faction;
}
public void deploy(Battle battle, Vector2I fieldPosition, Vector2I fieldOrientation) {
battle.getWaitingUnits().add(this);
setDeployedField(battle.getField());
setFieldPosition(fieldPosition);
setFieldOrientation(fieldOrientation);
}
@Override
public List<StatModifier> getModifiers() {
return modifiers;
}
public boolean hasTag(Tag tag) {
for (StatModifier modifier : modifiers) {
if (modifier.getTags().contains(tag)) {
return true;
}
}
return false;
}
@Override
public Map<Stat, Integer> getStats() {
return stats;
}
public List<Arte> getArtes() {
return artes;
}
public IUUID getAffectorByUUID(UUID uuid) {
for (Arte arte : artes) {
if (arte.getUUID().equals(uuid)) {
return arte;
}
}
return null;
}
public void startTurn() {
getStats().put(StatType.REMAINING_MOVE, getStats().get(StatType.MOVE));
getStats().put(StatType.REMAINING_ACTIONS, getStats().get(StatType.ACTIONS));
}
}
| UTF-8 | Java | 3,458 | java | Unit.java | Java | [] | null | [] | package com.tyrfing.games.id18.model.unit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.tyrfing.games.id18.model.battle.Battle;
import com.tyrfing.games.id18.model.field.Field;
import com.tyrfing.games.id18.model.field.IFieldObject;
import com.tyrfing.games.id18.model.tag.Tag;
import com.tyrfing.games.tyrlib3.model.IUUID;
import com.tyrfing.games.tyrlib3.model.game.stats.IModifiable;
import com.tyrfing.games.tyrlib3.model.game.stats.IStatHolder;
import com.tyrfing.games.tyrlib3.model.game.stats.Stat;
import com.tyrfing.games.tyrlib3.model.math.Vector2I;
import com.tyrfing.games.tyrlib3.model.resource.ISaveable;
public class Unit implements IFieldObject, IStatHolder<Integer>, IModifiable<StatModifier>, ISaveable, IUUID {
/**
*
*/
private static final long serialVersionUID = 6202604217909313414L;
private Vector2I fieldPosition;
private Vector2I fieldOrientation;
private Field deployedField;
private Faction faction;
private List<StatModifier> modifiers;
private Map<Stat, Integer> stats;
private List<Arte> artes;
private UUID uuid;
public Unit() {
fieldPosition = new Vector2I();
fieldOrientation = new Vector2I();
modifiers = new ArrayList<StatModifier>();
stats = new HashMap<Stat, Integer>();
artes = new ArrayList<Arte>();
uuid = UUID.randomUUID();
for (StatType statType : StatType.values()) {
stats.put(statType, 0);
}
}
@Override
public UUID getUUID() {
return uuid;
}
@Override
public Vector2I getFieldPosition() {
return fieldPosition;
}
public void setFieldPosition(Vector2I fieldPosition) {
this.fieldPosition = fieldPosition;
}
public Vector2I getFieldOrientation() {
return fieldOrientation;
}
public void setFieldOrientation(Vector2I fieldOrientation) {
this.fieldOrientation = fieldOrientation;
}
public void setDeployedField(Field field) {
if (this.deployedField != null) {
this.deployedField.getObjects().remove(this);
}
this.deployedField = field;
if (this.deployedField != null) {
this.deployedField.getObjects().add(this);
}
}
public Field getDeployedField() {
return deployedField;
}
public Faction getFaction() {
return faction;
}
public void setFaction(Faction faction) {
this.faction = faction;
}
public void deploy(Battle battle, Vector2I fieldPosition, Vector2I fieldOrientation) {
battle.getWaitingUnits().add(this);
setDeployedField(battle.getField());
setFieldPosition(fieldPosition);
setFieldOrientation(fieldOrientation);
}
@Override
public List<StatModifier> getModifiers() {
return modifiers;
}
public boolean hasTag(Tag tag) {
for (StatModifier modifier : modifiers) {
if (modifier.getTags().contains(tag)) {
return true;
}
}
return false;
}
@Override
public Map<Stat, Integer> getStats() {
return stats;
}
public List<Arte> getArtes() {
return artes;
}
public IUUID getAffectorByUUID(UUID uuid) {
for (Arte arte : artes) {
if (arte.getUUID().equals(uuid)) {
return arte;
}
}
return null;
}
public void startTurn() {
getStats().put(StatType.REMAINING_MOVE, getStats().get(StatType.MOVE));
getStats().put(StatType.REMAINING_ACTIONS, getStats().get(StatType.ACTIONS));
}
}
| 3,458 | 0.702429 | 0.688837 | 141 | 22.524822 | 21.783129 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.758865 | false | false | 9 |
65d60b009b80e3047b7e7cb008e638a64dcf3951 | 7,438,883,424,292 | b6e9696dd467db9ecbc0275297067787d74d273e | /LatePeriod/sound/SoundFX.java | 1b0b163f282eb445d77291f91ae5775472011b5d | [] | no_license | saba383810/JavaPractice | https://github.com/saba383810/JavaPractice | c746ab377287e78d7db6cb7b2ec8fdfec1b351a6 | 55afc90ca6a628481e33e21e5afd7831af2d6dfb | refs/heads/main | 2023-02-07T18:55:33.198000 | 2020-12-29T11:43:06 | 2020-12-29T11:43:06 | 310,215,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sound;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.awt.*;
import java.nio.file.Paths;
public class SoundFX extends Application {
PlayClip pc; //Clip 管理クラス
//--------main----------
public static void main (String[] args){
System.out.println("main");
launch();
}
//--------strat----------
public void start(Stage stage) throws Exception {
stage.setTitle("音楽を楽しもう");
stage.setWidth(500);
stage.setHeight(150);
Image playImg =new Image(Paths.get("images/play.png").toUri().toString());
Image stopImg =new Image(Paths.get("images/stop.png").toUri().toString());
Image resetImg =new Image(Paths.get("images/reset.png").toUri().toString());
Image forwardImg =new Image(Paths.get("images/forward.png").toUri().toString());
// Image playImg =new Image(getClass().getResourceAsStream("/images/play.png"));
// Image stopImg =new Image(getClass().getResourceAsStream("/images/stop.png"));
// Image resetImg =new Image(getClass().getResourceAsStream("/images/reset.png"));
// Image forwardImg =new Image(getClass().getResourceAsStream("/images/forward.png"));
Button btnPlay = new Button("", new ImageView(playImg)); //ボタン群の生成
btnPlay.setOnMouseClicked(event -> play(stage)); //ボタンにメソッド登録
Button stopBtn = new Button("",new ImageView(stopImg));
stopBtn.setOnMouseClicked(event ->stop(stage));
Button resetBtn = new Button("",new ImageView(resetImg));
resetBtn.setOnMouseClicked(event ->reset(stage));
Button forwardBtn = new Button("",new ImageView(forwardImg));
forwardBtn.setOnMouseClicked(event ->forward(stage));
FlowPane root = new FlowPane(); //横並びレイアウト
root.getChildren().addAll(btnPlay,stopBtn,resetBtn,forwardBtn); //レイアウトに載せる子ども(部品)たち
stage.setScene(new Scene(root));
stage.show();
pc = new PlayClip("bgm1.wav"); //音声情報 PlayClip 生成→準備だけて、再生はあと。
}
private void stop(Stage stage) {
pc.stop();
}
//--------strat----------
void play(Stage stage){
pc.play(); //音声スタート
}
void reset(Stage stage){
pc.reset();
}
void forward(Stage stage){
pc.forward();
}
} | UTF-8 | Java | 2,651 | java | SoundFX.java | Java | [] | null | [] | package sound;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.awt.*;
import java.nio.file.Paths;
public class SoundFX extends Application {
PlayClip pc; //Clip 管理クラス
//--------main----------
public static void main (String[] args){
System.out.println("main");
launch();
}
//--------strat----------
public void start(Stage stage) throws Exception {
stage.setTitle("音楽を楽しもう");
stage.setWidth(500);
stage.setHeight(150);
Image playImg =new Image(Paths.get("images/play.png").toUri().toString());
Image stopImg =new Image(Paths.get("images/stop.png").toUri().toString());
Image resetImg =new Image(Paths.get("images/reset.png").toUri().toString());
Image forwardImg =new Image(Paths.get("images/forward.png").toUri().toString());
// Image playImg =new Image(getClass().getResourceAsStream("/images/play.png"));
// Image stopImg =new Image(getClass().getResourceAsStream("/images/stop.png"));
// Image resetImg =new Image(getClass().getResourceAsStream("/images/reset.png"));
// Image forwardImg =new Image(getClass().getResourceAsStream("/images/forward.png"));
Button btnPlay = new Button("", new ImageView(playImg)); //ボタン群の生成
btnPlay.setOnMouseClicked(event -> play(stage)); //ボタンにメソッド登録
Button stopBtn = new Button("",new ImageView(stopImg));
stopBtn.setOnMouseClicked(event ->stop(stage));
Button resetBtn = new Button("",new ImageView(resetImg));
resetBtn.setOnMouseClicked(event ->reset(stage));
Button forwardBtn = new Button("",new ImageView(forwardImg));
forwardBtn.setOnMouseClicked(event ->forward(stage));
FlowPane root = new FlowPane(); //横並びレイアウト
root.getChildren().addAll(btnPlay,stopBtn,resetBtn,forwardBtn); //レイアウトに載せる子ども(部品)たち
stage.setScene(new Scene(root));
stage.show();
pc = new PlayClip("bgm1.wav"); //音声情報 PlayClip 生成→準備だけて、再生はあと。
}
private void stop(Stage stage) {
pc.stop();
}
//--------strat----------
void play(Stage stage){
pc.play(); //音声スタート
}
void reset(Stage stage){
pc.reset();
}
void forward(Stage stage){
pc.forward();
}
} | 2,651 | 0.642714 | 0.639904 | 65 | 37.338463 | 27.698528 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.753846 | false | false | 9 |
0a58e54c98ec5afafe48d444b253bf03b2e543f6 | 8,589,934,644,790 | 0dd8ff4c257337cbf791b0816c40f416290e8bc5 | /src/main/java/ua/com/internet_shop/service/PagesService.java | b4628d3d759a05f6f85a844b71121bf9a79945e8 | [] | no_license | Monostra/MobiStore | https://github.com/Monostra/MobiStore | 362760b5bf38413841b56f1cec2b09049fa1322f | 90fed8c5d78e43a0d99cc9e811d985964e4ee371 | refs/heads/master | 2020-05-26T00:10:00.102000 | 2017-09-19T07:54:16 | 2017-09-19T07:54:16 | 82,572,032 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.com.internet_shop.service;
import ua.com.internet_shop.entity.Pages;
import java.util.List;
public interface PagesService {
void save(Pages pages);
List<Pages> findAll();
Pages findOne(int id);
void delete(int id);
}
| UTF-8 | Java | 249 | java | PagesService.java | Java | [] | null | [] | package ua.com.internet_shop.service;
import ua.com.internet_shop.entity.Pages;
import java.util.List;
public interface PagesService {
void save(Pages pages);
List<Pages> findAll();
Pages findOne(int id);
void delete(int id);
}
| 249 | 0.706827 | 0.706827 | 14 | 16.785715 | 15.138308 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
577517cbce3f041c4f346a3b458ca25a92bb0dc2 | 2,723,009,280,352 | b95da61e79239b526289e1bfb5049a5728d32f02 | /MVC/src/es/studium/Ejercicio3/VistaEjercicio3.java | e11fa2cbf93cce68ce3257e254915a9f6e032189 | [] | no_license | chemarp99/EntornosDesarrollo | https://github.com/chemarp99/EntornosDesarrollo | a2d0c986e09704ea997f29b560fd42307822c735 | dac83149bd46b65a284d27e68aac4c52dd77dcfb | refs/heads/master | 2020-05-01T16:23:23.423000 | 2019-04-01T09:58:43 | 2019-04-01T09:58:43 | 177,570,811 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.studium.Ejercicio3;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class VistaEjercicio3 extends Frame implements WindowListener {
private static final long serialVersionUID = 1L;
Label lblEtiqueta2 = new Label("Numeros Separados por comas:");
Label lblEtiqueta3 = new Label("Máximo Común Divisor:");
Label lblEtiqueta4 = new Label("Mínimo Común Múltiplo");
Button btnCalcular = new Button("Calcular MCD y MCM");
TextField txtCampo = new TextField(15);
TextField txtCampo1 = new TextField(15);
TextField txtCampo2 = new TextField(15);
Panel pnlPanel = new Panel();
Panel pnlPanel1 = new Panel();
Panel pnlPanel2 = new Panel();
Panel pnlPanel3 = new Panel();
String t="Mcd y Mcm";
VistaEjercicio3() {
setTitle(t);
setLayout(new GridLayout(4,1));
setBounds(500,250,400,150);
pnlPanel.setLayout(new FlowLayout());
pnlPanel1.setLayout(new FlowLayout());
pnlPanel2.setLayout(new FlowLayout());
pnlPanel3.setLayout(new FlowLayout());
pnlPanel1.add(lblEtiqueta2);
pnlPanel2.add(lblEtiqueta3);
pnlPanel3.add(lblEtiqueta4);
pnlPanel3.add(txtCampo2);
pnlPanel.add(btnCalcular);
pnlPanel1.add(txtCampo);
pnlPanel2.add(txtCampo1);
add(pnlPanel1, "Center");
add(pnlPanel2, "Center");
add(pnlPanel3, "Center");
add(pnlPanel, "Center");
addWindowListener(this);
setVisible(true);
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowOpened(WindowEvent e) {
}
} | ISO-8859-1 | Java | 2,130 | java | VistaEjercicio3.java | Java | [] | null | [] | package es.studium.Ejercicio3;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class VistaEjercicio3 extends Frame implements WindowListener {
private static final long serialVersionUID = 1L;
Label lblEtiqueta2 = new Label("Numeros Separados por comas:");
Label lblEtiqueta3 = new Label("Máximo Común Divisor:");
Label lblEtiqueta4 = new Label("Mínimo Común Múltiplo");
Button btnCalcular = new Button("Calcular MCD y MCM");
TextField txtCampo = new TextField(15);
TextField txtCampo1 = new TextField(15);
TextField txtCampo2 = new TextField(15);
Panel pnlPanel = new Panel();
Panel pnlPanel1 = new Panel();
Panel pnlPanel2 = new Panel();
Panel pnlPanel3 = new Panel();
String t="Mcd y Mcm";
VistaEjercicio3() {
setTitle(t);
setLayout(new GridLayout(4,1));
setBounds(500,250,400,150);
pnlPanel.setLayout(new FlowLayout());
pnlPanel1.setLayout(new FlowLayout());
pnlPanel2.setLayout(new FlowLayout());
pnlPanel3.setLayout(new FlowLayout());
pnlPanel1.add(lblEtiqueta2);
pnlPanel2.add(lblEtiqueta3);
pnlPanel3.add(lblEtiqueta4);
pnlPanel3.add(txtCampo2);
pnlPanel.add(btnCalcular);
pnlPanel1.add(txtCampo);
pnlPanel2.add(txtCampo1);
add(pnlPanel1, "Center");
add(pnlPanel2, "Center");
add(pnlPanel3, "Center");
add(pnlPanel, "Center");
addWindowListener(this);
setVisible(true);
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowOpened(WindowEvent e) {
}
} | 2,130 | 0.696 | 0.672471 | 95 | 20.389473 | 18.203697 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.663158 | false | false | 9 |
a5658a41fbb9ea97345a5c188393fcd9838ec547 | 25,262,997,693,430 | 9c2d45ac090112a22662f4a16a72583491821b86 | /src/java/aplicacion/modelo/dominio/Carrito.java | 9b82f45ff655fe68117cf07a57735ce0880465e0 | [] | no_license | SantosKevin/Heladeria-Proyecto-Final | https://github.com/SantosKevin/Heladeria-Proyecto-Final | f0bebe8d90e2c918a9a26752b4c77ce4914e798a | 10357e84bc1f9abe9d9b7f306d191760345676d1 | refs/heads/master | 2020-05-31T04:57:24.559000 | 2019-07-03T19:39:28 | 2019-07-03T19:39:28 | 190,109,534 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aplicacion.modelo.dominio;
// Generated 26-jun-2019 23:30:49 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
/**
* Carrito generated by hbm2java
*/
public class Carrito implements java.io.Serializable {
private Integer carCodigo;
private Usuario usuario;
private double carTotal;
private Set helCars = new HashSet(0);
public Carrito() {
}
public Carrito(Usuario usuario, double carTotal) {
this.usuario = usuario;
this.carTotal = carTotal;
}
public Carrito(Integer carCodigo, Usuario usuario) {
this.carCodigo = carCodigo;
this.usuario = usuario;
}
public Carrito(Integer carCodigo, Usuario usuario, double carTotal,Set helCars) {
this.carCodigo = carCodigo;
this.usuario = usuario;
this.carTotal = carTotal;
this.helCars = helCars;
}
public Integer getCarCodigo() {
return this.carCodigo;
}
public void setCarCodigo(Integer carCodigo) {
this.carCodigo = carCodigo;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public double getCarTotal() {
return this.carTotal;
}
public void setCarTotal(double carTotal) {
this.carTotal = carTotal;
}
public Set getHelCars() {
return this.helCars;
}
public void setHelCars(Set helCars) {
this.helCars = helCars;
}
}
| UTF-8 | Java | 1,556 | java | Carrito.java | Java | [] | null | [] | package aplicacion.modelo.dominio;
// Generated 26-jun-2019 23:30:49 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
/**
* Carrito generated by hbm2java
*/
public class Carrito implements java.io.Serializable {
private Integer carCodigo;
private Usuario usuario;
private double carTotal;
private Set helCars = new HashSet(0);
public Carrito() {
}
public Carrito(Usuario usuario, double carTotal) {
this.usuario = usuario;
this.carTotal = carTotal;
}
public Carrito(Integer carCodigo, Usuario usuario) {
this.carCodigo = carCodigo;
this.usuario = usuario;
}
public Carrito(Integer carCodigo, Usuario usuario, double carTotal,Set helCars) {
this.carCodigo = carCodigo;
this.usuario = usuario;
this.carTotal = carTotal;
this.helCars = helCars;
}
public Integer getCarCodigo() {
return this.carCodigo;
}
public void setCarCodigo(Integer carCodigo) {
this.carCodigo = carCodigo;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public double getCarTotal() {
return this.carTotal;
}
public void setCarTotal(double carTotal) {
this.carTotal = carTotal;
}
public Set getHelCars() {
return this.helCars;
}
public void setHelCars(Set helCars) {
this.helCars = helCars;
}
}
| 1,556 | 0.622108 | 0.611183 | 76 | 19.460526 | 19.084604 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 9 |
062c556095666a6e872da912e25d0699d3f5fbb9 | 29,652,454,245,942 | e466663f859123176162028a86636aee19ef56dd | /app/src/main/java/com/picspacehd/picspacehd/mangazone/model/Chapter.java | de4a68f20db2fde81d8e48e3daaf9ae77d5afee8 | [] | no_license | TaiwoO/MangaReader | https://github.com/TaiwoO/MangaReader | e6272950570771bff4544159fcfdd069d54029d4 | 7922c69c9c08881ae8cb1ac8e3112a58d0ccbebc | refs/heads/master | 2021-01-19T01:13:35.247000 | 2017-08-27T19:19:14 | 2017-08-27T19:19:14 | 87,232,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.picspacehd.picspacehd.mangazone.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.picspacehd.picspacehd.mangazone.helper.AppConstants;
import java.util.List;
public class Chapter implements Parcelable {
private Long date;
private Double number;
private String id;
private String title;
public Chapter() {
}
public Chapter(Long date, Double number, String id, String title) {
this.date = date;
this.number = number;
this.id = id;
this.title = title;
}
/* Create a chapter according to the "chapters" array from the API*/
static Chapter createInstance(List<Object> list) {
Chapter chapter = new Chapter();
chapter.setDate((Double) list.get(AppConstants.CHAPTER_DATE));
chapter.setNumber((Double) list.get(AppConstants.CHAPTER_NUMBER));
chapter.setId((String) list.get(AppConstants.CHAPTER_ID));
chapter.setTitle((String) list.get(AppConstants.CHAPTER_TITLE));
return chapter;
}
public Long getDate() {
return date;
}
private void setDate(Double date) {
this.date = date.longValue();
}
public Double getNumber() {
return number;
}
private void setNumber(Double number) {
this.number = number;
}
public String getId() {
return id;
}
private void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}
public Chapter(Parcel in) {
this.date = in.readLong();
this.number = in.readDouble();
this.id = in.readString();
this.title = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(date);
parcel.writeDouble(number);
parcel.writeString(id);
parcel.writeString(title);
}
public static final Parcelable.Creator<Chapter> CREATOR = new Parcelable.Creator<Chapter>() {
@Override
public Chapter createFromParcel(Parcel parcel) {
return new Chapter(parcel);
}
@Override
public Chapter[] newArray(int i) {
return new Chapter[i];
}
};
}
| UTF-8 | Java | 2,401 | java | Chapter.java | Java | [] | null | [] | package com.picspacehd.picspacehd.mangazone.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.picspacehd.picspacehd.mangazone.helper.AppConstants;
import java.util.List;
public class Chapter implements Parcelable {
private Long date;
private Double number;
private String id;
private String title;
public Chapter() {
}
public Chapter(Long date, Double number, String id, String title) {
this.date = date;
this.number = number;
this.id = id;
this.title = title;
}
/* Create a chapter according to the "chapters" array from the API*/
static Chapter createInstance(List<Object> list) {
Chapter chapter = new Chapter();
chapter.setDate((Double) list.get(AppConstants.CHAPTER_DATE));
chapter.setNumber((Double) list.get(AppConstants.CHAPTER_NUMBER));
chapter.setId((String) list.get(AppConstants.CHAPTER_ID));
chapter.setTitle((String) list.get(AppConstants.CHAPTER_TITLE));
return chapter;
}
public Long getDate() {
return date;
}
private void setDate(Double date) {
this.date = date.longValue();
}
public Double getNumber() {
return number;
}
private void setNumber(Double number) {
this.number = number;
}
public String getId() {
return id;
}
private void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}
public Chapter(Parcel in) {
this.date = in.readLong();
this.number = in.readDouble();
this.id = in.readString();
this.title = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(date);
parcel.writeDouble(number);
parcel.writeString(id);
parcel.writeString(title);
}
public static final Parcelable.Creator<Chapter> CREATOR = new Parcelable.Creator<Chapter>() {
@Override
public Chapter createFromParcel(Parcel parcel) {
return new Chapter(parcel);
}
@Override
public Chapter[] newArray(int i) {
return new Chapter[i];
}
};
}
| 2,401 | 0.612245 | 0.611828 | 106 | 21.650944 | 21.506491 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40566 | false | false | 9 |
7abde57d35b447644949d7f515d9cfb37c57602f | 21,105,469,356,323 | 13dab835b1e7864883617a8edf8b1b4735328723 | /multi-layering-cache-aspecj/src/test/java/com/github/roger/key/impl/DefaultKeyGeneratorTest.java | a42c641348a44930c363a3f12d2bcce58dc566d9 | [] | no_license | clzj-yuyan/multi-layering-cache | https://github.com/clzj-yuyan/multi-layering-cache | 1025ccb023d96cbeed3a6bbd1d952289189e1800 | bb12b4fbece64443522f1671acc20349a683a3f8 | refs/heads/master | 2023-02-20T16:11:43.764000 | 2019-05-23T06:00:58 | 2019-05-23T06:00:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.roger.key.impl;
import org.junit.Test;
public class DefaultKeyGeneratorTest {
@Test
public void generate() {
DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator();
System.out.println(defaultKeyGenerator.generate(null,null,null));
System.out.println(defaultKeyGenerator.generate(null,null,"1"));
System.out.println(defaultKeyGenerator.generate(null,null,"1","2"));
}
} | UTF-8 | Java | 450 | java | DefaultKeyGeneratorTest.java | Java | [
{
"context": "package com.github.roger.key.impl;\n\n\nimport org.junit.Test;\n\npublic class ",
"end": 24,
"score": 0.9644951820373535,
"start": 19,
"tag": "USERNAME",
"value": "roger"
}
] | null | [] | package com.github.roger.key.impl;
import org.junit.Test;
public class DefaultKeyGeneratorTest {
@Test
public void generate() {
DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator();
System.out.println(defaultKeyGenerator.generate(null,null,null));
System.out.println(defaultKeyGenerator.generate(null,null,"1"));
System.out.println(defaultKeyGenerator.generate(null,null,"1","2"));
}
} | 450 | 0.715556 | 0.708889 | 17 | 25.529411 | 29.665028 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 9 |
a84d74ec4bbdf37f606e182745eefb558df480d4 | 25,074,019,140,557 | 079911b7afdcaad1fc9940ec5e9fe7a1050601d5 | /dao-microservice/src/main/java/by/senla/daomicroservice/controller/ExceptionHandlerController.java | df1c2d31894d8a3199424154b2c12fdf91bacad0 | [] | no_license | Kirill128/Shop | https://github.com/Kirill128/Shop | 4b6971a8e71916d2780ea0883b9e32f9e39500be | 5c74a4911384217322706c45b4b2c9ede40c0956 | refs/heads/master | 2023-07-18T05:21:19.986000 | 2021-06-25T12:23:33 | 2021-06-25T12:23:33 | 342,789,849 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.senla.daomicroservice.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestController
@RequestMapping
@RestControllerAdvice
@Slf4j
public class ExceptionHandlerController {
@ExceptionHandler(Exception.class)
public String catchException(Exception e){
log.error("Exception: "+e.getClass()+". "+e.getLocalizedMessage());
return "ERROR, CHECK DAO MICROSERVICE ";
}
}
| UTF-8 | Java | 664 | java | ExceptionHandlerController.java | Java | [] | null | [] | package by.senla.daomicroservice.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestController
@RequestMapping
@RestControllerAdvice
@Slf4j
public class ExceptionHandlerController {
@ExceptionHandler(Exception.class)
public String catchException(Exception e){
log.error("Exception: "+e.getClass()+". "+e.getLocalizedMessage());
return "ERROR, CHECK DAO MICROSERVICE ";
}
}
| 664 | 0.795181 | 0.790663 | 20 | 32.200001 | 25.317188 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 9 |
3cce20fa2dc39de90107da11c124bc2016fb3352 | 26,903,675,177,056 | 7cc867463d0a494c43929e14587eea3a4671ce4c | /cell.java | a413e2ce2645349aaea1a9e953b17a0e3efac13a | [] | no_license | orizait/dynamic-jdbc | https://github.com/orizait/dynamic-jdbc | c3883ff7cf8bc04a1929dbe48ed9c02c770c1a33 | 9bf80f53866987148b43a2eb0f8a8597e0bb0a0b | refs/heads/master | 2020-11-30T00:42:48.466000 | 2020-05-11T13:41:00 | 2020-05-11T13:41:00 | 230,253,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class cell
{
private int type;
private Object val;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Object getVal() {
return val;
}
public void setVal(Object val) {
this.val = val;
}
public cell(int type, Object val)
{
this.type = type;
this.val = val;
}
}
| UTF-8 | Java | 447 | java | cell.java | Java | [] | null | [] | public class cell
{
private int type;
private Object val;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Object getVal() {
return val;
}
public void setVal(Object val) {
this.val = val;
}
public cell(int type, Object val)
{
this.type = type;
this.val = val;
}
}
| 447 | 0.485459 | 0.485459 | 27 | 14.481482 | 12.494059 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
75d73821a8517224a63fae54719382bf567d7626 | 32,641,751,516,798 | 8bcf0a127941164dc66144a2f0b59b8b4435e8ae | /Robotica 2 NXT/src/standard/Yay.java | 866d3a44924ef936753284dc151e46b01db84777 | [] | no_license | GSamuel/Robotica-2-2013 | https://github.com/GSamuel/Robotica-2-2013 | cf94f68abcf32b18227835bf1f7639b24a5812f2 | edcf040662ef0affddc7b1c6b6c4a93a8193f69c | refs/heads/master | 2021-01-10T20:48:06.657000 | 2014-01-17T11:42:38 | 2014-01-17T11:42:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package standard;
import lejos.nxt.Button;
import lejos.nxt.MotorPort;
import lejos.nxt.NXTRegulatedMotor;
public class Yay
{
public static void main(String[] args)
{
final int SPEED = 1000;// 750
new StopProgram().start();
NXTRegulatedMotor mA = new NXTRegulatedMotor(MotorPort.A);
NXTRegulatedMotor mC = new NXTRegulatedMotor(MotorPort.C);
while (true)
{
Button.waitForAnyPress();
// TESTETSTETSETSET
mA.setSpeed(SPEED);
mA.forward();
mC.setSpeed(SPEED);
mC.forward();
Button.waitForAnyPress();
mA.suspendRegulation();
mC.suspendRegulation();
}
}
}
| UTF-8 | Java | 602 | java | Yay.java | Java | [] | null | [] | package standard;
import lejos.nxt.Button;
import lejos.nxt.MotorPort;
import lejos.nxt.NXTRegulatedMotor;
public class Yay
{
public static void main(String[] args)
{
final int SPEED = 1000;// 750
new StopProgram().start();
NXTRegulatedMotor mA = new NXTRegulatedMotor(MotorPort.A);
NXTRegulatedMotor mC = new NXTRegulatedMotor(MotorPort.C);
while (true)
{
Button.waitForAnyPress();
// TESTETSTETSETSET
mA.setSpeed(SPEED);
mA.forward();
mC.setSpeed(SPEED);
mC.forward();
Button.waitForAnyPress();
mA.suspendRegulation();
mC.suspendRegulation();
}
}
}
| 602 | 0.702658 | 0.69103 | 33 | 17.242424 | 16.365208 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.818182 | false | false | 9 |
deaecf1b53f824109d951f44355dd7ceccdf511e | 11,338,713,670,397 | ad70b98d784ea695c909e2643d0215784fb63e46 | /IBSVO/src/com/shrinfo/ibs/vo/business/CompanyVO.java | b1295351403420304aec8f7744069c80275c8695 | [] | no_license | m1012290/IBSRepo | https://github.com/m1012290/IBSRepo | 6266a8965afdb1921430dda0d2faef8814a82b4e | a071d94195802817979451ec5d6dd86c497aced0 | refs/heads/master | 2020-06-04T23:05:05.414000 | 2014-11-04T06:58:33 | 2014-11-04T06:58:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shrinfo.ibs.vo.business;
import com.shrinfo.ibs.cmn.vo.BaseVO;
/**
* @author Sunil Kumar - This class represents Company entity in the application. Company can
* further be broking company, insurance company. Hence this class will act as base abstract
* for basic company details.
*/
public abstract class CompanyVO extends BaseVO {
private static final long serialVersionUID = 8674776028827953900L;
private String code;
private String name;
private String shortName;
private ContactVO contactAndAddrDetails = new ContactVO();
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the shortName
*/
public String getShortName() {
return shortName;
}
/**
* @param shortName the shortName to set
*/
public void setShortName(String shortName) {
this.shortName = shortName;
}
public ContactVO getContactAndAddrDetails() {
return contactAndAddrDetails;
}
public void setContactAndAddrDetails(ContactVO contactAndAddrDetails) {
this.contactAndAddrDetails = contactAndAddrDetails;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CompanyVO other = (CompanyVO) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
return true;
}
}
| UTF-8 | Java | 2,164 | java | CompanyVO.java | Java | [
{
"context": " com.shrinfo.ibs.cmn.vo.BaseVO;\r\n\r\n/**\r\n * @author Sunil Kumar - This class represents Company entity in the app",
"end": 108,
"score": 0.9997826814651489,
"start": 97,
"tag": "NAME",
"value": "Sunil Kumar"
}
] | null | [] | package com.shrinfo.ibs.vo.business;
import com.shrinfo.ibs.cmn.vo.BaseVO;
/**
* @author <NAME> - This class represents Company entity in the application. Company can
* further be broking company, insurance company. Hence this class will act as base abstract
* for basic company details.
*/
public abstract class CompanyVO extends BaseVO {
private static final long serialVersionUID = 8674776028827953900L;
private String code;
private String name;
private String shortName;
private ContactVO contactAndAddrDetails = new ContactVO();
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the shortName
*/
public String getShortName() {
return shortName;
}
/**
* @param shortName the shortName to set
*/
public void setShortName(String shortName) {
this.shortName = shortName;
}
public ContactVO getContactAndAddrDetails() {
return contactAndAddrDetails;
}
public void setContactAndAddrDetails(ContactVO contactAndAddrDetails) {
this.contactAndAddrDetails = contactAndAddrDetails;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CompanyVO other = (CompanyVO) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
return true;
}
}
| 2,159 | 0.589649 | 0.57902 | 98 | 20.081633 | 20.899504 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755102 | false | false | 9 |
42f537edd3ee0e68093bfe806ed73f09e06d4fe1 | 33,500,744,976,811 | e615101180a1d3e78cbd1d66162ec42b8999bb9c | /m-cube/src/main/java/net/mcube/extensions/songs/comparators/TrackNumberSongComparatorTest.java | b7d8262d710354678eb6a5c375ec35ae6f428d04 | [] | no_license | espre05/test-projects | https://github.com/espre05/test-projects | 7522a76d41e6e6a822d2475e8246aab1730f2e46 | 26120053987e7570f0697a7e80b395edc0899475 | refs/heads/master | 2021-01-18T21:29:49.198000 | 2016-04-26T20:26:55 | 2016-04-26T20:26:55 | 31,580,648 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (C) 2003-2008 Daniele Dellafiore <daniele.dellafiore@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* Created on 24-lug-2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package net.mcube.extensions.songs.comparators;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
import net.mcube.extensions.songs.DefaultSong;
import net.mcube.extensions.songs.SongAttributes;
/**
* @author Daniele
*
*/
public class TrackNumberSongComparatorTest extends TestCase {
public void testSongs() {
TrackNumberSongComparator c = new TrackNumberSongComparator();
DefaultSong song1 = new DefaultSong();
song1.put(SongAttributes.TRACK_NUMBER, "4");
DefaultSong song2 = new DefaultSong();
song2.put(SongAttributes.TRACK_NUMBER, "3");
List list = new LinkedList();
list.add(song2);
list.add(song1);
List sortedList = new LinkedList();
sortedList.add(song1);
sortedList.add(song2);
assertNotSame(sortedList, list);
Collections.sort(list, c);
assertNotSame(sortedList, list);
song2.put(SongAttributes.TRACK_NUMBER, "11");
Collections.sort(list, c);
assertEquals(sortedList, list);
}
} | UTF-8 | Java | 2,094 | java | TrackNumberSongComparatorTest.java | Java | [
{
"context": "/**\n * Copyright (C) 2003-2008 Daniele Dellafiore <daniele.dellafiore@gmail.com>\n * \n * This progra",
"end": 49,
"score": 0.9998976588249207,
"start": 31,
"tag": "NAME",
"value": "Daniele Dellafiore"
},
{
"context": "**\n * Copyright (C) 2003-2008 Daniele Dellafiore <daniele.dellafiore@gmail.com>\n * \n * This program is free software; you can re",
"end": 79,
"score": 0.9999328851699829,
"start": 51,
"tag": "EMAIL",
"value": "daniele.dellafiore@gmail.com"
},
{
"context": "xtensions.songs.SongAttributes;\r\n\r\n/**\r\n * @author Daniele\r\n * \r\n */\r\npublic class TrackNumberSongComparator",
"end": 1274,
"score": 0.9996793866157532,
"start": 1267,
"tag": "NAME",
"value": "Daniele"
}
] | null | [] | /**
* Copyright (C) 2003-2008 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* Created on 24-lug-2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package net.mcube.extensions.songs.comparators;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
import net.mcube.extensions.songs.DefaultSong;
import net.mcube.extensions.songs.SongAttributes;
/**
* @author Daniele
*
*/
public class TrackNumberSongComparatorTest extends TestCase {
public void testSongs() {
TrackNumberSongComparator c = new TrackNumberSongComparator();
DefaultSong song1 = new DefaultSong();
song1.put(SongAttributes.TRACK_NUMBER, "4");
DefaultSong song2 = new DefaultSong();
song2.put(SongAttributes.TRACK_NUMBER, "3");
List list = new LinkedList();
list.add(song2);
list.add(song1);
List sortedList = new LinkedList();
sortedList.add(song1);
sortedList.add(song2);
assertNotSame(sortedList, list);
Collections.sort(list, c);
assertNotSame(sortedList, list);
song2.put(SongAttributes.TRACK_NUMBER, "11");
Collections.sort(list, c);
assertEquals(sortedList, list);
}
} | 2,061 | 0.699618 | 0.680993 | 66 | 30.030304 | 25.423664 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false | 9 |
ac9a404ac26b8f020f2959bbb81a33854818da6e | 23,751,169,211,476 | 4ec74c12c875cb3d8407e82a74b00176adf09799 | /spider-engine/src/main/java/com/gesangwu/spider/engine/kshape/task/SkyBigVolumeTask.java | f582d908372eaed5d0253cb89c13f48a19c99e13 | [] | no_license | vickzhu/stock | https://github.com/vickzhu/stock | 1b5282f08f311381047470931076e4807783ac8d | d79134ea95fb29ec5585a6ee432af3f9a457a594 | refs/heads/master | 2021-01-09T20:57:59.440000 | 2020-10-22T13:07:16 | 2020-10-22T13:07:16 | 61,874,853 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gesangwu.spider.engine.kshape.task;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import com.gesangwu.spider.biz.common.ShapeEnum;
import com.gesangwu.spider.biz.dao.model.KLine;
import com.gesangwu.spider.biz.dao.model.KLineExample;
@Component
public class SkyBigVolumeTask extends ShapeTask {
public void execute(){
KLineExample example = new KLineExample();
KLineExample.Criteria criteria = example.createCriteria();
criteria.andTradeDateGreaterThanOrEqualTo("2017-09-01");
criteria.andPercentGreaterThan(9.9);
criteria.andMa20IsNotNull();
List<KLine> klList = klService.selectByExample(example);
List<Long> idList = new ArrayList<Long>();
for (KLine kl : klList) {
Long id = getId(kl);
if(id == null){
continue;
}
idList.add(id);
}
klService.updateShape(ShapeEnum.SKY_BIG_VOLUME, idList);
}
private Long getId(KLine kl){
KLine kLine = getNextK(kl.getSymbol(), kl.getTradeDate());
if(kLine == null){
return null;
}
if(kl.getHigh() > kLine.getLow()){
return null;
}
if(kl.getVolume()*3 < kLine.getVolume()){
return kLine.getId();
}
return null;
}
private KLine getNextK(String symbol, String tradeDate){
KLineExample example = new KLineExample();
example.setOffset(0);
example.setRows(1);
example.setOrderByClause("trade_date");
KLineExample.Criteria criteria = example.createCriteria();
criteria.andSymbolEqualTo(symbol);
criteria.andTradeDateGreaterThan(tradeDate);
List<KLine> klList = klService.selectByExample(example);
return CollectionUtils.isEmpty(klList) ? null : klList.get(0);
}
public void execute(String tradeDate){
KLineExample example = new KLineExample();
KLineExample.Criteria criteria = example.createCriteria();
criteria.andTradeDateEqualTo(tradeDate);
criteria.andPercentGreaterThan(9.9);
criteria.andMa20IsNotNull();
List<KLine> klList = klService.selectByExample(example);
List<Long> idList = new ArrayList<Long>();
for (KLine kl : klList) {
Long id = getId(kl);
if(id == null){
continue;
}
idList.add(id);
}
klService.updateShape(ShapeEnum.SKY_BIG_VOLUME, idList);
}
}
| UTF-8 | Java | 2,326 | java | SkyBigVolumeTask.java | Java | [] | null | [] | package com.gesangwu.spider.engine.kshape.task;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import com.gesangwu.spider.biz.common.ShapeEnum;
import com.gesangwu.spider.biz.dao.model.KLine;
import com.gesangwu.spider.biz.dao.model.KLineExample;
@Component
public class SkyBigVolumeTask extends ShapeTask {
public void execute(){
KLineExample example = new KLineExample();
KLineExample.Criteria criteria = example.createCriteria();
criteria.andTradeDateGreaterThanOrEqualTo("2017-09-01");
criteria.andPercentGreaterThan(9.9);
criteria.andMa20IsNotNull();
List<KLine> klList = klService.selectByExample(example);
List<Long> idList = new ArrayList<Long>();
for (KLine kl : klList) {
Long id = getId(kl);
if(id == null){
continue;
}
idList.add(id);
}
klService.updateShape(ShapeEnum.SKY_BIG_VOLUME, idList);
}
private Long getId(KLine kl){
KLine kLine = getNextK(kl.getSymbol(), kl.getTradeDate());
if(kLine == null){
return null;
}
if(kl.getHigh() > kLine.getLow()){
return null;
}
if(kl.getVolume()*3 < kLine.getVolume()){
return kLine.getId();
}
return null;
}
private KLine getNextK(String symbol, String tradeDate){
KLineExample example = new KLineExample();
example.setOffset(0);
example.setRows(1);
example.setOrderByClause("trade_date");
KLineExample.Criteria criteria = example.createCriteria();
criteria.andSymbolEqualTo(symbol);
criteria.andTradeDateGreaterThan(tradeDate);
List<KLine> klList = klService.selectByExample(example);
return CollectionUtils.isEmpty(klList) ? null : klList.get(0);
}
public void execute(String tradeDate){
KLineExample example = new KLineExample();
KLineExample.Criteria criteria = example.createCriteria();
criteria.andTradeDateEqualTo(tradeDate);
criteria.andPercentGreaterThan(9.9);
criteria.andMa20IsNotNull();
List<KLine> klList = klService.selectByExample(example);
List<Long> idList = new ArrayList<Long>();
for (KLine kl : klList) {
Long id = getId(kl);
if(id == null){
continue;
}
idList.add(id);
}
klService.updateShape(ShapeEnum.SKY_BIG_VOLUME, idList);
}
}
| 2,326 | 0.708512 | 0.699914 | 77 | 28.207792 | 20.824772 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.25974 | false | false | 9 |
896b7967edf68b7d52918803a0a9a14b1ac63a96 | 9,337,258,950,636 | 3eceaec8261ba4528e39fcb997235b31a15dcdaf | /JavaProject/src/com/etc/ser/LendandreturnSer.java | 884f0524d208b4924809edbb6d1fed45ef402129 | [] | no_license | hqxczjx/git | https://github.com/hqxczjx/git | 25bccbd19fac11c1bcd4db373f33bac5fee7028a | b601b70fdb46c70b9a0f403e865fa0070470ee04 | refs/heads/master | 2021-01-21T17:38:47.828000 | 2018-02-24T10:03:16 | 2018-02-24T10:03:16 | 91,976,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.etc.ser;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.etc.biz.BookInfoBiz;
import com.etc.biz.MsgInfoBiz;
import com.etc.biz.RecordInfoBiz;
import com.etc.biz.UserInfoBiz;
import com.etc.entity.BookInfo;
import com.etc.entity.MsgInfo;
import com.etc.entity.PageUtil;
import com.etc.entity.RecordInfo;
import com.etc.entity.UserInfo;
@WebServlet("/admin/LendandreturnSer")
public class LendandreturnSer extends HttpServlet {
/**
* Constructor of the object.
*/
public LendandreturnSer() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 功能续借 还书
RecordInfoBiz biz = new RecordInfoBiz();
if (request.getParameter("action") != null) {
int id = Integer.parseInt(request.getParameter("id"));
if (request.getParameter("action").equals("toreturn")) {// 还书
java.sql.Date date = new java.sql.Date(
new java.util.Date().getTime());
RecordInfo record = new RecordInfo(id, date);
biz.recordReturn(record);
} else if (request.getParameter("action").equals("renew")) {// 续借
biz.recordXuReturn(id);
}
response.sendRedirect("./LendandreturnSer");
return;
}
if (request.getParameter("findid") != null) {
int findid = Integer.parseInt(request.getParameter("findid"));
RecordInfoBiz biz2 = new RecordInfoBiz();
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFindById(findid, index, 8);
request.setAttribute("pageUtil", p);
request.setAttribute("findid", findid);
request.getRequestDispatcher("./larfinduser.jsp").forward(request,
response);
return;
}
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFind(index, 8);
request.setAttribute("pageUtil", p);
request.getRequestDispatcher("./lendandreturn.jsp").forward(request,
response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("searchwhat") == null
|| request.getParameter("searchwhat") == "") {
response.sendRedirect("LendandreturnSer");
return;
}
// 通过radio判断是什么搜索 用户 书本
List<BookInfo> book = null;
String searchType = request.getParameter("searchType");
String searchwhat = request.getParameter("searchwhat");
if (searchType.equals("user")) {
RecordInfoBiz biz = new RecordInfoBiz();
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFindById(
Integer.parseInt(searchwhat), index, 8);
request.setAttribute("pageUtil", p);
request.setAttribute("findid", Integer.parseInt(searchwhat));
request.getRequestDispatcher("./larfinduser.jsp").forward(request,
response);
} else if (searchType.equals("book")) {
BookInfo books = null;
books = new BookInfoBiz().findBybookIdenAll(searchwhat);
if(books == null){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("找不到这本书,三秒钟后跳转至借书页面");
response.setHeader("refresh","3;LendandreturnSer");
return;
}
request.setAttribute("book", books);
request.getRequestDispatcher("/admin/details.jsp").forward(request,
response);
}
}
public void init() throws ServletException {
// Put your code here
}
}
| UTF-8 | Java | 4,255 | java | LendandreturnSer.java | Java | [] | null | [] | package com.etc.ser;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.etc.biz.BookInfoBiz;
import com.etc.biz.MsgInfoBiz;
import com.etc.biz.RecordInfoBiz;
import com.etc.biz.UserInfoBiz;
import com.etc.entity.BookInfo;
import com.etc.entity.MsgInfo;
import com.etc.entity.PageUtil;
import com.etc.entity.RecordInfo;
import com.etc.entity.UserInfo;
@WebServlet("/admin/LendandreturnSer")
public class LendandreturnSer extends HttpServlet {
/**
* Constructor of the object.
*/
public LendandreturnSer() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 功能续借 还书
RecordInfoBiz biz = new RecordInfoBiz();
if (request.getParameter("action") != null) {
int id = Integer.parseInt(request.getParameter("id"));
if (request.getParameter("action").equals("toreturn")) {// 还书
java.sql.Date date = new java.sql.Date(
new java.util.Date().getTime());
RecordInfo record = new RecordInfo(id, date);
biz.recordReturn(record);
} else if (request.getParameter("action").equals("renew")) {// 续借
biz.recordXuReturn(id);
}
response.sendRedirect("./LendandreturnSer");
return;
}
if (request.getParameter("findid") != null) {
int findid = Integer.parseInt(request.getParameter("findid"));
RecordInfoBiz biz2 = new RecordInfoBiz();
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFindById(findid, index, 8);
request.setAttribute("pageUtil", p);
request.setAttribute("findid", findid);
request.getRequestDispatcher("./larfinduser.jsp").forward(request,
response);
return;
}
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFind(index, 8);
request.setAttribute("pageUtil", p);
request.getRequestDispatcher("./lendandreturn.jsp").forward(request,
response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("searchwhat") == null
|| request.getParameter("searchwhat") == "") {
response.sendRedirect("LendandreturnSer");
return;
}
// 通过radio判断是什么搜索 用户 书本
List<BookInfo> book = null;
String searchType = request.getParameter("searchType");
String searchwhat = request.getParameter("searchwhat");
if (searchType.equals("user")) {
RecordInfoBiz biz = new RecordInfoBiz();
int index = 1;
if (request.getParameter("index") != null) {
index = Integer.parseInt(request.getParameter("index"));
}
PageUtil<RecordInfo> p = biz.pageFindById(
Integer.parseInt(searchwhat), index, 8);
request.setAttribute("pageUtil", p);
request.setAttribute("findid", Integer.parseInt(searchwhat));
request.getRequestDispatcher("./larfinduser.jsp").forward(request,
response);
} else if (searchType.equals("book")) {
BookInfo books = null;
books = new BookInfoBiz().findBybookIdenAll(searchwhat);
if(books == null){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("找不到这本书,三秒钟后跳转至借书页面");
response.setHeader("refresh","3;LendandreturnSer");
return;
}
request.setAttribute("book", books);
request.getRequestDispatcher("/admin/details.jsp").forward(request,
response);
}
}
public void init() throws ServletException {
// Put your code here
}
}
| 4,255 | 0.704529 | 0.702133 | 156 | 25.75 | 22.71722 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.282051 | false | false | 9 |
9e202cbba767bb6e0e2ed0c36d47a3e50242d266 | 24,361,054,505,393 | 6949513cef64ee93cf3d809f7a413d28460fed26 | /src/files/ListFile.java | 38c0cf42b562447194ba2850ec4c98d8f18af7a1 | [] | no_license | alyaazab/SICXEAssembler-TextEditor | https://github.com/alyaazab/SICXEAssembler-TextEditor | 979383b0377b355e097ae30624fbf825c3350ac3 | 3a0c40951f015486c559b911677ad51961142cc3 | refs/heads/master | 2022-01-14T14:05:02.924000 | 2019-05-18T16:21:01 | 2019-05-18T16:21:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package files;
import mainpackage.Line;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class ListFile {
private ArrayList<Line> lineArrayList;
public ListFile(ArrayList<Line> lineArrayList) {
this.lineArrayList = lineArrayList;
}
public void writeToListFile(){
try {
FileWriter fileWriter = new FileWriter("copyfile", true);
fileWriter.append("\n\n\n---------------Pass 2---------------\n\n");
for (Line line : lineArrayList){
fileWriter.write(line + "\n");
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 723 | java | ListFile.java | Java | [] | null | [] | package files;
import mainpackage.Line;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class ListFile {
private ArrayList<Line> lineArrayList;
public ListFile(ArrayList<Line> lineArrayList) {
this.lineArrayList = lineArrayList;
}
public void writeToListFile(){
try {
FileWriter fileWriter = new FileWriter("copyfile", true);
fileWriter.append("\n\n\n---------------Pass 2---------------\n\n");
for (Line line : lineArrayList){
fileWriter.write(line + "\n");
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 723 | 0.572614 | 0.571231 | 30 | 23.1 | 21.335964 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433333 | false | false | 9 |
1509195177612b6eb141e010e52b175fba4e937c | 15,118,284,933,470 | 4141cc60c7e7ed849564810ad5fe87f19814431a | /src/main/java/com/xmu/www/mymall/controller/AdminCartItemController.java | a4a8220ebc997d1875c5f6e9255194c26d2d1b43 | [] | no_license | oneplaidmonster/mymall | https://github.com/oneplaidmonster/mymall | 8afe76eb707a1324ed5bba453d3ed396237cbde8 | 066e61968fdf727ace68ac0773065b6dcfa0ea45 | refs/heads/master | 2022-11-13T14:10:10.162000 | 2020-07-15T03:18:17 | 2020-07-15T03:18:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xmu.www.mymall.controller;
import com.xmu.www.mymall.domain.CartItem;
import com.xmu.www.mymall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
public class AdminCartItemController {
@Autowired
CartService cartItemService;
@RequestMapping("showcartitems")
public String showCartItem(Model model){
List<CartItem> list = cartItemService.findAll();
model.addAttribute("list", list);
return "cartItem";
}
@RequestMapping("showcartitem")
public CartItem showCartItem(int cid){
return cartItemService.findByCid(cid);
}
@RequestMapping("addcartitem")
public String addCartItem(CartItem cartItem){
cartItemService.doAdd(cartItem);
return "redirect:showcartitem";
}
@RequestMapping("removecartitem")
public String removeCartItem(int cid){
cartItemService.doRemove(cid);
return "forward:showcartitem.do";
}
}
| UTF-8 | Java | 1,100 | java | AdminCartItemController.java | Java | [] | null | [] | package com.xmu.www.mymall.controller;
import com.xmu.www.mymall.domain.CartItem;
import com.xmu.www.mymall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
public class AdminCartItemController {
@Autowired
CartService cartItemService;
@RequestMapping("showcartitems")
public String showCartItem(Model model){
List<CartItem> list = cartItemService.findAll();
model.addAttribute("list", list);
return "cartItem";
}
@RequestMapping("showcartitem")
public CartItem showCartItem(int cid){
return cartItemService.findByCid(cid);
}
@RequestMapping("addcartitem")
public String addCartItem(CartItem cartItem){
cartItemService.doAdd(cartItem);
return "redirect:showcartitem";
}
@RequestMapping("removecartitem")
public String removeCartItem(int cid){
cartItemService.doRemove(cid);
return "forward:showcartitem.do";
}
}
| 1,100 | 0.721818 | 0.721818 | 41 | 25.829268 | 20.344475 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414634 | false | false | 9 |
85e2f752d2e18adfb5a8cab27e67dfc31c46d6e0 | 16,827,681,919,560 | 1410c3c798c115720e8a561173bd649a2a479ff6 | /src/Views/ShowComplaintsController.java | adacc474920e93742f015bfc00442d0199e3461e | [] | no_license | hilakhadad/EmerAgencyGUI | https://github.com/hilakhadad/EmerAgencyGUI | faaecb17bb3a6fd986f07154daf42dd3b51c1bce | cecb610552490c8f29f5f7996186e5bb98a5adc0 | refs/heads/master | 2020-06-02T10:25:58.459000 | 2019-06-16T18:36:44 | 2019-06-16T18:36:44 | 191,126,583 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Views;
import Controller.Controller;
import Objects.Complaint;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class ShowComplaintsController {
public TableView<Complaint> tv_ComplaintsTableView;
public TableColumn<Complaint,String> tc_defendant,tc_complainant,tc_description,tc_status;
void showResults(ObservableList<Complaint> searchResults) {
if (searchResults != null && searchResults.size()>0) {
tc_status.setCellValueFactory(cellData -> cellData.getValue().getSP_statusProperty());
tc_defendant.setCellValueFactory(cellData -> cellData.getValue().getSP_defendantProperty());
tc_complainant.setCellValueFactory(cellData -> cellData.getValue().getSP_complainantProperty());
tc_description.setCellValueFactory(cellData -> cellData.getValue().getSP_complaintDescription());
this.tv_ComplaintsTableView.setItems(searchResults);
}
}
}
| UTF-8 | Java | 1,022 | java | ShowComplaintsController.java | Java | [] | null | [] | package Views;
import Controller.Controller;
import Objects.Complaint;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class ShowComplaintsController {
public TableView<Complaint> tv_ComplaintsTableView;
public TableColumn<Complaint,String> tc_defendant,tc_complainant,tc_description,tc_status;
void showResults(ObservableList<Complaint> searchResults) {
if (searchResults != null && searchResults.size()>0) {
tc_status.setCellValueFactory(cellData -> cellData.getValue().getSP_statusProperty());
tc_defendant.setCellValueFactory(cellData -> cellData.getValue().getSP_defendantProperty());
tc_complainant.setCellValueFactory(cellData -> cellData.getValue().getSP_complainantProperty());
tc_description.setCellValueFactory(cellData -> cellData.getValue().getSP_complaintDescription());
this.tv_ComplaintsTableView.setItems(searchResults);
}
}
}
| 1,022 | 0.746575 | 0.745597 | 24 | 41.583332 | 37.776665 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false | 9 |
33d8a12f7c314d5fe0544cb5cbc73e6b85734caa | 10,591,389,376,415 | 7b3c8d607abab1d01587550f330ce50511c12480 | /src/main/java/com/monkey/apiManagement/repositories/OperatorInfoRepository.java | 05156f9194cfc320283735c47ab9af9cd4589385 | [] | no_license | mwkim0919/api_db_ui | https://github.com/mwkim0919/api_db_ui | be50adf0c2c42ee25bd6818d9fa1cd1ae80a796d | e9e8797b2522420df3e283d5f3d6191c5d691e36 | refs/heads/master | 2020-03-17T13:16:00.982000 | 2019-02-23T09:58:17 | 2019-02-23T09:58:17 | 133,624,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.monkey.apiManagement.repositories;
import com.monkey.apiManagement.domains.OperatorInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OperatorInfoRepository extends JpaRepository<OperatorInfo, Integer>,
JpaSpecificationExecutor<OperatorInfo> {
List<OperatorInfo> findAllByOrderByDsnName();
}
| UTF-8 | Java | 512 | java | OperatorInfoRepository.java | Java | [] | null | [] | package com.monkey.apiManagement.repositories;
import com.monkey.apiManagement.domains.OperatorInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OperatorInfoRepository extends JpaRepository<OperatorInfo, Integer>,
JpaSpecificationExecutor<OperatorInfo> {
List<OperatorInfo> findAllByOrderByDsnName();
}
| 512 | 0.839844 | 0.839844 | 15 | 33.133335 | 28.635332 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
92960ce5e405e4440fa3eec9f8ed99e8ae749721 | 31,250,182,081,553 | 25addefe28c7a91a1a7123217cfc56c507e2a03e | /src/gazitfbm/proje/vt/VeriTabaniErisim.java | 23806be1f0a42c0dd25d43d19df9dd4bfcd1ad15 | [] | no_license | specy-programmer/Hastane-Otomasyon-Sistemi | https://github.com/specy-programmer/Hastane-Otomasyon-Sistemi | e14cf46775c97d33ed1084cc5333c078852a4de5 | 75cb5b7465ae590567ee6d44f84a9278618f5e42 | refs/heads/master | 2023-02-23T20:34:29.695000 | 2019-12-19T17:51:54 | 2019-12-19T17:51:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gazitfbm.proje.vt;
import gazitfbm.proje.vt.IVeriTabaniErisim;
import javax.swing.*;
import java.sql.*;
public class VeriTabaniErisim implements IVeriTabaniErisim {
static Connection myConn;
@Override
public void baglantiKurulumu() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
myConn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hastane?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey","root","root");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public void veriEkle(String sql_sorguEkle) {
baglantiKurulumu();
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguEkle);
posted.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Bilgileri Hatalı Girdiniz");
System.out.println(e); }
finally {
System.out.println("Veri ekleme başarılı.");
}
}
@Override
public void veriSil(String sql_sorguSilme) {
baglantiKurulumu();
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguSilme);
posted.executeUpdate();
} catch (Exception e) {
System.out.println(e); }
finally {
System.out.println("Veri silme başarılı.");
}
}
@Override
public ResultSet girisSorgula(String sqlGirisi_sorgu){
baglantiKurulumu();
ResultSet myRs = null;
try{
PreparedStatement posted = myConn.prepareStatement(sqlGirisi_sorgu);
myRs = posted.executeQuery();
} catch (SQLException e){
e.printStackTrace();
}
return myRs;
}
@Override
public void veriGuncelle(String sql_sorguGuncelle) {
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguGuncelle);
posted.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
finally {
System.out.println("Veri güncelleme başarılı.");
}
}
public ResultSet veriListeleme(){
baglantiKurulumu();
ResultSet myRs = null;
try {
PreparedStatement posted = myConn.prepareStatement("SELECT * FROM hastalar");
myRs = posted.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return myRs ;
}
} | UTF-8 | Java | 2,578 | java | VeriTabaniErisim.java | Java | [] | null | [] | package gazitfbm.proje.vt;
import gazitfbm.proje.vt.IVeriTabaniErisim;
import javax.swing.*;
import java.sql.*;
public class VeriTabaniErisim implements IVeriTabaniErisim {
static Connection myConn;
@Override
public void baglantiKurulumu() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
myConn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hastane?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey","root","root");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public void veriEkle(String sql_sorguEkle) {
baglantiKurulumu();
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguEkle);
posted.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Bilgileri Hatalı Girdiniz");
System.out.println(e); }
finally {
System.out.println("Veri ekleme başarılı.");
}
}
@Override
public void veriSil(String sql_sorguSilme) {
baglantiKurulumu();
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguSilme);
posted.executeUpdate();
} catch (Exception e) {
System.out.println(e); }
finally {
System.out.println("Veri silme başarılı.");
}
}
@Override
public ResultSet girisSorgula(String sqlGirisi_sorgu){
baglantiKurulumu();
ResultSet myRs = null;
try{
PreparedStatement posted = myConn.prepareStatement(sqlGirisi_sorgu);
myRs = posted.executeQuery();
} catch (SQLException e){
e.printStackTrace();
}
return myRs;
}
@Override
public void veriGuncelle(String sql_sorguGuncelle) {
try {
PreparedStatement posted = myConn.prepareStatement(sql_sorguGuncelle);
posted.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
finally {
System.out.println("Veri güncelleme başarılı.");
}
}
public ResultSet veriListeleme(){
baglantiKurulumu();
ResultSet myRs = null;
try {
PreparedStatement posted = myConn.prepareStatement("SELECT * FROM hastalar");
myRs = posted.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return myRs ;
}
} | 2,578 | 0.59252 | 0.590962 | 88 | 28.181818 | 25.34738 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.443182 | false | false | 9 |
308a024587e34267f5fce3565c084c7c7ad3c45f | 10,299,331,633,263 | 8dcc635b2ca56ee5eae8a6869fe763524640fdd6 | /jai/src/app/jai/models/JenkinsArtifact.java | 6b4da979ffd3b107248fb1017de888114a85cdb6 | [] | no_license | khendricks/jai | https://github.com/khendricks/jai | f68925719f94eaf823f7851b230185b22ed785b1 | 911f795f0d290a146a4f8eb9224423f5e73ea7b1 | refs/heads/master | 2016-08-02T23:57:19.682000 | 2011-11-03T14:49:00 | 2011-11-03T14:49:00 | 2,332,307 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.jai.models;
public class JenkinsArtifact {
private String displayPath;
private String fileName;
private String relativePath;
public String getDisplayPath() {
return displayPath;
}
public String getFileName() {
return fileName;
}
public String getRelativePath() {
return relativePath;
}
}
| UTF-8 | Java | 332 | java | JenkinsArtifact.java | Java | [] | null | [] | package app.jai.models;
public class JenkinsArtifact {
private String displayPath;
private String fileName;
private String relativePath;
public String getDisplayPath() {
return displayPath;
}
public String getFileName() {
return fileName;
}
public String getRelativePath() {
return relativePath;
}
}
| 332 | 0.722892 | 0.722892 | 16 | 18.75 | 12.402117 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 9 |
737d453c42ef172ce65fc6bf06986b876d31456a | 10,393,820,877,918 | d940ad6740ebe84f8235233a5529ee1f70a14964 | /TheDevice/src/game/objects/behavior/Behavior.java | d5d1fc43a667d1de5a9cb70aef6f784a1d08ee00 | [] | no_license | putty174/TheDevice | https://github.com/putty174/TheDevice | fd5100b1fa22499fffc0f38bb857ea840972bda5 | 904eba76efb3e0ec91eef74df72e3a3ef6e43e12 | refs/heads/master | 2021-01-25T10:44:23.343000 | 2014-06-21T23:09:44 | 2014-06-21T23:09:44 | 15,623,282 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.objects.behavior;
import com.badlogic.gdx.math.Vector2;
import game.objects.DeviceObject;
public class Behavior {
/* Start */
/**
* Behavior of the object when it is created.
*
* @param self the main object.
*/
public void event_initialize(DeviceObject self) {}
/* Collision */
/**
* Behavior of when an object collides.
*
* @param self the main object that is colliding.
* @param other the object being collided with.
*/
public void event_collision(DeviceObject self, DeviceObject other) {}
/* Animation */
/**
* Behavior of when the object ends its animation.
*
* @param self the object whose animation has ended.
* @param animation_name the name of the animation.
*/
public void event_animationFinish(DeviceObject self, String animation_name) {}
/* Touch */
/**
* Behavior when player touches up.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchUp(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/**
* Behavior when player touch down.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchDown(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/**
* Behavior when player touch drags.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchDrag(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/* Event Triggers */
/**
* An unspecified behavior where if certain triggers happen, an event will happen.
*
* @param self the object doing the behaving.
* @param trigger_name the name of the trigger.
*/
public void event_trigger(DeviceObject self, String trigger_name) {}
/**
* An unspecified behavior where if certain triggers happen, an event will happen.
*
* @param self the object doing the behaving.
* @param trigger_name the name of the trigger.
* @param triggering_object the object triggering the trigger.
*/
public void event_trigger_fromObject(DeviceObject self, DeviceObject triggering_object, String trigger_name) {}
/**
* Behavior that happens at the start of every update.
*
* @param sel the object doing the behaving.
*/
public void event_updateStart(DeviceObject self) {}
/**
* Behavior that happens at the end of every update.
*
* @param self the object doing the behaving.
*/
public void event_updateEnd(DeviceObject self) {}
/**
* Behavior when the object is removed from the game.
*
* @param self the object doing the behaving.
*/
public void event_finalize(DeviceObject self) {}
}//END class Behavior
| UTF-8 | Java | 2,869 | java | Behavior.java | Java | [] | null | [] | package game.objects.behavior;
import com.badlogic.gdx.math.Vector2;
import game.objects.DeviceObject;
public class Behavior {
/* Start */
/**
* Behavior of the object when it is created.
*
* @param self the main object.
*/
public void event_initialize(DeviceObject self) {}
/* Collision */
/**
* Behavior of when an object collides.
*
* @param self the main object that is colliding.
* @param other the object being collided with.
*/
public void event_collision(DeviceObject self, DeviceObject other) {}
/* Animation */
/**
* Behavior of when the object ends its animation.
*
* @param self the object whose animation has ended.
* @param animation_name the name of the animation.
*/
public void event_animationFinish(DeviceObject self, String animation_name) {}
/* Touch */
/**
* Behavior when player touches up.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchUp(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/**
* Behavior when player touch down.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchDown(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/**
* Behavior when player touch drags.
*
* @param self the position of where the player touched.
* @param click_position the position of where the player clicked.
*/
public void event_touchDrag(DeviceObject self, DeviceObject touched_object, Vector2 click_position) {}
/* Event Triggers */
/**
* An unspecified behavior where if certain triggers happen, an event will happen.
*
* @param self the object doing the behaving.
* @param trigger_name the name of the trigger.
*/
public void event_trigger(DeviceObject self, String trigger_name) {}
/**
* An unspecified behavior where if certain triggers happen, an event will happen.
*
* @param self the object doing the behaving.
* @param trigger_name the name of the trigger.
* @param triggering_object the object triggering the trigger.
*/
public void event_trigger_fromObject(DeviceObject self, DeviceObject triggering_object, String trigger_name) {}
/**
* Behavior that happens at the start of every update.
*
* @param sel the object doing the behaving.
*/
public void event_updateStart(DeviceObject self) {}
/**
* Behavior that happens at the end of every update.
*
* @param self the object doing the behaving.
*/
public void event_updateEnd(DeviceObject self) {}
/**
* Behavior when the object is removed from the game.
*
* @param self the object doing the behaving.
*/
public void event_finalize(DeviceObject self) {}
}//END class Behavior
| 2,869 | 0.709306 | 0.707912 | 99 | 27.979797 | 29.318859 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.050505 | false | false | 9 |
9edcaa12e48c2b4c128ccc0b17b86efb01628918 | 13,537,736,981,406 | d6ed88ca1bb5a4a5ea269e8aecde47a76d60a2d7 | /Programs/P11-20/Program_20.java | 863112b7ec71b1c8e4c8e30e57e34a192549c898 | [
"Apache-2.0"
] | permissive | aschkun/Java | https://github.com/aschkun/Java | 4954265437ea55ffe672090664100ca44c800569 | 8be2893cdbafedf74418e4c7dc80e4e193afc7b9 | refs/heads/master | 2023-08-31T13:41:08.105000 | 2021-10-20T08:07:21 | 2021-10-20T08:07:21 | 409,479,565 | 0 | 0 | Apache-2.0 | true | 2021-09-23T08:27:10 | 2021-09-23T06:47:01 | 2021-09-23T08:25:00 | 2021-09-23T08:27:09 | 210 | 0 | 0 | 0 | Java | false | false | /** program to find roots of a quadratic equation */
import java.util.Scanner;
import java.lang.Math;
public class test{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
/** the coefficients are taken as input from the user */
System.out.println("Enter coefficient numbers: ");
float a = sc.nextFloat();
float b = sc.nextFloat();
float c = sc.nextFloat();
/** the imaginary roots conditiion is checked first */
float root = ((b * b) - (4 * a * c));
if (root < 0)
{
System.out.println("Imaginary roots");
}
/** both the roots of the equation are calculated */
else
{
double root1 = Math.sqrt(root);
root1 = - b + root1;
root1 = root1 / (2f * a);
double root2 = Math.sqrt(root);
root2 = - b - root2;
root2 = root2 / (2f * a);
System.out.println("Root1: " + root1);
System.out.println("Root2: " + root2);
}
}
}
| UTF-8 | Java | 921 | java | Program_20.java | Java | [] | null | [] | /** program to find roots of a quadratic equation */
import java.util.Scanner;
import java.lang.Math;
public class test{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
/** the coefficients are taken as input from the user */
System.out.println("Enter coefficient numbers: ");
float a = sc.nextFloat();
float b = sc.nextFloat();
float c = sc.nextFloat();
/** the imaginary roots conditiion is checked first */
float root = ((b * b) - (4 * a * c));
if (root < 0)
{
System.out.println("Imaginary roots");
}
/** both the roots of the equation are calculated */
else
{
double root1 = Math.sqrt(root);
root1 = - b + root1;
root1 = root1 / (2f * a);
double root2 = Math.sqrt(root);
root2 = - b - root2;
root2 = root2 / (2f * a);
System.out.println("Root1: " + root1);
System.out.println("Root2: " + root2);
}
}
}
| 921 | 0.608035 | 0.588491 | 39 | 22.615385 | 19.609802 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.769231 | false | false | 2 |
97ca10e34fa0e80239c54ad1b142cd97ab29cbe6 | 7,447,473,308,130 | 1b53f8d67b0dfd9157f3dee5c59af33475272790 | /baselibrary/src/main/java/gxut/gongpengming/baselibrary/util/threads/SingleThreadPoolUtil.java | b2292bf0bd8a8ba6e39b8cfbddd915278cbd48a6 | [] | no_license | gongpengming/Library-Project | https://github.com/gongpengming/Library-Project | 44b4ea1b6b4abca4837ec99fc89ce2308704f63d | a7449ccb5cc1a53d372ea51013c74fa57d108579 | refs/heads/master | 2016-08-24T20:04:22.838000 | 2016-08-04T09:49:35 | 2016-08-04T09:49:36 | 60,236,344 | 0 | 0 | null | false | 2016-07-01T10:02:20 | 2016-06-02T05:52:39 | 2016-06-02T10:09:12 | 2016-07-01T10:02:19 | 173 | 0 | 0 | 0 | Java | null | null | package gxut.gongpengming.baselibrary.util.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,
* 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下
* Created by gongpm on 2016/7/29.
*/
public class SingleThreadPoolUtil {
private static SingleThreadPoolUtil instance;
private static ExecutorService singleThreadExecutor;
public static SingleThreadPoolUtil getInstance() {
if (instance == null) {
synchronized (SingleThreadPoolUtil.class) {
instance = new SingleThreadPoolUtil();
}
}
return instance;
}
private SingleThreadPoolUtil() {
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
public void start(Runnable runnable) {
if (singleThreadExecutor == null) {
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
singleThreadExecutor.shutdown();
singleThreadExecutor.execute(runnable);
}
}
| UTF-8 | Java | 1,142 | java | SingleThreadPoolUtil.java | Java | [
{
"context": "所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下\n * Created by gongpm on 2016/7/29.\n */\npublic class SingleThreadPoolUt",
"end": 238,
"score": 0.9995622038841248,
"start": 232,
"tag": "USERNAME",
"value": "gongpm"
}
] | null | [] | package gxut.gongpengming.baselibrary.util.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,
* 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下
* Created by gongpm on 2016/7/29.
*/
public class SingleThreadPoolUtil {
private static SingleThreadPoolUtil instance;
private static ExecutorService singleThreadExecutor;
public static SingleThreadPoolUtil getInstance() {
if (instance == null) {
synchronized (SingleThreadPoolUtil.class) {
instance = new SingleThreadPoolUtil();
}
}
return instance;
}
private SingleThreadPoolUtil() {
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
public void start(Runnable runnable) {
if (singleThreadExecutor == null) {
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
singleThreadExecutor.shutdown();
singleThreadExecutor.execute(runnable);
}
}
| 1,142 | 0.686654 | 0.679884 | 36 | 27.722221 | 22.403635 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361111 | false | false | 2 |
696c69e9ffd6ced844a3c52dafffdc5646820c83 | 33,732,673,205,024 | bc73706d371a05319e9e6579a105d8ade0711692 | /J2EE/Day9.1/src/tester/TestHibernate.java | 8ec6fd6f483bbc9a064616c0540b8faeccb34824 | [] | no_license | mohit-rajadnya/eDAC | https://github.com/mohit-rajadnya/eDAC | 5bc698954f1d18ad5b7b05eb1bc11714228b074c | f7023b84a171f5accdf7d137463d93e756c77044 | refs/heads/master | 2023-04-19T19:56:34.204000 | 2021-05-03T08:42:02 | 2021-05-03T08:42:02 | 358,848,213 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tester;
import static utils.HibernateUtils.getSf;
import org.hibernate.*;
public class TestHibernate {
public static void main(String args[])
{
try(SessionFactory factory = getSf())
{
System.out.println("Hibernate up and running!!" + factory);
}catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 324 | java | TestHibernate.java | Java | [] | null | [] | package tester;
import static utils.HibernateUtils.getSf;
import org.hibernate.*;
public class TestHibernate {
public static void main(String args[])
{
try(SessionFactory factory = getSf())
{
System.out.println("Hibernate up and running!!" + factory);
}catch (Exception e) {
e.printStackTrace();
}
}
}
| 324 | 0.694444 | 0.694444 | 17 | 18.058823 | 18.306124 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.411765 | false | false | 2 |
2aae26e399df3b3e180b7ecc7edeb1050a0e03d3 | 24,962,349,925,158 | 40bb9da14fb4727f85c06fc674babbf30f0ec1fc | /ketos-ui-example-html/src/test/java/io/committed/ketos/example/ui/html/ExampleHtmlTest.java | 9abcf52d913dfc9f0227da360701b8671eb5968c | [
"Apache-2.0"
] | permissive | commitd/jonah-server | https://github.com/commitd/jonah-server | 3daa74d4f432b405bafdb27ab00a6a2fc69633bb | 86742ea732572bcf83c0e9c1b834423c15230018 | refs/heads/master | 2021-06-08T15:02:46.054000 | 2020-05-06T15:31:43 | 2020-05-06T15:31:43 | 142,595,266 | 0 | 0 | NOASSERTION | false | 2021-04-26T16:10:13 | 2018-07-27T15:37:15 | 2020-11-30T17:26:34 | 2021-04-26T16:10:12 | 1,368 | 0 | 0 | 1 | Java | false | false | package io.committed.ketos.example.ui.html;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import io.committed.invest.server.core.ServerCoreConfiguration;
import io.committed.invest.test.InvestTestContext;
@RunWith(SpringRunner.class)
@WebFluxTest
@ContextConfiguration(
classes = {InvestTestContext.class, ExampleHtmlUi.class, ServerCoreConfiguration.class}
)
@DirtiesContext
public class ExampleHtmlTest {
@Autowired private WebTestClient webClient;
@Test
public void getIndex() {
this.webClient
.get()
.uri("/ui/example-html/index.html")
.exchange()
.expectStatus()
.is2xxSuccessful();
}
}
| UTF-8 | Java | 1,050 | java | ExampleHtmlTest.java | Java | [] | null | [] | package io.committed.ketos.example.ui.html;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import io.committed.invest.server.core.ServerCoreConfiguration;
import io.committed.invest.test.InvestTestContext;
@RunWith(SpringRunner.class)
@WebFluxTest
@ContextConfiguration(
classes = {InvestTestContext.class, ExampleHtmlUi.class, ServerCoreConfiguration.class}
)
@DirtiesContext
public class ExampleHtmlTest {
@Autowired private WebTestClient webClient;
@Test
public void getIndex() {
this.webClient
.get()
.uri("/ui/example-html/index.html")
.exchange()
.expectStatus()
.is2xxSuccessful();
}
}
| 1,050 | 0.787619 | 0.785714 | 34 | 29.882353 | 25.049088 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441176 | false | false | 2 |
00542b67a28f7e75e58460bb72468486103ba300 | 7,215,545,060,231 | bd800ac81173988dd8bafa32ef63614926d8190a | /src/test/java/org/unitedata/client/example/DataQueryClientTest.java | 9d5a354a826611173bbb86c2d72bdde2d4f74aa9 | [] | no_license | unitedata-org-public/ud-example | https://github.com/unitedata-org-public/ud-example | 97aef7fd5a782dbac4a6836f2e9d5766a94e1ee0 | b28d1c5347f8a9be069450014b61e54a8799dd0e | refs/heads/master | 2020-03-29T01:21:47.605000 | 2018-10-15T02:18:42 | 2018-10-15T02:18:42 | 149,385,242 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.unitedata.client.example;
import org.junit.Test;
import org.unitedata.data.consumer.DataProducer;
import org.unitedata.data.consumer.DataQueryClient;
import org.unitedata.data.consumer.transaction.TransactionMode;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
/**
* Created by sry-cpu on 2018/9/26.
*/
public class DataQueryClientTest {
private static final String charset = "utf-8";
// eos 账户名称
private static final String account = "muhe1.5";
// eos 账户私钥
private static final String privateKey = "5KWLe3tsEHJ8JQY4h6s7rVy6sa6LZ4K8q4YfUmznTYbxkYyXfYo";
// eos 访问地址
private static final String contractUri = "http://eos-api1.ud-eos-api.k2.test.wacai.info/v1";
// 合约地址
private static final String contractId = "dr1tpf45wyv4";
// 交易 id
private static final String transactionId = "";
// 交易模型
private static final TransactionMode mode = TransactionMode.packageTime;
// 查询参数
private static final Map<String, Object> queryParameters
= new HashMap<>();
// 数据提供方筛选器
private static final Predicate<DataProducer> producerFilter = null;
@Test
public void QueryTest(){
try {
final Object data =
DataQueryClient.newProtocol(account, privateKey)
// [必填] 设置 eos 访问地址
.setContractUri(contractUri)
// [可选] 设置 http[s] 文本编码器,默认 utf-8
.setHttpEncoding(charset)
// [可选] 设置 预处理订单数量,默认 2
.setMinPreviousTransactionSize(2)
// [可选] 设置 当前批次交易的次数,或者有效天数,默认 1
.setTransactionTicks(30)
// 基于默认的按次计费的模式的交易订单的查询方式,交易订单可选
// .query(contractId, transactionId, queryParameters)
// 基于指定交易模式的交易订单的查询方式,交易订单可选
.query(mode, contractId, transactionId, queryParameters)
// 基于指定交易模式,以及主动筛选数据提供方的交易订单的查询方式,交易订单可选
// .query(mode, contractId, transactionId, queryParameters, producerFilter)
;
System.out.println("[data] --> "+ data);
}
catch (Exception cause){
cause.printStackTrace();
}
}
}
| UTF-8 | Java | 2,738 | java | DataQueryClientTest.java | Java | [
{
"context": "t java.util.function.Predicate;\n\n/**\n * Created by sry-cpu on 2018/9/26.\n */\npublic class DataQueryClientTes",
"end": 339,
"score": 0.9994903206825256,
"start": 332,
"tag": "USERNAME",
"value": "sry-cpu"
},
{
"context": "账户名称\n private static final String account = \"muhe1.5\";\n // eos 账户私钥\n private static final Stri",
"end": 509,
"score": 0.44197288155555725,
"start": 506,
"tag": "USERNAME",
"value": "he1"
},
{
"context": "户私钥\n private static final String privateKey = \"5KWLe3tsEHJ8JQY4h6s7rVy6sa6LZ4K8q4YfUmznTYbxkYyXfYo\";\n // eos 访问地址\n private static final String",
"end": 627,
"score": 0.999779462814331,
"start": 576,
"tag": "KEY",
"value": "5KWLe3tsEHJ8JQY4h6s7rVy6sa6LZ4K8q4YfUmznTYbxkYyXfYo"
}
] | null | [] | package org.unitedata.client.example;
import org.junit.Test;
import org.unitedata.data.consumer.DataProducer;
import org.unitedata.data.consumer.DataQueryClient;
import org.unitedata.data.consumer.transaction.TransactionMode;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
/**
* Created by sry-cpu on 2018/9/26.
*/
public class DataQueryClientTest {
private static final String charset = "utf-8";
// eos 账户名称
private static final String account = "muhe1.5";
// eos 账户私钥
private static final String privateKey = "<KEY>";
// eos 访问地址
private static final String contractUri = "http://eos-api1.ud-eos-api.k2.test.wacai.info/v1";
// 合约地址
private static final String contractId = "dr1tpf45wyv4";
// 交易 id
private static final String transactionId = "";
// 交易模型
private static final TransactionMode mode = TransactionMode.packageTime;
// 查询参数
private static final Map<String, Object> queryParameters
= new HashMap<>();
// 数据提供方筛选器
private static final Predicate<DataProducer> producerFilter = null;
@Test
public void QueryTest(){
try {
final Object data =
DataQueryClient.newProtocol(account, privateKey)
// [必填] 设置 eos 访问地址
.setContractUri(contractUri)
// [可选] 设置 http[s] 文本编码器,默认 utf-8
.setHttpEncoding(charset)
// [可选] 设置 预处理订单数量,默认 2
.setMinPreviousTransactionSize(2)
// [可选] 设置 当前批次交易的次数,或者有效天数,默认 1
.setTransactionTicks(30)
// 基于默认的按次计费的模式的交易订单的查询方式,交易订单可选
// .query(contractId, transactionId, queryParameters)
// 基于指定交易模式的交易订单的查询方式,交易订单可选
.query(mode, contractId, transactionId, queryParameters)
// 基于指定交易模式,以及主动筛选数据提供方的交易订单的查询方式,交易订单可选
// .query(mode, contractId, transactionId, queryParameters, producerFilter)
;
System.out.println("[data] --> "+ data);
}
catch (Exception cause){
cause.printStackTrace();
}
}
}
| 2,692 | 0.589722 | 0.5754 | 63 | 36.682541 | 27.076509 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492063 | false | false | 2 |
b5a89f83fe769ae4a2ce389c9940e7341a1e17af | 27,006,754,413,201 | bc63a86e04285119ddb8269649124dad1c9ad2b4 | /src/main/java/cn/org/hentai/nts/Test.java | f49dd6c7c80563ef3017f611f5a9439819749eaf | [
"Apache-2.0"
] | permissive | glaciall/number-to-speech | https://github.com/glaciall/number-to-speech | fb5da997d9515740b255cc5cb9dd89d1ede1788f | 2a62089e43ec13953639ff5e0c2e0fca14d26d3d | refs/heads/master | 2023-03-26T12:37:25.385000 | 2021-03-24T16:57:26 | 2021-03-24T16:57:26 | 351,154,060 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.org.hentai.nts;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) throws Exception
{
// 此处返回的pcm字节数组的内容,可以通过ffplay -f s16le -ar 16000 -ac 1来播放
byte[] pcm = NumberToSpeech.toVoice("12345.04", "alipay", "yuan");
// 这里我们比较随意的加个wav头,来保存到wav文件里,好进行测试播放
FileOutputStream fos = new FileOutputStream("d:\\test.wav");
// 资源交换文件标志
fos.write(new byte[] { 0x52, 0x49, 0x46, 0x46 });
// 后续数据长度
fos.write(toBytes(pcm.length + 36));
// WAVE标记
fos.write("WAVE".getBytes());
// 波形格式标志
fos.write("fmt ".getBytes());
// FMT块大小
fos.write(toBytes(0x00000010));
// 音频编码:线性PCM
fos.write(0x01);
fos.write(0x00);
// 声道数:1
fos.write(0x01);
fos.write(0x00);
// 每秒样本数:16000
fos.write(toBytes(0x3e80));
// 每秒字节数:32000
fos.write(toBytes(0x7d00));
// 每样本字节数:2
fos.write(0x02);
fos.write(0x00);
// 每样本比特数:16
fos.write(0x10);
fos.write(0x00);
// 数据体标志
fos.write("data".getBytes());
// 数据体长度
fos.write(toBytes(pcm.length));
// 写入音频数据体
fos.write(pcm);
fos.flush();
fos.close();
}
private static byte[] toBytes(int v)
{
byte[] x = new byte[4];
x[0] = (byte)(v & 0xff);
x[1] = (byte)((v >> 8) & 0xff);
x[2] = (byte)((v >> 16) & 0xff);
x[3] = (byte)((v >> 24) & 0xff);
return x;
}
} | UTF-8 | Java | 1,833 | java | Test.java | Java | [] | null | [] | package cn.org.hentai.nts;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) throws Exception
{
// 此处返回的pcm字节数组的内容,可以通过ffplay -f s16le -ar 16000 -ac 1来播放
byte[] pcm = NumberToSpeech.toVoice("12345.04", "alipay", "yuan");
// 这里我们比较随意的加个wav头,来保存到wav文件里,好进行测试播放
FileOutputStream fos = new FileOutputStream("d:\\test.wav");
// 资源交换文件标志
fos.write(new byte[] { 0x52, 0x49, 0x46, 0x46 });
// 后续数据长度
fos.write(toBytes(pcm.length + 36));
// WAVE标记
fos.write("WAVE".getBytes());
// 波形格式标志
fos.write("fmt ".getBytes());
// FMT块大小
fos.write(toBytes(0x00000010));
// 音频编码:线性PCM
fos.write(0x01);
fos.write(0x00);
// 声道数:1
fos.write(0x01);
fos.write(0x00);
// 每秒样本数:16000
fos.write(toBytes(0x3e80));
// 每秒字节数:32000
fos.write(toBytes(0x7d00));
// 每样本字节数:2
fos.write(0x02);
fos.write(0x00);
// 每样本比特数:16
fos.write(0x10);
fos.write(0x00);
// 数据体标志
fos.write("data".getBytes());
// 数据体长度
fos.write(toBytes(pcm.length));
// 写入音频数据体
fos.write(pcm);
fos.flush();
fos.close();
}
private static byte[] toBytes(int v)
{
byte[] x = new byte[4];
x[0] = (byte)(v & 0xff);
x[1] = (byte)((v >> 8) & 0xff);
x[2] = (byte)((v >> 16) & 0xff);
x[3] = (byte)((v >> 24) & 0xff);
return x;
}
} | 1,833 | 0.50665 | 0.444585 | 61 | 24.90164 | 17.269043 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57377 | false | false | 2 |
33fb11cf05fee49f926d6910ad3b927b9b18289a | 19,774,029,475,570 | c7836232544ed82aa6c46fe9f16b57d38e3ad0e5 | /Ecosistemas/app/src/main/java/com/eco/bravoperezquevedomarmolejo/finalintegrado_appestudiantes/Activities/EjemplosConstancias.java | 6bea2c1e8a2599e851a7bb3e82aa8581b9c0cd56 | [] | no_license | juanez1999/FinalIntegrado_2019-1 | https://github.com/juanez1999/FinalIntegrado_2019-1 | 875fb77e65a645b4a90b12703c65cdb28263aa59 | 43fe8d318406cb125d04487b066b9cd5f7baeff1 | refs/heads/master | 2020-05-27T10:05:58.868000 | 2019-05-30T22:38:57 | 2019-05-30T22:38:57 | 188,576,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.ModalConfirmarVolver;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.R;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.utils.Comunicacion;
public class EjemplosConstancias extends AppCompatActivity implements ModalConfirmarVolver.BottomSheetListener {
private Comunicacion ref;
private ImageButton volver;
private ImageButton forma;
private ImageButton tamano;
private ImageButton color;
private ImageButton practica;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ejemplos_constancias);
ref = Comunicacion.getRef();
volver = findViewById(R.id.btn_volver_ejemplosConstancias);
forma = findViewById(R.id.btn_forma_ejemplosConstancias);
tamano = findViewById(R.id.btn_tamano_ejemplosConstancias);
color = findViewById(R.id.btn_color_ejemplosConstancias);
practica = findViewById(R.id.btn_practicar_ejemplosConstancias);
volver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ModalConfirmarVolver modal = new ModalConfirmarVolver();
modal.show(getSupportFragmentManager(), "Modal");
}
});
forma.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploForma";
ref.enviar(msg);
}
});
tamano.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploTamano";
ref.enviar(msg);
}
});
color.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploColor";
ref.enviar(msg);
}
});
practica.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ref.enviar("Continuar");
Intent i = new Intent(EjemplosConstancias.this, PracticaConstancias.class);
startActivity(i);
}
});
}
@Override
public void OnButtonClicked(String boton) {
if(boton.matches("Confirmar")) {
Intent i = new Intent(EjemplosConstancias.this, AprendePercepcion.class);
startActivity(i);
}
}
}
| UTF-8 | Java | 2,938 | java | EjemplosConstancias.java | Java | [] | null | [] | package com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.ModalConfirmarVolver;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.R;
import com.eco.bravoperezquevedomarmolejo.finalintegrado_appestudiantes.utils.Comunicacion;
public class EjemplosConstancias extends AppCompatActivity implements ModalConfirmarVolver.BottomSheetListener {
private Comunicacion ref;
private ImageButton volver;
private ImageButton forma;
private ImageButton tamano;
private ImageButton color;
private ImageButton practica;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ejemplos_constancias);
ref = Comunicacion.getRef();
volver = findViewById(R.id.btn_volver_ejemplosConstancias);
forma = findViewById(R.id.btn_forma_ejemplosConstancias);
tamano = findViewById(R.id.btn_tamano_ejemplosConstancias);
color = findViewById(R.id.btn_color_ejemplosConstancias);
practica = findViewById(R.id.btn_practicar_ejemplosConstancias);
volver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ModalConfirmarVolver modal = new ModalConfirmarVolver();
modal.show(getSupportFragmentManager(), "Modal");
}
});
forma.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploForma";
ref.enviar(msg);
}
});
tamano.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploTamano";
ref.enviar(msg);
}
});
color.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "EjemploColor";
ref.enviar(msg);
}
});
practica.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ref.enviar("Continuar");
Intent i = new Intent(EjemplosConstancias.this, PracticaConstancias.class);
startActivity(i);
}
});
}
@Override
public void OnButtonClicked(String boton) {
if(boton.matches("Confirmar")) {
Intent i = new Intent(EjemplosConstancias.this, AprendePercepcion.class);
startActivity(i);
}
}
}
| 2,938 | 0.647039 | 0.646698 | 87 | 32.770115 | 27.476511 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.505747 | false | false | 2 |
6c50fd1641bab419d4aea3e8372998180ba56d3a | 14,766,097,613,636 | b0d07df10f5286d026f429787b5231d91f841f23 | /modules/client/src/main/java/org/sapia/corus/interop/client/BaseFileLogOutput.java | 355bc0ba13fcfdee4cab455223706a75968de14d | [
"Apache-2.0"
] | permissive | sapia-oss/corus_iop | https://github.com/sapia-oss/corus_iop | 3f735c3175d65da43874c8a8ab58c3fa283d18b3 | ef7e23b4f050cf3011537e79ffe6b59af3af1324 | refs/heads/master | 2021-01-20T06:57:23.277000 | 2016-02-06T18:51:26 | 2016-02-06T18:51:26 | 26,384,473 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sapia.corus.interop.client;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A {@link StdLogOutput} implementation that outputs logging statements to a file.
* This class supports archiving, so that log files are archived up until a
* given maximum number of archived files. Each archived file is identified with
* a counter (starting from 1). When the maximum is reached, archiving restarts
* from 1.
* <p>
* An instance of this class creates log file in the current directory by
* default (corresponding to the <code>user.dir</code> system property) - this
* may be overridden.
* <p>
* The full log file name has the following format:
*
* <pre>
* {fileName}.log
* </pre>
*
* For archived files, the counter is added:
*
* <pre>
* {fileName}-{counter}.log
* </pre>
*
* The value for <code>{fileName}</code> must be provided in the {@link Config}
* instance passed to this constructor of this class.
*
* The current log file is kept until its size reaches a given maximum number of
* megabytes (defaulting to 3). When the current log file reaches that size, it
* is archived using the next file counter.
* <p>
* The behavior of an instance of this class can be altered through system
* properties, or programatically. (see the javadoc further below for the
* configuration properties that are supported).
* <p>
* Lastly, {@link FileArchivingListener} instances can be registered with an
* instance of this class: these are notified whenever the current log file is
* archived.
*
* @author yduchesne
*
*/
public class BaseFileLogOutput implements StdLogOutput {
private static final int ONE_MEG = 1024 * 1024;
private static final int LOG_CHECK_INTERVAL = 100;
private Config conf;
private int logCheckInterval = LOG_CHECK_INTERVAL;
private File currentLogFile;
private AtomicInteger logCounter = new AtomicInteger();
private AtomicInteger fileCounter = new AtomicInteger();
private volatile boolean closed;
private FileWriter output;
private List<FileArchivingListener> listeners = Collections.synchronizedList(new ArrayList<FileArchivingListener>());
protected BaseFileLogOutput(Config config) {
this.conf = config;
}
public void addFileArchivingListener(FileArchivingListener listener) {
this.listeners.add(listener);
}
@Override
public void log(String msg) {
if (output == null || closed) {
createOutput();
}
output.write(msg);
if (logCounter.incrementAndGet() >= logCheckInterval) {
rotate();
}
}
@Override
public void log(Throwable error) {
if (output == null || closed) {
createOutput();
}
output.write(error);
if (logCounter.incrementAndGet() >= logCheckInterval) {
rotate();
}
}
@Override
public synchronized void close() {
if (output != null && !closed) {
output.close();
}
closed = true;
}
final void setLogCheckInterval(int logCheckInterval) {
this.logCheckInterval = logCheckInterval;
}
final Config getConf() {
return conf;
}
final int getFileCounter() {
return fileCounter.get();
}
private synchronized void createOutput() {
if (output == null || closed) {
currentLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + ".log");
output = createFileWriter(currentLogFile);
closed = false;
}
}
private synchronized void rotate() {
if (isMaxSizeReached(currentLogFile)) {
InMemoryFileWriter inMemory = new InMemoryFileWriter();
FileWriter oldOutput = output;
output = inMemory;
oldOutput.close();
if (fileCounter.incrementAndGet() > conf.getMaxArchive()) {
fileCounter.set(1);
}
File backLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + "-" + fileCounter + ".log");
deleteIfExists(backLogFile);
rename(currentLogFile, backLogFile);
currentLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + ".log");
synchronized (inMemory) {
FileWriter newOutput = createFileWriter(currentLogFile);
inMemory.flushTo(newOutput);
output = newOutput;
}
synchronized (listeners) {
for (FileArchivingListener listener : listeners) {
listener.onNewRotatedFile(backLogFile, fileCounter.get());
}
}
logCounter.set(0);
}
}
protected FileWriter createFileWriter(File target) {
try {
PrintWriter stream = new TimestampPrintWriter(new FileOutputStream(target, true));
return new StreamFileWriter(stream);
} catch (FileNotFoundException e) {
System.out.println("Could not create log file, will log to DEV/NULL");
e.printStackTrace();
return new NullFileWriter();
}
}
protected boolean isMaxSizeReached(File currentLogFile) {
return currentLogFile.length() >= ONE_MEG * conf.getMaxFileSize();
}
protected void deleteIfExists(File file) {
if (file.exists()) {
file.delete();
}
}
protected void rename(File toRename, File to) {
toRename.renameTo(to);
}
// ==========================================================================
// INNER CLASSES
public static class Config {
public static final int DEFAULT_MAX_ARCHIVE = 10;
public static final int DEFAULT_LOG_CHECK_INTERVAL = 100;
public static final int DEFAULT_MAX_FILE_SIZE = 3;
public static final String DEFAULT_LOG_DIRECTORY = System.getProperty("user.dir");
private File logDirectory = new File(DEFAULT_LOG_DIRECTORY);
private String logFileName;
private int archive = DEFAULT_MAX_ARCHIVE;
private int maxFileSize = DEFAULT_MAX_FILE_SIZE;
public File getLogDirectory() {
return logDirectory;
}
public Config setLogDirectory(File logDirectory) {
if (!logDirectory.exists()) {
logDirectory.mkdirs();
}
if (!logDirectory.isDirectory()) {
throw new IllegalArgumentException("File is not a directory: " + logDirectory.getAbsolutePath());
}
this.logDirectory = logDirectory;
return this;
}
public String getLogFileName() {
if (logFileName == null) {
throw new IllegalStateException("Log file name not set");
}
return logFileName;
}
public Config setLogFileName(String logFileName) {
this.logFileName = logFileName;
return this;
}
public int getMaxArchive() {
return archive;
}
public Config setMaxArchive(int archive) {
this.archive = archive;
return this;
}
public int getMaxFileSize() {
return maxFileSize;
}
public Config setMaxFileSize(int maxFileSize) {
this.maxFileSize = maxFileSize;
return this;
}
@Override
public String toString() {
return new StringBuilder("[")
.append("directory=").append(logDirectory)
.append("fileName=").append(logFileName)
.append("archive=").append(archive)
.append("maxFileSize=").append(maxFileSize)
.append("]").toString();
}
}
/**
* @param props the {@link Properties} objects to use.
* @param name the name of the property to look for.
* @param defaultValue the value to use if no property exists for the given name.
* @return an integer value.
*/
static int getIntProperty(Properties props, String name, int defaultValue) {
String val = System.getProperty(name);
if (val == null) {
return defaultValue;
}
return Integer.parseInt(val);
}
// --------------------------------------------------------------------------
/**
* An instance of this class can be registered with a
* {@link BaseFileLogOutput} to be notified upon a log file being archived.
*/
public interface FileArchivingListener {
/**
* @param archivedFile
* the {@link File} that was archived.
* @param fileCounter
* the file's corresponding counter.
*/
public void onNewRotatedFile(File archivedFile, int fileCounter);
}
// --------------------------------------------------------------------------
interface FileWriter {
public void write(String content);
public void write(Throwable err);
public void close();
}
// --------------------------------------------------------------------------
class NullFileWriter implements FileWriter {
@Override
public void write(String content) {
}
@Override
public void write(Throwable err) {
}
@Override
public void close() {
}
}
// --------------------------------------------------------------------------
class StreamFileWriter implements FileWriter {
private volatile PrintWriter writer;
StreamFileWriter(PrintWriter writer) {
this.writer = writer;
}
public void write(String content) {
writer.println(content);
writer.flush();
}
@Override
public void write(Throwable err) {
err.printStackTrace(writer);
writer.flush();
}
@Override
public void close() {
writer.flush();
writer.close();
}
}
// --------------------------------------------------------------------------
class InMemoryFileWriter implements FileWriter {
private static final int MAX_LINES = 1000;
private List<String> lines = new ArrayList<String>();
@Override
public synchronized void write(String content) {
if (lines.size() >= MAX_LINES) {
lines.remove(0);
}
lines.add(content);
}
@Override
public synchronized void write(Throwable err) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bos);
err.printStackTrace(ps);
ps.flush();
ps.close();
write(bos.toString());
}
public synchronized void flushTo(FileWriter other) {
for (String line : lines) {
other.write(line);
}
lines.clear();
}
@Override
public synchronized void close() {
}
}
}
| UTF-8 | Java | 10,372 | java | BaseFileLogOutput.java | Java | [
{
"context": "he current log file is\n * archived.\n * \n * @author yduchesne\n * \n */\npublic class BaseFileLogOutput implements",
"end": 1858,
"score": 0.9990386366844177,
"start": 1849,
"tag": "USERNAME",
"value": "yduchesne"
}
] | null | [] | package org.sapia.corus.interop.client;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A {@link StdLogOutput} implementation that outputs logging statements to a file.
* This class supports archiving, so that log files are archived up until a
* given maximum number of archived files. Each archived file is identified with
* a counter (starting from 1). When the maximum is reached, archiving restarts
* from 1.
* <p>
* An instance of this class creates log file in the current directory by
* default (corresponding to the <code>user.dir</code> system property) - this
* may be overridden.
* <p>
* The full log file name has the following format:
*
* <pre>
* {fileName}.log
* </pre>
*
* For archived files, the counter is added:
*
* <pre>
* {fileName}-{counter}.log
* </pre>
*
* The value for <code>{fileName}</code> must be provided in the {@link Config}
* instance passed to this constructor of this class.
*
* The current log file is kept until its size reaches a given maximum number of
* megabytes (defaulting to 3). When the current log file reaches that size, it
* is archived using the next file counter.
* <p>
* The behavior of an instance of this class can be altered through system
* properties, or programatically. (see the javadoc further below for the
* configuration properties that are supported).
* <p>
* Lastly, {@link FileArchivingListener} instances can be registered with an
* instance of this class: these are notified whenever the current log file is
* archived.
*
* @author yduchesne
*
*/
public class BaseFileLogOutput implements StdLogOutput {
private static final int ONE_MEG = 1024 * 1024;
private static final int LOG_CHECK_INTERVAL = 100;
private Config conf;
private int logCheckInterval = LOG_CHECK_INTERVAL;
private File currentLogFile;
private AtomicInteger logCounter = new AtomicInteger();
private AtomicInteger fileCounter = new AtomicInteger();
private volatile boolean closed;
private FileWriter output;
private List<FileArchivingListener> listeners = Collections.synchronizedList(new ArrayList<FileArchivingListener>());
protected BaseFileLogOutput(Config config) {
this.conf = config;
}
public void addFileArchivingListener(FileArchivingListener listener) {
this.listeners.add(listener);
}
@Override
public void log(String msg) {
if (output == null || closed) {
createOutput();
}
output.write(msg);
if (logCounter.incrementAndGet() >= logCheckInterval) {
rotate();
}
}
@Override
public void log(Throwable error) {
if (output == null || closed) {
createOutput();
}
output.write(error);
if (logCounter.incrementAndGet() >= logCheckInterval) {
rotate();
}
}
@Override
public synchronized void close() {
if (output != null && !closed) {
output.close();
}
closed = true;
}
final void setLogCheckInterval(int logCheckInterval) {
this.logCheckInterval = logCheckInterval;
}
final Config getConf() {
return conf;
}
final int getFileCounter() {
return fileCounter.get();
}
private synchronized void createOutput() {
if (output == null || closed) {
currentLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + ".log");
output = createFileWriter(currentLogFile);
closed = false;
}
}
private synchronized void rotate() {
if (isMaxSizeReached(currentLogFile)) {
InMemoryFileWriter inMemory = new InMemoryFileWriter();
FileWriter oldOutput = output;
output = inMemory;
oldOutput.close();
if (fileCounter.incrementAndGet() > conf.getMaxArchive()) {
fileCounter.set(1);
}
File backLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + "-" + fileCounter + ".log");
deleteIfExists(backLogFile);
rename(currentLogFile, backLogFile);
currentLogFile = new File(conf.getLogDirectory(), conf.getLogFileName() + ".log");
synchronized (inMemory) {
FileWriter newOutput = createFileWriter(currentLogFile);
inMemory.flushTo(newOutput);
output = newOutput;
}
synchronized (listeners) {
for (FileArchivingListener listener : listeners) {
listener.onNewRotatedFile(backLogFile, fileCounter.get());
}
}
logCounter.set(0);
}
}
protected FileWriter createFileWriter(File target) {
try {
PrintWriter stream = new TimestampPrintWriter(new FileOutputStream(target, true));
return new StreamFileWriter(stream);
} catch (FileNotFoundException e) {
System.out.println("Could not create log file, will log to DEV/NULL");
e.printStackTrace();
return new NullFileWriter();
}
}
protected boolean isMaxSizeReached(File currentLogFile) {
return currentLogFile.length() >= ONE_MEG * conf.getMaxFileSize();
}
protected void deleteIfExists(File file) {
if (file.exists()) {
file.delete();
}
}
protected void rename(File toRename, File to) {
toRename.renameTo(to);
}
// ==========================================================================
// INNER CLASSES
public static class Config {
public static final int DEFAULT_MAX_ARCHIVE = 10;
public static final int DEFAULT_LOG_CHECK_INTERVAL = 100;
public static final int DEFAULT_MAX_FILE_SIZE = 3;
public static final String DEFAULT_LOG_DIRECTORY = System.getProperty("user.dir");
private File logDirectory = new File(DEFAULT_LOG_DIRECTORY);
private String logFileName;
private int archive = DEFAULT_MAX_ARCHIVE;
private int maxFileSize = DEFAULT_MAX_FILE_SIZE;
public File getLogDirectory() {
return logDirectory;
}
public Config setLogDirectory(File logDirectory) {
if (!logDirectory.exists()) {
logDirectory.mkdirs();
}
if (!logDirectory.isDirectory()) {
throw new IllegalArgumentException("File is not a directory: " + logDirectory.getAbsolutePath());
}
this.logDirectory = logDirectory;
return this;
}
public String getLogFileName() {
if (logFileName == null) {
throw new IllegalStateException("Log file name not set");
}
return logFileName;
}
public Config setLogFileName(String logFileName) {
this.logFileName = logFileName;
return this;
}
public int getMaxArchive() {
return archive;
}
public Config setMaxArchive(int archive) {
this.archive = archive;
return this;
}
public int getMaxFileSize() {
return maxFileSize;
}
public Config setMaxFileSize(int maxFileSize) {
this.maxFileSize = maxFileSize;
return this;
}
@Override
public String toString() {
return new StringBuilder("[")
.append("directory=").append(logDirectory)
.append("fileName=").append(logFileName)
.append("archive=").append(archive)
.append("maxFileSize=").append(maxFileSize)
.append("]").toString();
}
}
/**
* @param props the {@link Properties} objects to use.
* @param name the name of the property to look for.
* @param defaultValue the value to use if no property exists for the given name.
* @return an integer value.
*/
static int getIntProperty(Properties props, String name, int defaultValue) {
String val = System.getProperty(name);
if (val == null) {
return defaultValue;
}
return Integer.parseInt(val);
}
// --------------------------------------------------------------------------
/**
* An instance of this class can be registered with a
* {@link BaseFileLogOutput} to be notified upon a log file being archived.
*/
public interface FileArchivingListener {
/**
* @param archivedFile
* the {@link File} that was archived.
* @param fileCounter
* the file's corresponding counter.
*/
public void onNewRotatedFile(File archivedFile, int fileCounter);
}
// --------------------------------------------------------------------------
interface FileWriter {
public void write(String content);
public void write(Throwable err);
public void close();
}
// --------------------------------------------------------------------------
class NullFileWriter implements FileWriter {
@Override
public void write(String content) {
}
@Override
public void write(Throwable err) {
}
@Override
public void close() {
}
}
// --------------------------------------------------------------------------
class StreamFileWriter implements FileWriter {
private volatile PrintWriter writer;
StreamFileWriter(PrintWriter writer) {
this.writer = writer;
}
public void write(String content) {
writer.println(content);
writer.flush();
}
@Override
public void write(Throwable err) {
err.printStackTrace(writer);
writer.flush();
}
@Override
public void close() {
writer.flush();
writer.close();
}
}
// --------------------------------------------------------------------------
class InMemoryFileWriter implements FileWriter {
private static final int MAX_LINES = 1000;
private List<String> lines = new ArrayList<String>();
@Override
public synchronized void write(String content) {
if (lines.size() >= MAX_LINES) {
lines.remove(0);
}
lines.add(content);
}
@Override
public synchronized void write(Throwable err) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bos);
err.printStackTrace(ps);
ps.flush();
ps.close();
write(bos.toString());
}
public synchronized void flushTo(FileWriter other) {
for (String line : lines) {
other.write(line);
}
lines.clear();
}
@Override
public synchronized void close() {
}
}
}
| 10,372 | 0.633243 | 0.63064 | 385 | 25.94026 | 25.350101 | 119 | false | false | 0 | 0 | 0 | 0 | 75 | 0.007231 | 0.348052 | false | false | 2 |
b17893fa8dc668644f0ef2fb3356e54dfdd38fb7 | 32,701,881,046,602 | aef000034726f883dd90e5efa140155534297174 | /app/src/main/java/id/ihwan/footballteam/main/MainPresenter.java | 96e54fef012796a9f4d6b58c4742c940e2d4da12 | [] | no_license | ASKU30/football | https://github.com/ASKU30/football | 7061406c9ca82c098d9921a64b4961469280f783 | adcd56de7f4980f8942d531da6f136ad75b1c0be | refs/heads/master | 2023-06-09T03:02:14.341000 | 2019-09-10T23:08:21 | 2019-09-10T23:08:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package id.ihwan.footballteam.main;
import android.content.Context;
import java.util.List;
import id.ihwan.footballteam.data.TeamDataSource;
import id.ihwan.footballteam.data.TeamRepository;
import id.ihwan.footballteam.model.Teams;
/**
* Created by ihwan on 20,December,2018
*/
public class MainPresenter implements MainContract.Presenter {
private final TeamRepository repository;
private final MainContract.View view;
public MainPresenter(TeamRepository repository, MainContract.View view) {
this.repository = repository;
this.view = view;
}
@Override
public void getDataListTeams(Context context) {
view.showProgress();
repository.getListTeams(context, new TeamDataSource.GetListTeamsCallback() {
@Override
public void onSuccess(List<Teams> data) {
view.hideProgress();
view.showDataList(data);
}
@Override
public void onFailed(String errorMessage) {
view.hideProgress();
view.showFailureMessage(errorMessage);
}
});
}
}
| UTF-8 | Java | 1,141 | java | MainPresenter.java | Java | [
{
"context": "ihwan.footballteam.model.Teams;\n\n/**\n * Created by ihwan on 20,December,2018\n */\npublic class MainPresente",
"end": 260,
"score": 0.9996328353881836,
"start": 255,
"tag": "USERNAME",
"value": "ihwan"
}
] | null | [] | package id.ihwan.footballteam.main;
import android.content.Context;
import java.util.List;
import id.ihwan.footballteam.data.TeamDataSource;
import id.ihwan.footballteam.data.TeamRepository;
import id.ihwan.footballteam.model.Teams;
/**
* Created by ihwan on 20,December,2018
*/
public class MainPresenter implements MainContract.Presenter {
private final TeamRepository repository;
private final MainContract.View view;
public MainPresenter(TeamRepository repository, MainContract.View view) {
this.repository = repository;
this.view = view;
}
@Override
public void getDataListTeams(Context context) {
view.showProgress();
repository.getListTeams(context, new TeamDataSource.GetListTeamsCallback() {
@Override
public void onSuccess(List<Teams> data) {
view.hideProgress();
view.showDataList(data);
}
@Override
public void onFailed(String errorMessage) {
view.hideProgress();
view.showFailureMessage(errorMessage);
}
});
}
}
| 1,141 | 0.655565 | 0.650307 | 43 | 25.534883 | 23.118853 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465116 | false | false | 2 |
fb1e7d48ebfaa71dfc1c0c5b4ace4250eae6813b | 18,760,417,164,303 | c17a0aa0bba9ba98c2854ca0d896abaaa0659a45 | /bean/src/main/java/com/ychp/java/bean/copy/package-info.java | 5ca2b84f54abf4f0d47731ea00cd200ea36a97e0 | [] | no_license | ychp/performance-compare | https://github.com/ychp/performance-compare | cef63b794402423b9f60cb5ee0bb3e2444661367 | 3fde2aee89fe1eba9577470ae9ab8b6d71ff5df3 | refs/heads/master | 2020-04-08T14:56:07.286000 | 2018-12-06T06:54:41 | 2018-12-06T06:54:41 | 159,458,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author yingchengpeng
* @date 2018/11/28
*/
package com.ychp.java.bean.copy; | UTF-8 | Java | 85 | java | package-info.java | Java | [
{
"context": "/**\n * @author yingchengpeng\n * @date 2018/11/28\n */\npackage com.ychp.java.bea",
"end": 28,
"score": 0.9985525012016296,
"start": 15,
"tag": "NAME",
"value": "yingchengpeng"
}
] | null | [] | /**
* @author yingchengpeng
* @date 2018/11/28
*/
package com.ychp.java.bean.copy; | 85 | 0.670588 | 0.576471 | 5 | 16.200001 | 11.54816 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 2 |
6549a278e486950b01fa757dfc7d69881cf0403a | 14,053,133,061,735 | 30465116768980bb23c8b13ebb28ababa5a571cb | /mapreduce2/src/main/java/com/openvalue/training/LongestWord.java | 89e164fc0c674eb3f607ce59966e18a0d870bd97 | [] | no_license | AmiraBMansour/MapReduce2 | https://github.com/AmiraBMansour/MapReduce2 | d812d483967b8e653452b6fab33ee16fe953fcb6 | e1286f827fee42475310241617e44c6b0be75c70 | refs/heads/master | 2020-07-10T17:35:47.571000 | 2016-08-27T08:34:46 | 2016-08-27T08:34:46 | 66,661,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.openvalue.training;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
public class LongestWord {
static HashMap<String,Integer> mMapOccurence = new HashMap<String,Integer>();
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
mMapOccurence.put(key.toString(),sum);
List<String> lKeyWithSameOcc = new ArrayList<String>();
for(Entry<String,Integer> entry : mMapOccurence.entrySet()){
if(entry.getValue().equals(sum)){
lKeyWithSameOcc.add(entry.getKey());
}
}
int max = 0;
String lLongestWord ="";
for(String name: lKeyWithSameOcc){
if(name.length() > max){
max = name.length();
lLongestWord = name;
}
}
if(lLongestWord.isEmpty()){
Text word = new Text(lLongestWord);
output.collect(word, new IntWritable(sum));
}
}
}
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(LongestWord.class);
conf.setJobName("wordcount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
}
| UTF-8 | Java | 3,130 | java | LongestWord.java | Java | [] | null | [] | package com.openvalue.training;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
public class LongestWord {
static HashMap<String,Integer> mMapOccurence = new HashMap<String,Integer>();
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
mMapOccurence.put(key.toString(),sum);
List<String> lKeyWithSameOcc = new ArrayList<String>();
for(Entry<String,Integer> entry : mMapOccurence.entrySet()){
if(entry.getValue().equals(sum)){
lKeyWithSameOcc.add(entry.getKey());
}
}
int max = 0;
String lLongestWord ="";
for(String name: lKeyWithSameOcc){
if(name.length() > max){
max = name.length();
lLongestWord = name;
}
}
if(lLongestWord.isEmpty()){
Text word = new Text(lLongestWord);
output.collect(word, new IntWritable(sum));
}
}
}
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(LongestWord.class);
conf.setJobName("wordcount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
}
| 3,130 | 0.723962 | 0.722364 | 96 | 30.604166 | 20.073032 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.5 | false | false | 2 |
5fc68c4203c87eda6bc23da8ca5b4b27d1129e35 | 5,377,299,056,551 | b79d79ae28493bdd907c1cb166274f5c82806e44 | /src/main/java/com/daansander/engine/component/ListenerComponent.java | 958c435585741a635150752c61a52b0b40cc953b | [
"MIT"
] | permissive | Hyxogen/Omega-Engine | https://github.com/Hyxogen/Omega-Engine | d1cc24b623f3f71f9e4d6855e803ae4ab65eb03a | c3eb51a776a79b8101bca10fa313d129f0d0e710 | refs/heads/master | 2021-05-29T22:35:19.920000 | 2015-10-09T16:25:09 | 2015-10-09T16:25:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.daansander.engine.component;
import com.daansander.engine.input.ComponentHandler;
import com.daansander.engine.math.Vector2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
/**
* Created by Daan on 8-10-2015.
*/
public class ListenerComponent extends ComponentHandler {
protected ArrayList<Vector2D> cpos = new ArrayList<>();
protected Vector2D mousePos;
protected Vector2D pos;
protected boolean mouseDown = false;
protected Component c;
public ListenerComponent(Component component) {
this.c = component;
this.pos = component.getPos();
mousePos = new Vector2D(0, 0);
}
public boolean onComponent() {
for (Vector2D v : cpos) {
if (mousePos == v) {
return true;
}
}
return false;
}
@Override
public void mouseDown(MouseEvent mouseEvent) {
mouseDown = true;
}
@Override
public void mouseUp(MouseEvent mouseEvent) {
mouseDown = false;
}
@Override
public void mouseMove(MouseEvent e) {
mousePos.setLocation(e.getX(), e.getY());
for (int i = 0; i < c.getWidth(); i++) {
for (int j = 0; j < c.getHeight(); j++) {
cpos.add(new Vector2D(i, j));
}
}
onComponent();
}
public Vector2D getMousePos() {
return mousePos;
}
public Vector2D getPos() {
return pos;
}
public boolean isMouseDown() {
return mouseDown;
}
}
| UTF-8 | Java | 1,544 | java | ListenerComponent.java | Java | [
{
"context": "nt;\nimport java.util.ArrayList;\n\n/**\n * Created by Daan on 8-10-2015.\n */\npublic class ListenerComponent ",
"end": 226,
"score": 0.9915160536766052,
"start": 222,
"tag": "NAME",
"value": "Daan"
}
] | null | [] | package com.daansander.engine.component;
import com.daansander.engine.input.ComponentHandler;
import com.daansander.engine.math.Vector2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
/**
* Created by Daan on 8-10-2015.
*/
public class ListenerComponent extends ComponentHandler {
protected ArrayList<Vector2D> cpos = new ArrayList<>();
protected Vector2D mousePos;
protected Vector2D pos;
protected boolean mouseDown = false;
protected Component c;
public ListenerComponent(Component component) {
this.c = component;
this.pos = component.getPos();
mousePos = new Vector2D(0, 0);
}
public boolean onComponent() {
for (Vector2D v : cpos) {
if (mousePos == v) {
return true;
}
}
return false;
}
@Override
public void mouseDown(MouseEvent mouseEvent) {
mouseDown = true;
}
@Override
public void mouseUp(MouseEvent mouseEvent) {
mouseDown = false;
}
@Override
public void mouseMove(MouseEvent e) {
mousePos.setLocation(e.getX(), e.getY());
for (int i = 0; i < c.getWidth(); i++) {
for (int j = 0; j < c.getHeight(); j++) {
cpos.add(new Vector2D(i, j));
}
}
onComponent();
}
public Vector2D getMousePos() {
return mousePos;
}
public Vector2D getPos() {
return pos;
}
public boolean isMouseDown() {
return mouseDown;
}
}
| 1,544 | 0.590026 | 0.577073 | 70 | 21.057142 | 18.246632 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 2 |
6433b15ae702e588c5e26c8cd66a98778e418adc | 19,567,871,003,721 | d8e2cdfc65a330da5116cd08d114290f8ef32c57 | /Entrega_Final/Projeto_Sistema_Escolar/src/br/edu/univas/si6/projeto_escolar/model/to/MateriasMedio.java | 788de3facae3ac4d5adf8b4e906cf7ed850c142c | [] | no_license | sbanetosbk/trabalho_lab6 | https://github.com/sbanetosbk/trabalho_lab6 | c5dc9d27745f7c777665b89fad91607a88709891 | a1dcc591a377704623da3667de34654798436a7a | refs/heads/master | 2020-05-17T08:38:52.236000 | 2014-12-11T08:50:42 | 2014-12-11T08:50:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.univas.si6.projeto_escolar.model.to;
public class MateriasMedio {
private Integer portugues;
private Integer matematica;
private Integer historia;
private Integer geografia;
private Integer fisica;
private Integer quimica;
private Integer biologia;
private Integer informatica;
private Integer edFisica;
private int portuguesCod = 1;
private int matematicaCod = 2;
private int historiaCod = 3;
private int geografiaCod = 4;
private int fisicaCod = 5;
private int quimicaCod = 6;
private int biologiaCod = 8;
private int informaticaCod = 9;
private int edFisicaCod = 10;
public Integer getPortugues() {
return portugues;
}
public void setPortugues(Integer portugues) {
this.portugues = portugues;
}
public Integer getMatematica() {
return matematica;
}
public void setMatematica(Integer matematica) {
this.matematica = matematica;
}
public Integer getHistoria() {
return historia;
}
public void setHistoria(Integer historia) {
this.historia = historia;
}
public Integer getGeografia() {
return geografia;
}
public void setGeografia(Integer geografia) {
this.geografia = geografia;
}
public Integer getFisica() {
return fisica;
}
public void setFisica(Integer fisica) {
this.fisica = fisica;
}
public Integer getQuimica() {
return quimica;
}
public void setQuimica(Integer quimica) {
this.quimica = quimica;
}
public Integer getBiologia() {
return biologia;
}
public void setBiologia(Integer biologia) {
this.biologia = biologia;
}
public Integer getInformatica() {
return informatica;
}
public void setInformatica(Integer informatica) {
this.informatica = informatica;
}
public Integer getEdFisica() {
return edFisica;
}
public void setEdFisica(Integer edFisica) {
this.edFisica = edFisica;
}
//Cods das matérias
public int getPortuguesCod() {
return portuguesCod;
}
public void setPortuguesCod(int portuguesCod) {
this.portuguesCod = portuguesCod;
}
public int getMatematicaCod() {
return matematicaCod;
}
public void setMatematicaCod(int matematicaCod) {
this.matematicaCod = matematicaCod;
}
public int getHistoriaCod() {
return historiaCod;
}
public void setHistoriaCod(int historiaCod) {
this.historiaCod = historiaCod;
}
public int getGeografiaCod() {
return geografiaCod;
}
public void setGeografiaCod(int geografiaCod) {
this.geografiaCod = geografiaCod;
}
public int getFisicaCod() {
return fisicaCod;
}
public void setFisicaCod(int fisicaCod) {
this.fisicaCod = fisicaCod;
}
public int getQuimicaCod() {
return quimicaCod;
}
public void setQuimicaCod(int quimicaCod) {
this.quimicaCod = quimicaCod;
}
public int getBiologiaCod() {
return biologiaCod;
}
public void setBiologiaCod(int biologiaCod) {
this.biologiaCod = biologiaCod;
}
public int getInformaticaCod() {
return informaticaCod;
}
public void setInformaticaCod(int informaticaCod) {
this.informaticaCod = informaticaCod;
}
public int getEdFisicaCod() {
return edFisicaCod;
}
public void setEdFisicaCod(int edFisicaCod) {
this.edFisicaCod = edFisicaCod;
}
}
| UTF-8 | Java | 3,118 | java | MateriasMedio.java | Java | [] | null | [] | package br.edu.univas.si6.projeto_escolar.model.to;
public class MateriasMedio {
private Integer portugues;
private Integer matematica;
private Integer historia;
private Integer geografia;
private Integer fisica;
private Integer quimica;
private Integer biologia;
private Integer informatica;
private Integer edFisica;
private int portuguesCod = 1;
private int matematicaCod = 2;
private int historiaCod = 3;
private int geografiaCod = 4;
private int fisicaCod = 5;
private int quimicaCod = 6;
private int biologiaCod = 8;
private int informaticaCod = 9;
private int edFisicaCod = 10;
public Integer getPortugues() {
return portugues;
}
public void setPortugues(Integer portugues) {
this.portugues = portugues;
}
public Integer getMatematica() {
return matematica;
}
public void setMatematica(Integer matematica) {
this.matematica = matematica;
}
public Integer getHistoria() {
return historia;
}
public void setHistoria(Integer historia) {
this.historia = historia;
}
public Integer getGeografia() {
return geografia;
}
public void setGeografia(Integer geografia) {
this.geografia = geografia;
}
public Integer getFisica() {
return fisica;
}
public void setFisica(Integer fisica) {
this.fisica = fisica;
}
public Integer getQuimica() {
return quimica;
}
public void setQuimica(Integer quimica) {
this.quimica = quimica;
}
public Integer getBiologia() {
return biologia;
}
public void setBiologia(Integer biologia) {
this.biologia = biologia;
}
public Integer getInformatica() {
return informatica;
}
public void setInformatica(Integer informatica) {
this.informatica = informatica;
}
public Integer getEdFisica() {
return edFisica;
}
public void setEdFisica(Integer edFisica) {
this.edFisica = edFisica;
}
//Cods das matérias
public int getPortuguesCod() {
return portuguesCod;
}
public void setPortuguesCod(int portuguesCod) {
this.portuguesCod = portuguesCod;
}
public int getMatematicaCod() {
return matematicaCod;
}
public void setMatematicaCod(int matematicaCod) {
this.matematicaCod = matematicaCod;
}
public int getHistoriaCod() {
return historiaCod;
}
public void setHistoriaCod(int historiaCod) {
this.historiaCod = historiaCod;
}
public int getGeografiaCod() {
return geografiaCod;
}
public void setGeografiaCod(int geografiaCod) {
this.geografiaCod = geografiaCod;
}
public int getFisicaCod() {
return fisicaCod;
}
public void setFisicaCod(int fisicaCod) {
this.fisicaCod = fisicaCod;
}
public int getQuimicaCod() {
return quimicaCod;
}
public void setQuimicaCod(int quimicaCod) {
this.quimicaCod = quimicaCod;
}
public int getBiologiaCod() {
return biologiaCod;
}
public void setBiologiaCod(int biologiaCod) {
this.biologiaCod = biologiaCod;
}
public int getInformaticaCod() {
return informaticaCod;
}
public void setInformaticaCod(int informaticaCod) {
this.informaticaCod = informaticaCod;
}
public int getEdFisicaCod() {
return edFisicaCod;
}
public void setEdFisicaCod(int edFisicaCod) {
this.edFisicaCod = edFisicaCod;
}
}
| 3,118 | 0.743022 | 0.739493 | 137 | 21.751825 | 15.607307 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.635036 | false | false | 2 |
7a3e8ad6976648a9b87c9fceb993f870747eb7e2 | 14,027,363,252,287 | 30045fb00c68306841ef742d583ec341b23c3121 | /iwsc2017/decompile/jfreechart/src/main/java/org/jfree/data/xml/DatasetReader.java | 55fd3f5f20a8837db370eb2642dda75067ac8370 | [] | no_license | cragkhit/crjk-iwsc17 | https://github.com/cragkhit/crjk-iwsc17 | df9132738e88d6fe47c1963f32faa5a100d41299 | a2915433fd2173e215b8e13e8fa0779bd5ccfe99 | refs/heads/master | 2021-01-13T15:12:15.553000 | 2016-12-12T16:13:07 | 2016-12-12T16:13:07 | 76,252,648 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jfree.data.xml;
import org.jfree.data.category.CategoryDataset;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import org.jfree.data.general.PieDataset;
import java.io.File;
public class DatasetReader {
public static PieDataset readPieDatasetFromXML ( final File file ) throws IOException {
final InputStream in = new FileInputStream ( file );
return readPieDatasetFromXML ( in );
}
public static PieDataset readPieDatasetFromXML ( final InputStream in ) throws IOException {
PieDataset result = null;
final SAXParserFactory factory = SAXParserFactory.newInstance();
try {
final SAXParser parser = factory.newSAXParser();
final PieDatasetHandler handler = new PieDatasetHandler();
parser.parse ( in, handler );
result = handler.getDataset();
} catch ( SAXException e ) {
System.out.println ( e.getMessage() );
} catch ( ParserConfigurationException e2 ) {
System.out.println ( e2.getMessage() );
}
return result;
}
public static CategoryDataset readCategoryDatasetFromXML ( final File file ) throws IOException {
final InputStream in = new FileInputStream ( file );
return readCategoryDatasetFromXML ( in );
}
public static CategoryDataset readCategoryDatasetFromXML ( final InputStream in ) throws IOException {
CategoryDataset result = null;
final SAXParserFactory factory = SAXParserFactory.newInstance();
try {
final SAXParser parser = factory.newSAXParser();
final CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse ( in, handler );
result = handler.getDataset();
} catch ( SAXException e ) {
System.out.println ( e.getMessage() );
} catch ( ParserConfigurationException e2 ) {
System.out.println ( e2.getMessage() );
}
return result;
}
}
| UTF-8 | Java | 2,252 | java | DatasetReader.java | Java | [] | null | [] | package org.jfree.data.xml;
import org.jfree.data.category.CategoryDataset;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import org.jfree.data.general.PieDataset;
import java.io.File;
public class DatasetReader {
public static PieDataset readPieDatasetFromXML ( final File file ) throws IOException {
final InputStream in = new FileInputStream ( file );
return readPieDatasetFromXML ( in );
}
public static PieDataset readPieDatasetFromXML ( final InputStream in ) throws IOException {
PieDataset result = null;
final SAXParserFactory factory = SAXParserFactory.newInstance();
try {
final SAXParser parser = factory.newSAXParser();
final PieDatasetHandler handler = new PieDatasetHandler();
parser.parse ( in, handler );
result = handler.getDataset();
} catch ( SAXException e ) {
System.out.println ( e.getMessage() );
} catch ( ParserConfigurationException e2 ) {
System.out.println ( e2.getMessage() );
}
return result;
}
public static CategoryDataset readCategoryDatasetFromXML ( final File file ) throws IOException {
final InputStream in = new FileInputStream ( file );
return readCategoryDatasetFromXML ( in );
}
public static CategoryDataset readCategoryDatasetFromXML ( final InputStream in ) throws IOException {
CategoryDataset result = null;
final SAXParserFactory factory = SAXParserFactory.newInstance();
try {
final SAXParser parser = factory.newSAXParser();
final CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse ( in, handler );
result = handler.getDataset();
} catch ( SAXException e ) {
System.out.println ( e.getMessage() );
} catch ( ParserConfigurationException e2 ) {
System.out.println ( e2.getMessage() );
}
return result;
}
}
| 2,252 | 0.678508 | 0.676732 | 52 | 42.307693 | 25.031164 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 2 |
c7122288cf9c54eeb7498d8ec8022eac6b449d27 | 1,108,101,573,004 | 3ff9d0cc921b9fd0412edb4f4476e45a2d0fa8fe | /src/main/java/com/wz/proxy/staticproxy/TestCount.java | 53304acee450ee4152316a1d9ddac083406ec909 | [] | no_license | ustcwangzi/design-pattern-demo | https://github.com/ustcwangzi/design-pattern-demo | e25286a3f55bbc06a6df82b3738f2f5fefd44849 | 835beaf857e9637383076b0f623352fb028c14a3 | refs/heads/master | 2021-01-02T08:43:55.324000 | 2019-04-14T07:33:03 | 2019-04-14T07:33:03 | 99,054,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wz.proxy.staticproxy;
/**
* 测试静态代理
* Created by wangzi on 2017-08-02.
*/
public class TestCount {
public static void main(String[] args) {
Count count = new CountProxy(new CountImpl());
count.query();
}
}
| UTF-8 | Java | 257 | java | TestCount.java | Java | [
{
"context": "wz.proxy.staticproxy;\n\n/**\n * 测试静态代理\n * Created by wangzi on 2017-08-02.\n */\npublic class TestCount {\n p",
"end": 69,
"score": 0.9995421767234802,
"start": 63,
"tag": "USERNAME",
"value": "wangzi"
}
] | null | [] | package com.wz.proxy.staticproxy;
/**
* 测试静态代理
* Created by wangzi on 2017-08-02.
*/
public class TestCount {
public static void main(String[] args) {
Count count = new CountProxy(new CountImpl());
count.query();
}
}
| 257 | 0.628571 | 0.595918 | 12 | 19.416666 | 17.858044 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
2e4768cb830e3820d03479096d3362ee7b66702f | 27,771,258,582,746 | 10632711897d35ff2e73d6e328e77b7f9c588640 | /src/main/java/br/com/cocus/automacaococus/bean/SelecionarLogicaBean.java | 42f1171a1300e4d5212eb68bb309182a5d28be84 | [] | no_license | junior3cefet/AutomacaoCocus | https://github.com/junior3cefet/AutomacaoCocus | 8d30be26095cff106243c582d197ecfdceea2a31 | 2c73cb39604133536b8373d956d3fdb4d6ba6efd | refs/heads/master | 2019-07-13T15:30:15.199000 | 2016-07-16T02:31:55 | 2016-07-16T02:31:55 | 59,966,519 | 0 | 0 | null | true | 2016-05-29T22:26:19 | 2016-05-29T22:26:19 | 2016-05-25T18:38:56 | 2016-05-25T18:38:54 | 6,357 | 0 | 0 | 0 | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.cocus.automacaococus.bean;
import br.com.cocus.automacaococus.dao.LogicaDAO;
import br.com.cocus.automacaococus.dao.LogicaEntradaDAO;
import br.com.cocus.automacaococus.dao.LogicaSaidaDAO;
import br.com.cocus.automacaococus.dao.PontoDao;
import br.com.cocus.automacaococus.model.Logica;
import br.com.cocus.automacaococus.model.LogicaEntrada;
import br.com.cocus.automacaococus.model.LogicaSaida;
import br.com.cocus.automacaococus.model.Ponto;
import br.com.cocus.automacaococus.model.pk.LogicaEntradaPK;
import br.com.cocus.automacaococus.model.pk.LogicaSaidaPK;
import br.com.cocus.automacaococus.tools.Mensagem;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.event.RowEditEvent;
/**
*
* @author junio
*/
@SessionScoped
@Named
public class SelecionarLogicaBean implements Serializable{
//Tools
@Inject
private Mensagem men;
//DAO
@Inject
private LogicaEntradaDAO lentradaDao;
@Inject
private LogicaSaidaDAO lsaidaDao;
@Inject
private PontoDao pDao;
@Inject
private LogicaDAO lDao;
//Model
private LogicaEntrada logicaEntrada;
private LogicaSaida logicaSaida;
private Ponto ponto;
private List<Ponto> pontos;
//Converter
private List<SelectItem> selLogicaEntradaConverter = new ArrayList<>();
private List<SelectItem> selLogicaSaidaConverter = new ArrayList<>();
private List<SelectItem> selPontoConverter = new ArrayList<>();
public void save() {
try {
System.out.println(ponto);
if (this.ponto.getLogicaEntradaList().isEmpty()){
this.ponto.getLogicaEntradaList().add(logicaEntrada);
for (LogicaEntrada le : this.ponto.getLogicaEntradaList()) {
if(le.getLogicaEntradaPK() == null){
le.setVlOff(le.getVlOn() == 0? 1 : 0);
le.setPonto(this.ponto);
le.setDtTransacao(new Date());
le.setLogicaEntradaPK(new LogicaEntradaPK(le.getLogica().getId(), le.getPonto().getId()));
lentradaDao.save(le);
} else{
lentradaDao.update(le);
}
}
}
if (this.ponto.getLogicaSaidaList().isEmpty()){
this.ponto.getLogicaSaidaList().add(logicaSaida);
for (LogicaSaida ls : this.ponto.getLogicaSaidaList()) {
if(ls.getLogicaSaidaPK() == null){
ls.setPonto(this.ponto);
ls.setVlOf(ls.getVlOn() == 0? 1 : 0);
ls.setDtTransacao(new Date());
ls.setLogicaSaidaPK(new LogicaSaidaPK(ls.getLogica().getId(), ls.getPonto().getId()));
lsaidaDao.save(ls);
} else{
lsaidaDao.update(ls);
}
}
}
men.info("Lógicas Adicionadas com Sucesso!!");
limpar();
} catch (Exception e) {
e.printStackTrace();
men.error("Erro ao Salvar Lógicas !");
}
}
public void del() {
try {
//remover logica de entrada
for (LogicaEntrada le : this.ponto.getLogicaEntradaList()) {
lentradaDao.remove(le);
}
//remover logica de saida
for (LogicaSaida ls : this.ponto.getLogicaSaidaList()) {
lsaidaDao.remove(ls);
}
limpar();
men.info("Lógicas Excluídas com Sucesso!!");
} catch (Exception e) {
men.error("Erro ao Excluir Lógicas");
}
}
public void limpar() {
this.ponto = new Ponto();
this.logicaEntrada = new LogicaEntrada();
this.logicaSaida = new LogicaSaida();
}
public void onRowEdit(RowEditEvent event) {
this.ponto = (Ponto) event.getObject();
save();
}
public Ponto getPonto() {
return ponto;
}
public void setPonto(Ponto p) {
this.ponto = p;
}
public List<Ponto> getPontos() {
if (this.pontos == null || this.pontos.isEmpty()) {
this.pontos = pDao.findAll("dataTransacao", Boolean.TRUE);
List<Ponto> preenchidos = new ArrayList<>();
for (Ponto p : pontos) {
if(p.getLogicaSaidaList().isEmpty()){
continue;
}
preenchidos.add(p);
}
this.pontos = preenchidos;
}
return this.pontos;
}
public void setPontos(List<Ponto> p) {
this.pontos = p;
}
public List<SelectItem> getSelPontoConverter() {
if (this.selPontoConverter == null || this.selPontoConverter.isEmpty()) {
this.selPontoConverter = this.pDao.getSelectItens("dataTransacao", Boolean.TRUE);
}
return selPontoConverter;
}
public void setSelPontoConverter(List<SelectItem> selPontoConverter) {
this.selPontoConverter = selPontoConverter;
}
public List<SelectItem> getSelLogicaEntradaConverter() {
if (this.selLogicaEntradaConverter == null || this.selLogicaEntradaConverter.isEmpty()) {
this.selLogicaEntradaConverter = this.lDao.getSelectItens("dtTransacao", Boolean.TRUE);
}
return selLogicaEntradaConverter;
}
public void setSelLogicaEntradaConverter(List<SelectItem> selLogicaEntradaConverter) {
this.selLogicaEntradaConverter = selLogicaEntradaConverter;
}
public List<SelectItem> getSelLogicaSaidaConverter() {
if (this.selLogicaSaidaConverter == null || this.selLogicaSaidaConverter.isEmpty()) {
this.selLogicaSaidaConverter = this.lDao.getSelectItens("dtTransacao", Boolean.TRUE);
}
return selLogicaSaidaConverter;
}
public void setSelLogicaSaidaConverter(List<SelectItem> selLogicaSaidaConverter) {
this.selLogicaSaidaConverter = selLogicaSaidaConverter;
}
public LogicaEntrada getLogicaEntrada() {
return logicaEntrada;
}
public void setLogicaEntrada(LogicaEntrada logicaEntrada) {
this.logicaEntrada = logicaEntrada;
}
public LogicaSaida getLogicaSaida() {
return logicaSaida;
}
public void setLogicaSaida(LogicaSaida logicaSaida) {
this.logicaSaida = logicaSaida;
}
}
| UTF-8 | Java | 7,044 | java | SelecionarLogicaBean.java | Java | [
{
"context": ".primefaces.event.RowEditEvent;\n\n/**\n *\n * @author junio\n */\n@SessionScoped\n@Named\npublic class Selecionar",
"end": 1125,
"score": 0.9577426314353943,
"start": 1120,
"tag": "USERNAME",
"value": "junio"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.cocus.automacaococus.bean;
import br.com.cocus.automacaococus.dao.LogicaDAO;
import br.com.cocus.automacaococus.dao.LogicaEntradaDAO;
import br.com.cocus.automacaococus.dao.LogicaSaidaDAO;
import br.com.cocus.automacaococus.dao.PontoDao;
import br.com.cocus.automacaococus.model.Logica;
import br.com.cocus.automacaococus.model.LogicaEntrada;
import br.com.cocus.automacaococus.model.LogicaSaida;
import br.com.cocus.automacaococus.model.Ponto;
import br.com.cocus.automacaococus.model.pk.LogicaEntradaPK;
import br.com.cocus.automacaococus.model.pk.LogicaSaidaPK;
import br.com.cocus.automacaococus.tools.Mensagem;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.event.RowEditEvent;
/**
*
* @author junio
*/
@SessionScoped
@Named
public class SelecionarLogicaBean implements Serializable{
//Tools
@Inject
private Mensagem men;
//DAO
@Inject
private LogicaEntradaDAO lentradaDao;
@Inject
private LogicaSaidaDAO lsaidaDao;
@Inject
private PontoDao pDao;
@Inject
private LogicaDAO lDao;
//Model
private LogicaEntrada logicaEntrada;
private LogicaSaida logicaSaida;
private Ponto ponto;
private List<Ponto> pontos;
//Converter
private List<SelectItem> selLogicaEntradaConverter = new ArrayList<>();
private List<SelectItem> selLogicaSaidaConverter = new ArrayList<>();
private List<SelectItem> selPontoConverter = new ArrayList<>();
public void save() {
try {
System.out.println(ponto);
if (this.ponto.getLogicaEntradaList().isEmpty()){
this.ponto.getLogicaEntradaList().add(logicaEntrada);
for (LogicaEntrada le : this.ponto.getLogicaEntradaList()) {
if(le.getLogicaEntradaPK() == null){
le.setVlOff(le.getVlOn() == 0? 1 : 0);
le.setPonto(this.ponto);
le.setDtTransacao(new Date());
le.setLogicaEntradaPK(new LogicaEntradaPK(le.getLogica().getId(), le.getPonto().getId()));
lentradaDao.save(le);
} else{
lentradaDao.update(le);
}
}
}
if (this.ponto.getLogicaSaidaList().isEmpty()){
this.ponto.getLogicaSaidaList().add(logicaSaida);
for (LogicaSaida ls : this.ponto.getLogicaSaidaList()) {
if(ls.getLogicaSaidaPK() == null){
ls.setPonto(this.ponto);
ls.setVlOf(ls.getVlOn() == 0? 1 : 0);
ls.setDtTransacao(new Date());
ls.setLogicaSaidaPK(new LogicaSaidaPK(ls.getLogica().getId(), ls.getPonto().getId()));
lsaidaDao.save(ls);
} else{
lsaidaDao.update(ls);
}
}
}
men.info("Lógicas Adicionadas com Sucesso!!");
limpar();
} catch (Exception e) {
e.printStackTrace();
men.error("Erro ao Salvar Lógicas !");
}
}
public void del() {
try {
//remover logica de entrada
for (LogicaEntrada le : this.ponto.getLogicaEntradaList()) {
lentradaDao.remove(le);
}
//remover logica de saida
for (LogicaSaida ls : this.ponto.getLogicaSaidaList()) {
lsaidaDao.remove(ls);
}
limpar();
men.info("Lógicas Excluídas com Sucesso!!");
} catch (Exception e) {
men.error("Erro ao Excluir Lógicas");
}
}
public void limpar() {
this.ponto = new Ponto();
this.logicaEntrada = new LogicaEntrada();
this.logicaSaida = new LogicaSaida();
}
public void onRowEdit(RowEditEvent event) {
this.ponto = (Ponto) event.getObject();
save();
}
public Ponto getPonto() {
return ponto;
}
public void setPonto(Ponto p) {
this.ponto = p;
}
public List<Ponto> getPontos() {
if (this.pontos == null || this.pontos.isEmpty()) {
this.pontos = pDao.findAll("dataTransacao", Boolean.TRUE);
List<Ponto> preenchidos = new ArrayList<>();
for (Ponto p : pontos) {
if(p.getLogicaSaidaList().isEmpty()){
continue;
}
preenchidos.add(p);
}
this.pontos = preenchidos;
}
return this.pontos;
}
public void setPontos(List<Ponto> p) {
this.pontos = p;
}
public List<SelectItem> getSelPontoConverter() {
if (this.selPontoConverter == null || this.selPontoConverter.isEmpty()) {
this.selPontoConverter = this.pDao.getSelectItens("dataTransacao", Boolean.TRUE);
}
return selPontoConverter;
}
public void setSelPontoConverter(List<SelectItem> selPontoConverter) {
this.selPontoConverter = selPontoConverter;
}
public List<SelectItem> getSelLogicaEntradaConverter() {
if (this.selLogicaEntradaConverter == null || this.selLogicaEntradaConverter.isEmpty()) {
this.selLogicaEntradaConverter = this.lDao.getSelectItens("dtTransacao", Boolean.TRUE);
}
return selLogicaEntradaConverter;
}
public void setSelLogicaEntradaConverter(List<SelectItem> selLogicaEntradaConverter) {
this.selLogicaEntradaConverter = selLogicaEntradaConverter;
}
public List<SelectItem> getSelLogicaSaidaConverter() {
if (this.selLogicaSaidaConverter == null || this.selLogicaSaidaConverter.isEmpty()) {
this.selLogicaSaidaConverter = this.lDao.getSelectItens("dtTransacao", Boolean.TRUE);
}
return selLogicaSaidaConverter;
}
public void setSelLogicaSaidaConverter(List<SelectItem> selLogicaSaidaConverter) {
this.selLogicaSaidaConverter = selLogicaSaidaConverter;
}
public LogicaEntrada getLogicaEntrada() {
return logicaEntrada;
}
public void setLogicaEntrada(LogicaEntrada logicaEntrada) {
this.logicaEntrada = logicaEntrada;
}
public LogicaSaida getLogicaSaida() {
return logicaSaida;
}
public void setLogicaSaida(LogicaSaida logicaSaida) {
this.logicaSaida = logicaSaida;
}
}
| 7,044 | 0.596818 | 0.595965 | 245 | 27.730612 | 26.396523 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.412245 | false | false | 2 |
600fe98bf8f08c7a2ecd9ee21c34c83684873237 | 27,771,258,583,643 | 09b83c451b13241922d2c8b00c9a9e003ef7fd73 | /app/src/main/java/com/hzy/jbox2d/effects/activity/EndlessBallActivity.java | b1251d51cb39ea9543aa3c266a5adefbae7be672 | [] | no_license | huzongyao/JBox2DEffects | https://github.com/huzongyao/JBox2DEffects | afeb7efc8a4832ba17dcc5efcdc4bb26a543396a | 6620ee17bb77cf78fd7793edafd1e9b714b8cf05 | refs/heads/master | 2020-03-17T20:34:05.060000 | 2019-07-13T11:03:57 | 2019-07-13T11:03:57 | 133,917,481 | 8 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hzy.jbox2d.effects.activity;
import android.os.Bundle;
import com.hzy.jbox2d.effects.R;
public class EndlessBallActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_endless_ball);
}
}
| UTF-8 | Java | 339 | java | EndlessBallActivity.java | Java | [] | null | [] | package com.hzy.jbox2d.effects.activity;
import android.os.Bundle;
import com.hzy.jbox2d.effects.R;
public class EndlessBallActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_endless_ball);
}
}
| 339 | 0.749263 | 0.743363 | 14 | 23.214285 | 22.255589 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 2 |
210367429937001508c9d18147ffd651a09cdb4b | 996,432,431,694 | b2f9592554aa1e734b933a726517804dab1845bd | /JAVA-Eclipse-workspace/order-processing/src/main/java/com/zensar/order/processing/repositoryprovider/OrderRepositoryProvider.java | d864cb95608e8b6478c59d920e925626be1218f4 | [] | no_license | krutishilp/Sample | https://github.com/krutishilp/Sample | 453f010215a70fd60783974328a64cc5935bc251 | 825b527addbe8bf23ea686da6e9be1ede2e14e53 | refs/heads/master | 2023-01-01T09:34:11.615000 | 2020-10-22T09:21:58 | 2020-10-22T09:21:58 | 306,285,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zensar.order.processing.repositoryprovider;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.zensar.order.processing.repository.OrderRepository;
public class OrderRepositoryProvider {
public static OrderRepository getRepository() {
Properties property = new Properties();
OrderRepository repositoryProvider = null;
try {
property.load(new FileReader("./src/main/resources/serviceprovider.properties"));
String service = property.getProperty("repository.provider");
repositoryProvider = (OrderRepository) Class.forName(service).newInstance();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return repositoryProvider;
}
}
| UTF-8 | Java | 1,190 | java | OrderRepositoryProvider.java | Java | [] | null | [] | package com.zensar.order.processing.repositoryprovider;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.zensar.order.processing.repository.OrderRepository;
public class OrderRepositoryProvider {
public static OrderRepository getRepository() {
Properties property = new Properties();
OrderRepository repositoryProvider = null;
try {
property.load(new FileReader("./src/main/resources/serviceprovider.properties"));
String service = property.getProperty("repository.provider");
repositoryProvider = (OrderRepository) Class.forName(service).newInstance();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return repositoryProvider;
}
}
| 1,190 | 0.753781 | 0.753781 | 38 | 30.31579 | 21.168629 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.052632 | false | false | 2 |
2a72befe47de114fbcc29630f240b54c33355967 | 2,851,858,349,946 | ed4bffc42c00b06c49c87417a6b2972e0b037b33 | /cb_ads/src/main/java/com/cloudbanter/adssdk/ad/manager/images/x/ZOldCbDownloadService.java | 6297d321eb4bc5b559ef948c4a3338e7a0abba51 | [] | no_license | umesh-lnt/cb-ads-sdk | https://github.com/umesh-lnt/cb-ads-sdk | 2c8176aa936f01ce894ac5acb2c5b839c0121007 | 387806d099f2d6d43be88a945dbe52215982949e | refs/heads/master | 2021-07-07T09:41:30.113000 | 2017-10-04T08:54:49 | 2017-10-04T08:54:49 | 105,748,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cloudbanter.adssdk.ad.manager.images.x;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import com.cloudbanter.adssdk.R;
import com.cloudbanter.adssdk.ad.manager.images.ImageRef;
import com.cloudbanter.adssdk.ad.model.CbSchedule;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
// TODO triggers for download ( startup, new schedule, time based )
// Called when app started or
// boot received
// --- beWellBehaved() ie: when wifi.isavailable && low impact time of day ,
// --- and use CbProtocol
// --- start and stop yourself
public class ZOldCbDownloadService extends IntentService {
protected static final String TAG = ZOldCbDownloadService.class.getSimpleName();
public static final String EXTRA_SCHEDULE = "schedule_extra";
public static final String EXTRA_SYNC_IMAGES = "sync_images_extra";
private static final Queue<ImageRef> que = new LinkedList<ImageRef>();
private static final Object lock = new Object();
Thread download = null; // worker
// thread
boolean debug;
boolean forceDownloads;
String bucketUrl;
String splitImageFilePrefix;
Context mContext = this;
CbSchedule mSchedule;
// CbImageManager.mSyncImages -- list of images that need to be downloaded
ArrayList<ImageRef> mSyncImages = new ArrayList<ImageRef>();
public ZOldCbDownloadService() {
super("CbDownloadService");
}
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (download != null) {
download.interrupt(); // Request immediate action by downloader
}
Log.d(TAG, "onStart sync:");
for (ImageRef r : mSyncImages) {
Log.d(TAG, "queueing img: " + r.mImageId);
que.add(r);
}
// start threaded process
run(startId);
return START_STICKY;
}
public void onCreate() {
// TODO move to configuration options...
// This goes into a Constants file...
debug = getResources().getBoolean(R.bool.debugThis);
// Ok here.
forceDownloads = getResources().getBoolean(R.bool.forceDownloads);
// TODO move bucketURL to configuration
bucketUrl = getResources().getString(R.string.imagesBucketUrl);
// Goes to Image ref / mgr
splitImageFilePrefix = getResources().getString(R.string.splitImageFilePrefix);
}
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "handleintent - image sync");
for (ImageRef r : mSyncImages) {
que.add(r);
}
run(0);
}
// TODO fix threading model ( QueueThread / FetchThread sync on que )
private void run(final int startId) {
download = new Thread() {
public void run() {
// TODO manage run time...
// long startTime =
// cyclical
// between hours of midnight and 6am local
// if ( not now ) wait safely;
// if (! isOnline() ) wait safely || check with user...
final int sequentialReference = startId;
new Thread() {
public void run() {
Log.d(TAG, "download attempt" + String.valueOf(sequentialReference));
download(sequentialReference);
forceDownloads = false;
// TODO download complete callback...
}
}.start();
}
};
download.start();
}
static boolean running = false;
private void download(int sequentialReference) {
ImageRef ref = null;
// if (serious bandwidth - parallelize...?
while (null != (ref = que.peek())) {
if (isOnline() && null != ref && que.contains(ref) && fetchImage(ref)) {
que.remove(ref); // when complete...
waitToRestart(false);
} else {
waitToRestart(true);
}
}
}
static final long INITIAL_WAIT_TIME = 500;
static final long WAIT_TIME_MULTIPLIER = 2;
static final long MAX_WAIT_TIME = 3600000;
static long waitTime = INITIAL_WAIT_TIME;
Thread waitThread = null;
// waits exponentially longer ...
private void waitToRestart(boolean wait) {
Log.d(TAG, "waiting to retry download");
if (!wait) {
waitTime = INITIAL_WAIT_TIME;
if (null != waitThread) {
waitThread.interrupt();
}
return;
}
try {
if (waitTime < MAX_WAIT_TIME) {
waitTime *= WAIT_TIME_MULTIPLIER;
}
if (null == waitThread) {
waitThread = new Thread();
}
waitThread.sleep(waitTime);
} catch (InterruptedException e) {
waitTime = INITIAL_WAIT_TIME;
}
}
private boolean fetchImage(ImageRef img) {
if (null != img.mUrl && !ImageRef.isPresent(img)) {
String fileName = ImageRef.getFileName(img);
// TODO update to https...
byte[] ba = httpGetFile(img.mUrl.replace("https", "http"));
if (null != ba && ba.length > 0) {
writeLocalFile(fileName, ba);
img.mSavedFileName = fileName;
return true;
}
}
return false;
}
// TODO if offline, use CbProtocol
private byte[] httpGetFile(String url) {
if (null == url) {
return null;
}
final ByteArrayOutputStream r = new ByteArrayOutputStream();
try {
final HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.connect();
Log.d(TAG, "Download bytecount: " + c.getContentLength());
final InputStream i = c.getInputStream();
final byte[] b = new byte[8192];
// TODO fix 1 Mb limit ??
for (int j = 0; j < 1000; ++j) {
int l = i.read(b, 0, b.length);
if (l < 0) {
break;
}
r.write(b, 0, l);
}
c.disconnect();
Log.d(TAG, "Read " + r.size() + " bytes from " + url);
return r.toByteArray();
} catch (UnknownHostException ue) { // UnknownHostException ... reset emulator ?
Log.d(TAG,
"Cannot download url: " + url + " because: " + ue.getMessage() + " reset emulator?");
} catch (Exception e) { // TODO manage connection errors: unqualified Exception is REALLY BAD
// FORM
Log.d(TAG, "Cannot download url: " + url + " because: " + e);
}
return null;
}
private void writeLocalFile(String file, byte[] data) {
try {
FileOutputStream o = openFileOutput(file, Context.MODE_PRIVATE);
o.write(data);
o.close();
} catch (Exception e) {
Log.d(TAG, "Unable to write to local file" + file + " because " + e);
}
}
private void findMe() {
File file = new File(this.getFilesDir(), "find_me");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
| UTF-8 | Java | 7,489 | java | ZOldCbDownloadService.java | Java | [] | null | [] | package com.cloudbanter.adssdk.ad.manager.images.x;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import com.cloudbanter.adssdk.R;
import com.cloudbanter.adssdk.ad.manager.images.ImageRef;
import com.cloudbanter.adssdk.ad.model.CbSchedule;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
// TODO triggers for download ( startup, new schedule, time based )
// Called when app started or
// boot received
// --- beWellBehaved() ie: when wifi.isavailable && low impact time of day ,
// --- and use CbProtocol
// --- start and stop yourself
public class ZOldCbDownloadService extends IntentService {
protected static final String TAG = ZOldCbDownloadService.class.getSimpleName();
public static final String EXTRA_SCHEDULE = "schedule_extra";
public static final String EXTRA_SYNC_IMAGES = "sync_images_extra";
private static final Queue<ImageRef> que = new LinkedList<ImageRef>();
private static final Object lock = new Object();
Thread download = null; // worker
// thread
boolean debug;
boolean forceDownloads;
String bucketUrl;
String splitImageFilePrefix;
Context mContext = this;
CbSchedule mSchedule;
// CbImageManager.mSyncImages -- list of images that need to be downloaded
ArrayList<ImageRef> mSyncImages = new ArrayList<ImageRef>();
public ZOldCbDownloadService() {
super("CbDownloadService");
}
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (download != null) {
download.interrupt(); // Request immediate action by downloader
}
Log.d(TAG, "onStart sync:");
for (ImageRef r : mSyncImages) {
Log.d(TAG, "queueing img: " + r.mImageId);
que.add(r);
}
// start threaded process
run(startId);
return START_STICKY;
}
public void onCreate() {
// TODO move to configuration options...
// This goes into a Constants file...
debug = getResources().getBoolean(R.bool.debugThis);
// Ok here.
forceDownloads = getResources().getBoolean(R.bool.forceDownloads);
// TODO move bucketURL to configuration
bucketUrl = getResources().getString(R.string.imagesBucketUrl);
// Goes to Image ref / mgr
splitImageFilePrefix = getResources().getString(R.string.splitImageFilePrefix);
}
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "handleintent - image sync");
for (ImageRef r : mSyncImages) {
que.add(r);
}
run(0);
}
// TODO fix threading model ( QueueThread / FetchThread sync on que )
private void run(final int startId) {
download = new Thread() {
public void run() {
// TODO manage run time...
// long startTime =
// cyclical
// between hours of midnight and 6am local
// if ( not now ) wait safely;
// if (! isOnline() ) wait safely || check with user...
final int sequentialReference = startId;
new Thread() {
public void run() {
Log.d(TAG, "download attempt" + String.valueOf(sequentialReference));
download(sequentialReference);
forceDownloads = false;
// TODO download complete callback...
}
}.start();
}
};
download.start();
}
static boolean running = false;
private void download(int sequentialReference) {
ImageRef ref = null;
// if (serious bandwidth - parallelize...?
while (null != (ref = que.peek())) {
if (isOnline() && null != ref && que.contains(ref) && fetchImage(ref)) {
que.remove(ref); // when complete...
waitToRestart(false);
} else {
waitToRestart(true);
}
}
}
static final long INITIAL_WAIT_TIME = 500;
static final long WAIT_TIME_MULTIPLIER = 2;
static final long MAX_WAIT_TIME = 3600000;
static long waitTime = INITIAL_WAIT_TIME;
Thread waitThread = null;
// waits exponentially longer ...
private void waitToRestart(boolean wait) {
Log.d(TAG, "waiting to retry download");
if (!wait) {
waitTime = INITIAL_WAIT_TIME;
if (null != waitThread) {
waitThread.interrupt();
}
return;
}
try {
if (waitTime < MAX_WAIT_TIME) {
waitTime *= WAIT_TIME_MULTIPLIER;
}
if (null == waitThread) {
waitThread = new Thread();
}
waitThread.sleep(waitTime);
} catch (InterruptedException e) {
waitTime = INITIAL_WAIT_TIME;
}
}
private boolean fetchImage(ImageRef img) {
if (null != img.mUrl && !ImageRef.isPresent(img)) {
String fileName = ImageRef.getFileName(img);
// TODO update to https...
byte[] ba = httpGetFile(img.mUrl.replace("https", "http"));
if (null != ba && ba.length > 0) {
writeLocalFile(fileName, ba);
img.mSavedFileName = fileName;
return true;
}
}
return false;
}
// TODO if offline, use CbProtocol
private byte[] httpGetFile(String url) {
if (null == url) {
return null;
}
final ByteArrayOutputStream r = new ByteArrayOutputStream();
try {
final HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.connect();
Log.d(TAG, "Download bytecount: " + c.getContentLength());
final InputStream i = c.getInputStream();
final byte[] b = new byte[8192];
// TODO fix 1 Mb limit ??
for (int j = 0; j < 1000; ++j) {
int l = i.read(b, 0, b.length);
if (l < 0) {
break;
}
r.write(b, 0, l);
}
c.disconnect();
Log.d(TAG, "Read " + r.size() + " bytes from " + url);
return r.toByteArray();
} catch (UnknownHostException ue) { // UnknownHostException ... reset emulator ?
Log.d(TAG,
"Cannot download url: " + url + " because: " + ue.getMessage() + " reset emulator?");
} catch (Exception e) { // TODO manage connection errors: unqualified Exception is REALLY BAD
// FORM
Log.d(TAG, "Cannot download url: " + url + " because: " + e);
}
return null;
}
private void writeLocalFile(String file, byte[] data) {
try {
FileOutputStream o = openFileOutput(file, Context.MODE_PRIVATE);
o.write(data);
o.close();
} catch (Exception e) {
Log.d(TAG, "Unable to write to local file" + file + " because " + e);
}
}
private void findMe() {
File file = new File(this.getFilesDir(), "find_me");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
| 7,489 | 0.628655 | 0.62505 | 255 | 28.368628 | 22.68206 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541176 | false | false | 2 |
3614057744e2c1ddeacef1f79b6ebe17cd359600 | 13,640,816,152,219 | 9da849c81db14a2c86631d3e9484c2d20d88f027 | /University-Management-System/src/main/java/com/project/univmgmt/repo/UniversityRepo.java | 75d9ca3706ac419ece86b7715a16f19cd93890c3 | [] | no_license | guptaajit9/university-management | https://github.com/guptaajit9/university-management | 5571ff0431731d6870b0d8bc2f5e51e91ab92d29 | 70a897e0dc80113a004695b64f60b53d5bfd65aa | refs/heads/master | 2020-12-01T17:43:16.001000 | 2020-01-03T14:55:03 | 2020-01-03T14:55:03 | 230,714,970 | 0 | 0 | null | false | 2020-10-13T18:36:14 | 2019-12-29T06:57:46 | 2020-01-03T14:55:37 | 2020-10-13T18:36:12 | 9 | 0 | 0 | 1 | Java | false | false | package com.project.univmgmt.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.project.univmgmt.model.University;
@Repository
public interface UniversityRepo extends JpaRepository<University,Integer>{
}
| UTF-8 | Java | 286 | java | UniversityRepo.java | Java | [] | null | [] | package com.project.univmgmt.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.project.univmgmt.model.University;
@Repository
public interface UniversityRepo extends JpaRepository<University,Integer>{
}
| 286 | 0.846154 | 0.846154 | 11 | 25 | 27.011782 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 2 |
8f72b200025a68e5f7f596321435821b27519d7b | 11,879,879,557,921 | a8854fe0ba07017a0f6c6446699a2b363f5a61da | /app/src/main/java/com/example/ajay/suicide/PlacesActivity.java | 0f176ce53068988a0b76571d06ad9e5bf920edbb | [] | no_license | kritz10/Suicide-Prevention | https://github.com/kritz10/Suicide-Prevention | d091558035b5bfd1b19628e545fcb7f7e38f86df | 25123bccc7f319e55fb60afac7a08e569fac8f13 | refs/heads/master | 2020-06-25T14:30:58.669000 | 2019-07-28T21:06:03 | 2019-07-28T21:06:03 | 199,336,844 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ajay.suicide;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class PlacesActivity extends AppCompatActivity {
ArrayList<String> place = new ArrayList<String>() ;
ArrayAdapter<String> adapterp ;
DataBaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
db=new DataBaseHelper(this);
Cursor cursor=db.getPlacesContents();
while(cursor.moveToNext()){
place.add(cursor.getString(1));
}
adapterp = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1 , place) ;
ListView listViewp = (ListView) findViewById(R.id.list_place) ;
Button button = (Button) findViewById(R.id.add_1) ;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
EditText editText = (EditText) findViewById(R.id.edit_text_2) ;
String s = editText.getText().toString() ;
if(s.length()!=0) {
boolean check=db.addPlaces(s);
if(check==true)
Toast.makeText(PlacesActivity.this,"Successfully inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(PlacesActivity.this,"Something went wrong!", Toast.LENGTH_LONG).show();
editText.setText("");
}
else{
Toast.makeText(PlacesActivity.this,"Empty text field! Enter text first", Toast.LENGTH_LONG).show();
}
place.add(s) ;
adapterp.notifyDataSetChanged();
//editText.setText("");
}
});
listViewp.setAdapter(adapterp);
listViewp.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
}
}
//public void addPlace(View view){
//}
| UTF-8 | Java | 3,077 | java | PlacesActivity.java | Java | [] | null | [] | package com.example.ajay.suicide;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class PlacesActivity extends AppCompatActivity {
ArrayList<String> place = new ArrayList<String>() ;
ArrayAdapter<String> adapterp ;
DataBaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
db=new DataBaseHelper(this);
Cursor cursor=db.getPlacesContents();
while(cursor.moveToNext()){
place.add(cursor.getString(1));
}
adapterp = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1 , place) ;
ListView listViewp = (ListView) findViewById(R.id.list_place) ;
Button button = (Button) findViewById(R.id.add_1) ;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
EditText editText = (EditText) findViewById(R.id.edit_text_2) ;
String s = editText.getText().toString() ;
if(s.length()!=0) {
boolean check=db.addPlaces(s);
if(check==true)
Toast.makeText(PlacesActivity.this,"Successfully inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(PlacesActivity.this,"Something went wrong!", Toast.LENGTH_LONG).show();
editText.setText("");
}
else{
Toast.makeText(PlacesActivity.this,"Empty text field! Enter text first", Toast.LENGTH_LONG).show();
}
place.add(s) ;
adapterp.notifyDataSetChanged();
//editText.setText("");
}
});
listViewp.setAdapter(adapterp);
listViewp.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
}
}
//public void addPlace(View view){
//}
| 3,077 | 0.59311 | 0.59116 | 87 | 34.356323 | 26.691071 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609195 | false | false | 2 |
688202ca873dc7ad5b5a65de87fbe6f4f39a2f96 | 16,956,530,915,747 | 1eaabb04e27d79bd2de1babcd624a178347e240f | /SystemDesign/src/com/uday/design/chess/HumanPlayer.java | 9145e86e836dadb08cc01f77d81e0f4761bcefa3 | [] | no_license | udayv1985/ProblemSolvingQ | https://github.com/udayv1985/ProblemSolvingQ | 87b5dcf610d295c6b16d4a5b1b9cd153df2d154f | 75f0bbda4dc5d46dd0a8825f36458cfbfdea1276 | refs/heads/master | 2021-06-27T04:00:44.179000 | 2020-10-19T19:47:26 | 2020-10-19T19:47:26 | 160,807,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.uday.design.chess;
public class HumanPlayer extends Player {
}
| UTF-8 | Java | 76 | java | HumanPlayer.java | Java | [] | null | [] | package com.uday.design.chess;
public class HumanPlayer extends Player {
}
| 76 | 0.789474 | 0.789474 | 4 | 18 | 17.930422 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
5ad674aa82e1c24a20395655fbc1a25650c73776 | 5,317,169,528,842 | 1c0c543009e6ce7a6f589e31f37bb165840664a8 | /src/ooga/data/factories/LayoutFactory.java | 22f2179db0942140d256d50eeca685f34e791866 | [
"MIT"
] | permissive | puzzler7/final_CS308 | https://github.com/puzzler7/final_CS308 | 2c418d072a8daa17dd57b4c40d30569fc94f4e12 | b724ecf2583626a09dcd13a561a62c73863dfc2b | refs/heads/master | 2022-11-30T06:32:10.392000 | 2020-08-20T08:02:28 | 2020-08-20T08:02:28 | 288,943,665 | 0 | 0 | MIT | false | 2020-08-20T08:02:30 | 2020-08-20T07:58:01 | 2020-08-20T07:59:11 | 2020-08-20T08:02:29 | 0 | 0 | 0 | 0 | Java | false | false | package ooga.data.factories;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import ooga.data.XMLException;
import ooga.data.XMLHelper;
import ooga.data.XMLValidator;
import ooga.data.style.Coordinate;
import ooga.data.style.ICoordinate;
import ooga.data.style.ILayout;
import ooga.data.style.Layout;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This LayoutFactory implements Factory and constructs an ILayout using the createLayout() method.
* This ILayout is used to store information about where cells should be located and how they should
* be drawn for a particular game.
*
* @author Andrew Krier, Tyler Jang
*/
public class LayoutFactory implements Factory {
private static String LAYOUT_TYPE = ILayout.DATA_TYPE;
private static String INVALID_ERROR = "INVALID_FILE";
private static final String LAYOUT_XSD = "src/ooga/data/factories/schemas/layout_schema.xsd";
private static final String KEY_CARD = "Card";
private static final String KEY_CARDS = "Cards";
private static final String KEY_CELL = "Cell";
private static final String KEY_CELLS = "Cells";
private static final String KEY_NAME = "Name";
private static final String KEY_X = "X";
private static final String KEY_Y = "Y";
private static final String KEY_START = "Start";
private static final String KEY_EXTENSION = "Extension";
private static final String COMMA = ",";
private static final String RESOURCES = "ooga.resources";
private static final String RESOURCE_PACKAGE = RESOURCES + "." + "layout_word";
private static final String RESOURCE_COORD_PACKAGE = RESOURCES + "." + "layout_coord";
private static final String RESOURCE_MAP_PACKAGE = RESOURCES + "." + "layout_deck";
private static final ResourceBundle layoutResources = ResourceBundle.getBundle(RESOURCE_PACKAGE);
private static final ResourceBundle coordResources = ResourceBundle
.getBundle(RESOURCE_COORD_PACKAGE);
private static final ResourceBundle mapResources = ResourceBundle.getBundle(RESOURCE_MAP_PACKAGE);
private LayoutFactory() {
}
/**
* Builds and returns an ILayout from a layout XML file. Requirements for layout XML can be found
* in doc/XML_Documentation.md.
*
* @param dataFile the file from which to build an ILayout implementation
* @return an ILayout implementation built from the layout XML
*/
public static ILayout createLayout(File dataFile) {
if (XMLValidator.validateXMLSchema(LAYOUT_XSD, dataFile.getPath())) {
try {
Element root = XMLHelper.getRootAndCheck(dataFile, LAYOUT_TYPE, INVALID_ERROR);
if (!root.hasChildNodes()) {
throw new XMLException(Factory.MISSING_ERROR + COMMA + LAYOUT_TYPE); // Very bad
}
Map<String, Integer> numberSettings = XMLHelper.readNumberSettings(root, layoutResources);
Map<String, ICoordinate> coordMap = coordinateMap(root);
Map<String, String> cardMap = cardMap(root);
return new Layout(coordMap, numberSettings, cardMap);
} catch (Exception e) {
throw new XMLException(e, Factory.MISSING_ERROR + COMMA + LAYOUT_TYPE);
}
} else {
throw new XMLException(Factory.INVALID_ERROR);
}
}
private static Map<String, ICoordinate> coordinateMap(Element root) {
Node cells = root.getElementsByTagName(coordResources.getString(KEY_CELLS)).item(0);
NodeList cellList = ((Element) cells).getElementsByTagName(coordResources.getString(KEY_CELL));
Map<String, ICoordinate> coordMap = new HashMap<>();
for (int k = 0; k < cellList.getLength(); k++) {
Element n = (Element) cellList.item(k);
String cellName = XMLHelper.getAttribute(n, coordResources.getString(KEY_NAME));
NodeList coordinate = n.getChildNodes();
Node x = XMLHelper.getNodeByName(coordinate, coordResources.getString(KEY_X));
Node y = XMLHelper.getNodeByName(coordinate, coordResources.getString(KEY_Y));
ICoordinate coord = new Coordinate(Double.parseDouble(x.getTextContent()),
Double.parseDouble(y.getTextContent()));
coordMap.put(cellName, coord);
}
return coordMap;
}
private static Map<String, String> cardMap(Element root) {
Node beginning = root.getElementsByTagName(mapResources.getString(KEY_START)).item(0);
Node ending = root.getElementsByTagName(mapResources.getString(KEY_EXTENSION)).item(0);
String intro = beginning.getTextContent();
String outro = ending.getTextContent();
Node deck = root.getElementsByTagName(mapResources.getString(KEY_CARDS)).item(0);
NodeList cardList = ((Element) deck).getElementsByTagName(mapResources.getString(KEY_CARD));
Map<String, String> cardMap = new HashMap<>();
for (int i = 0; i < cardList.getLength(); i++) {
String name = cardList.item(i).getTextContent();
String path = intro + name + outro;
cardMap.put(name, path);
}
return cardMap;
}
}
| UTF-8 | Java | 4,983 | java | LayoutFactory.java | Java | [
{
"context": "d\n * be drawn for a particular game.\n *\n * @author Andrew Krier, Tyler Jang\n */\npublic class LayoutFactory implem",
"end": 705,
"score": 0.9998793601989746,
"start": 693,
"tag": "NAME",
"value": "Andrew Krier"
},
{
"context": "for a particular game.\n *\n * @author Andrew Krier, Tyler Jang\n */\npublic class LayoutFactory implements Factory",
"end": 717,
"score": 0.9998829364776611,
"start": 707,
"tag": "NAME",
"value": "Tyler Jang"
}
] | null | [] | package ooga.data.factories;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import ooga.data.XMLException;
import ooga.data.XMLHelper;
import ooga.data.XMLValidator;
import ooga.data.style.Coordinate;
import ooga.data.style.ICoordinate;
import ooga.data.style.ILayout;
import ooga.data.style.Layout;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This LayoutFactory implements Factory and constructs an ILayout using the createLayout() method.
* This ILayout is used to store information about where cells should be located and how they should
* be drawn for a particular game.
*
* @author <NAME>, <NAME>
*/
public class LayoutFactory implements Factory {
private static String LAYOUT_TYPE = ILayout.DATA_TYPE;
private static String INVALID_ERROR = "INVALID_FILE";
private static final String LAYOUT_XSD = "src/ooga/data/factories/schemas/layout_schema.xsd";
private static final String KEY_CARD = "Card";
private static final String KEY_CARDS = "Cards";
private static final String KEY_CELL = "Cell";
private static final String KEY_CELLS = "Cells";
private static final String KEY_NAME = "Name";
private static final String KEY_X = "X";
private static final String KEY_Y = "Y";
private static final String KEY_START = "Start";
private static final String KEY_EXTENSION = "Extension";
private static final String COMMA = ",";
private static final String RESOURCES = "ooga.resources";
private static final String RESOURCE_PACKAGE = RESOURCES + "." + "layout_word";
private static final String RESOURCE_COORD_PACKAGE = RESOURCES + "." + "layout_coord";
private static final String RESOURCE_MAP_PACKAGE = RESOURCES + "." + "layout_deck";
private static final ResourceBundle layoutResources = ResourceBundle.getBundle(RESOURCE_PACKAGE);
private static final ResourceBundle coordResources = ResourceBundle
.getBundle(RESOURCE_COORD_PACKAGE);
private static final ResourceBundle mapResources = ResourceBundle.getBundle(RESOURCE_MAP_PACKAGE);
private LayoutFactory() {
}
/**
* Builds and returns an ILayout from a layout XML file. Requirements for layout XML can be found
* in doc/XML_Documentation.md.
*
* @param dataFile the file from which to build an ILayout implementation
* @return an ILayout implementation built from the layout XML
*/
public static ILayout createLayout(File dataFile) {
if (XMLValidator.validateXMLSchema(LAYOUT_XSD, dataFile.getPath())) {
try {
Element root = XMLHelper.getRootAndCheck(dataFile, LAYOUT_TYPE, INVALID_ERROR);
if (!root.hasChildNodes()) {
throw new XMLException(Factory.MISSING_ERROR + COMMA + LAYOUT_TYPE); // Very bad
}
Map<String, Integer> numberSettings = XMLHelper.readNumberSettings(root, layoutResources);
Map<String, ICoordinate> coordMap = coordinateMap(root);
Map<String, String> cardMap = cardMap(root);
return new Layout(coordMap, numberSettings, cardMap);
} catch (Exception e) {
throw new XMLException(e, Factory.MISSING_ERROR + COMMA + LAYOUT_TYPE);
}
} else {
throw new XMLException(Factory.INVALID_ERROR);
}
}
private static Map<String, ICoordinate> coordinateMap(Element root) {
Node cells = root.getElementsByTagName(coordResources.getString(KEY_CELLS)).item(0);
NodeList cellList = ((Element) cells).getElementsByTagName(coordResources.getString(KEY_CELL));
Map<String, ICoordinate> coordMap = new HashMap<>();
for (int k = 0; k < cellList.getLength(); k++) {
Element n = (Element) cellList.item(k);
String cellName = XMLHelper.getAttribute(n, coordResources.getString(KEY_NAME));
NodeList coordinate = n.getChildNodes();
Node x = XMLHelper.getNodeByName(coordinate, coordResources.getString(KEY_X));
Node y = XMLHelper.getNodeByName(coordinate, coordResources.getString(KEY_Y));
ICoordinate coord = new Coordinate(Double.parseDouble(x.getTextContent()),
Double.parseDouble(y.getTextContent()));
coordMap.put(cellName, coord);
}
return coordMap;
}
private static Map<String, String> cardMap(Element root) {
Node beginning = root.getElementsByTagName(mapResources.getString(KEY_START)).item(0);
Node ending = root.getElementsByTagName(mapResources.getString(KEY_EXTENSION)).item(0);
String intro = beginning.getTextContent();
String outro = ending.getTextContent();
Node deck = root.getElementsByTagName(mapResources.getString(KEY_CARDS)).item(0);
NodeList cardList = ((Element) deck).getElementsByTagName(mapResources.getString(KEY_CARD));
Map<String, String> cardMap = new HashMap<>();
for (int i = 0; i < cardList.getLength(); i++) {
String name = cardList.item(i).getTextContent();
String path = intro + name + outro;
cardMap.put(name, path);
}
return cardMap;
}
}
| 4,973 | 0.721052 | 0.719245 | 125 | 38.863998 | 32.286304 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728 | false | false | 2 |
f1ab20cb97445ea5dbfd7637f306d62cf62d1328 | 24,713,241,835,486 | eb7950134c568dde6c2ed036bb1f0773125168ce | /Procesos/src/ejerciciotema2parte2/ejercicio2_10.java | 43cfce371d300145556c8c41b12bab05c85a9418 | [] | no_license | FranLG100/PSP | https://github.com/FranLG100/PSP | 4763a13492f4a53a0ecf25277a165a42dc0828ab | e0b065c960620d4884846998d86b18e3bd21f409 | refs/heads/master | 2020-08-05T18:06:47.699000 | 2020-02-09T22:34:27 | 2020-02-09T22:34:27 | 212,646,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ejerciciotema2parte2;
public class ejercicio2_10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ColaSincronizada cola=new ColaSincronizada();
ProductorSync p=new ProductorSync(cola,1);
ConsumidorSync c=new ConsumidorSync(cola, 1);
ConsumidorSync c2=new ConsumidorSync(cola, 2);
//El productor produce 'Ping' y 'Pong' de forma alterna.
//Un consumidor cogera todos los Ping, y otro, todos los Pong
//Ya que se van turnando
//Cuando hay un Ping en la cola, c lo recoge, el productor produce un Pong
//y c2 lo recoge, el productor vuelve a producir un Ping
//Y asi 50 veces
p.start();
c.start();
c2.start();
}
}
| UTF-8 | Java | 713 | java | ejercicio2_10.java | Java | [] | null | [] | package ejerciciotema2parte2;
public class ejercicio2_10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ColaSincronizada cola=new ColaSincronizada();
ProductorSync p=new ProductorSync(cola,1);
ConsumidorSync c=new ConsumidorSync(cola, 1);
ConsumidorSync c2=new ConsumidorSync(cola, 2);
//El productor produce 'Ping' y 'Pong' de forma alterna.
//Un consumidor cogera todos los Ping, y otro, todos los Pong
//Ya que se van turnando
//Cuando hay un Ping en la cola, c lo recoge, el productor produce un Pong
//y c2 lo recoge, el productor vuelve a producir un Ping
//Y asi 50 veces
p.start();
c.start();
c2.start();
}
}
| 713 | 0.68864 | 0.670407 | 25 | 26.52 | 23.341156 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 2 |
89691f63e626d6799e46f592af6f8883ddd7096f | 31,971,736,591,775 | b9d98bd65c4936659dae1845eafa3cc7b41100b6 | /content/manual/source/development/testing_5.java | 9a7dbafcec23bc7e1174e8e9a8f7eeb80adb194c | [
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | permissive | kil0bait/documentation | https://github.com/kil0bait/documentation | 2341c2c72d649a97a54b646b9b70301e8906614f | 6d57743583df7b2112ea4a518e3481c75b12c7f4 | refs/heads/master | 2020-05-22T12:26:14.711000 | 2019-05-07T07:32:54 | 2019-05-07T07:32:54 | 186,337,838 | 0 | 0 | CC-BY-4.0 | true | 2019-05-13T03:17:42 | 2019-05-13T03:17:41 | 2019-05-07T07:33:14 | 2019-05-07T07:33:13 | 60,363 | 0 | 0 | 0 | null | false | false | public class CustomerLoadTest {
@ClassRule
public static SalesTestContainer cont = SalesTestContainer.Common.INSTANCE;
private Customer customer;
@Before
public void setUp() throws Exception {
customer = cont.persistence().createTransaction().execute(em -> {
Customer customer = cont.metadata().create(Customer.class);
customer.setName("testCustomer");
em.persist(customer);
return customer;
});
}
@After
public void tearDown() throws Exception {
cont.deleteRecord(customer);
}
@Test
public void test() {
try (Transaction tx = cont.persistence().createTransaction()) {
EntityManager em = cont.persistence().getEntityManager();
TypedQuery<Customer> query = em.createQuery(
"select c from sales$Customer c", Customer.class);
List<Customer> list = query.getResultList();
tx.commit();
assertTrue(list.size() > 0);
}
}
}
| UTF-8 | Java | 1,034 | java | testing_5.java | Java | [
{
"context": "te(Customer.class);\n customer.setName(\"testCustomer\");\n em.persist(customer);\n ",
"end": 404,
"score": 0.9991655945777893,
"start": 392,
"tag": "USERNAME",
"value": "testCustomer"
}
] | null | [] | public class CustomerLoadTest {
@ClassRule
public static SalesTestContainer cont = SalesTestContainer.Common.INSTANCE;
private Customer customer;
@Before
public void setUp() throws Exception {
customer = cont.persistence().createTransaction().execute(em -> {
Customer customer = cont.metadata().create(Customer.class);
customer.setName("testCustomer");
em.persist(customer);
return customer;
});
}
@After
public void tearDown() throws Exception {
cont.deleteRecord(customer);
}
@Test
public void test() {
try (Transaction tx = cont.persistence().createTransaction()) {
EntityManager em = cont.persistence().getEntityManager();
TypedQuery<Customer> query = em.createQuery(
"select c from sales$Customer c", Customer.class);
List<Customer> list = query.getResultList();
tx.commit();
assertTrue(list.size() > 0);
}
}
}
| 1,034 | 0.603482 | 0.602515 | 34 | 29.382353 | 25.472033 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 2 |
06b2a829ed77f6c194a3cae22aa73dbd749e41ef | 2,147,483,710,559 | a97f00c47a5eaca13b2301df683f55f1201a392b | /Record.java | bf88ca95bfa957a198034d88055afea5dff9b994 | [] | no_license | matt4885/COP4710-Data-Modeling-Project | https://github.com/matt4885/COP4710-Data-Modeling-Project | 93bcf5020e789b38585ca766874d14245babb6d7 | 722ce928ddff3b953447ffbf1103b2c433531325 | refs/heads/master | 2021-01-21T13:41:39.478000 | 2016-04-25T16:14:00 | 2016-04-25T16:14:00 | 54,659,785 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Record {
Date record_date;
List<Cell> listofCells = new ArrayList<>();
// record constructor
Record() {
this.record_date = (new Date());
} //Record Constructor
// constructor for loading database records
Record(Date date, List<Cell> tuples) {
record_date = date;
listofCells = tuples;
} //Record constructor
// toString
public String toString() {
if (this.listofCells.size() == 0)
return "";
else {
// enumerate through all items of the record, display them
String out = "";
for (int i = 0; i < this.listofCells.size(); i++) {
if (i != 0)
out += ", ";
out += this.listofCells.get(i);
}
return out;
} //else
}
} | UTF-8 | Java | 910 | java | Record.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Record {
Date record_date;
List<Cell> listofCells = new ArrayList<>();
// record constructor
Record() {
this.record_date = (new Date());
} //Record Constructor
// constructor for loading database records
Record(Date date, List<Cell> tuples) {
record_date = date;
listofCells = tuples;
} //Record constructor
// toString
public String toString() {
if (this.listofCells.size() == 0)
return "";
else {
// enumerate through all items of the record, display them
String out = "";
for (int i = 0; i < this.listofCells.size(); i++) {
if (i != 0)
out += ", ";
out += this.listofCells.get(i);
}
return out;
} //else
}
} | 910 | 0.520879 | 0.517582 | 35 | 25.028572 | 16.915733 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false | 2 |
f32194a28321df7c82f3fed4b095017100c09a31 | 18,760,417,178,399 | f2da1b8c633ead704c6801014b4f1bc57d85e0af | /src/main/java/com/kzhukov/rps/game/Move.java | 51a0afc3dc086b1b942402dc31c6e6cdbd91cdca | [] | no_license | nanotexnik/rockPaperScissors | https://github.com/nanotexnik/rockPaperScissors | 793e53f834916f508c4be7080edad154688fa205 | 51ba6075c04216adcd17a30121561e5fd79905bb | refs/heads/master | 2020-08-07T11:16:54.900000 | 2019-10-09T06:11:36 | 2019-10-09T06:11:36 | 213,428,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kzhukov.rps.game;
public enum Move {
ROCK,
PAPER,
SCISSORS;
static {
ROCK.loseTo = PAPER;
PAPER.loseTo = SCISSORS;
SCISSORS.loseTo = ROCK;
}
private Move loseTo;
public boolean isLoseTo(Move move) {
return this.loseTo.equals(move);
}
public Move getLoseTo() {
return this.loseTo;
}
}
| UTF-8 | Java | 381 | java | Move.java | Java | [] | null | [] | package com.kzhukov.rps.game;
public enum Move {
ROCK,
PAPER,
SCISSORS;
static {
ROCK.loseTo = PAPER;
PAPER.loseTo = SCISSORS;
SCISSORS.loseTo = ROCK;
}
private Move loseTo;
public boolean isLoseTo(Move move) {
return this.loseTo.equals(move);
}
public Move getLoseTo() {
return this.loseTo;
}
}
| 381 | 0.577428 | 0.577428 | 23 | 15.565217 | 13.637628 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 2 |
a348bab97f2321b9696339a675da6c2eac1f0042 | 678,604,853,231 | 6b3d4f54aa83cc457a15937e00e844063df26285 | /app/src/main/java/com/optimalorange/cooltechnologies/ui/viewholder/RecyclerEmptyViewHolder.java | e36ea3d1919813f6a261ef48e881c51675e58039 | [
"Apache-2.0"
] | permissive | treejames/CoolTechnologies | https://github.com/treejames/CoolTechnologies | 61cecb3c6ead8c06028304474159550c88b34d84 | 007cc90654cede33f86e3fde6bef8f721e2fc9ea | refs/heads/master | 2017-05-31T23:27:50.001000 | 2015-12-16T03:56:39 | 2015-12-16T03:56:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.optimalorange.cooltechnologies.ui.viewholder;
import com.optimalorange.cooltechnologies.R;
import com.optimalorange.cooltechnologies.ui.entity.Empty;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RecyclerEmptyViewHolder extends RecyclerView.ViewHolder {
public final TextView hint;
public RecyclerEmptyViewHolder(View itemView) {
super(itemView);
hint = (TextView) itemView.findViewById(R.id.hint);
}
public static class Factory extends BaseVHFactory<Empty, RecyclerEmptyViewHolder> {
@Override
public Class<Empty> forClass() {
return Empty.class;
}
@Override
public RecyclerEmptyViewHolder createViewHolder(
LayoutInflater inflater, ViewGroup parent) {
return new RecyclerEmptyViewHolder(
inflater.inflate(R.layout.recycler_empty, parent, false));
}
@Override
public void bindViewHolder(RecyclerEmptyViewHolder holder, Empty value, int position) {
holder.hint.setText(value.hint);
}
}
}
| UTF-8 | Java | 1,230 | java | RecyclerEmptyViewHolder.java | Java | [] | null | [] | package com.optimalorange.cooltechnologies.ui.viewholder;
import com.optimalorange.cooltechnologies.R;
import com.optimalorange.cooltechnologies.ui.entity.Empty;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RecyclerEmptyViewHolder extends RecyclerView.ViewHolder {
public final TextView hint;
public RecyclerEmptyViewHolder(View itemView) {
super(itemView);
hint = (TextView) itemView.findViewById(R.id.hint);
}
public static class Factory extends BaseVHFactory<Empty, RecyclerEmptyViewHolder> {
@Override
public Class<Empty> forClass() {
return Empty.class;
}
@Override
public RecyclerEmptyViewHolder createViewHolder(
LayoutInflater inflater, ViewGroup parent) {
return new RecyclerEmptyViewHolder(
inflater.inflate(R.layout.recycler_empty, parent, false));
}
@Override
public void bindViewHolder(RecyclerEmptyViewHolder holder, Empty value, int position) {
holder.hint.setText(value.hint);
}
}
}
| 1,230 | 0.7 | 0.699187 | 42 | 28.285715 | 26.979961 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 2 |
424f17d4db0fb0ecded389a4fe015e57ca5f5b65 | 30,039,001,331,715 | c69c8312c2cc89bf7747c1393530e37aeb1d9d86 | /Materials/Lab/Lab3/src/hero/EquipItemFailedException.java | b4f02964d8c228e9e4f389671539467045210145 | [] | no_license | chayapat09/Prog_Meth | https://github.com/chayapat09/Prog_Meth | 8f2f28e390dd1f6186732395a7035b4faa73540c | ea2e0dbeb68ab7766929dc7efea0b78f7140a48d | refs/heads/master | 2020-08-02T19:38:53.189000 | 2019-10-29T18:19:30 | 2019-10-29T18:19:30 | 211,482,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hero;
// you CAN modify the first line
public class EquipItemFailedException {
// you CAN add SerialVersionID if eclipse gives you warning
}
| UTF-8 | Java | 153 | java | EquipItemFailedException.java | Java | [] | null | [] | package hero;
// you CAN modify the first line
public class EquipItemFailedException {
// you CAN add SerialVersionID if eclipse gives you warning
}
| 153 | 0.771242 | 0.771242 | 7 | 20.857143 | 21.61632 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 2 |
3080aa36cdb25754556539c982ed44519288d004 | 10,797,547,817,324 | 445c852c1247486767c63b1a743d520268b99605 | /src/edu/gvsu/cis350/checkers/Move.java | 56a3a2e316271c9f02ce92108f19cc3505ef4e6d | [] | no_license | JakeYoung187/Checkers | https://github.com/JakeYoung187/Checkers | c3c51a0156dcde8a042f5eb998b8815b33477933 | 4bae60616a7b72fb2a12405fdf3baba55b47ec9a | refs/heads/master | 2021-01-11T00:02:06.572000 | 2016-10-18T04:13:06 | 2016-10-18T04:13:06 | 70,742,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.gvsu.cis350.checkers;
/********************************************************************
* Move constructs the movement of pieces from starting point to end.
*
* @author Nate Benson, Kaye Suarez, Jake Young
* @version 1.0
********************************************************************/
public class Move {
/** start and end position of piece. */
public int fromRow, fromColumn, toRow, toColumn;
/*********************************************************
* Move constructs move based from start and end position.
* @param fromRow start row
* @param fromColumn start column
* @param toRow end row
* @param toColumn end column
*********************************************************/
public Move(final int fromRow, final int fromColumn,
final int toRow, final int toColumn) {
this.fromRow = fromRow;
this.fromColumn = fromColumn;
this.toRow = toRow;
this.toColumn = toColumn;
}
}
| UTF-8 | Java | 975 | java | Move.java | Java | [
{
"context": "ieces from starting point to end.\r\n * \r\n * @author Nate Benson, Kaye Suarez, Jake Young\r\n * @version 1.0 \r\n ****",
"end": 208,
"score": 0.9998270869255066,
"start": 197,
"tag": "NAME",
"value": "Nate Benson"
},
{
"context": "arting point to end.\r\n * \r\n * @author Nate Benson, Kaye Suarez, Jake Young\r\n * @version 1.0 \r\n *****************",
"end": 221,
"score": 0.9998646378517151,
"start": 210,
"tag": "NAME",
"value": "Kaye Suarez"
},
{
"context": "to end.\r\n * \r\n * @author Nate Benson, Kaye Suarez, Jake Young\r\n * @version 1.0 \r\n *****************************",
"end": 233,
"score": 0.9998542070388794,
"start": 223,
"tag": "NAME",
"value": "Jake Young"
}
] | null | [] | package edu.gvsu.cis350.checkers;
/********************************************************************
* Move constructs the movement of pieces from starting point to end.
*
* @author <NAME>, <NAME>, <NAME>
* @version 1.0
********************************************************************/
public class Move {
/** start and end position of piece. */
public int fromRow, fromColumn, toRow, toColumn;
/*********************************************************
* Move constructs move based from start and end position.
* @param fromRow start row
* @param fromColumn start column
* @param toRow end row
* @param toColumn end column
*********************************************************/
public Move(final int fromRow, final int fromColumn,
final int toRow, final int toColumn) {
this.fromRow = fromRow;
this.fromColumn = fromColumn;
this.toRow = toRow;
this.toColumn = toColumn;
}
}
| 961 | 0.497436 | 0.492308 | 30 | 30.5 | 23.006884 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false | 2 |
250f1b5166903eae5bc6fbeb3eda88cae2291a13 | 10,797,547,817,112 | 61551be55d8c6e774da26814770e0da865b79a06 | /设计模式与设计原则/DesignModel/Mediator/Mediator2/ConcreteColleague1.java | 37dbb9f942a2666633ac9603e33bd4358147d51c | [] | no_license | 1317061006/C | https://github.com/1317061006/C | 99326a3977db22acfbef6bf4b012369c9a34fb28 | 9b132e33110364c10568c75d5fe095737b5f1459 | refs/heads/master | 2021-01-11T04:59:39.424000 | 2019-02-03T05:59:27 | 2019-02-03T05:59:27 | 71,909,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DesignMode.DesignModel.Mediator.Mediator2;
/**
* Created by han on 2017/2/26.
*/
public class ConcreteColleague1 extends Colleague {
//通过构造函数传入中介者
public ConcreteColleague1(Mediator _mediator) {
super(_mediator);
}
//自有方法 selfMethod
public void selfMethod(){
//处理自己的业务逻辑
}
//依赖方法 depMethod
public void depMethod1() {
//处理自己的业务逻辑
super.mediator.doSomething1();
}
}
| UTF-8 | Java | 519 | java | ConcreteColleague1.java | Java | [
{
"context": "DesignModel.Mediator.Mediator2;\n\n/**\n * Created by han on 2017/2/26.\n */\npublic class ConcreteColleague1",
"end": 73,
"score": 0.9844943881034851,
"start": 70,
"tag": "USERNAME",
"value": "han"
}
] | null | [] | package DesignMode.DesignModel.Mediator.Mediator2;
/**
* Created by han on 2017/2/26.
*/
public class ConcreteColleague1 extends Colleague {
//通过构造函数传入中介者
public ConcreteColleague1(Mediator _mediator) {
super(_mediator);
}
//自有方法 selfMethod
public void selfMethod(){
//处理自己的业务逻辑
}
//依赖方法 depMethod
public void depMethod1() {
//处理自己的业务逻辑
super.mediator.doSomething1();
}
}
| 519 | 0.640449 | 0.613483 | 24 | 17.541666 | 16.938564 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 2 |
1641a28173dfa71176c8db523269eecea7748b9b | 2,224,793,079,567 | c2c4e4baa1dd589dec85a6c472cfafebf617bf43 | /legacy_lib/application/nkr-efinance-app/src/main/java/com/nokor/efinance/gui/ui/panel/contract/user/phone/UserContactPhoneTable.java | 880f2041569764a3b7430c0bd22a8b483e0c6dad | [] | no_license | StevesRoger/legacy-lib | https://github.com/StevesRoger/legacy-lib | 79139eafbc302ffebff279372bba23ffa3cd9751 | d80e3ea3c6d438397e7a8b83f02f674d228ff17a | refs/heads/master | 2020-04-06T21:23:36.084000 | 2018-11-16T02:33:09 | 2018-11-16T02:33:09 | 157,801,685 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nokor.efinance.gui.ui.panel.contract.user.phone;
import java.util.ArrayList;
import java.util.List;
import org.seuksa.frmk.i18n.I18N;
import org.seuksa.frmk.model.entity.Entity;
import org.seuksa.frmk.model.entity.MEntityA;
import org.vaadin.dialogs.ConfirmDialog;
import com.nokor.efinance.core.applicant.model.Individual;
import com.nokor.efinance.core.applicant.model.IndividualContactInfo;
import com.nokor.efinance.core.helper.FinServicesHelper;
import com.nokor.efinance.gui.ui.panel.contract.user.ApplicantIndividualPanel;
import com.nokor.ersys.core.hr.model.address.MBaseAddress;
import com.nokor.ersys.core.hr.model.eref.ETypeContactInfo;
import com.nokor.ersys.core.hr.model.organization.ContactInfo;
import com.nokor.frmk.vaadin.ui.widget.dialog.MessageBox;
import com.nokor.frmk.vaadin.ui.widget.dialog.MessageBox.ButtonType;
import com.nokor.frmk.vaadin.ui.widget.table.ColumnDefinition;
import com.nokor.frmk.vaadin.ui.widget.table.impl.SimpleTable;
import com.nokor.frmk.vaadin.ui.widget.toolbar.NavigationPanel;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.Resource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table.Align;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;
/**
* User contact phone table
* @author uhout.cheng
*/
public class UserContactPhoneTable extends VerticalLayout implements ItemClickListener, ClickListener, FinServicesHelper {
/** */
private static final long serialVersionUID = 6266946435480360095L;
private final static String CONTACTDETAIL = "contact.detail";
private final static String PRIMARY = "primary";
private SimpleTable<Entity> phonesSimpleTable;
private SimpleTable<Entity> otherContactsSimpleTable;
private Button btnAdd;
private Button btnEdit;
private Button btnDelete;
private Item phonesSelectedItem;
private Item otherContactSelectedItem;
private ApplicantIndividualPanel delegate;
private UserContactPhoneForm userContactPhoneForm;
private Individual individual;
private Long selectedId;
private CheckBox cbPrimary;
/**
*
* @param userPanel
*/
public UserContactPhoneTable(ApplicantIndividualPanel delegate) {
this.delegate = delegate;
init();
}
/**
*
* @param icon
* @return
*/
private Button getButton(String caption, Resource icon) {
Button button = new NativeButton(I18N.message(caption));
button.setIcon(icon);
button.addClickListener(this);
return button;
}
/**
*
* @param columnDefinitions
* @return
*/
private SimpleTable<Entity> getSimpleTable(List<ColumnDefinition> columnDefinitions) {
SimpleTable<Entity> simpleTable = new SimpleTable<Entity>(columnDefinitions);
simpleTable.setSizeUndefined();
simpleTable.setPageLength(3);
simpleTable.addItemClickListener(this);
return simpleTable;
}
/**
*
*/
private void init() {
phonesSimpleTable = getSimpleTable(getColumnDefinitions());
otherContactsSimpleTable = getSimpleTable(getColumnDefinitionsOthersContactInfo());
btnAdd = getButton("add", FontAwesome.PLUS);
btnEdit = getButton("edit", FontAwesome.PENCIL);
btnDelete = getButton("delete", FontAwesome.TRASH_O);
userContactPhoneForm = new UserContactPhoneForm();
userContactPhoneForm.getBtnBack().addClickListener(new ClickListener() {
/** */
private static final long serialVersionUID = 6395257387229157270L;
/**
* @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
*/
@Override
public void buttonClick(ClickEvent event) {
individual = INDIVI_SRV.getById(Individual.class, individual.getId());
assignValues(individual);
delegate.getUserContactLayout().removeComponent(userContactPhoneForm);
delegate.setVisibleContactTable(true);
}
});
NavigationPanel navigationPanel = new NavigationPanel();
navigationPanel.setSizeUndefined();
navigationPanel.addButton(btnAdd);
navigationPanel.addButton(btnEdit);
navigationPanel.addButton(btnDelete);
Panel phonesPanel = new Panel(phonesSimpleTable);
phonesPanel.setCaption(I18N.message("phones"));
phonesPanel.setStyleName(Reindeer.PANEL_LIGHT);
Panel otherContactsPanel = new Panel(otherContactsSimpleTable);
otherContactsPanel.setCaption(I18N.message("other.contacts"));
otherContactsPanel.setStyleName(Reindeer.PANEL_LIGHT);
setSpacing(true);
addComponent(navigationPanel);
addComponent(phonesPanel);
addComponent(otherContactsPanel);
}
/**
*
* @return
*/
private List<ColumnDefinition> getColumnDefinitions() {
List<ColumnDefinition> columnDefinitions = new ArrayList<ColumnDefinition>();
columnDefinitions.add(new ColumnDefinition(MEntityA.ID, I18N.message("id"), Long.class, Align.LEFT, 70));
columnDefinitions.add(new ColumnDefinition(MBaseAddress.TYPE, I18N.message("contact.type"), String.class, Align.LEFT, 150));
columnDefinitions.add(new ColumnDefinition(CONTACTDETAIL, I18N.message("contact.detail"), String.class, Align.LEFT, 300));
columnDefinitions.add(new ColumnDefinition(PRIMARY, I18N.message("primary"), CheckBox.class, Align.LEFT, 75));
return columnDefinitions;
}
/**
*
* @return
*/
private List<ColumnDefinition> getColumnDefinitionsOthersContactInfo() {
List<ColumnDefinition> columnDefinitions = new ArrayList<ColumnDefinition>();
columnDefinitions.add(new ColumnDefinition(MEntityA.ID, I18N.message("id"), Long.class, Align.LEFT, 70));
columnDefinitions.add(new ColumnDefinition(MBaseAddress.TYPE, I18N.message("contact.type"), String.class, Align.LEFT, 150));
columnDefinitions.add(new ColumnDefinition(CONTACTDETAIL, I18N.message("contact.detail"), String.class, Align.LEFT, 300));
return columnDefinitions;
}
/**
*
* @param individual
*/
public void assignValues(Individual individual) {
this.individual = individual;
setUserContactPhonesValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
setUserOtherContactsValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
userContactPhoneForm.assignValues(individual);
}
/**
*
* @param individualContactInfos
*/
@SuppressWarnings("unchecked")
public void setUserContactPhonesValueIndexedContainer(List<IndividualContactInfo> individualContactInfos) {
phonesSimpleTable.removeAllItems();
phonesSelectedItem = null;
Container indexedContainer = phonesSimpleTable.getContainerDataSource();
if (!individualContactInfos.isEmpty()) {
for (IndividualContactInfo indConInfo : individualContactInfos) {
ContactInfo contactInfo = INDIVI_SRV.getById(ContactInfo.class, indConInfo.getContactInfo().getId());
cbPrimary = new CheckBox();
cbPrimary.setEnabled(false);
if (contactInfo != null && contactInfo.getId() != null) {
if (ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())
|| ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
cbPrimary.setValue(contactInfo.isPrimary());
Item item = indexedContainer.addItem(contactInfo.getId());
item.getItemProperty(MEntityA.ID).setValue(contactInfo.getId());
item.getItemProperty(MBaseAddress.TYPE).setValue(contactInfo.getTypeInfo() != null ? contactInfo.getTypeInfo().getDescLocale() : "");
item.getItemProperty(CONTACTDETAIL).setValue(getContactDetailByType(contactInfo));
item.getItemProperty(PRIMARY).setValue(cbPrimary);
}
}
}
}
}
/**
*
* @param individualContactInfos
*/
@SuppressWarnings("unchecked")
public void setUserOtherContactsValueIndexedContainer(List<IndividualContactInfo> individualContactInfos) {
otherContactsSimpleTable.removeAllItems();
otherContactSelectedItem = null;
Container indexedContainer = otherContactsSimpleTable.getContainerDataSource();
if (!individualContactInfos.isEmpty()) {
for (IndividualContactInfo indConInfo : individualContactInfos) {
ContactInfo contactInfo = INDIVI_SRV.getById(ContactInfo.class, indConInfo.getContactInfo().getId());
cbPrimary = new CheckBox();
cbPrimary.setEnabled(false);
if (contactInfo != null && contactInfo.getId() != null) {
if (!ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())
&& !ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
cbPrimary.setValue(contactInfo.isPrimary());
Item item = indexedContainer.addItem(contactInfo.getId());
item.getItemProperty(MEntityA.ID).setValue(contactInfo.getId());
item.getItemProperty(MBaseAddress.TYPE).setValue(contactInfo.getTypeInfo() != null ? contactInfo.getTypeInfo().getDescLocale() : "");
item.getItemProperty(CONTACTDETAIL).setValue(contactInfo.getValue());
}
}
}
}
}
/**
*
* @param contactInfo
* @return
*/
private String getContactDetailByType(ContactInfo contactInfo) {
StringBuffer stringBuffer = new StringBuffer();
if (ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())) {
stringBuffer.append(contactInfo.getValue());
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getTypeAddress() != null ? contactInfo.getTypeAddress().getDescLocale() : "");
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getRemark() != null ? contactInfo.getRemark() : "");
} else if (ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
stringBuffer.append(contactInfo.getValue());
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getRemark() != null ? contactInfo.getRemark() : "");
}
return stringBuffer.toString();
}
/**
* @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
*/
@Override
public void buttonClick(ClickEvent event) {
if (event.getButton().equals(btnAdd)) {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.reset();
} else if (event.getButton().equals(btnEdit)) {
if (phonesSelectedItem == null && otherContactSelectedItem == null) {
MessageBox mb = new MessageBox(UI.getCurrent(), "300px", "160px", I18N.message("information"),
MessageBox.Icon.INFO, I18N.message("edit.item.not.selected"), Alignment.MIDDLE_RIGHT,
new MessageBox.ButtonConfig(ButtonType.OK, I18N.message("ok")));
mb.show();
} else {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.removedMessagePanel();
userContactPhoneForm.assignValuesToControls(ENTITY_SRV.getById(ContactInfo.class, selectedId));
}
} else if (event.getButton().equals(btnDelete)) {
if (phonesSelectedItem == null && otherContactSelectedItem == null) {
MessageBox mb = new MessageBox(UI.getCurrent(), "300px", "160px", I18N.message("information"),
MessageBox.Icon.INFO, I18N.message("delete.item.not.selected"), Alignment.MIDDLE_RIGHT,
new MessageBox.ButtonConfig(ButtonType.OK, I18N.message("ok")));
mb.show();
} else {
ConfirmDialog.show(UI.getCurrent(), I18N.message("delete.mgs.single",
new String[] {selectedId.toString()}),
new ConfirmDialog.Listener() {
/** */
private static final long serialVersionUID = -1278300263633872114L;
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
INDIVI_SRV.deleteContactInfo(individual.getId(), selectedId);
getNotificationDesc("item.deleted.successfully");
assignValues(individual);
}
}
});
}
}
}
/**
*
* @param description
* @return
*/
private Notification getNotificationDesc(String description) {
Notification notification = new Notification("", Type.HUMANIZED_MESSAGE);
notification.setDescription(I18N.message(description, new String[]{ selectedId.toString() }));
notification.setDelayMsec(3000);
notification.show(Page.getCurrent());
return notification;
}
/**
* @see com.vaadin.event.ItemClickEvent.ItemClickListener#itemClick(com.vaadin.event.ItemClickEvent)
*/
@Override
public void itemClick(ItemClickEvent event) {
phonesSelectedItem = null;
otherContactSelectedItem = null;
if (phonesSimpleTable == event.getComponent()) {
phonesSelectedItem = event.getItem();
} else {
otherContactSelectedItem = event.getItem();
}
if (phonesSelectedItem != null) {
selectedId = (Long) phonesSelectedItem.getItemProperty(MEntityA.ID).getValue();
setUserOtherContactsValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
} else if (otherContactSelectedItem != null) {
selectedId = (Long) otherContactSelectedItem.getItemProperty(MEntityA.ID).getValue();
setUserContactPhonesValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
}
if (event.isDoubleClick()) {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.assignValuesToControls(ENTITY_SRV.getById(ContactInfo.class, selectedId));
userContactPhoneForm.removedMessagePanel();
}
}
}
| UTF-8 | Java | 13,510 | java | UserContactPhoneTable.java | Java | [
{
"context": "deer;\n\n/**\n * User contact phone table \n * @author uhout.cheng\n */\npublic class UserContactPhoneTable extends Ve",
"end": 1812,
"score": 0.9802036285400391,
"start": 1801,
"tag": "NAME",
"value": "uhout.cheng"
}
] | null | [] | package com.nokor.efinance.gui.ui.panel.contract.user.phone;
import java.util.ArrayList;
import java.util.List;
import org.seuksa.frmk.i18n.I18N;
import org.seuksa.frmk.model.entity.Entity;
import org.seuksa.frmk.model.entity.MEntityA;
import org.vaadin.dialogs.ConfirmDialog;
import com.nokor.efinance.core.applicant.model.Individual;
import com.nokor.efinance.core.applicant.model.IndividualContactInfo;
import com.nokor.efinance.core.helper.FinServicesHelper;
import com.nokor.efinance.gui.ui.panel.contract.user.ApplicantIndividualPanel;
import com.nokor.ersys.core.hr.model.address.MBaseAddress;
import com.nokor.ersys.core.hr.model.eref.ETypeContactInfo;
import com.nokor.ersys.core.hr.model.organization.ContactInfo;
import com.nokor.frmk.vaadin.ui.widget.dialog.MessageBox;
import com.nokor.frmk.vaadin.ui.widget.dialog.MessageBox.ButtonType;
import com.nokor.frmk.vaadin.ui.widget.table.ColumnDefinition;
import com.nokor.frmk.vaadin.ui.widget.table.impl.SimpleTable;
import com.nokor.frmk.vaadin.ui.widget.toolbar.NavigationPanel;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.Resource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table.Align;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;
/**
* User contact phone table
* @author uhout.cheng
*/
public class UserContactPhoneTable extends VerticalLayout implements ItemClickListener, ClickListener, FinServicesHelper {
/** */
private static final long serialVersionUID = 6266946435480360095L;
private final static String CONTACTDETAIL = "contact.detail";
private final static String PRIMARY = "primary";
private SimpleTable<Entity> phonesSimpleTable;
private SimpleTable<Entity> otherContactsSimpleTable;
private Button btnAdd;
private Button btnEdit;
private Button btnDelete;
private Item phonesSelectedItem;
private Item otherContactSelectedItem;
private ApplicantIndividualPanel delegate;
private UserContactPhoneForm userContactPhoneForm;
private Individual individual;
private Long selectedId;
private CheckBox cbPrimary;
/**
*
* @param userPanel
*/
public UserContactPhoneTable(ApplicantIndividualPanel delegate) {
this.delegate = delegate;
init();
}
/**
*
* @param icon
* @return
*/
private Button getButton(String caption, Resource icon) {
Button button = new NativeButton(I18N.message(caption));
button.setIcon(icon);
button.addClickListener(this);
return button;
}
/**
*
* @param columnDefinitions
* @return
*/
private SimpleTable<Entity> getSimpleTable(List<ColumnDefinition> columnDefinitions) {
SimpleTable<Entity> simpleTable = new SimpleTable<Entity>(columnDefinitions);
simpleTable.setSizeUndefined();
simpleTable.setPageLength(3);
simpleTable.addItemClickListener(this);
return simpleTable;
}
/**
*
*/
private void init() {
phonesSimpleTable = getSimpleTable(getColumnDefinitions());
otherContactsSimpleTable = getSimpleTable(getColumnDefinitionsOthersContactInfo());
btnAdd = getButton("add", FontAwesome.PLUS);
btnEdit = getButton("edit", FontAwesome.PENCIL);
btnDelete = getButton("delete", FontAwesome.TRASH_O);
userContactPhoneForm = new UserContactPhoneForm();
userContactPhoneForm.getBtnBack().addClickListener(new ClickListener() {
/** */
private static final long serialVersionUID = 6395257387229157270L;
/**
* @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
*/
@Override
public void buttonClick(ClickEvent event) {
individual = INDIVI_SRV.getById(Individual.class, individual.getId());
assignValues(individual);
delegate.getUserContactLayout().removeComponent(userContactPhoneForm);
delegate.setVisibleContactTable(true);
}
});
NavigationPanel navigationPanel = new NavigationPanel();
navigationPanel.setSizeUndefined();
navigationPanel.addButton(btnAdd);
navigationPanel.addButton(btnEdit);
navigationPanel.addButton(btnDelete);
Panel phonesPanel = new Panel(phonesSimpleTable);
phonesPanel.setCaption(I18N.message("phones"));
phonesPanel.setStyleName(Reindeer.PANEL_LIGHT);
Panel otherContactsPanel = new Panel(otherContactsSimpleTable);
otherContactsPanel.setCaption(I18N.message("other.contacts"));
otherContactsPanel.setStyleName(Reindeer.PANEL_LIGHT);
setSpacing(true);
addComponent(navigationPanel);
addComponent(phonesPanel);
addComponent(otherContactsPanel);
}
/**
*
* @return
*/
private List<ColumnDefinition> getColumnDefinitions() {
List<ColumnDefinition> columnDefinitions = new ArrayList<ColumnDefinition>();
columnDefinitions.add(new ColumnDefinition(MEntityA.ID, I18N.message("id"), Long.class, Align.LEFT, 70));
columnDefinitions.add(new ColumnDefinition(MBaseAddress.TYPE, I18N.message("contact.type"), String.class, Align.LEFT, 150));
columnDefinitions.add(new ColumnDefinition(CONTACTDETAIL, I18N.message("contact.detail"), String.class, Align.LEFT, 300));
columnDefinitions.add(new ColumnDefinition(PRIMARY, I18N.message("primary"), CheckBox.class, Align.LEFT, 75));
return columnDefinitions;
}
/**
*
* @return
*/
private List<ColumnDefinition> getColumnDefinitionsOthersContactInfo() {
List<ColumnDefinition> columnDefinitions = new ArrayList<ColumnDefinition>();
columnDefinitions.add(new ColumnDefinition(MEntityA.ID, I18N.message("id"), Long.class, Align.LEFT, 70));
columnDefinitions.add(new ColumnDefinition(MBaseAddress.TYPE, I18N.message("contact.type"), String.class, Align.LEFT, 150));
columnDefinitions.add(new ColumnDefinition(CONTACTDETAIL, I18N.message("contact.detail"), String.class, Align.LEFT, 300));
return columnDefinitions;
}
/**
*
* @param individual
*/
public void assignValues(Individual individual) {
this.individual = individual;
setUserContactPhonesValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
setUserOtherContactsValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
userContactPhoneForm.assignValues(individual);
}
/**
*
* @param individualContactInfos
*/
@SuppressWarnings("unchecked")
public void setUserContactPhonesValueIndexedContainer(List<IndividualContactInfo> individualContactInfos) {
phonesSimpleTable.removeAllItems();
phonesSelectedItem = null;
Container indexedContainer = phonesSimpleTable.getContainerDataSource();
if (!individualContactInfos.isEmpty()) {
for (IndividualContactInfo indConInfo : individualContactInfos) {
ContactInfo contactInfo = INDIVI_SRV.getById(ContactInfo.class, indConInfo.getContactInfo().getId());
cbPrimary = new CheckBox();
cbPrimary.setEnabled(false);
if (contactInfo != null && contactInfo.getId() != null) {
if (ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())
|| ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
cbPrimary.setValue(contactInfo.isPrimary());
Item item = indexedContainer.addItem(contactInfo.getId());
item.getItemProperty(MEntityA.ID).setValue(contactInfo.getId());
item.getItemProperty(MBaseAddress.TYPE).setValue(contactInfo.getTypeInfo() != null ? contactInfo.getTypeInfo().getDescLocale() : "");
item.getItemProperty(CONTACTDETAIL).setValue(getContactDetailByType(contactInfo));
item.getItemProperty(PRIMARY).setValue(cbPrimary);
}
}
}
}
}
/**
*
* @param individualContactInfos
*/
@SuppressWarnings("unchecked")
public void setUserOtherContactsValueIndexedContainer(List<IndividualContactInfo> individualContactInfos) {
otherContactsSimpleTable.removeAllItems();
otherContactSelectedItem = null;
Container indexedContainer = otherContactsSimpleTable.getContainerDataSource();
if (!individualContactInfos.isEmpty()) {
for (IndividualContactInfo indConInfo : individualContactInfos) {
ContactInfo contactInfo = INDIVI_SRV.getById(ContactInfo.class, indConInfo.getContactInfo().getId());
cbPrimary = new CheckBox();
cbPrimary.setEnabled(false);
if (contactInfo != null && contactInfo.getId() != null) {
if (!ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())
&& !ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
cbPrimary.setValue(contactInfo.isPrimary());
Item item = indexedContainer.addItem(contactInfo.getId());
item.getItemProperty(MEntityA.ID).setValue(contactInfo.getId());
item.getItemProperty(MBaseAddress.TYPE).setValue(contactInfo.getTypeInfo() != null ? contactInfo.getTypeInfo().getDescLocale() : "");
item.getItemProperty(CONTACTDETAIL).setValue(contactInfo.getValue());
}
}
}
}
}
/**
*
* @param contactInfo
* @return
*/
private String getContactDetailByType(ContactInfo contactInfo) {
StringBuffer stringBuffer = new StringBuffer();
if (ETypeContactInfo.LANDLINE.equals(contactInfo.getTypeInfo())) {
stringBuffer.append(contactInfo.getValue());
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getTypeAddress() != null ? contactInfo.getTypeAddress().getDescLocale() : "");
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getRemark() != null ? contactInfo.getRemark() : "");
} else if (ETypeContactInfo.MOBILE.equals(contactInfo.getTypeInfo())) {
stringBuffer.append(contactInfo.getValue());
stringBuffer.append(" | ");
stringBuffer.append(contactInfo.getRemark() != null ? contactInfo.getRemark() : "");
}
return stringBuffer.toString();
}
/**
* @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
*/
@Override
public void buttonClick(ClickEvent event) {
if (event.getButton().equals(btnAdd)) {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.reset();
} else if (event.getButton().equals(btnEdit)) {
if (phonesSelectedItem == null && otherContactSelectedItem == null) {
MessageBox mb = new MessageBox(UI.getCurrent(), "300px", "160px", I18N.message("information"),
MessageBox.Icon.INFO, I18N.message("edit.item.not.selected"), Alignment.MIDDLE_RIGHT,
new MessageBox.ButtonConfig(ButtonType.OK, I18N.message("ok")));
mb.show();
} else {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.removedMessagePanel();
userContactPhoneForm.assignValuesToControls(ENTITY_SRV.getById(ContactInfo.class, selectedId));
}
} else if (event.getButton().equals(btnDelete)) {
if (phonesSelectedItem == null && otherContactSelectedItem == null) {
MessageBox mb = new MessageBox(UI.getCurrent(), "300px", "160px", I18N.message("information"),
MessageBox.Icon.INFO, I18N.message("delete.item.not.selected"), Alignment.MIDDLE_RIGHT,
new MessageBox.ButtonConfig(ButtonType.OK, I18N.message("ok")));
mb.show();
} else {
ConfirmDialog.show(UI.getCurrent(), I18N.message("delete.mgs.single",
new String[] {selectedId.toString()}),
new ConfirmDialog.Listener() {
/** */
private static final long serialVersionUID = -1278300263633872114L;
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
INDIVI_SRV.deleteContactInfo(individual.getId(), selectedId);
getNotificationDesc("item.deleted.successfully");
assignValues(individual);
}
}
});
}
}
}
/**
*
* @param description
* @return
*/
private Notification getNotificationDesc(String description) {
Notification notification = new Notification("", Type.HUMANIZED_MESSAGE);
notification.setDescription(I18N.message(description, new String[]{ selectedId.toString() }));
notification.setDelayMsec(3000);
notification.show(Page.getCurrent());
return notification;
}
/**
* @see com.vaadin.event.ItemClickEvent.ItemClickListener#itemClick(com.vaadin.event.ItemClickEvent)
*/
@Override
public void itemClick(ItemClickEvent event) {
phonesSelectedItem = null;
otherContactSelectedItem = null;
if (phonesSimpleTable == event.getComponent()) {
phonesSelectedItem = event.getItem();
} else {
otherContactSelectedItem = event.getItem();
}
if (phonesSelectedItem != null) {
selectedId = (Long) phonesSelectedItem.getItemProperty(MEntityA.ID).getValue();
setUserOtherContactsValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
} else if (otherContactSelectedItem != null) {
selectedId = (Long) otherContactSelectedItem.getItemProperty(MEntityA.ID).getValue();
setUserContactPhonesValueIndexedContainer(INDIVI_SRV.getIndividualContactInfos(individual.getId()));
}
if (event.isDoubleClick()) {
delegate.setVisibleContactTable(false);
delegate.getUserContactLayout().addComponent(userContactPhoneForm);
userContactPhoneForm.assignValuesToControls(ENTITY_SRV.getById(ContactInfo.class, selectedId));
userContactPhoneForm.removedMessagePanel();
}
}
}
| 13,510 | 0.757513 | 0.747742 | 352 | 37.38068 | 32.610783 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.644886 | false | false | 2 |
adcdbf7d9c56f470895df7ce043b5d1f0f8cdd12 | 22,840,636,104,730 | 8c14555541e3425d0d220cbead52f719084a2dc4 | /loja/Administrativo.java | 3152cd5d303a46bac8a7b5faa2f9902848fa621c | [] | no_license | Darkisda/PooHomeWorks | https://github.com/Darkisda/PooHomeWorks | 5d1d9f3ff6dbb230a34fbc62d666682424255203 | 195999979462084ab3c724140db353c5057a3fd0 | refs/heads/master | 2020-08-13T17:52:06.654000 | 2019-10-14T17:45:47 | 2019-10-14T17:45:47 | 215,011,242 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package loja;
/**
*
* @author Aluno
*/
public class Administrativo extends Funcionario{
private double horas;
public Administrativo(int matricula, double salario, String nome, String cpf) {
super(matricula, salario, nome, cpf);
}
public double getHoras() {
return horas;
}
public void setHoras(double horas) {
this.horas += horas;
}
@Override
public String toString() {
return "\nNome: "+getNome()+"\tCPF: "+ getCpf()+"\nSalário: R$"+getSalario()+"\tHoras: "+getHoras();
}
@Override
public double calcPagamento(){
setSalario(getSalario() + ((getSalario()*0.01)*horas));
return getSalario();
}
}
| UTF-8 | Java | 749 | java | Administrativo.java | Java | [
{
"context": "\r\npackage loja;\r\n\r\n/**\r\n *\r\n * @author Aluno\r\n */\r\npublic class Administrativo extends Funcion",
"end": 44,
"score": 0.9995220899581909,
"start": 39,
"tag": "NAME",
"value": "Aluno"
}
] | null | [] |
package loja;
/**
*
* @author Aluno
*/
public class Administrativo extends Funcionario{
private double horas;
public Administrativo(int matricula, double salario, String nome, String cpf) {
super(matricula, salario, nome, cpf);
}
public double getHoras() {
return horas;
}
public void setHoras(double horas) {
this.horas += horas;
}
@Override
public String toString() {
return "\nNome: "+getNome()+"\tCPF: "+ getCpf()+"\nSalário: R$"+getSalario()+"\tHoras: "+getHoras();
}
@Override
public double calcPagamento(){
setSalario(getSalario() + ((getSalario()*0.01)*horas));
return getSalario();
}
}
| 749 | 0.568182 | 0.564171 | 33 | 20.60606 | 25.209352 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false | 2 |
ffda28e349f79e595b52e90b236c9458c21df0b5 | 33,741,263,101,241 | 6529fda2d8a97bb243228a8577def82afb2d1db0 | /app/src/main/java/com/example/dima/bsofttask/ui/adapter/ListImageAdapter.java | 80ba3e71503b0fc8b12e5018bce5fe02dbc2fa8c | [] | no_license | snuyp/ImageController | https://github.com/snuyp/ImageController | 6433d05f4bd48722c92268740e3d406d67de56c8 | f3196eeb49a77285a25e1807bf607855f391466f | refs/heads/master | 2020-03-19T07:41:20.990000 | 2018-06-06T11:09:55 | 2018-06-06T11:09:55 | 136,139,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.dima.bsofttask.ui.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.dima.bsofttask.R;
import com.example.dima.bsofttask.common.Common;
import com.example.dima.bsofttask.common.ItemClickListener;
import com.example.dima.bsofttask.mvp.model.Image;
import com.example.dima.bsofttask.mvp.model.ListImages;
import com.example.dima.bsofttask.remote.Service;
import com.example.dima.bsofttask.ui.InfoActivity;
import com.example.dima.bsofttask.ui.fragment.PhotoFragment;
import com.google.gson.JsonObject;
import java.util.List;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
ItemClickListener itemClickListener;
TextView title;
ImageView image;
public ItemViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_photo_name);
image = itemView.findViewById(R.id.image);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), false);
}
@Override
public boolean onLongClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), true);
return true;
}
}
public class ListImageAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private Context context;
private List<Image> listImage;
public ListImageAdapter(Context context, List<Image> listImage) {
this.listImage = listImage;
this.context = context;
notifyDataSetChanged();
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.photo_card_layout, parent, false);
return new ItemViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull final ItemViewHolder holder, int position) {
holder.title.setText(listImage.get(position).getDateFormat());
Glide.with(holder.itemView)
.load(listImage.get(position).getUrl())
.apply(new RequestOptions()
.placeholder(R.drawable.ic_terrain_black_24dp))
.into(holder.image);
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
if (!isLongClick) {
Intent intent = new Intent(context, InfoActivity.class);
intent.putExtra("image", listImage.get(position));
context.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.sure_delete)
.setCancelable(true)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int idImage = listImage.get(holder.getAdapterPosition()).getId();
deletePosition(idImage, 0, holder);//потом подправить
dialog.cancel();
}
})
.setNegativeButton(R.string.return_dialog,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
}
@Override
public int getItemCount() {
return listImage.size();
}
private void deletePosition(int id, int page, final ItemViewHolder holder) {
Service service = Common.getRetrofitService();
service.deleteImage(Common.token, id, page).enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()) {
Toasty.info(context, "Delete").show();
listImage.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
notifyItemRangeChanged(holder.getAdapterPosition(), listImage.size());
} else {
Toasty.error(context, response.errorBody().toString()).show();
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Toasty.error(context, t.getMessage()).show();
}
});
}
} | UTF-8 | Java | 5,917 | java | ListImageAdapter.java | Java | [] | null | [] | package com.example.dima.bsofttask.ui.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.dima.bsofttask.R;
import com.example.dima.bsofttask.common.Common;
import com.example.dima.bsofttask.common.ItemClickListener;
import com.example.dima.bsofttask.mvp.model.Image;
import com.example.dima.bsofttask.mvp.model.ListImages;
import com.example.dima.bsofttask.remote.Service;
import com.example.dima.bsofttask.ui.InfoActivity;
import com.example.dima.bsofttask.ui.fragment.PhotoFragment;
import com.google.gson.JsonObject;
import java.util.List;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
ItemClickListener itemClickListener;
TextView title;
ImageView image;
public ItemViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_photo_name);
image = itemView.findViewById(R.id.image);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), false);
}
@Override
public boolean onLongClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), true);
return true;
}
}
public class ListImageAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private Context context;
private List<Image> listImage;
public ListImageAdapter(Context context, List<Image> listImage) {
this.listImage = listImage;
this.context = context;
notifyDataSetChanged();
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.photo_card_layout, parent, false);
return new ItemViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull final ItemViewHolder holder, int position) {
holder.title.setText(listImage.get(position).getDateFormat());
Glide.with(holder.itemView)
.load(listImage.get(position).getUrl())
.apply(new RequestOptions()
.placeholder(R.drawable.ic_terrain_black_24dp))
.into(holder.image);
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
if (!isLongClick) {
Intent intent = new Intent(context, InfoActivity.class);
intent.putExtra("image", listImage.get(position));
context.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.sure_delete)
.setCancelable(true)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int idImage = listImage.get(holder.getAdapterPosition()).getId();
deletePosition(idImage, 0, holder);//потом подправить
dialog.cancel();
}
})
.setNegativeButton(R.string.return_dialog,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
}
@Override
public int getItemCount() {
return listImage.size();
}
private void deletePosition(int id, int page, final ItemViewHolder holder) {
Service service = Common.getRetrofitService();
service.deleteImage(Common.token, id, page).enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()) {
Toasty.info(context, "Delete").show();
listImage.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
notifyItemRangeChanged(holder.getAdapterPosition(), listImage.size());
} else {
Toasty.error(context, response.errorBody().toString()).show();
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Toasty.error(context, t.getMessage()).show();
}
});
}
} | 5,917 | 0.610979 | 0.609624 | 155 | 37.08387 | 28.435995 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.658065 | false | false | 2 |
00c498266daa651c44af1493b681c7bc49925c46 | 7,310,034,346,081 | 91b92c03fef2b52382b34af2adbe6d176b89005c | /Project/src/Player.java | cd342f0e3658bca75e1f58d2d3d0926c92978bdc | [] | no_license | RohanGupta24/FoilMaker-Part-2 | https://github.com/RohanGupta24/FoilMaker-Part-2 | 97131f4eb826258d4db38c364bada8a1b3ebc1a6 | a8b85b4a0769082619361e3e9501762cbf4a8118 | refs/heads/master | 2021-03-22T04:43:14.576000 | 2016-12-05T21:39:54 | 2016-12-05T21:39:54 | 73,669,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.net.Socket;
public class Player {
private String username;
private String userToken;
private String gameToken;
private String password;
private int cumulativeScore;
private int fooled;
private int fooled_by;
private String suggestion;
private String choice;
private boolean loggedInAndPlaying;
private int port;
private String message;
private int wordOn;
public Player(String username, String password) {
this.username = username;
this.password = password;
}
/*public Player(String username, String userToken, String gameToken, String password, int cumulativeScore, int fooled, int fooled_by,
String suggestion, String choice, boolean loggedInAndPlaying, int port, String message,int wordOn) {
this.username = username;
this.userToken = userToken;
this.password = password;
this.cumulativeScore = cumulativeScore;
this.fooled = fooled;
this.fooled_by = fooled_by;
this.suggestion = null;
this.choice = choice;
this.loggedInAndPlaying = false;
this.gameToken = gameToken;
this.port = port;
this.message = "Hello";
this.wordOn = 0;
}*/
public Player() {
}
public synchronized String getUsername() {
return this.username;
}
public synchronized void setUsername(String username) {
this.username = username;
}
public synchronized String getPassword() {
return this.password;
}
public synchronized void setPassword(String password) {
this.password = password;
}
public synchronized String getUserToken() {
return this.userToken;
}
public synchronized void setUserToken(String userToken) {
this.userToken = userToken;
}
public synchronized String getGameToken() {
return this.gameToken;
}
public synchronized void setGameToken(String gameToken) {
this.gameToken = gameToken;
}
public synchronized int getCumulativeScore() {
return this.cumulativeScore;
}
public synchronized void setCumulativeScore(int cumulativeScore) {
this.cumulativeScore = cumulativeScore;
}
public synchronized int getFooled() {
return this.fooled;
}
public synchronized void setFooled(int fooled) {
this.fooled = fooled;
}
public synchronized int getFooled_by() {
return this.fooled_by;
}
public synchronized void setFooled_by(int fooled_by) {
this.fooled_by = fooled_by;
}
public synchronized String getSuggestion() {
return this.suggestion;
}
public synchronized void setSuggestion(String suggestion) {
this.suggestion = suggestion;
}
public synchronized String getChoice() {
return this.choice;
}
public synchronized void setChoice(String choice) {
this.choice = choice;
}
public synchronized boolean getLoggedInAndPlaying() {
return this.loggedInAndPlaying;
}
public synchronized void setLoggedInAndPlaying(boolean loggedInAndPlaying) {
this.loggedInAndPlaying = loggedInAndPlaying;
}
public synchronized void setPort(int port){this.port = port;}
public synchronized int getPort(){return this.port;}
public synchronized void setMessage(String message){
this.message = message;
}
public synchronized String getMessage(){
return this.message;
}
public synchronized int getWordOn(){
return this.wordOn;
}
public synchronized void addWordOn(){
this.wordOn++;
}
}
| UTF-8 | Java | 3,986 | java | Player.java | Java | [
{
"context": "ername, String password) {\n this.username = username;\n this.password = password;\n }\n\n /*p",
"end": 508,
"score": 0.9681670665740967,
"start": 500,
"tag": "USERNAME",
"value": "username"
},
{
"context": " this.username = username;\n this.password = password;\n }\n\n /*public Player(String username, Stri",
"end": 542,
"score": 0.9632592797279358,
"start": 534,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ring message,int wordOn) {\n this.username = username;\n this.userToken = userToken;\n this",
"end": 840,
"score": 0.9985275268554688,
"start": 832,
"tag": "USERNAME",
"value": "username"
},
{
"context": "his.userToken = userToken;\n this.password = password;\n this.cumulativeScore = cumulativeScore;\n",
"end": 910,
"score": 0.9990180134773254,
"start": 902,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ord(String password) {\n this.password = password;\n }\n\n public synchronized String ge",
"end": 1695,
"score": 0.9948880076408386,
"start": 1687,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | import java.net.Socket;
public class Player {
private String username;
private String userToken;
private String gameToken;
private String password;
private int cumulativeScore;
private int fooled;
private int fooled_by;
private String suggestion;
private String choice;
private boolean loggedInAndPlaying;
private int port;
private String message;
private int wordOn;
public Player(String username, String password) {
this.username = username;
this.password = <PASSWORD>;
}
/*public Player(String username, String userToken, String gameToken, String password, int cumulativeScore, int fooled, int fooled_by,
String suggestion, String choice, boolean loggedInAndPlaying, int port, String message,int wordOn) {
this.username = username;
this.userToken = userToken;
this.password = <PASSWORD>;
this.cumulativeScore = cumulativeScore;
this.fooled = fooled;
this.fooled_by = fooled_by;
this.suggestion = null;
this.choice = choice;
this.loggedInAndPlaying = false;
this.gameToken = gameToken;
this.port = port;
this.message = "Hello";
this.wordOn = 0;
}*/
public Player() {
}
public synchronized String getUsername() {
return this.username;
}
public synchronized void setUsername(String username) {
this.username = username;
}
public synchronized String getPassword() {
return this.password;
}
public synchronized void setPassword(String password) {
this.password = <PASSWORD>;
}
public synchronized String getUserToken() {
return this.userToken;
}
public synchronized void setUserToken(String userToken) {
this.userToken = userToken;
}
public synchronized String getGameToken() {
return this.gameToken;
}
public synchronized void setGameToken(String gameToken) {
this.gameToken = gameToken;
}
public synchronized int getCumulativeScore() {
return this.cumulativeScore;
}
public synchronized void setCumulativeScore(int cumulativeScore) {
this.cumulativeScore = cumulativeScore;
}
public synchronized int getFooled() {
return this.fooled;
}
public synchronized void setFooled(int fooled) {
this.fooled = fooled;
}
public synchronized int getFooled_by() {
return this.fooled_by;
}
public synchronized void setFooled_by(int fooled_by) {
this.fooled_by = fooled_by;
}
public synchronized String getSuggestion() {
return this.suggestion;
}
public synchronized void setSuggestion(String suggestion) {
this.suggestion = suggestion;
}
public synchronized String getChoice() {
return this.choice;
}
public synchronized void setChoice(String choice) {
this.choice = choice;
}
public synchronized boolean getLoggedInAndPlaying() {
return this.loggedInAndPlaying;
}
public synchronized void setLoggedInAndPlaying(boolean loggedInAndPlaying) {
this.loggedInAndPlaying = loggedInAndPlaying;
}
public synchronized void setPort(int port){this.port = port;}
public synchronized int getPort(){return this.port;}
public synchronized void setMessage(String message){
this.message = message;
}
public synchronized String getMessage(){
return this.message;
}
public synchronized int getWordOn(){
return this.wordOn;
}
public synchronized void addWordOn(){
this.wordOn++;
}
}
| 3,992 | 0.606623 | 0.606372 | 153 | 25.052288 | 24.422958 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 2 |
b2bed32517a075e3dd6f4a9dd340db37070349a0 | 11,622,181,515,558 | 638fd8acc108ff0d80c141fb4924384095e03498 | /src/main/java/com/rui/xb/modules/xb/entity/RuiOrderItem.java | 1db1c2227c2f7ead7a2314d555512b841ec3a45b | [
"Apache-2.0"
] | permissive | djd2088/purple_java | https://github.com/djd2088/purple_java | 022b471ef211a5bf7ef65170baf107e21c8ef90c | 45aff90781ab9bb9f580a3b9ce15a21e729d1b18 | refs/heads/master | 2020-03-09T22:52:35.206000 | 2018-07-11T08:04:19 | 2018-07-11T08:04:19 | 129,045,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.rui.xb.modules.xb.entity;
import com.google.gson.annotations.Expose;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.rui.xb.common.persistence.DataEntity;
/**
* 单表生成Entity
* @author ThinkGem
* @version 2018-06-12
*/
public class RuiOrderItem extends DataEntity<RuiOrderItem> {
private static final long serialVersionUID = 1L;
@Expose
private Long orderId; // order_id
@Expose
private String unitprice; // 商品单价
@Expose
private String number; // 购买数量
@Expose
private String productId; // product_id
private String sellerId; // seller_id
private String buyerId; // buyer_id
@Expose
private String isAppraise; // 是否评价
private String activityId; // 活动id
private String activityType; // 活动类型
private Date createTime; // create_time
private Date updateTime; // update_time
private String commisRate; // 分佣比例
@Expose
private String mainPic; // pre1
@Expose
private String productName; // pre2
private String pre3; // pre3
public RuiOrderItem() {
super();
}
public RuiOrderItem(String id){
super(id);
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
@Length(min=0, max=11, message="商品单价长度必须介于 0 和 11 之间")
public String getUnitprice() {
return unitprice;
}
public void setUnitprice(String unitprice) {
this.unitprice = unitprice;
}
@Length(min=0, max=11, message="购买数量长度必须介于 0 和 11 之间")
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Length(min=0, max=11, message="product_id长度必须介于 0 和 11 之间")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
@Length(min=0, max=11, message="seller_id长度必须介于 0 和 11 之间")
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
@Length(min=0, max=11, message="buyer_id长度必须介于 0 和 11 之间")
public String getBuyerId() {
return buyerId;
}
public void setBuyerId(String buyerId) {
this.buyerId = buyerId;
}
@Length(min=0, max=4, message="是否评价长度必须介于 0 和 4 之间")
public String getIsAppraise() {
return isAppraise;
}
public void setIsAppraise(String isAppraise) {
this.isAppraise = isAppraise;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Length(min=0, max=11, message="分佣比例长度必须介于 0 和 11 之间")
public String getCommisRate() {
return commisRate;
}
public void setCommisRate(String commisRate) {
this.commisRate = commisRate;
}
public String getMainPic() {
return mainPic;
}
public void setMainPic(String mainPic) {
this.mainPic = mainPic;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Length(min=0, max=255, message="pre3长度必须介于 0 和 255 之间")
public String getPre3() {
return pre3;
}
public void setPre3(String pre3) {
this.pre3 = pre3;
}
} | UTF-8 | Java | 4,062 | java | RuiOrderItem.java | Java | [
{
"context": "ight © 2012-2016 <a href=\"https://github.com/thinkgem/jeesite\">JeeSite</a> All rights reserved.\n */\npac",
"end": 70,
"score": 0.9991934299468994,
"start": 62,
"tag": "USERNAME",
"value": "thinkgem"
},
{
"context": "sistence.DataEntity;\n\n/**\n * 单表生成Entity\n * @author ThinkGem\n * @version 2018-06-12\n */\npublic class RuiOrderI",
"end": 413,
"score": 0.9995614290237427,
"start": 405,
"tag": "USERNAME",
"value": "ThinkGem"
}
] | null | [] | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.rui.xb.modules.xb.entity;
import com.google.gson.annotations.Expose;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.rui.xb.common.persistence.DataEntity;
/**
* 单表生成Entity
* @author ThinkGem
* @version 2018-06-12
*/
public class RuiOrderItem extends DataEntity<RuiOrderItem> {
private static final long serialVersionUID = 1L;
@Expose
private Long orderId; // order_id
@Expose
private String unitprice; // 商品单价
@Expose
private String number; // 购买数量
@Expose
private String productId; // product_id
private String sellerId; // seller_id
private String buyerId; // buyer_id
@Expose
private String isAppraise; // 是否评价
private String activityId; // 活动id
private String activityType; // 活动类型
private Date createTime; // create_time
private Date updateTime; // update_time
private String commisRate; // 分佣比例
@Expose
private String mainPic; // pre1
@Expose
private String productName; // pre2
private String pre3; // pre3
public RuiOrderItem() {
super();
}
public RuiOrderItem(String id){
super(id);
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
@Length(min=0, max=11, message="商品单价长度必须介于 0 和 11 之间")
public String getUnitprice() {
return unitprice;
}
public void setUnitprice(String unitprice) {
this.unitprice = unitprice;
}
@Length(min=0, max=11, message="购买数量长度必须介于 0 和 11 之间")
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Length(min=0, max=11, message="product_id长度必须介于 0 和 11 之间")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
@Length(min=0, max=11, message="seller_id长度必须介于 0 和 11 之间")
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
@Length(min=0, max=11, message="buyer_id长度必须介于 0 和 11 之间")
public String getBuyerId() {
return buyerId;
}
public void setBuyerId(String buyerId) {
this.buyerId = buyerId;
}
@Length(min=0, max=4, message="是否评价长度必须介于 0 和 4 之间")
public String getIsAppraise() {
return isAppraise;
}
public void setIsAppraise(String isAppraise) {
this.isAppraise = isAppraise;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Length(min=0, max=11, message="分佣比例长度必须介于 0 和 11 之间")
public String getCommisRate() {
return commisRate;
}
public void setCommisRate(String commisRate) {
this.commisRate = commisRate;
}
public String getMainPic() {
return mainPic;
}
public void setMainPic(String mainPic) {
this.mainPic = mainPic;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Length(min=0, max=255, message="pre3长度必须介于 0 和 255 之间")
public String getPre3() {
return pre3;
}
public void setPre3(String pre3) {
this.pre3 = pre3;
}
} | 4,062 | 0.713354 | 0.693532 | 182 | 20.071428 | 19.545956 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 2 |
8c463f575bed65047c501d1a2143f7af84115e3a | 12,146,167,564,310 | 45909cca259c496221013db8f8d9b55ceff90593 | /src/matcher/src/test/java/com/axibase/chartstesting/screenshotmatcher/proxy/configuration/filters/ReplaceMatchingFilterTest.java | ad533d1713f3c3ab7665c80bcaf21bc4928fba17 | [
"Apache-2.0"
] | permissive | axibase/chartlab-matcher | https://github.com/axibase/chartlab-matcher | bcec46114949f9793ff5a127476e4858bf45aa78 | 3b6abcced43f6bd49ed6d1adf214097a1cac8d84 | refs/heads/master | 2021-01-18T17:41:10.945000 | 2018-05-14T07:09:32 | 2018-05-14T07:09:32 | 70,049,644 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.axibase.chartstesting.screenshotmatcher.proxy.configuration.filters;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by aleksandr on 25.10.16.
*/
public class ReplaceMatchingFilterTest {
private final LineFilter filter = new ReplaceMatchingFilter("hello\\s*\\w+", "test");
@Test
public void testReplacingMatching() throws Exception {
assertEquals("replaces \"hello world\" with \"test\"", "test", filter.filter("hello world", null));
assertEquals("replaces \"helloworld\" with \"test\"", "test", filter.filter("helloworld", null));
assertEquals("replaces \"hello\nworld\" with \"test\"", "test", filter.filter("hello\nworld", null));
assertEquals("replaces \"hello \n d\" with \"test\"", "test", filter.filter("hello \n d", null));
}
@Test
public void testNotReplacingMatching() throws Exception {
assertEquals("does not replace \"hell world\" ", "hell world", filter.filter("hell world", null));
assertEquals("does not replace \"hellworld\" ", "hellworld", filter.filter("hellworld", null));
assertEquals("does not replace \"hello-world\" ", "hello-world", filter.filter("hello-world", null));
assertEquals("does not replace \" hello world\" ", " hello world", filter.filter(" hello world", null));
}
} | UTF-8 | Java | 1,351 | java | ReplaceMatchingFilterTest.java | Java | [
{
"context": " org.junit.Assert.assertEquals;\n\n/**\n * Created by aleksandr on 25.10.16.\n */\npublic class ReplaceMatchingFilt",
"end": 179,
"score": 0.9995872378349304,
"start": 170,
"tag": "USERNAME",
"value": "aleksandr"
}
] | null | [] | package com.axibase.chartstesting.screenshotmatcher.proxy.configuration.filters;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by aleksandr on 25.10.16.
*/
public class ReplaceMatchingFilterTest {
private final LineFilter filter = new ReplaceMatchingFilter("hello\\s*\\w+", "test");
@Test
public void testReplacingMatching() throws Exception {
assertEquals("replaces \"hello world\" with \"test\"", "test", filter.filter("hello world", null));
assertEquals("replaces \"helloworld\" with \"test\"", "test", filter.filter("helloworld", null));
assertEquals("replaces \"hello\nworld\" with \"test\"", "test", filter.filter("hello\nworld", null));
assertEquals("replaces \"hello \n d\" with \"test\"", "test", filter.filter("hello \n d", null));
}
@Test
public void testNotReplacingMatching() throws Exception {
assertEquals("does not replace \"hell world\" ", "hell world", filter.filter("hell world", null));
assertEquals("does not replace \"hellworld\" ", "hellworld", filter.filter("hellworld", null));
assertEquals("does not replace \"hello-world\" ", "hello-world", filter.filter("hello-world", null));
assertEquals("does not replace \" hello world\" ", " hello world", filter.filter(" hello world", null));
}
} | 1,351 | 0.670614 | 0.666173 | 28 | 47.285713 | 44.991154 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.321429 | false | false | 2 |
f0026698bd2ca152ce2514cbe258ba1fabd1af10 | 8,435,315,795,307 | 44536ac0a1979dea1ce1fe929ab505a4f2447c2f | /com.shark.lang.dd/src-gen/com/shark/lang/dd/CheckExpression.java | f3c5f96a0d24d2a531b97b3ee5f95a43127ac72d | [] | no_license | sharklang/com.shark.lang.dd.parent | https://github.com/sharklang/com.shark.lang.dd.parent | 2a7c3290a37df4d6370231d4857060894edc8f19 | 5f095f62227b91d5d67da6c499f80ea71f7a84a6 | refs/heads/main | 2023-03-25T17:59:52.946000 | 2021-02-08T22:13:06 | 2021-02-08T22:13:06 | 316,913,712 | 0 | 0 | null | false | 2021-02-07T10:54:22 | 2020-11-29T09:10:23 | 2020-12-13T16:24:07 | 2021-02-07T10:54:22 | 2,245 | 0 | 0 | 0 | Java | false | false | /**
* generated by Xtext 2.23.0
*/
package com.shark.lang.dd;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Check Expression</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.shark.lang.dd.CheckExpression#getChkDesc <em>Chk Desc</em>}</li>
* <li>{@link com.shark.lang.dd.CheckExpression#getName <em>Name</em>}</li>
* <li>{@link com.shark.lang.dd.CheckExpression#getExpr <em>Expr</em>}</li>
* </ul>
*
* @see com.shark.lang.dd.DdPackage#getCheckExpression()
* @model
* @generated
*/
public interface CheckExpression extends EObject
{
/**
* Returns the value of the '<em><b>Chk Desc</b></em>' containment reference list.
* The list contents are of type {@link com.shark.lang.dd.LineComment}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Chk Desc</em>' containment reference list.
* @see com.shark.lang.dd.DdPackage#getCheckExpression_ChkDesc()
* @model containment="true"
* @generated
*/
EList<LineComment> getChkDesc();
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see com.shark.lang.dd.DdPackage#getCheckExpression_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link com.shark.lang.dd.CheckExpression#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Expr</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Expr</em>' containment reference.
* @see #setExpr(SharkExpression)
* @see com.shark.lang.dd.DdPackage#getCheckExpression_Expr()
* @model containment="true"
* @generated
*/
SharkExpression getExpr();
/**
* Sets the value of the '{@link com.shark.lang.dd.CheckExpression#getExpr <em>Expr</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Expr</em>' containment reference.
* @see #getExpr()
* @generated
*/
void setExpr(SharkExpression value);
} // CheckExpression
| UTF-8 | Java | 2,575 | java | CheckExpression.java | Java | [] | null | [] | /**
* generated by Xtext 2.23.0
*/
package com.shark.lang.dd;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Check Expression</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.shark.lang.dd.CheckExpression#getChkDesc <em>Chk Desc</em>}</li>
* <li>{@link com.shark.lang.dd.CheckExpression#getName <em>Name</em>}</li>
* <li>{@link com.shark.lang.dd.CheckExpression#getExpr <em>Expr</em>}</li>
* </ul>
*
* @see com.shark.lang.dd.DdPackage#getCheckExpression()
* @model
* @generated
*/
public interface CheckExpression extends EObject
{
/**
* Returns the value of the '<em><b>Chk Desc</b></em>' containment reference list.
* The list contents are of type {@link com.shark.lang.dd.LineComment}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Chk Desc</em>' containment reference list.
* @see com.shark.lang.dd.DdPackage#getCheckExpression_ChkDesc()
* @model containment="true"
* @generated
*/
EList<LineComment> getChkDesc();
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see com.shark.lang.dd.DdPackage#getCheckExpression_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link com.shark.lang.dd.CheckExpression#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Expr</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Expr</em>' containment reference.
* @see #setExpr(SharkExpression)
* @see com.shark.lang.dd.DdPackage#getCheckExpression_Expr()
* @model containment="true"
* @generated
*/
SharkExpression getExpr();
/**
* Sets the value of the '{@link com.shark.lang.dd.CheckExpression#getExpr <em>Expr</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Expr</em>' containment reference.
* @see #getExpr()
* @generated
*/
void setExpr(SharkExpression value);
} // CheckExpression
| 2,575 | 0.625631 | 0.624078 | 86 | 28.94186 | 27.709185 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.093023 | false | false | 2 |
5e7aab6457bb50053342ad95d5eb952e90223356 | 19,267,223,303,628 | 08e84ca082fd7ec5ce277a80e38283c340bf45c5 | /src/Entity/ERP_AC/AcCounter.java | f5a72e3615c22e8d66e5b49cbee75305887dd851 | [] | no_license | miccgood/importData | https://github.com/miccgood/importData | b499f18273f8b0fb5c38f14d7a2befbbfe25e761 | d8953844a04059a59b52357bb0354d32979d6d89 | refs/heads/master | 2021-01-02T09:20:51.123000 | 2014-03-17T11:05:20 | 2014-03-17T11:05:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entity.ERP_AC;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
/**
*
* @author tanet-t
*/
@Entity
@Table(name = "AC_COUNTER")
@TableGenerator(
name="counter_ac_counter",
table="AC_COUNTER",
pkColumnName="name",
valueColumnName="value",
pkColumnValue="AC_COUNTER",
initialValue=1,
allocationSize=10)
@NamedQuery(name = "AcCounter.findByName", query = "SELECT s FROM AcCounter s WHERE s.name = :name")
public class AcCounter implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="counter_ac_counter")
@Column(name = "NAME")
private String name;
@Column(name = "VALUE")
private Integer value;
public AcCounter() {
}
public AcCounter(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| UTF-8 | Java | 1,618 | java | AcCounter.java | Java | [
{
"context": "persistence.TableGenerator;\r\n\r\n/**\r\n *\r\n * @author tanet-t\r\n */\r\n@Entity\r\n@Table(name = \"AC_COUNTER\")\r\n@Tabl",
"end": 572,
"score": 0.999614953994751,
"start": 565,
"tag": "USERNAME",
"value": "tanet-t"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entity.ERP_AC;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
/**
*
* @author tanet-t
*/
@Entity
@Table(name = "AC_COUNTER")
@TableGenerator(
name="counter_ac_counter",
table="AC_COUNTER",
pkColumnName="name",
valueColumnName="value",
pkColumnValue="AC_COUNTER",
initialValue=1,
allocationSize=10)
@NamedQuery(name = "AcCounter.findByName", query = "SELECT s FROM AcCounter s WHERE s.name = :name")
public class AcCounter implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="counter_ac_counter")
@Column(name = "NAME")
private String name;
@Column(name = "VALUE")
private Integer value;
public AcCounter() {
}
public AcCounter(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| 1,618 | 0.668109 | 0.665637 | 66 | 22.515152 | 20.639946 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 2 |
0fe1a6727943d5d445f7be55069661be91222210 | 24,592,982,737,194 | e8183e29deefa2b4f1562ddffc50af2d0fff8d7c | /samples/core/src/main/java/io/oasp/gastronomy/restaurant/tablemanagement/service/impl/ws/v1_0/TablemanagementWebServiceImpl.java | 0bf219340b9c7788ffd3e101f38301d902962c4a | [
"Apache-2.0"
] | permissive | devonfw/training-devon-server | https://github.com/devonfw/training-devon-server | 44e7ad481e417d17ee9769d500999758e941ce6b | eef7dcdfa29af9b640bae217044a2a13a9840657 | refs/heads/develop | 2021-01-15T16:56:50.863000 | 2018-07-25T08:28:32 | 2018-07-25T08:28:32 | 37,984,719 | 3 | 97 | Apache-2.0 | true | 2018-07-09T12:36:46 | 2015-06-24T13:05:23 | 2017-07-26T12:17:30 | 2018-07-09T12:36:01 | 1,984 | 3 | 194 | 4 | null | false | null | package io.oasp.gastronomy.restaurant.tablemanagement.service.impl.ws.v1_0;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jws.WebService;
import io.oasp.gastronomy.restaurant.tablemanagement.logic.api.Tablemanagement;
import io.oasp.gastronomy.restaurant.tablemanagement.logic.api.to.TableEto;
import io.oasp.gastronomy.restaurant.tablemanagement.service.api.ws.v1_0.TablemanagmentWebService;
/**
* Implementation of {@link TablemanagmentWebService}.
*
* @author jmetzler
*/
@Named("TablemanagementWebService")
@WebService(endpointInterface = "io.oasp.gastronomy.restaurant.tablemanagement.service.api.ws.v1_0.TablemanagmentWebService")
public class TablemanagementWebServiceImpl implements TablemanagmentWebService {
private Tablemanagement tableManagement;
/**
* This method sets the field <tt>tableManagement</tt>.
*
* @param tableManagement the new value of the field ${bare_field_name}
*/
@Inject
public void setTableManagement(Tablemanagement tableManagement) {
this.tableManagement = tableManagement;
}
@Override
public TableEto getTable(long id) {
return this.tableManagement.findTable(id);
}
}
| UTF-8 | Java | 1,174 | java | TablemanagementWebServiceImpl.java | Java | [
{
"context": "of {@link TablemanagmentWebService}.\n *\n * @author jmetzler\n */\n@Named(\"TablemanagementWebService\")\n@WebServi",
"end": 499,
"score": 0.9943121075630188,
"start": 491,
"tag": "USERNAME",
"value": "jmetzler"
}
] | null | [] | package io.oasp.gastronomy.restaurant.tablemanagement.service.impl.ws.v1_0;
import javax.inject.Inject;
import javax.inject.Named;
import javax.jws.WebService;
import io.oasp.gastronomy.restaurant.tablemanagement.logic.api.Tablemanagement;
import io.oasp.gastronomy.restaurant.tablemanagement.logic.api.to.TableEto;
import io.oasp.gastronomy.restaurant.tablemanagement.service.api.ws.v1_0.TablemanagmentWebService;
/**
* Implementation of {@link TablemanagmentWebService}.
*
* @author jmetzler
*/
@Named("TablemanagementWebService")
@WebService(endpointInterface = "io.oasp.gastronomy.restaurant.tablemanagement.service.api.ws.v1_0.TablemanagmentWebService")
public class TablemanagementWebServiceImpl implements TablemanagmentWebService {
private Tablemanagement tableManagement;
/**
* This method sets the field <tt>tableManagement</tt>.
*
* @param tableManagement the new value of the field ${bare_field_name}
*/
@Inject
public void setTableManagement(Tablemanagement tableManagement) {
this.tableManagement = tableManagement;
}
@Override
public TableEto getTable(long id) {
return this.tableManagement.findTable(id);
}
}
| 1,174 | 0.787905 | 0.782794 | 39 | 29.102564 | 33.30265 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25641 | false | false | 2 |
8072c0708d164fdd59ebc6726b3214d5f69b5ace | 19,292,993,121,977 | bbc3c7202ece08908a4ab7e135a0fdd23f54a8b3 | /Pyramid_Solitare_JackFinlay/test/pyramid_solitare_jackfinlay/model/DeckTest.java | 23d3a4b03dcf2d613b599c4d0db4f38476f413df | [] | no_license | JackWFinlay/PDCProject2014S2 | https://github.com/JackWFinlay/PDCProject2014S2 | 4839c69a329f7e1850df9eda0af4b52d13b11c31 | 8a2fce5eb07440430d2f84b81ecb99dd59532487 | refs/heads/master | 2021-01-18T14:31:26.535000 | 2014-10-23T19:47:05 | 2014-10-23T19:47:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pyramid_solitare_jackfinlay.model;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for the Deck class.
*
* @author Jack Finlay ID: 1399273
*/
public class DeckTest {
Deck deck1, deck2;
public DeckTest() {
}
@Before
public void setUp() {
deck1 = new Deck();
deck2 = new Deck();
}
@After
public void tearDown() {
deck1 = null;
deck2 = null;
}
/**
* Test of createDeck method, of class Deck.
*/
@Test
public void testCreateDeck() {
deck1.createDeck();
assertEquals(deck1.getSize(), 52);
}
/**
* Test of addCard method, of class Deck.
*/
@Test
public void testAddCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck2.addCard(card1);
deck2.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck2.getDeckAsList().contains(card1));
assertTrue(deck2.getDeckAsList().contains(card2));
}
/**
* Test of removeCard method, of class Deck.
*/
@Test
public void testRemoveCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck1.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck1.getDeckAsList().contains(card2));
deck1.removeCard(card1);
deck1.removeCard(card2);
assertFalse(deck1.getDeckAsList().contains(card1));
assertFalse(deck1.getDeckAsList().contains(card2));
}
/**
* Test of getCard method, of class Deck.
*/
@Test
public void testGetCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck1.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck1.getDeckAsList().contains(card2));
assertEquals(deck1.getCard(1), card1);
assertEquals(deck1.getCard(0), card2);
}
}
| UTF-8 | Java | 2,232 | java | DeckTest.java | Java | [
{
"context": "\n/**\r\n * Tests for the Deck class.\r\n *\r\n * @author Jack Finlay ID: 1399273\r\n */\r\npublic class DeckTest {\r\n\r\n ",
"end": 219,
"score": 0.9998679161071777,
"start": 208,
"tag": "NAME",
"value": "Jack Finlay"
}
] | null | [] | package pyramid_solitare_jackfinlay.model;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for the Deck class.
*
* @author <NAME> ID: 1399273
*/
public class DeckTest {
Deck deck1, deck2;
public DeckTest() {
}
@Before
public void setUp() {
deck1 = new Deck();
deck2 = new Deck();
}
@After
public void tearDown() {
deck1 = null;
deck2 = null;
}
/**
* Test of createDeck method, of class Deck.
*/
@Test
public void testCreateDeck() {
deck1.createDeck();
assertEquals(deck1.getSize(), 52);
}
/**
* Test of addCard method, of class Deck.
*/
@Test
public void testAddCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck2.addCard(card1);
deck2.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck2.getDeckAsList().contains(card1));
assertTrue(deck2.getDeckAsList().contains(card2));
}
/**
* Test of removeCard method, of class Deck.
*/
@Test
public void testRemoveCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck1.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck1.getDeckAsList().contains(card2));
deck1.removeCard(card1);
deck1.removeCard(card2);
assertFalse(deck1.getDeckAsList().contains(card1));
assertFalse(deck1.getDeckAsList().contains(card2));
}
/**
* Test of getCard method, of class Deck.
*/
@Test
public void testGetCard() {
Card card1 = new Card();
Card card2 = new Card();
deck1.addCard(card1);
deck1.addCard(card2);
assertTrue(deck1.getDeckAsList().contains(card1));
assertTrue(deck1.getDeckAsList().contains(card2));
assertEquals(deck1.getCard(1), card1);
assertEquals(deck1.getCard(0), card2);
}
}
| 2,227 | 0.563172 | 0.53405 | 96 | 21.25 | 18.726095 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.