blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a7326f73e9e361e32390a299d05dc9f2a6c44a45 | f4925f13cf982a2bcd4f45380674cde216383a61 | /app/src/main/java/com/manmeet/moviescentralbeta/Adapters/MovieAdapter.java | 39c98710eb1282b70383c65306c8eab7b351295e | [] | no_license | manmeet-22/MoviesCentral-App | 637698eb7dcfed0dd17f501da14c593c770d6c9b | c5326a701258f0e49d570e8c3084de2cfcbf73ec | refs/heads/master | 2021-03-27T13:02:33.869531 | 2018-09-26T11:38:23 | 2018-09-26T11:38:23 | 123,617,208 | 0 | 0 | null | 2018-09-24T10:10:25 | 2018-03-02T18:44:53 | Java | UTF-8 | Java | false | false | 2,769 | java | package com.manmeet.moviescentralbeta.Adapters;
/**
* Created by Manmeet on 24-Oct-17.
*/
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.manmeet.moviescentralbeta.DetailActivity;
import com.manmeet.moviescentralbeta.R;
import com.manmeet.moviescentralbeta.Pojos.movie.DiscoverMoviesResults;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private List<DiscoverMoviesResults> movieList;
private Context mContext;
public MovieAdapter(Context context, List<DiscoverMoviesResults> moviesList) {
this.mContext = context;
this.movieList = moviesList;
}
@Override
public MovieAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View returnHolderView = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(returnHolderView);
}
@Override
public void onBindViewHolder(MovieAdapter.MovieViewHolder holder, int position) {
DiscoverMoviesResults currMovie = movieList.get(position);
Picasso.with(holder.itemView.getContext())
.load("https://image.tmdb.org/t/p/w500"+currMovie.getPosterPath())
.placeholder(R.drawable.no_poster)
.error(R.drawable.error_image).
into(holder.thumbView);
}
@Override
public int getItemCount() {
if (movieList != null)
return movieList.size();
else
return 0;
}
public void setMovieData(ArrayList<DiscoverMoviesResults> list) {
if (movieList != null)
movieList.clear();
movieList = list;
notifyDataSetChanged();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements RecyclerView.OnClickListener {
ImageView thumbView;
public MovieViewHolder(View itemView) {
super(itemView);
thumbView = itemView.findViewById(R.id.imageView_movies_listItem);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
DiscoverMoviesResults currMovie = movieList.get(getAdapterPosition());
String id = currMovie.getId();
//Log.i("Id is", id);
Intent intent = new Intent(view.getContext(), DetailActivity.class);
intent.putExtra("id", id);
view.getContext().startActivity(intent);
}
}
}
| [
"[email protected]"
] | |
c58ead1bbd0f61c5ce03a17f7027eea82762c217 | 101a5889f5c91a8dad7fe03f715a8a22d72262db | /src/main/wikiduper/wikipedia/language/ArabicWikipediaPage.java | 33316a5516c23dc40931fa400d4432e6789949ce | [
"Apache-2.0"
] | permissive | lintool/wikiduper | 0519650275ab1b85944178439b118f680ff96e2d | cc52438e49076eee7eed04b44eebad0691f61dbd | refs/heads/master | 2020-04-07T17:03:15.309192 | 2015-07-08T14:45:20 | 2015-07-08T14:45:20 | 158,554,664 | 1 | 0 | null | 2018-11-21T13:47:32 | 2018-11-21T13:47:31 | null | UTF-8 | Java | false | false | 3,327 | java | /*
* Cloud9: A MapReduce Library for Hadoop
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package wikiduper.wikipedia.language;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringEscapeUtils;
import wikiduper.wikipedia.WikipediaPage;
/**
* An Arabic page from Wikipedia.
*
* @author Ferhan Ture
*/
public class ArabicWikipediaPage extends WikipediaPage {
/**
* Language dependent identifiers of disambiguation, redirection, and stub pages.
*/
private static final String IDENTIFIER_REDIRECTION_UPPERCASE = "#REDIRECT";
private static final String IDENTIFIER_REDIRECTION_LOWERCASE = "#redirect";
private static final String IDENTIFIER_STUB_TEMPLATE = "stub}}";
private static final String IDENTIFIER_STUB_WIKIPEDIA_NAMESPACE = "Wikipedia:Stub";
private static final Pattern disambPattern = Pattern.compile("\\{\\{\u062A\u0648\u0636\u064A\u062D\\}\\}", Pattern.CASE_INSENSITIVE);
private static final String LANGUAGE_CODE = "ar";
/**
* Creates an empty <code>ArabicWikipediaPage</code> object.
*/
public ArabicWikipediaPage() {
super();
}
@Override
protected void processPage(String s) {
this.language = LANGUAGE_CODE;
// parse out title
int start = s.indexOf(XML_START_TAG_TITLE);
int end = s.indexOf(XML_END_TAG_TITLE, start);
this.title = StringEscapeUtils.unescapeHtml(s.substring(start + 7, end));
// determine if article belongs to the article namespace
start = s.indexOf(XML_START_TAG_NAMESPACE);
end = s.indexOf(XML_END_TAG_NAMESPACE);
this.isArticle = s.substring(start + 4, end).trim().equals("0");
// parse out the document id
start = s.indexOf(XML_START_TAG_ID);
end = s.indexOf(XML_END_TAG_ID);
this.mId = s.substring(start + 4, end);
// parse out actual text of article
this.textStart = s.indexOf(XML_START_TAG_TEXT);
this.textEnd = s.indexOf(XML_END_TAG_TEXT, this.textStart);
// determine if article is a disambiguation, redirection, and/or stub page.
Matcher matcher = disambPattern.matcher(page);
this.isDisambig = matcher.find();
this.isRedirect = s.substring(this.textStart + XML_START_TAG_TEXT.length(), this.textStart + XML_START_TAG_TEXT.length() + IDENTIFIER_REDIRECTION_UPPERCASE.length()).compareTo(IDENTIFIER_REDIRECTION_UPPERCASE) == 0 ||
s.substring(this.textStart + XML_START_TAG_TEXT.length(), this.textStart + XML_START_TAG_TEXT.length() + IDENTIFIER_REDIRECTION_LOWERCASE.length()).compareTo(IDENTIFIER_REDIRECTION_LOWERCASE) == 0;
this.isStub = s.indexOf(IDENTIFIER_STUB_TEMPLATE, this.textStart) != -1 ||
s.indexOf(IDENTIFIER_STUB_WIKIPEDIA_NAMESPACE) != -1;
}
}
| [
"[email protected]"
] | |
0139796f1889ef87c5b3f18af9b173b3d5ae6440 | eeb94fa2680ae8681d8b74fec2f0fee01faf7681 | /tw_new/androidProject/VdaoAppBranch/vdaoProject/commonutilLib/src/main/java/com/common/lib/global/CrashHandler.java | 74cc032da61b8287719a08bb5f90219d807748e4 | [] | no_license | iqiangzi/www | 0b0a369e69438c4e0984526f170288025b2f9c22 | 4daea51c4c5d0c8e5ad08d01b8b6acb9a2289376 | refs/heads/master | 2020-08-02T22:20:48.299576 | 2019-01-24T03:51:25 | 2019-01-24T03:51:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,098 | java | package com.common.lib.global;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
import com.common.lib.base.BaseApplication;
import com.common.lib.fileutils.FileConstants;
import com.common.lib.fileutils.FileUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import java.util.TreeSet;
/**
* 自定义系统的Crash捕捉类,用Toast替换系统的对话框
* 将软件版本信息,设备信息,出错信息保存在sd卡中,你可以上传到服务器中
* http://www.cnblogs.com/freeliver54/archive/2011/10/25/2223729.html
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
/** Debug Log tag*/
public static final String TAG = "CrashHandler";
/** 是否开启日志输出,在Debug状态下开启,
* 在Release状态下关闭以提示程序性能
* */
public static final boolean DEBUG = false;
/** 系统默认的UncaughtException处理类 */
private Thread.UncaughtExceptionHandler mDefaultHandler;
/** CrashHandler实例 */
private static CrashHandler INSTANCE;
/** 程序的Context对象 */
private Context mContext;
/** 使用Properties来保存设备的信息和错误堆栈信息*/
private Properties mDeviceCrashInfo = new Properties();
private static final String VERSION_NAME = "versionName";
private static final String VERSION_CODE = "versionCode";
private static final String STACK_TRACE = "STACK_TRACE";
/** 错误报告文件的扩展名 */
private static final String CRASH_REPORTER_EXTENSION = ".cr";
//用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
/** 保证只有一个CrashHandler实例 */
private CrashHandler() {}
/** 获取CrashHandler实例 ,单例模式*/
public static CrashHandler getInstance() {
if (INSTANCE == null) {
INSTANCE = new CrashHandler();
}
return INSTANCE;
}
/**
* 初始化,注册Context对象,
* 获取系统默认的UncaughtException处理器,
* 设置该CrashHandler为程序的默认处理器
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
//Sleep一会后结束程序
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
/**
* 自定义错误处理,收集错误信息
* 发送错误报告等操作均在此完成.
* 开发者可以根据自己的情况来自定义异常处理逻辑
* @param ex
* @return true:如果处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
Log.w(TAG, "handleException --- ex==null");
return true;
}
final String msg = ex.getLocalizedMessage();
if(msg == null) {
return false;
}
//使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast toast = Toast.makeText(mContext, "程序出错,即将退出:\r\n" + msg,
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
// MsgPrompt.showMsg(mContext, "程序出错啦", msg+"\n点确认退出");
Looper.loop();
}
}.start();
//收集设备信息
collectCrashDeviceInfo(mContext);
//保存错误报告文件
saveCrashInfoToFile(ex);
//发送错误报告到服务器
//sendCrashReportsToServer(mContext);
return true;
}
/**
* 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
*/
public void sendPreviousReportsToServer() {
sendCrashReportsToServer(mContext);
}
/**
* 把错误报告发送给服务器,包含新产生的和以前没发送的.
* @param ctx
*/
private void sendCrashReportsToServer(Context ctx) {
String[] crFiles = getCrashReportFiles(ctx);
if (crFiles != null && crFiles.length > 0) {
TreeSet<String> sortedFiles = new TreeSet<String>();
sortedFiles.addAll(Arrays.asList(crFiles));
for (String fileName : sortedFiles) {
File cr = new File(ctx.getFilesDir(), fileName);
postReport(cr);
cr.delete();// 删除已发送的报告
}
}
}
private void postReport(File file) {
// TODO 发送错误报告到服务器
}
/**
* 获取错误报告文件名
* @param ctx
* @return
*/
private String[] getCrashReportFiles(Context ctx) {
File filesDir = ctx.getFilesDir();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(CRASH_REPORTER_EXTENSION);
}
};
return filesDir.list(filter);
}
/**
* 保存错误信息到文件中
* @param ex
* @return
*/
private String saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
String result = info.toString();
printWriter.close();
mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
mDeviceCrashInfo.put(STACK_TRACE, result);
try {
//long timestamp = System.currentTimeMillis();
/*Time t = new Time("GMT+8");
t.setToNow(); // 取得系统时间
int date = t.year * 10000 + t.month * 100 + t.monthDay;
int time = t.hour * 10000 + t.minute * 100 + t.second;
String fileName = "crash-" + date + "-" + time + CRASH_REPORTER_EXTENSION;*/
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + CRASH_REPORTER_EXTENSION;
/*String QIDUSTOREDIR="APP_DEFAULT_CACHE/";
String state = Environment.getExternalStorageState();
String basePath= state.equals(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+QIDUSTOREDIR: mContext.getCacheDir().getAbsolutePath()+ File.separator+QIDUSTOREDIR;*/
File basePath= FileUtils.getDiskCacheDir(BaseApplication.getInstance(), FileConstants.CRASH_LOG);
File file = new File(basePath ,fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(result.getBytes());
fos.close();
/*FileOutputStream trace = mContext.openFileOutput(fileName,
Context.MODE_PRIVATE);
mDeviceCrashInfo.store(trace, "CrashHandler");
trace.flush();
trace.close();*/
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing report file...", e);
}
return null;
}
/**
* 收集程序崩溃的设备信息
*
* @param ctx
*/
public void collectCrashDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
mDeviceCrashInfo.put(VERSION_NAME,
pi.versionName == null ? "not set" : pi.versionName);
mDeviceCrashInfo.put(VERSION_CODE, ""+pi.versionCode);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Error while collect package info", e);
}
//使用反射来收集设备信息.在Build类中包含各种设备信息,
//例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
//具体信息请参考后面的截图
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName(), ""+field.get(null));
if (DEBUG) {
Log.d(TAG, field.getName() + " : " + field.get(null));
}
} catch (Exception e) {
Log.e(TAG, "Error while collect crash info", e);
}
}
}
}
| [
"[email protected]"
] | |
af43d815f1a808e2b844b8aaae15620c7ea45f25 | e80bdefb248c1c7b82272f845016adfce6d52ad5 | /spring/Languages/src/test/java/com/hope/languages/LanguagesApplicationTests.java | 035ab3d7fd7833722bafcee4e0d70101e0478329 | [] | no_license | hope-crichlow/Java | ee2d4f3d84791a5499c47e4a16b8f7fbdeeb97f4 | 061cad9425c7630f96dc57a9c321ad017a7f0ded | refs/heads/main | 2023-07-14T06:18:29.337081 | 2021-08-21T01:55:17 | 2021-08-21T01:55:17 | 392,078,715 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 213 | java | package com.hope.languages;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LanguagesApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
930e4d6f67595152a350f4fdb773153547926b27 | 2c4dd2d3c598ce398821b5f4692559e96a970ab1 | /app/src/main/java/com/ouri/java_android_mvp_project/MVP/Main/Shirt.java | 10ee58c36b8cfe1aff49bc5b747a30540bba21dd | [] | no_license | ourialkada/Java-Android-MVP-Project | 73222331bfefc50ad53a138fb321b92f14567c61 | bcbce9435526919223088573a815e963bd55f3be | refs/heads/master | 2020-07-25T00:13:04.947508 | 2019-09-12T21:43:53 | 2019-09-12T21:43:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,155 | java | package com.ouri.java_android_mvp_project.MVP.Main;
import android.graphics.Bitmap;
import android.widget.ImageView;
public class Shirt {
private String title;
private String description;
private Bitmap image;
private String ID;
private String type;
public Shirt(String t,String d,String id,String ty,Bitmap i)
{
title = t;
description=d;
ID = id;
type=ty;
image = i;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getID() {
return ID;
}
public void setID(String description) {
this.ID = ID;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
}
| [
"[email protected]"
] | |
2f79571aa2812ef1672b6fb1de792f8c80d5caac | 8e8c015a18eefc906e92e92dd2ccafa607165fbd | /support/cas-server-support-fortress/src/test/java/org/apereo/cas/adaptors/fortress/FortressAuthenticationHandlerTests.java | 6c317e3f9a0fe8e32c94cdc4529b21823895fdf9 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-free-unknown"
] | permissive | hxiangli/cas | 6e26d2cc3d92d183f592382a214951c78f17f77f | 31aeeec9033b98685d52b34249b101f9d13ee6be | refs/heads/master | 2022-04-04T03:49:26.953386 | 2020-02-09T20:05:22 | 2020-02-09T20:05:22 | 239,459,364 | 1 | 0 | Apache-2.0 | 2020-02-10T08:12:22 | 2020-02-10T08:12:22 | null | UTF-8 | Java | false | false | 2,958 | java | package org.apereo.cas.adaptors.fortress;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import lombok.SneakyThrows;
import lombok.val;
import org.apache.directory.fortress.core.AccessMgr;
import org.apache.directory.fortress.core.GlobalErrIds;
import org.apache.directory.fortress.core.PasswordException;
import org.apache.directory.fortress.core.model.Session;
import org.apache.directory.fortress.core.model.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import javax.security.auth.login.FailedLoginException;
import javax.xml.bind.JAXBContext;
import java.io.StringWriter;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link FortressAuthenticationHandler}.
*
* @author yudhi.k.surtan
* @since 5.2.0
*/
public class FortressAuthenticationHandlerTests {
@Mock
private AccessMgr accessManager;
@InjectMocks
private FortressAuthenticationHandler fortressAuthenticationHandler;
@BeforeEach
public void initializeTest() {
MockitoAnnotations.initMocks(this);
fortressAuthenticationHandler.setAccessManager(accessManager);
}
@Test
public void verifyUnauthorizedUserLoginIncorrect() throws Exception {
Mockito.when(accessManager.createSession(ArgumentMatchers.any(User.class), ArgumentMatchers.anyBoolean()))
.thenThrow(new PasswordException(GlobalErrIds.USER_PW_INVLD, "error message"));
assertThrows(FailedLoginException.class,
() -> fortressAuthenticationHandler.authenticateUsernamePasswordInternal(
CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), null));
}
@Test
@SneakyThrows
public void verifyAuthenticateSuccessfully() {
val sessionId = UUID.randomUUID();
val session = new Session(new User(CoreAuthenticationTestUtils.CONST_USERNAME), sessionId.toString());
session.setAuthenticated(true);
Mockito.when(accessManager.createSession(ArgumentMatchers.any(User.class), ArgumentMatchers.anyBoolean())).thenReturn(session);
val handlerResult = fortressAuthenticationHandler.authenticateUsernamePasswordInternal(
CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(), null);
assertEquals(CoreAuthenticationTestUtils.CONST_USERNAME,
handlerResult.getPrincipal().getId());
val jaxbContext = JAXBContext.newInstance(Session.class);
val marshaller = jaxbContext.createMarshaller();
val writer = new StringWriter();
marshaller.marshal(session, writer);
assertEquals(writer.toString(), handlerResult.getPrincipal()
.getAttributes().get(FortressAuthenticationHandler.FORTRESS_SESSION_KEY).get(0));
}
}
| [
"[email protected]"
] | |
cabc0a6643bd12675e849e7ef3f25f3ba62a788d | bd2e9fcb13b01071111b2ca141ecd568e33c35dc | /src/main/java/chapter04/section01/thread_4_1_9/pro_1_Fair_noFair_test/RunFair.java | 8ded0990b9a10357572904f9d340ad54f0668ff1 | [
"Apache-2.0"
] | permissive | turoDog/java-multi-thread-programming | 59bf392bcea73da7f5f43c06ff35e87a4b127f8a | cb0d5e1735577fb76e57ec2b53d692c8063d6d66 | refs/heads/master | 2020-09-03T12:47:58.686757 | 2019-12-03T15:19:19 | 2019-12-03T15:19:19 | 219,465,626 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 886 | java | package chapter04.section01.thread_4_1_9.pro_1_Fair_noFair_test;
/**
* Project Name:java-multi-thread-programming <br/>
* Package Name:chapter04.thread_4_1_9.pro_1_Fair_noFair_test <br/>
* Date:2019/11/27 11:39 <br/>
*
* @author <a href="mailto:[email protected]">chenzy</a><br/>
*/
public class RunFair {
public static void main(String[] args) throws InterruptedException {
final Service service = new Service(true);
Runnable runnable = () -> {
System.out.println("★线程" + Thread.currentThread().getName()
+ "运行了");
service.serviceMethod();
};
Thread[] threadArray = new Thread[10];
for (int i = 0; i < 10; i++) {
threadArray[i] = new Thread(runnable);
}
for (int i = 0; i < 10; i++) {
threadArray[i].start();
}
}
}
| [
"[email protected]"
] | |
ae25fea99958fe2743fff0beea0748c8f72a6dc4 | 8418e33f233d305b24dca9d2e8d9bb224352292f | /src/com/wpc/webapp/controller/AppVersionController.java | 9ff0dcf1e578aa4fd7cfc657b2486714f22a8091 | [] | no_license | 54meng/wisdom_plan_check | e616ddc088e31d79f6e595dd1634d15ef279df1d | 6f9be1ba0e87b9bfb8f9008af9ce6f89ed7e91bd | refs/heads/master | 2020-05-31T13:27:23.118954 | 2019-06-05T03:27:20 | 2019-06-05T03:27:20 | 190,303,344 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,794 | java | package com.wpc.webapp.controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.google.gson.Gson;
import com.wpc.dfish.framework.FrameworkHelper;
import com.wpc.dfish.util.Utils;
import com.wpc.persistence.AppVersion;
import com.wpc.service.ServiceLocator;
import com.wpc.utils.FileUtil;
import com.wpc.utils.SystemEnvInfo;
public class AppVersionController extends MultiActionController {
Gson gson = new Gson();
SimpleDateFormat pathFormat = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public ModelAndView addOrEdit(HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<AppVersion> list = ServiceLocator.getAppVersionService().findList();
AppVersion appVersion = null;
if(Utils.notEmpty(list)){
appVersion = list.get(0);
String apkUrl = appVersion.getApkUrl();
String ipaUrl = appVersion.getIpaUrl();
if(Utils.notEmpty(apkUrl)){
appVersion.setApkUrl(apkUrl.substring(apkUrl.lastIndexOf("\\")+1));
}
if(Utils.notEmpty(ipaUrl)){
appVersion.setIpaUrl(ipaUrl.substring(ipaUrl.lastIndexOf("\\")+1));
}
}
ModelAndView modelAndView = new ModelAndView("admin/template/admin/app_version_mgr.jsp");
modelAndView.addObject("appVersion", appVersion);
return modelAndView;
}
public ModelAndView save(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String id = request.getParameter("id");
AppVersion entity = ServiceLocator.getAppVersionService().findById(id);
boolean isNew = false;
if(entity==null){
isNew = true;
entity = new AppVersion();
}
String androidVersion = Utils.getParameter(request, "androidVersion");
String iosVersion = Utils.getParameter(request, "iosVersion");
String androidUpdContent = Utils.getParameter(request, "androidUpdContent");
String iosUpdContent = Utils.getParameter(request, "iosUpdContent");
String androidDownloadUrl = Utils.getParameter(request, "androidDownloadUrl");
String iosDownloadUrl = Utils.getParameter(request, "iosDownloadUrl");
String iosIsForce = Utils.getParameter(request, "iosIsForce");
String androidIsForce = Utils.getParameter(request, "androidIsForce");
entity.setAndroidVersion(androidVersion);
entity.setIosVersion(iosVersion);
entity.setAndroidUpdContent(androidUpdContent);
entity.setIosUpdContent(iosUpdContent);
entity.setAndroidDownloadUrl(androidDownloadUrl);
entity.setIosDownloadUrl(iosDownloadUrl);
entity.setIosIsForce(Integer.parseInt(iosIsForce));
entity.setAndroidIsForce(Integer.parseInt(androidIsForce));
//文件上传
MultipartHttpServletRequest multipartRequest = null;
String apkUrl = null;
String ipaUrl = null;
if(request instanceof MultipartHttpServletRequest){
multipartRequest = (MultipartHttpServletRequest) request;
String floderPath = SystemEnvInfo.getResourcePath();
MultipartFile[] apkUrlFile = FrameworkHelper.getFiles(multipartRequest, "apkUrl");
if (apkUrlFile != null && apkUrlFile.length > 0) {
for (int i = 0; i < apkUrlFile.length; i++) {
try {
String originalFileName = apkUrlFile[i].getOriginalFilename();
FileUtil.saveFile(apkUrlFile[i].getInputStream(), floderPath, originalFileName);
apkUrl = SystemEnvInfo.getResourceRelativePath()+File.separator+originalFileName;
} catch (Exception e) {
e.printStackTrace();
}
}
}
MultipartFile[] ipaUrlFile = FrameworkHelper.getFiles(multipartRequest, "ipaUrl");
if (ipaUrlFile != null && ipaUrlFile.length > 0) {
for (int i = 0; i < ipaUrlFile.length; i++) {
try {
String originalFileName = ipaUrlFile[i].getOriginalFilename();
FileUtil.saveFile(ipaUrlFile[i].getInputStream(), floderPath, originalFileName);
ipaUrl = SystemEnvInfo.getResourceRelativePath()+File.separator+originalFileName;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
if(Utils.notEmpty(apkUrl)){
entity.setApkUrl(apkUrl);
}
if(Utils.notEmpty(ipaUrl)){
entity.setIpaUrl(ipaUrl);
}
try {
if(isNew){
ServiceLocator.getAppVersionService().save(entity);
}else{
ServiceLocator.getAppVersionService().update(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
Utils.outPutJson(response, 1);
return null;
}
}
| [
"[email protected]"
] | |
626d8ad09231928c337cb736223a779b9ee9044b | f15bb0ddf9e28ea808f4c49e8c442c29e6f53218 | /bus-core/src/main/java/org/aoju/bus/core/io/FileOperator.java | ce10304bb195b2b784e1212a2836277604510043 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | erickwang/bus | 7f31a19ace167b2ce525105d4393b379118a525e | a8ed185f2f1c0f085d8a2be5e005bcbf50431386 | refs/heads/master | 2022-04-15T15:28:06.342430 | 2020-03-26T06:14:42 | 2020-03-26T06:14:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,747 | java | /*********************************************************************************
* *
* The MIT License *
* *
* Copyright (c) 2015-2020 aoju.org and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
********************************************************************************/
package org.aoju.bus.core.io;
import java.io.EOFException;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* 读取和写入目标文件
*
* @author Kimi Liu
* @version 5.8.1
* @since JDK 1.8+
*/
public final class FileOperator {
private final FileChannel fileChannel;
public FileOperator(FileChannel fileChannel) {
this.fileChannel = fileChannel;
}
/**
* 将{@code byteCount}字节从{@code source}写到{@code pos}的文件中
*
* @param pos 写入大小
* @param source 缓存流信息
* @param byteCount 字节流大小
* @throws IOException 异常
*/
public void write(long pos, Buffer source, long byteCount) throws IOException {
if (byteCount < 0 || byteCount > source.size()) throw new IndexOutOfBoundsException();
while (byteCount > 0L) {
long bytesWritten = fileChannel.transferFrom(source, pos, byteCount);
pos += bytesWritten;
byteCount -= bytesWritten;
}
}
/**
* 将{@code byteCount}字节从文件{@code pos}复制到{@code source}
* 调用者有责任确保有足够的字节来读取:如果没有,这个方法会抛出一个{@link EOFException}
*
* @param pos 写入大小
* @param sink 缓存流信息
* @param byteCount 字节流大小
* @throws IOException 异常
*/
public void read(long pos, Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IndexOutOfBoundsException();
while (byteCount > 0L) {
long bytesRead = fileChannel.transferTo(pos, byteCount, sink);
pos += bytesRead;
byteCount -= bytesRead;
}
}
}
| [
"[email protected]"
] | |
0ef6e56ce91cdb45d3e564eab2694c48af4ad162 | 104db50f9274ba3da0c35b15d9a787191b40106b | /Java/ProtoDebugger/src/protodebugger/controller/EditorController.java | 09b1f201152f699b5d25e86fe7b6259fec12155a | [] | no_license | slopyjoe/ProtoCapstonProject | 61a9cda5410994911d404360ef5ea4910e9a31ae | 7606e0ca3af7f77c0fa8020b788c45547a912aba | refs/heads/master | 2021-01-20T12:00:35.058660 | 2012-11-09T09:45:45 | 2012-11-09T09:45:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,868 | java | package protodebugger.controller;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import protodebugger.model.protos.ProtoPkgContainer.ProtoInstance;
import protodebugger.model.protos.ProtoPkgContainer.ProtoMessage;
import protodebugger.util.ParseProtoMessage;
import protodebugger.util.ProtoEvents;
import com.google.protobuf.GeneratedMessage;
public enum EditorController implements PropertyChangeListener {
INSTANCE;
private final String DEFAULT_METHOD = "getDefaultInstance";
private ProtoInstance editedMessage;
private Map<String, GeneratedMessage> generatedClasses =
new HashMap<String, GeneratedMessage>();
private GeneratedMessage getGenMsgForString(String className)
{
try {
Class<?> genMsg = Class.forName(className);
Object obj = genMsg.getMethod(DEFAULT_METHOD, null).invoke(
genMsg, null);
if (obj instanceof GeneratedMessage) {
return (GeneratedMessage) obj;
}
} catch (ClassNotFoundException | NoSuchMethodException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException | SecurityException cnfe) {
cnfe.printStackTrace();
}
return null;
}
public void editMessage(ProtoMessage msg, ProtoInstance instance)
{
if(!generatedClasses.containsKey(msg.getClassName()))
{
GeneratedMessage genMsg = getGenMsgForString(msg.getClassName());
generatedClasses.put(msg.getClassName(), genMsg);
}
ParseProtoMessage.INSTANCE.selectionChange(generatedClasses.get(msg.getClassName()));
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
ProtoEvents protoEvents = ProtoEvents.valueOf(evt.getPropertyName());
switch (protoEvents){
}
}
}
| [
"[email protected]"
] | |
725fe10b4c5c5ccc1c1fcd2578764bb870bd7072 | b65493a5b4adb6038337b41bccea690784350e7e | /core/src/com/mygdx/game/Sprites/Turtle.java | 34dc52ee5a12ffb2a118f7ef7e79812a41c15033 | [] | no_license | GeorgebigG/Mario_Bros | 3303f634ab3a048ea8d2c8b504c076fe67c7f260 | c5abf9bbe5ca71cd1cac7f2a645d7ba2dce4a7dc | refs/heads/master | 2021-01-20T19:52:27.068135 | 2016-06-23T06:36:41 | 2016-06-23T06:36:41 | 61,780,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,702 | java | package com.mygdx.game.Sprites;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.mygdx.game.MarioBros;
import com.mygdx.game.screens.PlayScreen;
/**
* Created by gio on 13/04/16.
*/
public class Turtle extends Enemy {
Vector2 direction;
public Turtle(PlayScreen screen, float x, float y) {
super(screen, x, y);
setRegion(screen.getAtlas().findRegion("turtle"), 0, 0, 16, 32);
setBounds(x, y, 21 / MarioBros.PPM, 21 / MarioBros.PPM);
direction = new Vector2(0, -1f);
}
@Override
protected void defineEnemy(float x, float y) {
BodyDef bdef = new BodyDef();
bdef.position.set(x, y);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
CircleShape shape = new CircleShape();
FixtureDef fdef = new FixtureDef();
shape.setRadius(6 / MarioBros.PPM);
fdef.filter.categoryBits = MarioBros.ENEMY_BIT;
fdef.filter.maskBits = MarioBros.GROUND_BIT |
MarioBros.BRICK_BIT |
MarioBros.MARIO_BIT |
MarioBros.COIN_BIT |
MarioBros.OBJECT_BIT;
fdef.shape = shape;
b2body.createFixture(fdef).setUserData(this);
}
@Override
public void update(float dt) {
b2body.setLinearVelocity(direction);
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
//setRegion(walkAnimation.getKeyFrame(stateTimer, true));
}
@Override
public void hitOnHead() {
}
}
| [
"[email protected]"
] | |
66351e37c93cc024a3498c5cf0cf37176273e244 | 7ccc7840476fd8d43853b80eb64646d79cb897db | /src/main/java/com/alpha/community/mapper/CommentMapper.java | 07d379a38de1953df0c847576ab9aa5dad9be2d3 | [] | no_license | Alpha188/community | 54014f72b98f5ebe72a7d8b348bc027a6704ac41 | d486bd171a3c2fc3132bbd06b2cc605955d934ed | refs/heads/master | 2022-07-02T00:25:25.333964 | 2020-04-16T13:05:49 | 2020-04-16T13:05:49 | 246,515,545 | 0 | 0 | null | 2022-06-21T03:00:49 | 2020-03-11T08:30:36 | Java | UTF-8 | Java | false | false | 854 | java | package com.alpha.community.mapper;
import com.alpha.community.model.Comment;
import com.alpha.community.model.CommentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface CommentMapper {
long countByExample(CommentExample example);
int deleteByExample(CommentExample example);
int deleteByPrimaryKey(Long id);
int insert(Comment record);
int insertSelective(Comment record);
List<Comment> selectByExample(CommentExample example);
Comment selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") Comment record, @Param("example") CommentExample example);
int updateByExample(@Param("record") Comment record, @Param("example") CommentExample example);
int updateByPrimaryKeySelective(Comment record);
int updateByPrimaryKey(Comment record);
} | [
"[email protected]"
] | |
f63b0701ab94d859695592b9d9ea594b7199c997 | 3e4f2bee10f16d0d77106213d59d6d33ef9fd0eb | /src/test/java/Runner/AnyName.java | 63ac04f7cf093e33da6e7c9dc3ec11f86ce022c4 | [] | no_license | daisyatul/batch14_Testing_Repositrory | a916c1f6235715b2ed80e959ee6b452616408d44 | faf07c44f3aab6fb1f3725361603315ee45a6e7f | refs/heads/main | 2023-08-11T12:16:03.343139 | 2021-09-13T13:54:47 | 2021-09-13T13:54:47 | 392,760,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 820 | java | package Runner;
import StepDef.StepDef;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.testng.annotations.DataProvider;
@CucumberOptions(
features = "classpath:features",
glue = "StepDef",
tags = "@LogIn",
plugin = {"pretty",
"html:target/cucumber-reports.html",
"com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"
},
dryRun = false
)
public class AnyName extends AbstractTestNGCucumberTests {
@Override
@DataProvider(parallel = true)
public Object[][] scenarios() {
return super.scenarios();
}
}
| [
"daisyatul"
] | daisyatul |
c0fb012871967287a806e67a25610fb1c997f6ee | a6f6f8fb5d6d3c01fad7f2aaf79ede8987462209 | /src/main/java/com/manniwood/cl4pg/v1/exceptions/Cl4pgFileNotFoundException.java | 4dc38fdba15471c2e67c3d3f7482f70ff601f545 | [
"MIT"
] | permissive | manniwood/cl4pg | 843d08520690b2b1d3b7b6670254a8a4b71bc7f7 | 1d832eb1d8917004bff4dc188b8e65218a37a3b1 | refs/heads/master | 2021-06-15T02:48:36.630744 | 2021-04-16T13:32:53 | 2021-04-16T13:32:53 | 21,470,065 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,805 | java | /*
The MIT License (MIT)
Copyright (c) 2014 Manni Wood
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.manniwood.cl4pg.v1.exceptions;
public class Cl4pgFileNotFoundException extends Cl4pgException {
private static final long serialVersionUID = 1L;
public Cl4pgFileNotFoundException() {
super();
}
public Cl4pgFileNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public Cl4pgFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public Cl4pgFileNotFoundException(String message) {
super(message);
}
public Cl4pgFileNotFoundException(Throwable cause) {
super(cause);
}
}
| [
"[email protected]"
] | |
9b2b28c72b22341d1059323a25129b468910a481 | 8107c00ba811d9d6a76762f098474d4258cd12f5 | /wp-embed-client/src/main/java/com/muye/wp/embed/protocol/ProtoMethod.java | f6817d4270e1f11e33e7dff87e7e9f47135220c3 | [] | no_license | muyed/wisdom-parking-web | 201d8026dde00ba744921cc4a5d5860c9cf825b0 | 41c30788b6a08c97bfb2415a00a3cf8986b87e36 | refs/heads/master | 2022-08-24T13:12:29.631451 | 2022-07-21T08:30:34 | 2022-07-21T08:30:34 | 118,620,728 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 983 | java | package com.muye.wp.embed.protocol;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Created by muye on 18/4/12.
*
*/
public enum ProtoMethod {
INIT((byte)0), //客户端首次链接
REFRESH((byte) 1), //重置所有数据
ADD((byte)2), //添加业主车牌号
ADD_TEMP((byte)3), //添加临时车牌号
DEL((byte)4), //删除业主车牌号
DEL_TEMP((byte)5), //删除临时车牌号
GET_PHOTO((byte)6); //查看照片
private byte method;
ProtoMethod(byte method){
this.method = method;
}
public byte getMethod() {
return method;
}
public static ProtoMethod ofMethod(byte method){
Optional<ProtoMethod> optional = Stream.of(ProtoMethod.values())
.filter(protoMethod -> protoMethod.method == method)
.findFirst();
if (optional.isPresent()) return optional.get();
return null;
}
}
| [
"[email protected]"
] | |
f74194bc45c6803ad49927990633043b4278e726 | 8c524d7625986b751819146d56726852d3782139 | /Tkcsapcd_cadastros/src/br/com/tkcsapcd/model/command/ExcluirRecursosHumanos.java | e26ba8c420aa4046d78c7fbbed697919ba630a40 | [] | no_license | JosueSantos49/SISPROMAPER-Gestao-de-Projetos | e76f563f654a9f8193af96008c52dfa91b43148e | 462cd8958b9e940345594de2ed2d2a0b22ae113c | refs/heads/master | 2021-06-23T22:32:36.125619 | 2021-04-01T17:12:21 | 2021-04-01T17:12:21 | 218,196,029 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,484 | java | /*
Autor: Josué da Conceição Santos
E-mail: [email protected]
Ano: 2015
*/
package br.com.tkcsapcd.model.command;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.tkcsapcd.model.dao.InterfaceRecursosHumanosDAO;
public class ExcluirRecursosHumanos implements InterfaceCommand {
private InterfaceRecursosHumanosDAO recursosHumanosDAO;
public ExcluirRecursosHumanos(InterfaceRecursosHumanosDAO recursosHumanosDAO) {
super();
this.recursosHumanosDAO = recursosHumanosDAO;
}
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
recursosHumanosDAO.excluir(Integer.valueOf(request.getParameter("codigo")));
request.setAttribute("mensagem", "Recursos Humanos excluído com sucesso!");
} catch (NumberFormatException e) {
request.setAttribute("mensagem", "Código inválido: "+request.getParameter("codigo"));
e.printStackTrace();
}catch (SQLException e) {//Atenção por padão todas os Editar esta como SQLException, mas nesta linha da erro sempre!!!
request.setAttribute("mensagem", "Problemas com a base de dados!");
e.printStackTrace();
}
request.setAttribute("titulo","Consulta - Recursos Humanos");
return "TkcsapcdController?cmd=consultarRecursosHumanos";
//Cadastre esse comando no helper!
}
}
| [
"[email protected]"
] | |
6d9a1d2a81d3e32f775113b529bffa64835facfe | 4c1b59312ecf261c30e933ea751e3f25d7ece627 | /src/main/java/com/thinkgem/jeesite/modules/weixin/controller/WeixinRequestController.java | e178aedc9132f4397fa17ed143dff11a3067c68e | [
"Apache-2.0"
] | permissive | nowimwrok/zd_ztpor | e18d58545ac0f02c64cff81e38bfb0510352047d | 1e53899726f0a5e89ce8dab647504be7b4e68a03 | refs/heads/master | 2021-04-05T23:43:06.065526 | 2018-03-09T06:17:07 | 2018-03-09T06:17:07 | 124,496,758 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 9,477 | java | /**
*
*/
package com.thinkgem.jeesite.modules.weixin.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.util.TextUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.DataDic;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.DateUtil;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.Tools;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.UsernamePasswordToken;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.weixin.constant.ConstantWeChat;
import com.thinkgem.jeesite.modules.weixin.entity.AccessTokenOAuth;
import com.thinkgem.jeesite.modules.weixin.entity.user.UserWeiXin;
import com.thinkgem.jeesite.modules.weixin.service.JSSignService;
import com.thinkgem.jeesite.modules.weixin.service.OAuthService;
import com.thinkgem.jeesite.modules.weixin.utils.WeixinUtil;
/**
* 微信Controller
*
* @author
* @version
*/
@Controller
@RequestMapping(value = "${weixinPath}/weixin/")
public class WeixinRequestController extends BaseController {
/**
* 微信OAuth认证,获取OpenId
*
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value = { "oauth", "" }, method = RequestMethod.GET)
public void oAuth(HttpServletRequest request, HttpServletResponse response, Model model) {
// 获取微信请求数据
String from = request.getParameter("from"); // 功能请求地址
String code = request.getParameter("code"); // 授权码
if (!"authdeny".equals(code)) {
}
// 获取access_token
AccessTokenOAuth ato = OAuthService.getOAuthAccessToken(code);
// 初始化获取
if (null == ato) {
// /获取微信用户的相关的信息
ato = OAuthService.getOAuthAccessToken(code);
if (null == ato) {
}
}
// 将要跳转的用户页面
String toPage = "";
// 获取微信用户的OPEN_ID
String openID = ato.getOpenid();
String oldOpen_id="";
request.setAttribute("openID", openID);
request.setAttribute("fromPage", from);
// new一个新的user参数对象
User args = new User();
String headImgUrl = "";// 定义微信用户的头像
String userName = "";// 定义微信用户的用户名
try {
// 获取微信用户的基本信息
UserWeiXin userInfo = OAuthService.getUserInfoOauth(ato.getAccessToken(), openID);
if (userInfo != null) {
headImgUrl = (!Tools.IsNullOrWhiteSpace(userInfo.getHeadimgurl()) ? userInfo.getHeadimgurl() : "");
userName = (!Tools.IsNullOrWhiteSpace(userInfo.getNickname()) ? userInfo.getNickname() : "");
request.setAttribute("headImgUrl", headImgUrl);
request.setAttribute("userName", userName);
}
///是否存在缓存
boolean isnohavu=true;
////获取缓存用户
User user = UserUtils.getUser();
////如果存在用户缓存继续走-去相关的页面
if(user !=null && !Tools.IsNullOrWhiteSpace(user.getId())){
isnohavu=false;
oldOpen_id=user.getUserinfo().getOpenid();
///判断当前用户的open_id 是否等于数据库中的openid,如果不等,则清空缓存,重新绑定
if(openID == null ||!openID.equals(oldOpen_id)){
isnohavu=true;
UserUtils.clearCache();
}
}
args.setSearchinfo(openID);
args = UserUtils.getByCondition(args);// 通过openid查询openid是否存在
if ("login".equals(from)) {// 用户的跳转链接为登录页面时
// /当前用户的微信未绑定将去登录页面
if (null == args && isnohavu) {
// 获取用户的头像和昵称
request.setAttribute("headImgUrl", headImgUrl);
request.setAttribute("userName", userName);
toPage="user/tologin?openID="+openID;
} else {
// 如果说存在绑定后
request.setAttribute("headImgUrl", headImgUrl);
request.setAttribute("userName", userName);
toPage="user/tologin?openID="+openID;
}
} else if ("userHome".equals(from)) { // 当去用户个人中心的时候
if (null == args && isnohavu) { // 没有绑定过
request.setAttribute("headImgUrl", headImgUrl);
request.setAttribute("userName", userName);
toPage="user/tologin?openID="+openID;
}
else {
//bindLogin(user.getPhone(),openID);
toPage="user/userHome?openID="+openID;
}
} else if ("chooseusertype".equals(from)) { // 当点击注册的时候去选择用户角色的时候
if (null == args && isnohavu) { // 没有绑定过
toPage="chooseusertype";
} else {
toPage="user/userHome";
}
} else if ("informationHall".equals(from)) {// /////信息大厅
if (null == args && isnohavu) { // 没有绑定过
request.setAttribute("headImgUrl", headImgUrl);
request.setAttribute("userName", userName);
toPage="user/tologin";
} else if (openID.equals(args.getUserinfo().getOpenid())) {
toPage="informationHall/infoHall_list";
}
} else {
toPage="user/tologin?openID="+openID;
}
request.getRequestDispatcher(toPage).forward(request, response);
// 跳转对应功能页面
/*request.getRequestDispatcher(toPage.toString()).forward(request, response);*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
toPage="user/tologin?openID="+openID;
request.getRequestDispatcher(toPage).forward(request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
/*return toPage;*/
}
/**
* 已绑定的用户微信自动登录
* @param loginName
* @param openid
*/
public int bindLogin(String loginName,String openid){
int state = DataDic.RETURN_STATUS_SYSBUG;
// 自定义登录
// 创建用户名和密码的令牌
if(StringUtils.isNoneBlank(openid)){
try {
String pwd = UserUtils.getPlainpwd(openid);
if(StringUtils.isNoneBlank(pwd)){
UserUtils.clearCache();
UsernamePasswordToken token = new UsernamePasswordToken(loginName, pwd.toCharArray(), false, "",
"", true);
// 记录该令牌,如果不记录则类似购物车功能不能使用。
token.setRememberMe(true);
// subject理解成权限对象。类似user
Subject subject = SecurityUtils.getSubject();
subject.login(token); // 保存登录
state = DataDic.RETURN_STATUS_NORMAL;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return state;
}
/* 获取jsapi_ticket与签名信息用于使用js-sdk */
@ResponseBody
@RequestMapping(value = "getJSSign")
public Object getJSSign(HttpServletRequest request, HttpServletResponse response,
RedirectAttributes redirectAttributes, Model model) {
String url = request.getParameter("Url");
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<Object, Object> map = new HashMap<Object, Object>();
Map<String, String> ret = JSSignService.sign(url);
map.put("appId", ConstantWeChat.APPID);
for (Entry<String, String> entry : ret.entrySet()) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
/* 从微信服务器下载图片 */
@ResponseBody
@RequestMapping(value = "downloadImg")
public Object downloadImg(HttpServletRequest request, HttpServletResponse response) {
String userId = "";
if (StringUtils.isNotBlank(UserUtils.getUser().getId())) {
userId = UserUtils.getUser().getId() + "/";
}
String mediaID = request.getParameter("ServerID");
String folderName = request.getParameter("FolderName");// 获取文件名
String accessToken = WeixinUtil.getToken();
Map<String, Object> map = new HashMap<String, Object>();
if (!TextUtils.isEmpty(accessToken)) {
String filepath = Global.USERFILES_BASE_URL;
int index = filepath.indexOf("/", 0);
if (index >= 0) {
filepath = filepath.substring(1);
}
String month = String.valueOf(new Date().getMonth() + 1 + "/");
if (month.length() == 2) {
month = "0" + month;
}
// 上传的绝对路径
String savePath = Global.getUserfilesBaseDir() + filepath + userId + "images/" + folderName + "/"
+ DateUtil.getYear() + "/" + month;
// 返回页面的相对路径
String imagePath = Global.USERFILES_BASE_URL + userId + "images/" + folderName + "/" + DateUtil.getYear()
+ "/" + month;
String imageName = UUID.randomUUID().toString().trim().replaceAll("-", "") + ".jpg";
boolean downState = WeixinUtil.downloadImage(accessToken, mediaID, savePath, imageName);
map.put("result", downState);
if (downState) {
map.put("ImageName", imagePath + imageName);
}
} else {
logger.info("Get access_token failed!");
}
return map;
}
}
| [
"[email protected]"
] | |
14b1ffc40a9dd313e96a2f59198f5a1cd0530eaf | 9bebd05897cac83885e115f6bd20b7edcc00ccd7 | /Turn_Machine_MONTOYA_DAVID/src/model/Time.java | db2ff065378e85590e7311c01fe057d85eb7325e | [] | no_license | DSMontoyaP/Turn-Machine | f2cb771baeb1ca5b11c98d87ef9f00e733692548 | c77df3226eed1b0532f4b2ab76d5c2d04eb3c780 | refs/heads/master | 2021-01-02T21:19:47.865725 | 2020-03-15T16:22:59 | 2020-03-15T16:22:59 | 239,806,709 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,037 | java | package model;
import java.io.Serializable;
import java.util.Calendar;
@SuppressWarnings("serial")
public class Time implements Serializable{
private int hour;
private int minute;
private int seconds;
public Time(int hour, int minute, int seconds) {
this.hour = hour;
this.minute = minute;
this.seconds = seconds;
}
/**
* *<b>Name:</b> getAll. <br>
* This method gets all the values of Time
* @return a String with all the values from Time attributes
*/
public String getAll() {
String a = "";
a = hour + ":" + minute + ":" + seconds;
return a;
}
/**
* *<b>Name:</b> getHour. <br>
* This method gets the hour value of Time
* @return Hour
*/
public int getHour() {
return hour;
}
/**
* *<b>Name:</b> setHour. <br>
* This method sets the current hour value as the difference between an instance of Calendar and the one given by the user
* @param hour integer given by the user as hour
*/
public void setHour(int hour) {
Calendar x = Calendar.getInstance();
this.hour = hour - x.get(Calendar.HOUR);
}
/**
* *<b>Name:</b> getMinute. <br>
* This method gets the minute value of Time
* @return minute
*/
public int getMinute() {
return minute;
}
/**
* *<b>Name:</b> setMinute. <br>
* This method sets the current minute value as the difference between an instance of Calendar and the one given by the user
* @param minute integer given by the user as minute
*/
public void setMinute(int minute) {
Calendar x = Calendar.getInstance();
this.minute = minute - x.get(Calendar.MINUTE);
}
/**
* *<b>Name:</b> getSeconds. <br>
* This method gets the seconds value of Time
* @return seconds
*/
public int getSeconds() {
return seconds;
}
/**
* *<b>Name:</b> setSeconds. <br>
* This method sets the current seconds value as the difference between an instance of Calendar and the one given by the user
* @param seconds integer given by the user as seconds
*/
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
| [
"[email protected]"
] | |
98aebb8a71fbf0d832bbdc37fb110d18341681b7 | 2a3c46c64cd0276febade763fc5a0cca10524afe | /hoho130/src/main/java/com/hotel/kg/employee/service/IMngInqrySvc.java | 066674d13dddbccde7644705cf16701bb64a21e3 | [] | no_license | hisynn/kgHotel | 8c674f28151308858fe994a5a137c229021c087f | 3fdcabb2c00494ee9ee7c98cc958673fc282a474 | refs/heads/master | 2022-11-27T23:04:44.345948 | 2020-12-03T01:35:19 | 2020-12-03T01:35:19 | 254,589,737 | 0 | 0 | null | 2022-11-16T08:28:14 | 2020-04-10T08:59:14 | CSS | UTF-8 | Java | false | false | 316 | java | package com.hotel.kg.employee.service;
import java.util.HashMap;
import com.hotel.kg.employee.dto.InqryDto;
public interface IMngInqrySvc {
HashMap<String, Object> selectList(String selectOption, int pageNum);
InqryDto selectOne(String email, String inqry_Date);
void update(InqryDto dto) throws Exception;
}
| [
"[email protected]"
] | |
256a9f36068ea6d5aa7ba881a6131142336e48d9 | c5a83ab63eba66c2ae9fd137c9fa734284367ab0 | /WordsFormedByCharacters.java | e82842ff0151695d9ca31e03cf1d1482976a8f92 | [] | no_license | gireeshsingh/Interview_practice_questions | 10e8c5b9c565aef8555c5685eae4a79dfe5b1856 | 789f72891c45c8dac9e735d96c9dea55bc4e8ea9 | refs/heads/master | 2021-07-21T19:24:37.151491 | 2020-07-06T16:44:33 | 2020-07-06T16:44:33 | 192,006,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,054 | java | class WordsFormedByCharacters {
public int countCharacters(String[] words, String chars) {
if(chars==null || words==null || words.length ==0 || chars.length()==0)
return 0;
HashMap<String, Integer> hm = new HashMap<String, Integer>();
for(String str : chars.split(""))
hm.put(str, hm.getOrDefault(str, 0)+1);
int i=0, count=0;
HashMap<String, Integer> temphm = new HashMap<String, Integer>();
for(i=0;i<words.length;i++){
temphm = (HashMap) hm.clone();
String[] tempStr=words[i].split("");
int j=0;
for(j=0;j<tempStr.length;j++){
if(temphm.containsKey(tempStr[j])){
if(temphm.get(tempStr[j])<=0) break;
else temphm.put(tempStr[j], temphm.get(tempStr[j])-1);
}
else
break;
}
if(j==tempStr.length)
count+=j;
}
return count;
}
} | [
"[email protected]"
] | |
1680c58c61ad3233ed8d81f9dabfcd31afde4403 | cc5072b5a74c0b5cd240512536caa545633ff025 | /src/main/java/smile/identity/core/MoshiUtils.java | 8d0de551740bf5f25dac04aa84a4f52083f2a349 | [
"MIT"
] | permissive | smileidentity/smile-identity-core-java | a0744abfff718f15ba1e07a4ca833372d4d47922 | 9a9e941f14278b8f33fa26966eaa68df7a3302df | refs/heads/main | 2023-09-01T06:05:34.952658 | 2023-08-04T16:37:59 | 2023-08-04T16:37:59 | 200,832,227 | 1 | 4 | null | 2023-09-08T12:07:24 | 2019-08-06T10:47:26 | Java | UTF-8 | Java | false | false | 1,363 | java | package smile.identity.core;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.adapters.PolymorphicJsonAdapterFactory;
import smile.identity.core.adapters.*;
import smile.identity.core.models.IDResponse;
import smile.identity.core.models.JobResponse;
import java.lang.reflect.Type;
public class MoshiUtils {
/*
Returns an instance of Moshi with Smile Identity Custom Adapters
*/
public static Moshi getMoshi() {
PolymorphicJsonAdapterFactory<JobResponse> factory = PolymorphicJsonAdapterFactory.of(JobResponse.class, "ResultType")
.withSubtype(IDResponse.class, "ID Verification")
.withSubtype(IDResponse.class, "Document Verification")
.withFallbackJsonAdapter(new Moshi.Builder()
.add(new JobTypeAdapter())
.add(new ImageTypeAdapter())
.add(new PartnerParamsAdapter())
.add(new InstantAdapter()).build().adapter((Type) JobResponse.class));
return new Moshi.Builder()
.add(factory)
.add(new PartnerParamsAdapter())
.add(new ImageTypeAdapter())
.add(new JobTypeAdapter())
.add(new InstantAdapter())
.add(new JobStatusResponseResultAdapter())
.build();
}
}
| [
"[email protected]"
] | |
5419d15987d8c97fb42166ef9b4a7a97a36a7075 | 298d3f97235f7506e2adac74de30643d49a07f9a | /src/main/java/Yahoo_Page_Object/Yahoo_RegistrationPage.java | 2156d6f46d236522a33e9465760e642f8a42960d | [] | no_license | mirazk04/mavenAutomation | 43a2e689f8a372874b496561e12cc503db96b0de | ad271ad36b449e28709c8436ab6ae08f0a2b8eb2 | refs/heads/master | 2021-06-21T11:42:22.083821 | 2019-10-14T20:10:21 | 2019-10-14T20:10:21 | 214,686,366 | 0 | 0 | null | 2021-04-26T19:35:21 | 2019-10-12T17:20:29 | Java | UTF-8 | Java | false | false | 5,139 | java | package Yahoo_Page_Object;
import Reusable_Classes.Abstract_Class;
import Reusable_Classes.Reusable_Library_Loggers_POM;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.asserts.SoftAssert;
import java.io.IOException;
public class Yahoo_RegistrationPage extends Abstract_Class {
ExtentTest logger;
//create constructor
public Yahoo_RegistrationPage(WebDriver driver) {
super();
PageFactory.initElements(driver, this);
this.logger = super.logger;
}
@FindBy(xpath = "//*[@name='firstName']")
public static WebElement firstNameLocator;
@FindBy(xpath = "//*[@name='lastName']")
public static WebElement lastNameLocator;
@FindBy(xpath = "//*[@name='yid']")
public static WebElement emailLocator;
@FindBy(xpath = "//*[@name='password']")
public static WebElement passwordLocator;
@FindBy(xpath = "//*[@name='phone']")
public static WebElement phoneNumberLocator;
@FindBy(xpath = "//*[@name='mm']")
public static WebElement birthMonthLocator;
@FindBy(xpath = "//*[@name='dd']")
public static WebElement birthDayLocator;
@FindBy(xpath = "//*[@name='yyyy']")
public static WebElement birthYearLocator;
@FindBy(xpath = "//*[text()='Continue']")
public static WebElement continueButtonLocator;
@FindBy(css = "#recaptcha-script > h1")
public static WebElement messageLocator;
//fist name method
public Yahoo_RegistrationPage FirstName(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, firstNameLocator, 0, userInput, logger, "Firstname Field");
return new Yahoo_RegistrationPage(driver);
}
//last name method
public Yahoo_RegistrationPage LastName(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, lastNameLocator, 0, userInput, logger, "Lastname Field");
return new Yahoo_RegistrationPage(driver);
}
//email method
public Yahoo_RegistrationPage Email(String emailAddress) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, emailLocator, 0, emailAddress, logger, "Email Address Field");
return new Yahoo_RegistrationPage(driver);
}
//password method
public Yahoo_RegistrationPage Password(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, passwordLocator, 0, userInput, logger, "Password Field");
return new Yahoo_RegistrationPage(driver);
}
//Phone Number method
public Yahoo_RegistrationPage PhoneNum(String digits) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, phoneNumberLocator, 0, digits, logger, "Phone Number Field");
return new Yahoo_RegistrationPage(driver);
}
//Birth Month method
public Yahoo_RegistrationPage BirthMonth(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.dropDownByText(driver, birthMonthLocator, userInput, 0, logger, "Birth Month Dropdown");
return new Yahoo_RegistrationPage(driver);
}
//Birth Day method
public Yahoo_RegistrationPage BirthDay(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, birthDayLocator, 0, userInput, logger, "Birthday Field");
return new Yahoo_RegistrationPage(driver);
}
//Birth Year method
public Yahoo_RegistrationPage BirthYear(String userInput) throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.userInput(driver, birthYearLocator, 0, userInput, logger, "Birthday Field");
return new Yahoo_RegistrationPage(driver);
}
//Continue button method
public Yahoo_RegistrationPage ContinueButton() throws IOException, InterruptedException {
Reusable_Library_Loggers_POM.click(driver, continueButtonLocator, 0, logger, "Continue Button");
return new Yahoo_RegistrationPage(driver);
}
//verification method
//since this is returning a text you can't create this method as a contructor return method
//has to be regular return method
public String captchaMessage() throws IOException, InterruptedException {
Thread.sleep(3000);
logger.log(LogStatus.INFO, "Switching to Iframe for Verification Message");
try {
driver.switchTo().frame("recaptcha-iframe");
} catch (Exception e) {
logger.log(LogStatus.FAIL, "Unable to switch to captch iFrame... " + e);
getScreenshot(driver, logger, "captchaFrameIssue");
}
String text = Reusable_Library_Loggers_POM.captureTextByIndex(driver, messageLocator, 0, logger, "Verification Message");
return text;
}//end of verification method
}//end of class
| [
"[email protected]"
] | |
563300b556e1e185eb3b3ea445008cd0483db296 | 4fc5bc198812b2f031fc7543e59ba3d622f8de90 | /spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/RxNettyWebSocketSession.java | 455b5d8eb0cef59b0e7224acb588a24db649cef8 | [
"Apache-2.0"
] | permissive | XBBGIT/spring-framework | e5798851b72721a7159442a195cc0f82221d2a46 | adb80f4099e4994e918ae9edace731847ae9d78a | refs/heads/master | 2020-06-18T01:24:26.305078 | 2016-11-28T02:44:51 | 2016-11-28T02:44:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,934 | java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.socket.adapter;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.reactivex.netty.protocol.http.ws.WebSocketConnection;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Observable;
import rx.RxReactiveStreams;
import org.springframework.core.io.buffer.NettyDataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.socket.CloseStatus;
import org.springframework.web.reactive.socket.WebSocketMessage;
/**
*
* @author Rossen Stoyanchev
* @since 5.0
*/
public class RxNettyWebSocketSession extends WebSocketSessionSupport<WebSocketConnection> {
private static final Map<Class<?>, WebSocketMessage.Type> MESSAGE_TYPES;
static {
MESSAGE_TYPES = new HashMap<>(4);
MESSAGE_TYPES.put(TextWebSocketFrame.class, WebSocketMessage.Type.TEXT);
MESSAGE_TYPES.put(BinaryWebSocketFrame.class, WebSocketMessage.Type.BINARY);
MESSAGE_TYPES.put(PingWebSocketFrame.class, WebSocketMessage.Type.PING);
MESSAGE_TYPES.put(PongWebSocketFrame.class, WebSocketMessage.Type.PONG);
}
private final String id;
private final URI uri;
private final NettyDataBufferFactory bufferFactory;
public RxNettyWebSocketSession(WebSocketConnection conn, URI uri, NettyDataBufferFactory factory) {
super(conn);
Assert.notNull(uri, "'uri' is required.");
Assert.notNull(uri, "'bufferFactory' is required.");
this.id = ObjectUtils.getIdentityHexString(getDelegate());
this.uri = uri;
this.bufferFactory = factory;
}
@Override
public String getId() {
return this.id;
}
@Override
public URI getUri() {
return this.uri;
}
@Override
public Flux<WebSocketMessage> receive() {
return Flux.from(RxReactiveStreams.toPublisher(getDelegate().getInput()))
.filter(frame -> !(frame instanceof CloseWebSocketFrame))
.window()
.concatMap(flux -> flux.takeUntil(WebSocketFrame::isFinalFragment).buffer())
.map(this::toMessage);
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
private WebSocketMessage toMessage(List<WebSocketFrame> frames) {
Class<?> frameType = frames.get(0).getClass();
if (frames.size() == 1) {
NettyDataBuffer buffer = this.bufferFactory.wrap(frames.get(0).content());
return WebSocketMessage.create(MESSAGE_TYPES.get(frameType), buffer);
}
return frames.stream()
.map(socketFrame -> bufferFactory.wrap(socketFrame.content()))
.reduce(NettyDataBuffer::write)
.map(buffer -> WebSocketMessage.create(MESSAGE_TYPES.get(frameType), buffer))
.get();
}
@Override
public Mono<Void> send(Publisher<WebSocketMessage> messages) {
Observable<WebSocketFrame> frames = RxReactiveStreams.toObservable(messages).map(this::toFrame);
Observable<Void> completion = getDelegate().write(frames);
return Mono.from(RxReactiveStreams.toPublisher(completion));
}
private WebSocketFrame toFrame(WebSocketMessage message) {
ByteBuf byteBuf = NettyDataBufferFactory.toByteBuf(message.getPayload());
if (WebSocketMessage.Type.TEXT.equals(message.getType())) {
return new TextWebSocketFrame(byteBuf);
}
else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
return new BinaryWebSocketFrame(byteBuf);
}
else if (WebSocketMessage.Type.PING.equals(message.getType())) {
return new PingWebSocketFrame(byteBuf);
}
else if (WebSocketMessage.Type.BINARY.equals(message.getType())) {
return new PongWebSocketFrame(byteBuf);
}
else {
throw new IllegalArgumentException("Unexpected message type: " + message.getType());
}
}
@Override
protected Mono<Void> closeInternal(CloseStatus status) {
return Mono.from(RxReactiveStreams.toPublisher(getDelegate().close()));
}
}
| [
"[email protected]"
] | |
5b8b917c4916d02053f70475d8d3075e4362e996 | 41dbec9ef50049b5472ad3869e70c0adad67aa41 | /mybatismember/src/main/java/com/example/mybatismember/entity/Member.java | ada0deabe2873d2f3d69dbebfbe8f665cee4329c | [
"MIT"
] | permissive | silenc3502/JSP-MyBatis-Spring | 8c51ffcf701cea79311d1a83dfd9b68b68056c64 | 70ede772e53a1071825bcafe95ac57dca3a48415 | refs/heads/main | 2023-03-25T13:38:50.765826 | 2021-03-16T03:15:57 | 2021-03-16T03:15:57 | 347,540,333 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package com.example.mybatismember.entity;
import java.time.LocalDateTime;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Member {
private int userNo;
private String userId;
private String userPw;
private String userName;
private LocalDateTime regDate;
private LocalDateTime updDate;
private List<MemberAuth> authList;
}
| [
"[email protected]"
] | |
45678baf3c00ac71c7d3910788b6cf663e54129e | dd16be49db6ebc6c24a858579ff145df65026214 | /chenzhw/src/com/test/datacontrol/ConnectionParam.java | bc6b3a5ab03e8327413a5c0af3dbcbeea31cf290 | [] | no_license | brooktran/jeelee | 478ddf9d023dc3127a529e4faedcf844addf4eca | 04c9ee86771bf9b6bde419992621af8c74cfa04f | refs/heads/master | 2021-01-25T12:20:32.994631 | 2013-01-13T18:31:36 | 2013-01-13T18:31:36 | 7,576,005 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,339 | java | package com.test.datacontrol;
/**
*
* @author Brook Tran. Email: <a href="mailto:[email protected]">[email protected]<\a>
* @version Ver 1.0 2009-1-2 新建
* @since eclipse Ver 1.0
*
*/
public class ConnectionParam {
/**
* 数据库驱动程序
*/
private String driver;
/**
* 数据连接的资源
*/
private String source;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
private int maxSize=10;
/**
* 连接的最大空闲时间
*/
private int timeOut=6000;
/**
* 等待连接的时间
*/
private long waitTime=3000;
/**
* @return driver
*/
public String getDriver() {
return driver;
}
/**
* 作用:
* @since eclipse
*/
public ConnectionParam(String driver,String source) {
this.driver=driver;
this.source=source;
}
/**
* @param driver 要设置的 driver
*/
public void setDriver(String driver) {
this.driver = driver;
}
/**
* @return password
*/
public String getPassword() {
return password;
}
/**
* @param password 要设置的 password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return source
*/
public String getSource() {
return source;
}
/**
* @param source 要设置的 source
*/
public void setSource(String source) {
this.source = source;
}
/**
* @return timeOut
*/
public int getTimeOut() {
return timeOut;
}
/**
* @param timeOut 要设置的 timeOut
*/
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
/**
* @return username
*/
public String getUsername() {
return username;
}
/**
* @param username 要设置的 username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return waitTime
*/
public long getWaitTime() {
return waitTime;
}
/**
* @param waitTime 要设置的 waitTime
*/
public void setWaitTime(long waitTime) {
this.waitTime = waitTime;
}
/**
* @return maxSize
*/
public int getMaxSize() {
return maxSize;
}
/**
* @param maxSize 要设置的 maxSize
*/
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
}
| [
"[email protected]"
] | |
bf67579f2eb928932ae28a17aa9f1fdba95d4515 | f8f6d45b553d40ee3f3240cfec7ccd4b4b4982dd | /src/main/java/com/trabalho/crud/resource/exception/StandardError.java | 803c09633e32ff870bcbe48fc558ebc853664ac4 | [] | no_license | brunovicentealves/capitulo-crud-trabalho | 3f59f25cc6c6a137c0a744af11a755489adffa39 | bd68e8b85941ad1044a030a04e6b141a1562b214 | refs/heads/main | 2023-07-07T13:52:43.049807 | 2021-08-05T01:39:56 | 2021-08-05T01:39:56 | 392,131,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 965 | java | package com.trabalho.crud.resource.exception;
import java.io.Serializable;
import java.time.Instant;
public class StandardError implements Serializable {
private static final long serialVersionUID = 1L;
private Instant timestamp;
private Integer status;
private String error;
private String message;
private String path;
public StandardError() {
}
public Instant getTimestamp() {
return timestamp;
}
public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
| [
"[email protected]"
] | |
212844f2835be7dea7735d3ad3edf0e08c8f0a55 | 4525fefa57848bf2bff6b3dd9704ee57194de031 | /app/src/main/java/com/github/kencordero/cookbook/activities/IngredientListActivity.java | 8a58223d1c95d42f4d9787647844d542a4ebb423 | [] | no_license | kencordero/CookBook | 4d3853aa8e74070f1c1ef546ba160e2f2cd13d04 | 470dd649a207d505805ad208c44d884bb287e5aa | refs/heads/master | 2020-04-08T06:54:15.324959 | 2015-08-17T02:36:01 | 2015-08-17T02:36:01 | 16,163,453 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,342 | java | package com.github.kencordero.cookbook.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.util.Log;
import com.github.kencordero.cookbook.fragments.IngredientFragment;
import com.github.kencordero.cookbook.fragments.IngredientListFragment;
import com.github.kencordero.cookbook.R;
import com.github.kencordero.cookbook.models.Ingredient;
public class IngredientListActivity extends SingleFragmentActivity implements
IngredientListFragment.OnFragmentInteractionListener,
IngredientFragment.OnFragmentInteractionListener {
private static final String TAG = IngredientListActivity.class.getSimpleName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setIcon(R.drawable.ic_launcher);
ab.setDisplayShowHomeEnabled(true);
}
}
@Override
protected Fragment createFragment() {
Log.i(TAG, "createFragment");
return new IngredientListFragment();
}
@Override
protected int getLayoutResId() {
return R.layout.activity_masterDetail;
}
@Override
public void onIngredientUpdated(Ingredient ingredient) {
FragmentManager fm = getSupportFragmentManager();
IngredientListFragment listFragment = (IngredientListFragment)fm.findFragmentById(R.id.fragmentContainer);
listFragment.updateUI();
}
@Override
public void onIngredientSelected(Ingredient ingredient) {
Log.i(TAG, "onIngredientSelected");
if (findViewById(R.id.detailFragmentContainer) == null) {
// phone
Intent i = new Intent(this, IngredientPagerActivity.class);
i.putExtra(IngredientFragment.EXTRA_INGREDIENT_ID, ingredient.getUuid());
startActivity(i);
}
else {
// tablet
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment oldDetail = fm.findFragmentById(R.id.detailFragmentContainer);
Fragment newDetail = IngredientFragment.newInstance(ingredient.getUuid());
if (oldDetail != null)
ft.remove(oldDetail);
ft.add(R.id.detailFragmentContainer, newDetail).commit();
}
}
}
| [
"[email protected]"
] | |
f39fcb7a59f5dfc29a85eb6d83959e7b01358e0f | 2869c9cf1bc533a343586a1d96198a5ce2da541e | /Java_Workspace/GUItest3/src/sign.java | 9c96a28d0f321108a4e927506fc1214dc264bcfc | [] | no_license | gunddol/Univ_Class | bace5c8023a932493042063f6c977ac270790475 | b9be3382d13cf3c412a80eb6ba9991e562284ec6 | refs/heads/master | 2020-04-10T20:01:42.566518 | 2018-12-20T02:52:21 | 2018-12-20T02:52:21 | 161,254,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 322 | java | import javax.swing.*;
public class sign {
private javax.swing.JPanel JPanel;
private JTextArea textArea1;
private JTextArea textArea2;
private JTextArea textArea3;
private JTextArea textArea4;
private void createUIComponents() {
// TODO: place custom component creation code here
}
}
| [
"[email protected]"
] | |
cf78bf14033943db6909b47abb417f20e8dc4903 | 2feb9e37a3683cd43ade89fe523354eadde5c029 | /ppy.blogs/src/servlet/manager/DeleteUser.java | 2998f61a0a7e4000b64b1caff8e1f8cf3c1892f2 | [] | no_license | PIPIYANG233/ppyStorehouse | 48975339575d6bf8cb3bd70afae57ba1b9cbce6a | 9e3aabbbd14ca4eb2ccaaa086178470b1520660e | refs/heads/master | 2023-02-11T10:54:08.245316 | 2021-01-09T01:04:57 | 2021-01-09T01:04:57 | 328,044,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,106 | java | package servlet.manager;
import domain.Manager;
import domain.User;
import service.userOption.UserOptionImp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/DeleteUser")
public class DeleteUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
int index = Integer.valueOf(req.getParameter("index"));
Manager manager = (Manager)req.getSession().getAttribute("manager");
List<User> users = manager.getUsers();
User user = users.get(index);
users.remove(index);
new UserOptionImp().deleteUser(user.getId());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
| [
"[email protected]"
] | |
509048350269c66d1e37e5cd452dd531c0eac2a2 | c6a80eabb23928275bbdeddbe1fdb57d02b2d045 | /src/d2_1966.java | 5b8387ecd176f25a20a9ea95a0cd52e962603980 | [] | no_license | binne614/SWExpertAcademy | 12cce319495ccefc1bc8c42949c25e91f8a12cc1 | 2c1122c48f3c3de308b45ff27c9cfb006be607ff | refs/heads/master | 2020-04-23T14:26:29.147870 | 2019-03-03T15:13:49 | 2019-03-03T15:13:49 | 171,231,937 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 958 | java | import java.util.*;
public class d2_1966 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
int N = scanner.nextInt();
int[][] num;
for(int i = 0; i < t; i++) {
num = new int[t][N];
for (int j = 0; j < N; j++) {
num[i][j] = scanner.nextInt();
}
for (int k = N - 1; k >= 0; k--) {
for (int j = k - 1; j >= 0; j--) {
if (num[i][k] < num[i][j]) {
int temp = num[i][k];
num[i][k] = num[i][j];
num[i][j] = temp;
}
}
}
System.out.print("#" + (i+1) + " " );
for (int j = 0; j < N; j++) {
System.out.print(num[i][j] + " ");
}
System.out.println();
}
}
}
| [
"[email protected]"
] | |
d8065bff4f24f00e54aa811fb7ddb428f9a76ef4 | cc037330e66713ac3dde164600a8af20b1d26f0c | /src/com/collection/TestHashMap.java | a5dad7c824bdcd9c8017c48654a7393934635f04 | [] | no_license | darth-xiaozhijun/JavaProgram | 1bb5708b1ff164ecede68e6956429d6ec4fa1d23 | d143d195ac5a0276a83307340b1d8441262e4563 | refs/heads/master | 2020-04-08T04:22:18.777052 | 2019-06-29T11:08:54 | 2019-06-29T11:08:54 | 159,013,545 | 0 | 0 | null | 2019-06-29T11:08:55 | 2018-11-25T08:49:49 | Java | UTF-8 | Java | false | false | 1,769 | java | package com.collection;
import java.util.HashMap;
import java.util.Map;
/**
* 测试HashMap的使用
* @author Administrator
*
*/
public class TestHashMap {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
System.out.println(map.get(1));
System.out.println(map.size());
System.out.println(map.isEmpty());
System.out.println(map.containsKey(1));
System.out.println(map.containsValue("four"));
Map<Integer, String> map2 = new HashMap<>();
map2.put(4, "四");
map2.put(5, "五");
map.putAll(map2);
System.out.println(map);
map.put(3, "三");
System.out.println(map);
Employee employee = new Employee(1001, "小小", "3000");
Employee employee2 = new Employee(1002, "李二", "4500");
Employee employee3 = new Employee(1003, "王五", "40000");
Map<Integer, Employee> map3 = new HashMap<>();
map3.put(1001, employee);
map3.put(1002, employee2);
map3.put(1003, employee3);
Employee employee4 = map3.get(1001);
System.out.println(employee4.getEname());
}
}
class Employee{
private Integer id;
private String ename;
private String salary;
public Employee(Integer id, String ename, String salary) {
super();
this.id = id;
this.ename = ename;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
}
| [
"[email protected]"
] | |
01e0194af7ad82a95cd53e566dc8779af0d5a9f0 | e51c767c5effe0fe81c75c0705135f8f5c8311b7 | /weave-shared/weave-dataclient/weave-dataclient-core/src/main/java/io/aftersound/weave/dataclient/DataClientFactoryRegistry.java | f63fba2e4cca59f5abe8686d56d130865fba59c4 | [
"Apache-2.0"
] | permissive | shaoxt/weave | edd597b8ee59cbda6b8e35aa6c8baaca3809ea0d | 7c3998be46684f2dc8800e29bf70d379806e38e8 | refs/heads/master | 2020-08-31T12:41:25.141326 | 2019-10-31T05:20:30 | 2019-10-31T05:20:30 | 218,693,302 | 1 | 0 | Apache-2.0 | 2019-10-31T05:48:12 | 2019-10-31T05:48:12 | null | UTF-8 | Java | false | false | 3,007 | java | package io.aftersound.weave.dataclient;
import io.aftersound.weave.actor.ActorBindings;
import io.aftersound.weave.common.NamedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* Registry that maintains {@link DataClientFactory} for known data clients.
*/
public class DataClientFactoryRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(DataClientFactoryRegistry.class);
private final Object lock = new Object();
private final DataClientRegistry dataClientRegistry;
private final ActorBindings<Endpoint, DataClientFactory<?>, Object> dataClientFactoryBindings;
private Map<Class<?>, DataClientFactory<?>> factoryByClientType = new HashMap<>();
DataClientFactoryRegistry(
DataClientRegistry dataClientRegistry,
ActorBindings<Endpoint, DataClientFactory<?>, Object> dataClientFactoryBindings) {
this.dataClientRegistry = dataClientRegistry;
this.dataClientFactoryBindings = dataClientFactoryBindings;
}
DataClientFactoryRegistry initialize() throws Exception {
synchronized (lock) {
NamedTypes<Endpoint> controlTypes = dataClientFactoryBindings.controlTypes();
NamedTypes<Object> clientTypes = dataClientFactoryBindings.productTypes();
for (String name : controlTypes.names()) {
Class<?> clientType = clientTypes.get(name).type();
Class<?> factoryType = dataClientFactoryBindings.getActorType(name);
DataClientFactory<?> factory = createFactory0(factoryType);
factoryByClientType.put(clientType, factory);
}
}
return this;
}
public <CLIENT> void unregisterDataClientFactory(Class<CLIENT> clientType) {
synchronized (lock) {
factoryByClientType.remove(clientType);
}
}
@SuppressWarnings("unchecked")
public <CLIENT> DataClientFactory<CLIENT> getDataClientFactory(Class<CLIENT> clientType) throws Exception {
return (DataClientFactory<CLIENT>) factoryByClientType.get(clientType);
}
private DataClientFactory<?> createFactory0(Class<?> factoryType) throws Exception {
try {
Constructor<? extends DataClientFactory<?>> constructor =
(Constructor<? extends DataClientFactory<?>>)factoryType.getDeclaredConstructor(DataClientRegistry.class);
return constructor.newInstance(dataClientRegistry);
} catch (Exception any) {
LOGGER.error("failed to instantiate an instance of " + factoryType, any);
throw any;
}
}
public <CLIENT, FACTORY extends DataClientFactory<CLIENT>> FACTORY getDataClientFactory(String name) throws Exception {
Class<CLIENT> clientType = (Class<CLIENT>) dataClientFactoryBindings.getProductTypeByName(name);
return (FACTORY) getDataClientFactory(clientType);
}
}
| [
"[email protected]"
] | |
4caf7e453350cd8b072b017713c4eec13e6a5968 | 192e38513ff24afc68a07bbb162eb0b16a6e0c4e | /src/_39_HW_MenuItemsInputOutput/menu/Menu.java | 082a56a5abc3d50ba5855b48ad7c67287d61f720 | [] | no_license | Vinny198405/MyUtil | 4cbb5051f2f519b91f5d1f3188b2d11a19df429a | 092bad7c46110ddb7b36ece1e4ed7da0c146cb49 | refs/heads/master | 2021-04-09T03:03:49.515577 | 2020-07-09T07:21:06 | 2020-07-09T07:21:06 | 248,832,629 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package _39_HW_MenuItemsInputOutput.menu;
public class Menu {
private Item[] items;
private InputOutput inputOutput;
public Menu(Item[] items, InputOutput inputOutput) {
this.items = items;
this.inputOutput = inputOutput;
}
public void menuRun() {
Item item = null;
do {
for (int i = 1; i <= items.length; i++) {
inputOutput.displayLine(i + ". " + items[i - 1].displayName());
}
int nItem = inputOutput.inputInteger
("Select item number", 1, items.length);
item = items[nItem - 1];
try {
item.perform();
} catch (Exception e) {
inputOutput.displayLine(e.getMessage());
}
} while (!item.isExit());
}
}
| [
"[email protected]"
] | |
2e9f626f4319bf9b3d206197eea7f0cf4eea6f22 | dae71225fbfb7f64e6ffdc06a894bc7eb7cf39c8 | /app/src/test/java/cn/edu/gdmec/s07150850/mymediaplayer/ExampleUnitTest.java | 0b55578149a2c7066621c3017a957616afbfcddc | [] | no_license | gdmec07150850/MyMediaPlayer | e9f0346692ac561060f00086ccc79e0f5e791aef | ccdc52fb2420d97f141f5ddd79add5b21857a64c | refs/heads/master | 2021-01-13T17:01:32.731302 | 2016-12-18T08:18:30 | 2016-12-18T08:18:30 | 76,771,180 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 329 | java | package cn.edu.gdmec.s07150850.mymediaplayer;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
5b97f4ad315389ac6fd2fe5aa553c51a8347f508 | 7ccf732874799285508a2417d7f365e90d26a8c7 | /src/main/java/pl/sda/dao/StudentDAO.java | a668ba836f52d5c02c61faeefe1d369f2d45162b | [] | no_license | jakubfraczek/spring-mvc | ee46e6dcfe9233b5a79cb53b6230f781c4c259df | 898a0231c9b783f34c3b328e6948e27c7f11b4e0 | refs/heads/master | 2021-01-20T04:46:10.948326 | 2017-04-23T19:57:02 | 2017-04-23T19:57:02 | 89,724,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | package pl.sda.dao;
import pl.sda.model.Student;
import java.util.List;
public interface StudentDAO {
Student getStudentByLogin(String login);
boolean addStudent(Student student);
boolean removeStudent(String login);
void updateStudent(Student student);
List<Student> getAllStudents();
List<Student> findStudentsByName(String name);
}
| [
"[email protected]"
] | |
1b03b0744c9073ee23e360c14402f8e62424b5be | 51951e037aaf45068c0323f715b3513f26c48691 | /core/src/main/java/com/mohammadsayed/architecture/network/BaseRequest.java | 19a897ef6ce85e3f3a01ad22020a48e58e5b0873 | [] | no_license | mohammad-sayed/Celebrities | 40ede69e9cee0694acde0cea24a9d13c9e3fb603 | 3e60298666db0898c45a4ec52ac4d30c0f7472aa | refs/heads/master | 2021-08-06T11:20:35.007462 | 2017-11-04T19:00:42 | 2017-11-04T19:00:42 | 109,392,081 | 0 | 0 | null | 2017-11-04T19:00:43 | 2017-11-03T12:17:58 | Java | UTF-8 | Java | false | false | 3,369 | java | package com.mohammadsayed.architecture.network;
import android.net.Uri;
import com.mohammadsayed.architecture.utils.ExceptionUtil;
import com.mohammadsayed.architecture.utils.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mohammad on 1/16/17.
*/
public abstract class BaseRequest {
private Map<String, String> headers;
private String url;
private ArrayList<String> pathParameters;
private String operationTag;
protected BaseRequest(String url) {
setUrl(url);
setHeaders(new HashMap<String, String>());
setPathParameters(new ArrayList<String>());
}
//Methods --------------------------------------------------------------------------------------
abstract public NetworkConstants.RequestMethod getRequestMethod();
public void addHeader(String key, String value) {
getHeaders().put(key, value);
}
public void addPathParameter(String parameter) {
getPathParameters().add(parameter);
}
private String concatenatePathParameters() {
Uri.Builder builder = Uri.parse(url).buildUpon();
for (String string : pathParameters) {
builder.appendPath(string);
}
return builder.build().toString();
}
//Getters and Setters --------------------------------------------------------------------------
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getUrl() {
return concatenatePathParameters();
}
public void setUrl(String url) {
this.url = url;
}
public void setUri(String uri) {
this.url = getUrl() + uri;
}
public ArrayList<String> getPathParameters() {
return pathParameters;
}
public void setPathParameters(ArrayList<String> pathParameters) {
this.pathParameters = pathParameters;
}
public String getOperationTag() {
return operationTag;
}
public void setOperationTag(String operationTag) {
this.operationTag = operationTag;
}
abstract public static class Builder<R extends BaseRequest, B extends Builder> {
private R request;
public B setUrl(String url) {
request.setUrl(url);
return (B) this;
}
public B setUri(String uri) {
request.setUri(uri);
return (B) this;
}
public B setPathParameters(ArrayList<String> pathParameters) {
request.setPathParameters(pathParameters);
return (B) this;
}
public B setHeaders(Map<String, String> headers) {
request.setHeaders(headers);
return (B) this;
}
public B setOperationTag(String operationTag) {
request.setOperationTag(operationTag);
return (B) this;
}
public R build() {
if (StringUtil.isEmpty(request.getUrl(), true)) {
ExceptionUtil.throwRuntimeException("No URL inserted");
}
return request;
}
protected R getRequest() {
return request;
}
protected void setRequest(R request) {
this.request = request;
}
}
}
| [
"[email protected]"
] | |
8f06846647166a52fa4f7af802873eee5c2227c3 | 9fff14fc070ab9dd6ce19b6c51c8b6e5cd2248c5 | /ColorTribe/ColorHealer/src/fr/hd3d/colortribe/gui/HealerMainWindow.java | 1f61dc5ce742ed7957d896098627f6a0102738fe | [
"BSD-3-Clause"
] | permissive | shootthemoonfilms/OpenDisplayCalib | 3bfc90f825b8d4104bdac780bb7f7d03d90d7cd6 | 8e90914d965e943b11add4f8ad0b7bec0564c4ab | refs/heads/master | 2021-01-18T02:52:27.474589 | 2016-03-02T16:25:06 | 2016-03-02T16:25:06 | 52,976,703 | 0 | 0 | null | 2016-03-02T16:08:49 | 2016-03-02T16:08:49 | null | UTF-8 | Java | false | false | 8,790 | java | package fr.hd3d.colortribe.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import fr.hd3d.colortribe.core.ColorHealerModel;
import fr.hd3d.colortribe.core.probes.IProbe;
import fr.hd3d.colortribe.gui.components.JHealerMenu;
import fr.hd3d.colortribe.gui.steps.Step;
public class HealerMainWindow extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 8666214186131138078L;
private JPanel _step;
private JHealerMenu _menu;
private JButton _closeButt;
private JPanel _mainContainer = new JPanel(new BorderLayout());
static public HealerMainWindow _instance = new HealerMainWindow();
private HealerMainWindow()
{
super("ColorHealer");
setSize(790, 610);
_mainContainer = new JPanel(new BorderLayout());
// register the shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run()
{
ColorHealerModel._instance.getSocketServer().closeServer();
IProbe probe = ColorHealerModel._instance.getProbe();
if (probe != null)
probe.close();
}
});
;
/*
* try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException e)
* {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch
* (UnsupportedLookAndFeelException e) {}
*/
UIManager.put("Panel.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("Panel.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("Label.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("Label.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("TextArea.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("TextArea.foreground", JHealerColors.TEXT_COLOR);
// ///button
UIManager.put("Button.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("Button.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("Button.shadow", JHealerColors.DISABLE_TEXT_COLOR);
UIManager.put("Button.disabledText", JHealerColors.DISABLE_TEXT_COLOR);
UIManager.put("Button.border", new LineBorder(Color.black, 2));
UIManager.put("ToggleButton.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("ToggleButton.foreground", JHealerColors.TEXT_COLOR);
// UIManager.put("ToggleButton.shadow", SHADOW_COLOR);
// UIManager.put("ToggleButton.disabledText", SHADOW_COLOR);
// UIManager.put("ToggleButton.border", new LineBorder(BORDER_COLOR, 1));
UIManager.put("ToggleButton.select", Color.black);
// /
UIManager.put("ComboBox.background", JHealerColors.BACKGROUNG_COLOR.brighter());
UIManager.put("ComboBox.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("ComboBox.selectionBackground", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("ComboBox.selectionForeground", JHealerColors.TEXT_COLOR);
UIManager.put("List.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("List.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("List.selectionBackground", JHealerColors.BACKGROUNG_COLOR.darker());
UIManager.put("List.selectionForeground", JHealerColors.TEXT_COLOR);
// ComboBox.background
// ComboBox.buttonBackground
// ComboBox.buttonDarkShadow
// ComboBox.buttonHighlight
// ComboBox.buttonShadow
// ComboBox.disabledBackground
// ComboBox.disabledForeground
// ComboBox.font
// ComboBox.foreground
// ComboBox.selectionBackground
// ComboBox.selectionForeground
// ComboBox.timeFactor
// //////error dialogs
UIManager.put("OptionPane.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("OptionPane.border.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("OptionPane.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("OptionPane.messageForeground", JHealerColors.TEXT_COLOR);
// font //
UIManager.put("TextField.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("TextField.foreground", JHealerColors.TEXT_COLOR);
UIManager.put("TextField.caretForeground", JHealerColors.TEXT_COLOR);
// //
// UIManager.put("TextField.font", FONT);
// UIManager.put("TextArea.font", FONT);
// UIManager.put("Label.font", FONT_BOLD);
// UIManager.put("Button.font", FONT_BOLD);
UIManager.put("ToolTip.foreground", JHealerColors.TEXT_COLOR.brighter());
UIManager.put("Slider.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("Slider.messageForeground", JHealerColors.TEXT_COLOR);
UIManager.put("RadioButton.background", JHealerColors.BACKGROUNG_COLOR);
UIManager.put("CheckBox.background", JHealerColors.BACKGROUNG_COLOR);
// tree
UIManager.put("Tree.background", JHealerColors.BACKGROUNG_COLOR);
add(_mainContainer);
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension size = this.getSize();
if (size.height > screenSize.height)
size.height = screenSize.height;
setLocation((int) getLocation().getX() + 5, (screenSize.height - size.height) / 2);
JPanel downPan = new JPanel();
_closeButt = new JButton("Close");
_closeButt.setPreferredSize(new Dimension(80, 20));
_closeButt.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e)
{
int reponse = 66;
if (!ColorHealerModel._instance.isCalibUpdated())
reponse = JOptionPane.showConfirmDialog(null,
"Screen calibration is not over.\nDo you really want to quit ?", "Quit ?",
JOptionPane.YES_NO_OPTION);
if (ColorHealerModel._instance.isCalibUpdated() || reponse == JOptionPane.YES_OPTION)
{
try
{
ColorHealerModel._instance.getSocketServer().sendMessage(
"BUH_BYE " + ColorHealerModel._instance.getDisplayDevice().getOsIndex() + "\n");
}
catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
System.exit(0);
}
}
});
downPan.add(_closeButt);
_mainContainer.add(downPan, BorderLayout.SOUTH);
add(_mainContainer);
}
private boolean isInit = false;
private void init()
{
if (!isInit)
{
_step = ColorHealerModel._instance.getProtocol().getSelectedStep().getContentPane();
_mainContainer.add(_step, BorderLayout.CENTER);
_menu = new JHealerMenu(this);
_mainContainer.add(_menu, BorderLayout.WEST);
isInit = true;
}
}
void open()
{
init();
setVisible(true);
}
public void rePaintStep()
{
_mainContainer.remove(_step);
Step currStep = ColorHealerModel._instance.getProtocol().getSelectedStep();
currStep.init();
_step = currStep.getContentPane();
_mainContainer.add(_step);
_mainContainer.validate();
_mainContainer.repaint();
// validate();
// repaint();
}
public void rePaintMenu()
{
_menu.validate();
_menu.repaint();
// validate();
// repaint();
}
public void paint(Graphics g)
{
super.paint(g);
int height = this.getHeight();
int width = this.getWidth();
g.setColor(Color.black);
g.drawRect(0, 0, width - 2, height - 2);
}
}
| [
"[email protected]"
] | |
21a9f1f39c30221c93b16e2ab1eeea6d88589f62 | a92a04a1816136d682f5dbbb12de16e5fadbcbbe | /src/nl/visi/interaction_framework/editor/v14/ExcelReportGenerator14.java | b6339a02218f8a01ec1229801d39d58cf2473523 | [] | no_license | PeterInfraBIM/Interaction-Framework-Editor | 17cb1e5c4d83730a02b53639f9e53d3db4d563ad | 33340f1ce82aed0edfec230cb21751c8886c456e | refs/heads/master | 2022-08-21T19:43:02.059203 | 2022-07-30T09:38:29 | 2022-07-30T09:38:29 | 226,647,032 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 32,702 | java | package nl.visi.interaction_framework.editor.v14;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import jxl.CellView;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import nl.visi.interaction_framework.editor.v14.ComplexElementsPanelControl14.SimpleElementsTableModel;
//import nl.visi.interaction_framework.editor.v14.ComplexElementsPanelControl14.SubComplexElementsTableModel;
import nl.visi.interaction_framework.editor.v14.MainPanelControl14.Tabs;
import nl.visi.interaction_framework.editor.v14.MessagesPanelControl14.TransactionsTableModel;
import nl.visi.interaction_framework.editor.v14.TransactionsPanelControl14.MessagesTableModel;
import nl.visi.schemas._20140331.AppendixTypeType;
import nl.visi.schemas._20140331.ComplexElementTypeType;
import nl.visi.schemas._20140331.ElementType;
import nl.visi.schemas._20140331.MessageInTransactionTypeType;
import nl.visi.schemas._20140331.MessageInTransactionTypeType.Message;
import nl.visi.schemas._20140331.MessageInTransactionTypeType.Transaction;
import nl.visi.schemas._20140331.MessageTypeType;
import nl.visi.schemas._20140331.RoleTypeType;
import nl.visi.schemas._20140331.SimpleElementTypeType;
import nl.visi.schemas._20140331.SimpleElementTypeType.UserDefinedType;
import nl.visi.schemas._20140331.TransactionTypeType;
import nl.visi.schemas._20140331.TransactionTypeType.Executor;
import nl.visi.schemas._20140331.TransactionTypeType.Initiator;
import nl.visi.schemas._20140331.UserDefinedTypeType;
class ExcelReportGenerator14 extends Control14 {
private final MainPanelControl14 mainPanelControl;
public ExcelReportGenerator14(MainPanelControl14 mainPanel) {
this.mainPanelControl = mainPanel;
}
public void writeReport(File excelFile) throws IOException {
try {
WritableWorkbook workbook = Workbook.createWorkbook(excelFile);
writeRoleTypesSheet(workbook, 0);
writeTransactionTypesSheet(workbook, 1);
writeMessageTypesSheet(workbook, 2);
writeComplexElementTypesSheet(workbook, 3);
writeSimpleElementTypesSheet(workbook, 4);
writeDataTypesSheet(workbook, 5);
writeAppendixTypesSheet(workbook, 6);
workbook.write();
workbook.close();
} catch (WriteException e) {
throw new IOException(e);
}
}
private DateFormat customDateFormat = new DateFormat("dd MMM yyyy");
private WritableCellFormat headingFormat;
private WritableCellFormat dataFormat;
private WritableCellFormat dateFormat;
private WritableCellFormat getHeadingFormat() throws WriteException {
if (headingFormat == null) {
headingFormat = new WritableCellFormat();
headingFormat.setBackground(Colour.OCEAN_BLUE);
headingFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
WritableFont headingFont = new WritableFont(WritableFont.ARIAL, 9, WritableFont.BOLD);
headingFont.setColour(Colour.WHITE);
headingFormat.setFont(headingFont);
}
return headingFormat;
}
private WritableCellFormat getDateFormat() throws WriteException {
if (dateFormat == null) {
dateFormat = new WritableCellFormat(customDateFormat);
// dataFormat.setBackground(Colour.OCEAN_BLUE);
dateFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
WritableFont headingFont = new WritableFont(WritableFont.ARIAL, 9, WritableFont.NO_BOLD);
// headingFont.setColour(Colour.WHITE);
dateFormat.setFont(headingFont);
dateFormat.setWrap(true);
}
return dateFormat;
}
private WritableCellFormat getDataFormat() throws WriteException {
if (dataFormat == null) {
dataFormat = new WritableCellFormat();
// dataFormat.setBackground(Colour.OCEAN_BLUE);
dataFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
WritableFont headingFont = new WritableFont(WritableFont.ARIAL, 9, WritableFont.NO_BOLD);
// headingFont.setColour(Colour.WHITE);
dataFormat.setFont(headingFont);
dataFormat.setWrap(true);
}
return dataFormat;
}
private void writeRoleTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_RoleTypesSheet"), tabIndex);
initColumnView(sheet, 0);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_RoleTypesSheet")));
List<RoleTypeType> roleTypes = Editor14.getStore14().getElements(RoleTypeType.class);
for (RoleTypeType roleType : roleTypes) {
row++;
sheet.addCell(new Label(col, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getId(), getHeadingFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Description"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getDescription(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_StartDate"), getDataFormat()));
XMLGregorianCalendar startDate = roleType.getStartDate();
if (startDate != null) {
sheet.addCell(new DateTime(col + 1, row, roleType.getStartDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_EndDate"), getDataFormat()));
XMLGregorianCalendar endDate = roleType.getEndDate();
if (endDate != null) {
sheet.addCell(new DateTime(col + 1, row, roleType.getEndDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_State"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getState(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Language"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getLanguage(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Category"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getCategory(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_HelpInfo"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getHelpInfo(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Code"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getCode(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row,
getBundle().getString("lbl_Responsibility") + " " + getBundle().getString("lbl_Scope"),
getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getResponsibilityScope(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row,
getBundle().getString("lbl_Responsibility") + " " + getBundle().getString("lbl_Task"),
getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getResponsibilityTask(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row,
getBundle().getString("lbl_Responsibility") + " " + getBundle().getString("lbl_SupportTask"),
getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getResponsibilitySupportTask(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row,
getBundle().getString("lbl_Responsibility") + " " + getBundle().getString("lbl_Feedback"),
getDataFormat()));
sheet.addCell(new Label(col + 1, row, roleType.getResponsibilityFeedback(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Transactions"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
row++;
List<TransactionTypeType> elements = Editor14.getStore14().getElements(TransactionTypeType.class);
for (TransactionTypeType transaction : elements) {
Initiator initiator = transaction.getInitiator();
if (initiator != null) {
RoleTypeType rt = initiator.getRoleType();
if (rt == null) {
rt = (RoleTypeType) initiator.getRoleTypeRef().getIdref();
}
if (roleType.equals(rt)) {
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row,
transaction.getId() + " (" + getBundle().getString("lbl_Initiator") + ")",
getDataFormat()));
row++;
continue;
}
}
Executor executor = transaction.getExecutor();
if (executor != null) {
RoleTypeType rt = executor.getRoleType();
if (rt == null) {
rt = (RoleTypeType) executor.getRoleTypeRef().getIdref();
}
if (roleType.equals(rt)) {
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row,
transaction.getId() + " (" + getBundle().getString("lbl_Executor") + ")",
getDataFormat()));
row++;
continue;
}
}
}
}
}
private void writeTransactionTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_TransactionTypesSheet"), tabIndex);
initColumnView(sheet, 1);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_TransactionTypesSheet")));
int transactionIndex = -1;
List<TransactionTypeType> transactionTypes = Editor14.getStore14().getElements(TransactionTypeType.class);
for (TransactionTypeType transactionType : transactionTypes) {
transactionIndex++;
row++;
sheet.addCell(new Label(col, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getId(), getHeadingFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Description"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getDescription(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_StartDate"), getDataFormat()));
XMLGregorianCalendar startDate = transactionType.getStartDate();
if (startDate != null) {
sheet.addCell(new DateTime(col + 1, row, transactionType.getStartDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_EndDate"), getDataFormat()));
XMLGregorianCalendar endDate = transactionType.getEndDate();
if (endDate != null) {
sheet.addCell(new DateTime(col + 1, row, transactionType.getEndDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_State"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getState(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Language"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getLanguage(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Category"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getCategory(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_HelpInfo"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getHelpInfo(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Code"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getCode(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Result"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getResult(), getDataFormat()));
row++;
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Initiator"), getDataFormat()));
Initiator initiator = transactionType.getInitiator();
RoleTypeType roleType = null;
if (initiator != null) {
roleType = initiator.getRoleType();
if (roleType == null) {
roleType = (RoleTypeType) initiator.getRoleTypeRef().getIdref();
}
}
sheet.addCell(new Label(col + 1, row, roleType != null ? roleType.getId() : "", getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Executor"), getDataFormat()));
Executor executor = transactionType.getExecutor();
if (executor != null) {
roleType = executor.getRoleType();
if (roleType == null) {
roleType = (RoleTypeType) executor.getRoleTypeRef().getIdref();
}
}
sheet.addCell(new Label(col + 1, row, roleType != null ? roleType.getId() : "", getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Messages"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
mainPanelControl.tabs.setSelectedIndex(Tabs.Transactions.ordinal());
TransactionsPanelControl14 transactionsPC = MainPanelControl14.getTransactionsPC();
transactionsPC.tbl_Elements.getSelectionModel().setSelectionInterval(transactionIndex, transactionIndex);
MessagesTableModel messagesTableModel = transactionsPC.getMessagesTableModel();
for (int msgIndex = 0; msgIndex < messagesTableModel.getRowCount(); msgIndex++) {
MessageInTransactionTypeType mitt = messagesTableModel.get(msgIndex);
Message message = mitt.getMessage();
MessageTypeType messageType = message.getMessageType();
if (messageType == null) {
messageType = (MessageTypeType) message.getMessageTypeRef().getIdref();
}
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getId(), getDataFormat()));
}
row++;
}
}
private void writeMessageTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_MessageTypesSheet"), tabIndex);
initColumnView(sheet, 2);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_MessageTypesSheet")));
int messageIndex = -1;
List<MessageTypeType> messageTypes = Editor14.getStore14().getElements(MessageTypeType.class);
for (MessageTypeType messageType : messageTypes) {
messageIndex++;
row++;
sheet.addCell(new Label(col, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getId(), getHeadingFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Description"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getDescription(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_StartDate"), getDataFormat()));
XMLGregorianCalendar startDate = messageType.getStartDate();
if (startDate != null) {
sheet.addCell(new DateTime(col + 1, row, messageType.getStartDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_EndDate"), getDataFormat()));
XMLGregorianCalendar endDate = messageType.getEndDate();
if (endDate != null) {
sheet.addCell(new DateTime(col + 1, row, messageType.getEndDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_State"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getState(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Language"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getLanguage(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Category"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getCategory(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_HelpInfo"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getHelpInfo(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Code"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, messageType.getCode(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Transactions"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
mainPanelControl.tabs.setSelectedIndex(Tabs.Messages.ordinal());
MessagesPanelControl14 messagesPC = MainPanelControl14.getMessagesPC();
messagesPC.tbl_Elements.getSelectionModel().setSelectionInterval(messageIndex, messageIndex);
TransactionsTableModel transactionsTableModel = messagesPC.getTransactionsTableModel();
for (int trnsIndex = 0; trnsIndex < transactionsTableModel.getRowCount(); trnsIndex++) {
MessageInTransactionTypeType mitt = transactionsTableModel.get(trnsIndex);
Transaction transaction = mitt.getTransaction();
TransactionTypeType transactionType = transaction.getTransactionType();
if (transactionType == null) {
transactionType = (TransactionTypeType) transaction.getTransactionTypeRef().getIdref();
}
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, transactionType.getId(), getDataFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_ComplexElements"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
List<ComplexElementTypeType> complexElements = Control14.getComplexElements(messageType);
for (ComplexElementTypeType complexElementTypeType : complexElements) {
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementTypeType.getId(), getDataFormat()));
}
row++;
}
}
private void writeComplexElementTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_ComplexElementTypesSheet"), tabIndex);
initColumnView(sheet, 3);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_ComplexElementTypesSheet")));
int complexElementIndex = -1;
List<ComplexElementTypeType> complexElementTypes = Editor14.getStore14()
.getElements(ComplexElementTypeType.class);
for (ComplexElementTypeType complexElementType : complexElementTypes) {
complexElementIndex++;
row++;
sheet.addCell(new Label(col, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getId(), getHeadingFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Description"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getDescription(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_StartDate"), getDataFormat()));
XMLGregorianCalendar startDate = complexElementType.getStartDate();
if (startDate != null) {
sheet.addCell(new DateTime(col + 1, row,
complexElementType.getStartDate().toGregorianCalendar().getTime(), getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_EndDate"), getDataFormat()));
XMLGregorianCalendar endDate = complexElementType.getEndDate();
if (endDate != null) {
sheet.addCell(new DateTime(col + 1, row,
complexElementType.getEndDate().toGregorianCalendar().getTime(), getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_State"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getState(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Language"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getLanguage(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Category"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getCategory(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_HelpInfo"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementType.getHelpInfo(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_ComplexElements"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
mainPanelControl.tabs.setSelectedIndex(Tabs.ComplexElements.ordinal());
ComplexElementsPanelControl14 complexElementsPC = MainPanelControl14.getComplexElementsPC();
complexElementsPC.tbl_Elements.getSelectionModel().setSelectionInterval(complexElementIndex,
complexElementIndex);
List<ComplexElementTypeType> complexElements = Control14.getComplexElements(complexElementType);
if (complexElements != null) {
for (ComplexElementTypeType subComplexElementType : complexElements) {
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, subComplexElementType.getId(), getDataFormat()));
}
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_SimpleElements"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
SimpleElementsTableModel simpleElementsTableModel = complexElementsPC.getSimpleElementsTableModel();
for (int smpeIndex = 0; smpeIndex < simpleElementsTableModel.getRowCount(); smpeIndex++) {
SimpleElementTypeType simpleElementTypeType = simpleElementsTableModel.get(smpeIndex);
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, simpleElementTypeType.getId(), getDataFormat()));
}
row++;
}
}
private void writeSimpleElementTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_SimpleElementTypesSheet"), tabIndex);
initColumnView(sheet, 4);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_SimpleElementTypesSheet")));
row++;
sheet.addCell(new Label(col++, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_Description"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_InterfaceType"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_State"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_Language"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_Category"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_HelpInfo"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_ValueList"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_UserDefinedType"), getHeadingFormat()));
row++;
List<SimpleElementTypeType> simpleElementTypes = Editor14.getStore14().getElements(SimpleElementTypeType.class);
for (SimpleElementTypeType simpleElementType : simpleElementTypes) {
col = 0;
sheet.addCell(new Label(col++, row, simpleElementType.getId(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getDescription(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getInterfaceType(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getState(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getLanguage(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getCategory(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getHelpInfo(), getDataFormat()));
sheet.addCell(new Label(col++, row, simpleElementType.getValueList(), getDataFormat()));
UserDefinedTypeType userDefinedType = getUserDefinedType(simpleElementType.getUserDefinedType());
sheet.addCell(
new Label(col++, row, userDefinedType != null ? userDefinedType.getId() : "", getDataFormat()));
row++;
}
}
private UserDefinedTypeType getUserDefinedType(UserDefinedType udt) {
UserDefinedTypeType userDefinedType = null;
if (udt != null) {
userDefinedType = udt.getUserDefinedType();
if (userDefinedType == null) {
userDefinedType = (UserDefinedTypeType) udt.getUserDefinedTypeRef().getIdref();
}
}
return userDefinedType;
}
private void writeDataTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_DataTypesSheet"), tabIndex);
initColumnView(sheet, 5);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_DataTypesSheet")));
row++;
sheet.addCell(new Label(col++, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_Description"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_State"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_BaseType"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_XsdRestriction"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_Language"), getHeadingFormat()));
sheet.addCell(new Label(col++, row, getBundle().getString("lbl_HelpInfo"), getHeadingFormat()));
row++;
List<UserDefinedTypeType> userDefinedTypes = Editor14.getStore14().getElements(UserDefinedTypeType.class);
for (UserDefinedTypeType userDefinedType : userDefinedTypes) {
col = 0;
sheet.addCell(new Label(col++, row, userDefinedType.getId(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getDescription(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getState(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getBaseType(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getXsdRestriction(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getLanguage(), getDataFormat()));
sheet.addCell(new Label(col++, row, userDefinedType.getHelpInfo(), getDataFormat()));
row++;
}
}
private void writeAppendixTypesSheet(WritableWorkbook workbook, int tabIndex) throws WriteException {
WritableSheet sheet = workbook.createSheet(getBundle().getString("lbl_AppendixTypesSheet"), tabIndex);
initColumnView(sheet, 2);
int col = 0;
int row = 0;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_AppendixTypesSheet")));
int miscellaneousIndex = 0;
MiscellaneousPanelControl14 miscellaneousPC = MainPanelControl14.getMiscellaneousPC();
ElementType elementType = null;
nl.visi.interaction_framework.editor.v14.MiscellaneousPanelControl14.ComplexElementsTableModel complexElementsTableModel = null;
// do {
// miscellaneousPC.tbl_Elements.getSelectionModel().setSelectionInterval(miscellaneousIndex, miscellaneousIndex);
// elementType = miscellaneousPC.elementsTableModel.get(miscellaneousIndex++);
// complexElementsTableModel = miscellaneousPC.getComplexElementsTableModel();
// } while (!(elementType instanceof AppendixTypeType) && miscellaneousIndex < miscellaneousPC.tbl_Elements.getRowCount());
List<AppendixTypeType> appendixTypes = Editor14.getStore14().getElements(AppendixTypeType.class);
for (AppendixTypeType appendixType : appendixTypes) {
miscellaneousIndex++;
row++;
sheet.addCell(new Label(col, row, "ID", getHeadingFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getId(), getHeadingFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Description"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getDescription(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_StartDate"), getDataFormat()));
XMLGregorianCalendar startDate = appendixType.getStartDate();
if (startDate != null) {
sheet.addCell(new DateTime(col + 1, row, appendixType.getStartDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_EndDate"), getDataFormat()));
XMLGregorianCalendar endDate = appendixType.getEndDate();
if (endDate != null) {
sheet.addCell(new DateTime(col + 1, row, appendixType.getEndDate().toGregorianCalendar().getTime(),
getDateFormat()));
}
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_State"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getState(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Language"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getLanguage(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Category"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getCategory(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_HelpInfo"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getHelpInfo(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_Code"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, appendixType.getCode(), getDataFormat()));
row++;
sheet.addCell(new Label(col, row, getBundle().getString("lbl_ComplexElements"), getDataFormat()));
sheet.addCell(new Label(col + 1, row, "", getDataFormat()));
mainPanelControl.tabs.setSelectedIndex(Tabs.Miscellaneous.ordinal());
while (!(elementType instanceof AppendixTypeType)
&& miscellaneousIndex < miscellaneousPC.tbl_Elements.getRowCount()) {
miscellaneousPC.tbl_Elements.getSelectionModel().setSelectionInterval(miscellaneousIndex,
miscellaneousIndex);
elementType = miscellaneousPC.elementsTableModel.get(miscellaneousIndex++);
complexElementsTableModel = miscellaneousPC.getComplexElementsTableModel();
}
for (int trnsIndex = 0; trnsIndex < complexElementsTableModel.getRowCount(); trnsIndex++) {
ComplexElementTypeType complexElementTypeType = complexElementsTableModel.get(trnsIndex);
row++;
sheet.addCell(new Label(col, row, "", getDataFormat()));
sheet.addCell(new Label(col + 1, row, complexElementTypeType.getId(), getDataFormat()));
}
row++;
}
}
private void initColumnView(WritableSheet sheet, int sheetIndex) {
CellView cv = new CellView();
switch (sheetIndex) {
case 0:
case 1:
case 2:
case 3:
cv.setSize(28 * 256);
sheet.setColumnView(0, cv);
cv.setSize(50 * 256);
sheet.setColumnView(1, cv);
break;
case 4:
cv.setSize(28 * 256);
sheet.setColumnView(0, cv);
cv.setSize(28 * 256);
sheet.setColumnView(1, cv);
cv.setSize(6 * 256);
sheet.setColumnView(2, cv);
cv.setSize(10 * 256);
sheet.setColumnView(3, cv);
cv.setSize(15 * 256);
sheet.setColumnView(4, cv);
cv.setSize(35 * 256);
sheet.setColumnView(5, cv);
cv.setSize(8 * 256);
sheet.setColumnView(6, cv);
cv.setSize(16 * 256);
sheet.setColumnView(7, cv);
break;
case 5:
cv.setSize(28 * 256);
sheet.setColumnView(0, cv);
cv.setSize(28 * 256);
sheet.setColumnView(1, cv);
cv.setSize(6 * 256);
sheet.setColumnView(2, cv);
cv.setSize(10 * 256);
sheet.setColumnView(3, cv);
cv.setSize(50 * 256);
sheet.setColumnView(4, cv);
cv.setSize(10 * 256);
sheet.setColumnView(5, cv);
cv.setSize(28 * 256);
sheet.setColumnView(6, cv);
break;
}
}
} | [
"[email protected]"
] | |
102c699a850f3c7026a20ef83e9931bf90cab4e7 | 6f06a3c38c961e3fe8cfc14d3af622a628b62827 | /app/src/main/java/com/codepath/apps/restclienttemplate/TwitterClient.java | ef8c1f498b73153bf229cbe59ee7abee138eb00b | [
"MIT"
] | permissive | DanielPallares23/MySimpleTweets | fa5810393c4ac1527f11436556ac7d5d92acb059 | b4098f6eda457e94d8a031f66a8dd7be78dc7cdd | refs/heads/master | 2020-12-14T08:48:12.630092 | 2017-06-30T03:09:01 | 2017-06-30T03:09:01 | 95,497,743 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,741 | java | package com.codepath.apps.restclienttemplate;
import android.content.Context;
import com.codepath.oauth.OAuthBaseClient;
import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.api.BaseApi;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/*
*
* This is the object responsible for communicating with a REST API.
* Specify the constants below to change the API being communicated with.
* See a full list of supported API classes:
* https://github.com/scribejava/scribejava/tree/master/scribejava-apis/src/main/java/com/github/scribejava/apis
* Key and Secret are provided by the developer site for the given API i.e dev.twitter.com
* Add methods for each relevant endpoint in the API.
*
* NOTE: You may want to rename this object based on the service i.e TwitterClient or FlickrClient
*
*/
public class TwitterClient extends OAuthBaseClient {
public static final BaseApi REST_API_INSTANCE = TwitterApi.instance(); // Change this
public static final String REST_URL = "https://api.twitter.com/1.1"; // Change this, base API URL
public static final String REST_CONSUMER_KEY = "oR3PYacyvJlHN0tTu3S3Dlr2r"; // Change this
public static final String REST_CONSUMER_SECRET = "meW6TNITJhYY69fRpRWXd3pKRwtaaMOcej21Ln7aDYYYhH9fd0"; // Change this
// Landing page to indicate the OAuth flow worked in case Chrome for Android 25+ blocks navigation back to the app.
public static final String FALLBACK_URL = "https://codepath.github.io/android-rest-client-template/success.html";
// See https://developer.chrome.com/multidevice/android/intents
public static final String REST_CALLBACK_URL_TEMPLATE = "intent://%s#Intent;action=android.intent.action.VIEW;scheme=%s;package=%s;S.browser_fallback_url=%s;end";
public TwitterClient(Context context) {
super(context, REST_API_INSTANCE,
REST_URL,
REST_CONSUMER_KEY,
REST_CONSUMER_SECRET,
String.format(REST_CALLBACK_URL_TEMPLATE, context.getString(R.string.intent_host),
context.getString(R.string.intent_scheme), context.getPackageName(), FALLBACK_URL));
}
// CHANGE THIS
// DEFINE METHODS for different API endpoints here
public void getHomeTimeline(AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("statuses/home_timeline.json");
// Can specify query string params directly or through RequestParams.
RequestParams params = new RequestParams();
params.put("count", 25);
params.put("since_id", 1);
client.get(apiUrl, params, handler);
}
/* 1. Define the endpoint URL with getApiUrl and pass a relative path to the endpoint
* i.e getApiUrl("statuses/home_timeline.json");
* 2. Define the parameters to pass to the request (query or body)
* i.e RequestParams params = new RequestParams("foo", "bar");
* 3. Define the request method and make a call to the client
* i.e client.get(apiUrl, params, handler);
* i.e client.post(apiUrl, params, handler);
*/
public void sendTweet(String message, AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("statuses/update.json");
// Can specify query string params directly or through RequestParams.
RequestParams params = new RequestParams();
params.put("status", message);
client.post(apiUrl, params, handler);
}
public void getScreenName(AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("account/settings.json");
client.get(apiUrl, handler);
}
public void getProfileDetails(String name, AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("users/show.json");
RequestParams params = new RequestParams();
params.put("screen_name", name);
client.get(apiUrl,params, handler);
}
}
| [
"[email protected]"
] | |
0ee3100a4014f7f50f7eb61321606215af6b68a3 | 9678e69be568d3683bd7b22c835a5e6c936ae686 | /Tools/Workbench/src/edu/uwb/braingrid/provenance/ProvMgr.java | 7260717141a0f56c583e62bdd5821b2acc13f2c1 | [
"Apache-2.0"
] | permissive | JewelYLee/BrainGrid | 545481debb8a4f35d8a7dfb2ba2ef649aaa2586e | a641fff5e2255bbd1bdf4ba68ed4a0cdf4d4d968 | refs/heads/main | 2021-01-21T03:54:39.564871 | 2016-11-29T09:15:42 | 2016-11-29T09:15:42 | 58,486,597 | 0 | 0 | null | 2016-10-11T08:07:26 | 2016-05-10T19:04:43 | C++ | UTF-8 | Java | false | false | 34,767 | java | package edu.uwb.braingrid.provenance;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.uwb.braingrid.provenance.model.ProvOntology;
import edu.uwb.braingrid.workbench.FileManager;
import edu.uwb.braingrid.workbench.project.ProjectMgr;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RiotNotFoundException;
/**
* <h2>Manages provenance for projects specified within the Brain Grid Toolbox
* Workbench.</h2>
*
* <p>
* Basic construction requires input files, simulator process, and an output
* file.</p>
*
* <p>
* Provenance may also be built as a work-in-progress using the add
* functions.</p>
*
* <hr><i>Required Libraries: All libraries included within Apache Jena 2.1</i>
*
* @author Del Davis
* @version 0.1
*/
public class ProvMgr {
// <editor-fold defaultstate="collapsed" desc="Members">
/* URI's and labels used to describe the provenance */
private String provOutputFileURI;
private static String localNameSpaceURI;
private static String remoteNameSpaceURI;
/* flags called prior to an operation through respective query functions */
/* RDF in-memory representation of the provenance */
private Model model;
public static final String ipServiceURL = "http://checkip.amazonaws.com/";
public static String REMOTE_NS_PREFIX = "remote";
public static String LOCAL_NS_PREFIX = "local";
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Construction">
/**
* Constructs the Provenance Constructor object from a previously recorded
* provenance file.
*
* @param project - Used as the base-name for the provenance file
* @param load - True if the provenance should be loaded from an existing
* file, Otherwise false, in which case a new provenance model will be
* created which has not yet been persisted to file storage anywhere
* @throws java.io.IOException, RiotNotFoundException
*/
public ProvMgr(ProjectMgr project, boolean load) throws IOException {
if (load) {
load(project);
} else {
init(project);
}
}
/**
* Empty initialization. Sets safety values for members.
*/
private void init(ProjectMgr project) throws IOException {
// create RDF model
model = ModelFactory.createDefaultModel();
provOutputFileURI
= project.determineProvOutputLocation()
+ project.getName() + ".ttl";
// set prefixes for...
// RDF syntax
model.setNsPrefix("rdf", ProvOntology.getRDFNameSpaceURI());
// RDF schema
model.setNsPrefix("rdfs", ProvOntology.getRDFSNameSpaceURI());
// w3 Prov Ontology
model.setNsPrefix("prov", ProvOntology.getPROVNameSpaceURI());
// XML schema
model.setNsPrefix("xsd", ProvOntology.getXSDNameSpaceURI());
localNameSpaceURI = getLocalNameSpaceURI();
// BrainGrid Prov
model.setNsPrefix(LOCAL_NS_PREFIX, localNameSpaceURI);
}
/**
* Loads a model from a previously saved turtle file
*
* @param projectName - The base name of the file containing the provenance
* @return true if the file loaded a model properly, otherwise false
*/
private void load(ProjectMgr project) throws RiotNotFoundException, IOException {
String name = project.getName();
provOutputFileURI = project.determineProvOutputLocation()
+ name + ".ttl";
model = RDFDataMgr.loadModel(provOutputFileURI);
localNameSpaceURI = getLocalNameSpaceURI();
model.setNsPrefix(LOCAL_NS_PREFIX, localNameSpaceURI);
trimRemoteNS();
}
/**
* Removes the provenance filename from which the model was loaded from all
* name spaces associated with remote machines.
*/
private void trimRemoteNS() {
Map<String, String> nsMap = model.getNsPrefixMap();
for (Entry entry : nsMap.entrySet()) {
String nameSpace = (String) entry.getKey();
String uri = (String) entry.getValue();
if (nameSpace.startsWith(REMOTE_NS_PREFIX)) {
remoteNameSpaceURI = uri.substring(uri.lastIndexOf('/') + 1);
model.setNsPrefix(nameSpace, remoteNameSpaceURI);
}
}
}
/**
* Sets a prefix in the model. This may be used to eliminate the file
* name-spacing that occurs when the provenance model is loaded from a file.
* A # separator is appended to the end of the URI as a delimiter
* automatically, do not include it at the end of the URI. URIs in the model
* which begin with the prefix URI
*
* @param prefix - Identifier for the name space
* @param uri - The URI of the name space
*/
public void setNsPrefix(String prefix, String uri) {
// if the model doesn't have a prefix for the uri
if (model.getNsURIPrefix(uri + "#") == null) {
model.setNsPrefix(prefix, uri + "#");
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Getters">
/**
* Retrieves the URI for the output file of the provenance model
*
* @return The URI of the provenance output file
*/
public String getProvFileURI() {
return provOutputFileURI;
}
/**
* Gets the RDF model maintained by the manager
*
* @return the resource description framework model maintained by the
* manager
*/
public Model getModel() {
return model;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Model Manipulation">
/**
* Adds an entity to the provenance model. An entity is a physical, digital,
* conceptual, or other kind of thing with some fixed aspects; entities may
* be real or imaginary.
*
* Note: This method may return an existing Resource with the correct URI
* and model, or it may construct a fresh one, as the
* com.hp.hpl.jena.rdf.model.Model.createResource sees fit. However, you may
* specify replacement of an existing entity, by providing the replace
* parameter with a true value.
*
* @param uri - the URI of the entity to be created
* @param label - optional text used in applying a label to the entity
* resource (used for group queries)
* @param remote - True if the remote name space prefix should be used
* @param replace - True if all instances of existing resources with the
* specified URI should be removed from the model prior to adding this
* entity resource
* @return The resource representing the entity (used for method chaining or
* complex construction)
*/
public Resource addEntity(String uri, String label, boolean remote, boolean replace) {
uri = uri.replaceAll("\\\\", "/");
String fullUri = remote ? getProjectFullRemoteURI(uri)
: getProjectFullLocalURI(uri);
if (replace) {
removeResource(uri);
}
// make parts necessary for defining this particular entity in the model
Resource entityToAdd = createStatement(fullUri,
ProvOntology.getRDFTypeFullURI(),
ProvOntology.getEntityStartingPointClassFullURI());
// add the label
if (label != null) {
labelResource(entityToAdd, label);
}
// provide the resource to the caller for method-chaining
return entityToAdd;
}
/**
* Adds an activity to the provenance model. An activity is something that
* occurs over a period of time and acts upon or with entities; it may
* include consuming, processing, transforming, modifying, relocating,
* using, or generating entities.
*
* Note: This method may return an existing Resource with the correct URI
* and model, or it may construct a fresh one, as the
* com.hp.hpl.jena.rdf.model.Model.createResource sees fit. However, you may
* specify replacement of an existing entity, by providing the replace
* parameter with a true value.
*
* @param uri - the URI of the activity to be created
* @param label - optional text used in applying a label to the entity
* resource (used for group queries)
* @param remote - True if the remote name space prefix should be used
* @param replace - True if all instances of existing resources with the
* specified URI should be removed from the model prior to adding this
* activity resource
* @return The resource representing the entity (used for method chaining or
* complex construction)
*/
public Resource addActivity(String uri, String label, boolean remote, boolean replace) {
uri = uri.replaceAll("\\\\", "/");
String fullUri = remote ? getProjectFullRemoteURI(uri)
: getProjectFullLocalURI(uri);
if (replace) {
removeResource(uri);
}
// make parts necessary for defining this activity in the model
Resource activityToAdd = createStatement(fullUri,
ProvOntology.getRDFTypeFullURI(),
ProvOntology.getActivityStartingPointClassFullURI());
// add the label if one was provided
if (label != null) {
labelResource(activityToAdd, label);
}
// provide the resource to the caller for method-chaining
return activityToAdd;
}
/**
* Adds a software agent to the provenance model. A software agent is
* running software.
*
* Note: This method may return an existing Resource with the correct URI
* and model, or it may construct a fresh one, as the
* com.hp.hpl.jena.rdf.model.Model.createResource sees fit. However, you may
* specify replacement of an existing entity, by providing the replace
* parameter with a true value.
*
* @param uri - the URI of the software agent to be created
* @param label - optional text used in applying a label to the entity
* resource (used for group queries)
* @param remote - True if the remote name space prefix should be used
* @param replace - True if all instances of existing resources with the
* specified URI should be removed from the model prior to adding this agent
* resource
* @return The resource representing the software agent (used for method
* chaining or complex construction)
*/
public Resource addSoftwareAgent(String uri, String label, boolean remote, boolean replace) {
uri = uri.replaceAll("\\\\", "/");
String fullUri = remote ? getProjectFullRemoteURI(uri)
: getProjectFullLocalURI(uri);
//removeResource(uri);
// make parts necessary for defining this particular agent in the model
Resource agentToAdd = createStatement(fullUri,
ProvOntology.getRDFTypeFullURI(),
ProvOntology.getSoftwareAgentExpandedClassFullURI());
// add the label if one was provided
if (label != null) {
labelResource(agentToAdd, label);
}
// provide the resource to the caller for method-chaining
return agentToAdd;
}
/**
* Describes the association of an activity to an agent. An activity
* association is an assignment of responsibility to an agent for an
* activity, indicating that the agent had a role in the activity. It
* further allows for a plan to be specified, which is the plan intended by
* the agent to achieve some goals in the context of this activity.
*
* Note: Activity and agent resources must first be described in the model
* before calling this method.
*
* @param activity - A resource description of the activity for which the
* agent is responsible
* @param agent - A resource description of the agent that is responsible
* for activity
* @return - The statement resource describing this association (used for
* method chaining or complex construction)
*/
public Resource wasAssociatedWith(Resource activity, Resource agent) {
return createStatement(activity.getURI(),
ProvOntology.getWasAssociatedWithStartingPointPropertyFullURI(),
agent.getURI());
}
/**
* Describes usage of an entity for an activity. Usage is the beginning of
* utilizing an entity by an activity. Before usage, the activity had not
* begun to utilize this entity and could not have been affected by the
* entity.
*
* Note: Activity and entity resources must first be described in the model
* before calling this method.
*
* @param activity - A resource description of the activity for which agent
* is responsible
* @param entity
* @return - The statement resource describing this usage (used for method
* chaining or complex construction)
*/
public Resource used(Resource activity, Resource entity) {
return createStatement(activity.getURI(),
ProvOntology.getUsedStartingPointPropertyFullURI(),
entity.getURI());
}
/**
* Specifies the derivation of an destination entity from an existing source
* entity. A derivation is a transformation of an entity into another, an
* update of an entity resulting in a new one, or the construction of a new
* entity based on a pre-existing entity.
*
* @param source - An existing entity resource from the provenance record
* @param dest - A newly derived entity resource. Note: This entity must be
* generated in the provenance record prior to a call to this function.
* @return - The derivation statement from created by this function call.
*/
public Resource wasDerivedFrom(Resource source, Resource dest) {
return createStatement(source.getURI(),
ProvOntology.getWasDerivedFromStartingPointPropertyFullURI(),
dest.getURI());
}
/**
* Qualifies a "generated" statement (see ProvMgr.generated), which
* specifies the generation of an entity. Generation is the completion of
* production of a new entity by an activity. This entity did not exist
* before generation and becomes available for usage after this generation.
* Note: In terms of the provenance record, a statement of the entity's
* existence must first be added to the provenance record in order to show
* generation. However, for the purposes of inference-based queries, the
* entity does not exist until it has been generated (by this function).
*
* @param activity - The activity that generated the specified entity
* @param entity - The entity that was generated by the specified activity
* @return The statement that has been added to the provenance record
* through the invocation of this function.
*/
private Resource wasGeneratedBy(Resource entity, Resource activity) {
return createStatement(entity.getURI(),
ProvOntology.getWasGeneratedByStartingPointPropertyFullURI(),
activity.getURI());
}
/**
* Specifies the generation of an entity. Generation is the completion of
* production of a new entity by an activity. This entity did not exist
* before generation and becomes available for usage after this generation.
*
* Note: In terms of the provenance record, a statement of the entity's
* existence must first be added to the provenance record in order to show
* generation. However, for the purposes of inference-based queries, the
* entity does not exist until it has been generated (by calling this
* function).
*
* Note: This function will also add its inverse (ProvMgr.wasGeneratedBy) to
* the model.
*
* @param entity - The entity that was generated by the specified activity
* @param activity - The activity that generated the specified entity
* @return The statement that has been added to the provenance record
* through the invocation of this function.
*/
public Resource generated(Resource activity, Resource entity) {
wasGeneratedBy(entity, activity);
return createStatement(activity.getURI(),
ProvOntology.getGeneratedExpandedPropertyFullURI(),
entity.getURI());
}
/**
* Describes when an instantaneous event occurred. The PROV data model is
* implicitly based on a notion of instantaneous events (or just events),
* that mark transitions in the world. Events include generation, usage, or
* invalidation of entities, as well as starting or ending of activities.
* This notion of event is not first-class in the data model, but it is
* useful for explaining its other concepts and its semantics.
*
* @param activity - The activity that occurred
* @param instantaneousEvent -
* @return No uses of the resulting statement are known to be any better
* than using the activity resource, consider using the activity resource if
* it is available (you can look up its URI by calling getSubject)
*/
public Resource atTime(Resource activity, Resource instantaneousEvent) {
return createStatement(activity.getURI(),
ProvOntology.getAtTimeQualifiedPropertyFullURI(),
instantaneousEvent.getURI());
}
/**
* Describes when an activity started (use this for activities, use atTime
* for instantaneous events)
*
* @param activity - The activity that occurred
* @param date - A date representing the time at which the activity started
* @return No uses of the resulting statement are known to be any better
* than using the activity resource, consider using the activity resource it
* is available (you can look up its URI by calling getSubject)
*/
public Resource startedAtTime(Resource activity, Date date) {
Statement atTime = model.createStatement(activity,
model.createProperty(ProvOntology.
getStartedAtTimeStartingPointPropertyFullURI()),
getDateLiteral(date));
model.add(atTime);
return activity;
}
/**
* Describes when an activity ended (use this for activities, use atTime for
* instantaneous events)
*
* @param activity - The activity that occurred
* @param date - A date representing the time at which the activity ended
* @return No uses of the resulting statement are known to be any better
* than using the activity resource, consider using the activity resource it
* is available (you can look up its URI by calling getSubject)
*/
public Resource endedAtTime(Resource activity, Date date) {
Statement atTime = model.createStatement(activity,
model.createProperty(ProvOntology.
getEndedAtTimeStartingPointPropertyFullURI()),
getDateLiteral(date));
model.add(atTime);
return activity;
}
/**
* Creates a definition for the provenance class resource in the model.
*
* @param resourceURI - The direct URI to be given to the resource. This
* means that any prefixing is applied to the URI before this method is
* called.
* @param propertyURI - The direct property URI. This is a URI from the prov
* ontology or RDF schema. Direct means that any prefixing is taken care of
* prior to this method call.
* @param definitionURI - The direct definition URI. This must already
* contain the corresponding prov ontology uri
* @return The resource that was added to the provenance model.
*/
private Resource createStatement(String resourceURI, String propertyURI,
String definitionURI) {
// create parts
Resource resource = model.createResource(resourceURI);
Property property = model.createProperty(propertyURI);
Resource definition = model.createResource(definitionURI);
// make a statement out of them
Statement stmt = model.createStatement(resource, property, definition);
// add it to the model
model.add(stmt);
// provide the resource to the caller for future use
return resource;
}
/**
* This should only be used when optimistic provenance recording is used and
* a resource has failed to be generated or be of importance to the
* provenance record. Do not use this method to overwrite an existing
* resource. If this method is used, all statements in which the resource
* specified is the subject of the statement will be removed from the
* provenance record.
*
* @param resourceURI - Identifies the statements that should be removed
* from the provenance record. All statements whose subject has this URI
* will be removed from the provenance record.
*/
public void removeResource(String resourceURI) {
Resource resource = model.getResource(resourceURI);
StmtIterator si = model.listStatements(resource, (Property) null,
(RDFNode) null);
while (si.hasNext()) {
Statement s = si.nextStatement();
model.remove(s);
}
}
/**
* Adds a label to a resource for ease of query
*
* @param resource - The resource to label
* @param labelText - The text of the literal used as a label
* @return The same resource that was provided (for method-chaining)
*/
private Resource labelResource(Resource resource, String labelText) {
// create parts
Property labelProperty = model.createProperty(
ProvOntology.getRDFSLabelFullURI());
Literal label = model.createLiteral(labelText);
// add the label to the resource
resource.addLiteral(labelProperty, label);
// provide the resource to the caller for method-chaining
return resource;
}
/**
* Creates a labeled collection resource. This function must be invoked
* prior to adding resources to a collection. The uri should be a folder
* location where the input files reside (or at least one of the input files
* resides)
*
* @param uri - The identifier that points to the collection resource
* @param label - Optional label, for group queries
* @return The resource that was defined for the collection
*/
public Resource createCollection(String uri, String label) {
Resource collection = createStatement(uri,
ProvOntology.getRDFTypeFullURI(),
ProvOntology.getCollectionExpandedClassFullURI());
labelResource(collection, label);
return collection;
}
/**
* Adds a resource to a collection. Members are added to a collection, but
* the members should first be defined as entities in the model. Use
* addEntity to accomplish this, prior to adding the member to the
* collection.
*
* @param collection - The collection to add the entity to
* @param entity - The resource to add to the collection
* @return - A reference to resource which describes the collection (used
* for method chaining)
*/
public Resource addToCollection(Resource collection, Resource entity) {
Property hadMember = model.createProperty(ProvOntology.
getHadMemberExpandedPropertyFullURI());
Statement s = model.createStatement(collection, hadMember, entity);
return collection;
}
/**
* Adds a series of statements indicating that an agent created a file at a
* given location. If the agent does not yet exist, it is first added to the
* model.
*
* @param activityURI
* @param activityLabel
* @param agentURI - Identifies the agent responsible for generating the
* file
* @param agentLabel - Optional label for the agent created with agentURI
* @param remoteAgent - Indicates the locale of the agent with respect to
* the locale where this function was invoked
* @param fileURI - Identifies the file that was generated
* @param fileLabel - Optional label for the generated file created with
* fileURI
* @param remoteFile - Indicates the locale of the file with respect to the
* locale where this activity occurred
* @return The resource object associated with the file that was generated
*/
public Resource addFileGeneration(String activityURI, String activityLabel,
String agentURI, String agentLabel, boolean remoteAgent,
String fileURI, String fileLabel, boolean remoteFile) {
Resource activity = addActivity(activityURI, activityLabel, remoteAgent, false);
Resource program = addSoftwareAgent(agentURI, agentLabel, remoteAgent, false);
Resource file = addEntity(fileURI, fileLabel, remoteFile, false);
wasGeneratedBy(file, activity);
generated(activity, file);
wasAssociatedWith(activity, program);
return file;
}
/**
* Adds a series of statements indicating that an agent created a file at a
* given location.
*
* @param activity - An existing resource defining the file generation
* activity
* @param agent - An existing agent resource (possibly a software agent)
* defining the agent that is responsible for generating the file
* @param file - An existing entity resource for the file
* @return The resource associated with the file that was generated
*/
public Resource addFileGeneration(Resource activity, Resource agent,
Resource file) {
wasGeneratedBy(file, activity);
generated(activity, file);
wasAssociatedWith(activity, agent);
return file;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Query Support">
public List<String> getSubjects(List<String> fullURIs) {
List<String> abbreviatedURI = new ArrayList<>();
StmtIterator si = model.listStatements();
Resource r;
String uri;
Statement s;
while (si.hasNext()) {
s = si.nextStatement();
r = s.getSubject();
uri = r.getURI();
fullURIs.add(uri);
abbreviatedURI.add(FileManager.getSimpleFilename(uri));
}
return abbreviatedURI;
}
public Collection<String> getPredicates() {
HashSet<String> fullURISet = new HashSet<>();
StmtIterator si = model.listStatements();
while (si.hasNext()) {
fullURISet.add(si.nextStatement().getPredicate().toString());
}
return fullURISet;
}
public List<String> getObjects(List<String> fullURIs) {
List<String> abbreviatedURI = new ArrayList<>();
StmtIterator si = model.listStatements();
Statement s;
while (si.hasNext()) {
s = si.nextStatement();
fullURIs.add(s.getObject().toString());
abbreviatedURI.add(FileManager.getSimpleFilename(s.getObject().toString()));
}
return abbreviatedURI;
}
/**
* Provides a readable textual representation of provenance statements where
* subjectURI contains subjectText, predicateURI contains predicateText, and
* objectURI contains objectText. Any and all of the fields may be used as
* wildcards by passing a null value for the respective field.
*
* @param subjectText - text that should be contained within the subject of
* a statement if the statement matches
* @param predicateText - text that should be contained within the predicate
* of a statement if the statement matches
* @param objectText - text that should be contained within the object of a
* statement if the statement matches
* @param lineDelimiter - separates statements from each other
* @return statements that match the query
*/
public String queryProvenance(String subjectText, String predicateText, String objectText, String lineDelimiter) {
String statements = "";
Statement stmt;
String subject, predicate, object;
RDFNode objectNode;
boolean isVowel;
char letter;
StmtIterator iter = model.listStatements();
while (iter.hasNext()) {
stmt = iter.nextStatement();
subject = stmt.getSubject().getURI();
predicate = stmt.getPredicate().getURI();
objectNode = stmt.getObject();
if (objectNode.isURIResource()) {
object = objectNode.asResource().getURI();
} else if (objectNode.isAnon()) {
object = objectNode.asNode().getURI();
} else if (objectNode.isLiteral()) {
object = objectNode.asLiteral().getString();
} else {
object = objectNode.asResource().toString();
}
if (object.length() > 0) {
letter = object.charAt(0);
isVowel = letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u' || letter == 'h';
if (subject.toLowerCase().contains(subjectText.toLowerCase())
&& predicate.toLowerCase().contains(predicateText.toLowerCase())
&& object.toLowerCase().contains(objectText.toLowerCase())) {
predicate = ProvOntology.translatePredicate(predicate,
isVowel);
statements += subject + " " + predicate + " " + object;
if (iter.hasNext()) {
statements += lineDelimiter;
}
}
}
}
return statements;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Utility Functions">
/**
* Converts the specified URI to its full form, which includes the
* associated namespace URI.
*
* @param uri - The URI to be converted
* @return The full form of the URI, which includes the associated namespace
* URI
*/
private String getProjectFullLocalURI(String uri) {
//return localNS + uri;
return LOCAL_NS_PREFIX + ":" + uri;
}
/**
* Converts the specified URI to its full form, which includes the
* associated namespace URI.
*
* @param uri - The URI to be converted
* @return The full form of the URI, which includes the associated namespace
* URI
*/
private String getProjectFullRemoteURI(String uri) {
return REMOTE_NS_PREFIX + ":" + uri;
}
/**
* Uses a web service to determine the external IP of the host machine. If
* this is not available, the loop back address is used along with the host
* name of the local machine. If the local host name cannot be ascertained
* then a default assignment is made.
*
* @return A description of the host name along with the most uniquely
* describing IP available (may or may not come from the InetAddress)
*/
private String getLocalNameSpaceURI() {
String localNameSpace = "";
try {
URL locator = new URL(ipServiceURL);
URLConnection connection = locator.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String str = null;
str = reader.readLine();
if (null == str) {
str = "127.0.0.1";
}
localNameSpace = InetAddress.getLocalHost().getHostName()
+ "@" + str + "#";
} catch (IOException e) {
try {
localNameSpace = InetAddress.getLocalHost().getHostName()
+ "@" + InetAddress.getLoopbackAddress() + "#";
} catch (UnknownHostException ex) {
localNameSpace = "[email protected]#";
}
}
return localNameSpace;
}
/**
* Writes the model to the file with the output filename specified during
* construction or initialization
*
* @param project - The project that this provenance is recorded for. The
* project maintains its name, which is used as the base name for the
* provenance file
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public void persist(ProjectMgr project) throws FileNotFoundException, IOException {
String directory = project.determineProvOutputLocation();
(new File(directory)).mkdirs();
model.write(new FileOutputStream(directory + project.getName()
+ ".ttl", false), "TURTLE");
}
/**
* Outputs a constructed model to a stream (may be System.out or a network
* or file-based stream)
*
* Assumption: The caller has checked that the model was assembled properly
* by calling isAssembled. Model will not be written if not assembled.
*
* @param out - The stream to print the model to
*/
public void outputModel(PrintStream out) {
if (model != null) {
model.write(out);
}
}
/**
* Converts a java date to the format required by Jena's Riot package.
*
* @param date - The java date object to convert
* @return - An xsd formatted date time string
*/
private Literal getDateLiteral(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return model.createTypedLiteral(cal);
}
// </editor-fold>
}
| [
"[email protected]"
] | |
37a7d67e1953fb4d39b6fa6873f7e70392572d9b | 6c7fd3f14fd569e361172363f36a05767812ead8 | /src/main/java/br/gov/caixa/gitecsa/siarg/model/comparator/RelatorioDemandasPorSituacaoDTOComparator.java | 22d922c0cf7cb57b6015820949e4d08bf92f7180 | [] | no_license | diegobucher/siarg | e3c85d4f1ce0e0a69688f802a6f05c8114e49694 | 987a03d85045c08258b7cef425a7d38b31c90675 | refs/heads/master | 2022-10-03T07:50:06.755498 | 2019-06-27T14:14:44 | 2019-06-27T14:14:44 | 194,107,517 | 0 | 0 | null | 2022-09-01T23:09:12 | 2019-06-27T14:10:52 | Java | UTF-8 | Java | false | false | 500 | java | package br.gov.caixa.gitecsa.siarg.model.comparator;
import java.util.Comparator;
import br.gov.caixa.gitecsa.siarg.dto.RelatorioDemandasPorSituacaoDTO;
public class RelatorioDemandasPorSituacaoDTOComparator implements Comparator<RelatorioDemandasPorSituacaoDTO> {
@Override
public int compare(RelatorioDemandasPorSituacaoDTO rel1, RelatorioDemandasPorSituacaoDTO rel2) {
return rel1.getCaixaPostalEnvolvida().toUpperCase().compareTo(rel2.getCaixaPostalEnvolvida().toUpperCase());
}
}
| [
"[email protected]"
] | |
ba7dd59af092a1cf3bbadda667f35ecec9e4ebf1 | 1f6dceaf2342decd4614da351ba4c7ee2ecce3b1 | /Exemplo Apache Shiro/target/tmp/jsp/org/apache/jsp/WEB_002dINF/views/perfil/login_jspx.java | 8af44d59e8751e35185da6a8a47eb4717ede4280 | [] | no_license | edutm/Estudo-Projetos-Java | 49da0475a83e8a7eae73f6c5a111b3a4a6069c5c | ab8108bcfcf7ec8222e13dd29bd8651257065dda | refs/heads/master | 2021-05-31T17:55:49.550897 | 2016-04-13T16:12:56 | 2016-04-13T16:12:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,939 | java | package org.apache.jsp.WEB_002dINF.views.perfil;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class login_jspx extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(3);
_jspx_dependants.add("/WEB-INF/tags/form/login.tagx");
_jspx_dependants.add("/WEB-INF/tags/util/panel.tagx");
_jspx_dependants.add("/WEB-INF/tags/form/fields/input.tagx");
}
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("<div version=\"2.0\">");
if (_jspx_meth_form_login_0(_jspx_page_context))
return;
out.write("</div>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_form_login_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:login
org.apache.jsp.tag.web.form.login_tagx _jspx_th_form_login_0 = (_jspx_resourceInjector != null) ? _jspx_resourceInjector.createTagHandlerInstance(org.apache.jsp.tag.web.form.login_tagx.class) : new org.apache.jsp.tag.web.form.login_tagx();
_jspx_th_form_login_0.setJspContext(_jspx_page_context);
_jspx_th_form_login_0.setZ("user-managed");
_jspx_th_form_login_0.setPath("/perfil/login");
_jspx_th_form_login_0.setModelAttribute("usuario");
_jspx_th_form_login_0.setId("fc_br_com_devmedia_javamagazine_apacheshiro_model_bean_Usuario");
_jspx_th_form_login_0.setJspBody(new login_jspxHelper( 0, _jspx_page_context, _jspx_th_form_login_0, null));
_jspx_th_form_login_0.doTag();
return false;
}
private boolean _jspx_meth_field_input_0(javax.servlet.jsp.tagext.JspTag _jspx_parent, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// field:input
org.apache.jsp.tag.web.form.fields.input_tagx _jspx_th_field_input_0 = (_jspx_resourceInjector != null) ? _jspx_resourceInjector.createTagHandlerInstance(org.apache.jsp.tag.web.form.fields.input_tagx.class) : new org.apache.jsp.tag.web.form.fields.input_tagx();
_jspx_th_field_input_0.setJspContext(_jspx_page_context);
_jspx_th_field_input_0.setParent(_jspx_parent);
_jspx_th_field_input_0.setZ("user-managed");
_jspx_th_field_input_0.setId("c_br_com_devmedia_javamagazine_apacheshiro_model_bean_Usuario_login");
_jspx_th_field_input_0.setRequired(new Boolean(true));
_jspx_th_field_input_0.setField("login");
_jspx_th_field_input_0.doTag();
return false;
}
private boolean _jspx_meth_field_input_1(javax.servlet.jsp.tagext.JspTag _jspx_parent, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// field:input
org.apache.jsp.tag.web.form.fields.input_tagx _jspx_th_field_input_1 = (_jspx_resourceInjector != null) ? _jspx_resourceInjector.createTagHandlerInstance(org.apache.jsp.tag.web.form.fields.input_tagx.class) : new org.apache.jsp.tag.web.form.fields.input_tagx();
_jspx_th_field_input_1.setJspContext(_jspx_page_context);
_jspx_th_field_input_1.setParent(_jspx_parent);
_jspx_th_field_input_1.setZ("user-managed");
_jspx_th_field_input_1.setId("c_br_com_devmedia_javamagazine_apacheshiro_model_bean_Usuario_senha");
_jspx_th_field_input_1.setRequired(new Boolean(true));
_jspx_th_field_input_1.setField("senha");
_jspx_th_field_input_1.setType("password");
_jspx_th_field_input_1.doTag();
return false;
}
private class login_jspxHelper
extends org.apache.jasper.runtime.JspFragmentHelper
{
private javax.servlet.jsp.tagext.JspTag _jspx_parent;
private int[] _jspx_push_body_count;
public login_jspxHelper( int discriminator, JspContext jspContext, javax.servlet.jsp.tagext.JspTag _jspx_parent, int[] _jspx_push_body_count ) {
super( discriminator, jspContext, _jspx_parent );
this._jspx_parent = _jspx_parent;
this._jspx_push_body_count = _jspx_push_body_count;
}
public boolean invoke0( JspWriter out )
throws Throwable
{
if (_jspx_meth_field_input_0((javax.servlet.jsp.tagext.JspTag) _jspx_parent, _jspx_page_context))
return true;
if (_jspx_meth_field_input_1((javax.servlet.jsp.tagext.JspTag) _jspx_parent, _jspx_page_context))
return true;
return false;
}
public void invoke( java.io.Writer writer )
throws JspException
{
JspWriter out = null;
if( writer != null ) {
out = this.jspContext.pushBody(writer);
} else {
out = this.jspContext.getOut();
}
try {
switch( this.discriminator ) {
case 0:
invoke0( out );
break;
}
}
catch( Throwable e ) {
if (e instanceof SkipPageException)
throw (SkipPageException) e;
throw new JspException( e );
}
finally {
if( writer != null ) {
this.jspContext.popBody();
}
}
}
}
}
| [
"[email protected]"
] | |
d94c9da5338bfcea2b92c179504aeb28f98f7145 | 32544d3ffb4c16a239fc56e8bb8551700568b11a | /src/main/java/com/yidai/business/dao/basic/UserAwardMapper.java | dbd1d67bd81ffa7499ab2d2cb3a98b20908c5486 | [] | no_license | KissMyeyes/generator | 401a2c4f750e538607001a1d8049bed31e74003f | 1324d334e94572058168d26257ccdf25198ea5ec | refs/heads/master | 2020-04-07T22:38:23.766524 | 2019-01-16T03:17:27 | 2019-01-16T03:17:27 | 158,778,418 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 392 | java | package com.yidai.business.dao.basic;
import com.yidai.model.entity.basic.UserAward;
public interface UserAwardMapper {
int deleteByPrimaryKey(Integer id);
int insert(UserAward record);
int insertSelective(UserAward record);
UserAward selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserAward record);
int updateByPrimaryKey(UserAward record);
} | [
"[email protected]"
] | |
b4c66ba8a00e0d1acdc873c2f717fd40bfc5408d | 52d717b29b5a275afa506dd60f5d517228d859f2 | /io.github.scottbrand.common/src/io/github/scottbrand/common/Numbers.java | bb6f48c0e96754d019f5171d7e516ba35fdfb2dd | [] | no_license | scottbrand/common | eaf9b1041b89efb08d6af55bc630248214994a74 | 89c258ac10c5c26dedb9fd62e976e15f20646683 | refs/heads/master | 2021-01-22T23:33:20.028998 | 2017-04-18T19:22:53 | 2017-04-18T19:22:53 | 85,649,175 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,766 | java | package io.github.scottbrand.common;
public class Numbers
{
public enum Operators
{
EQUAL,
NOT_EQUAL,
LESS_THAN,
LESS_THAN_OR_EQUAL,
GREATER_THAN,
GREATER_THAN_OR_EQUAL,
};
public enum RangeOperators
{
BETWEEN,
NOT_BETWEEN
};
public static final Integer getInteger(String value, int defaultValue, Integer min, Integer max)
{
if (value == null)
return defaultValue;
int v = defaultValue;
try
{
v = Integer.parseInt(value);
if (min != null && v < min)
return defaultValue;
if (max != null && v > max)
return defaultValue;
return v;
}
catch (Throwable t)
{
return defaultValue;
}
}
public static final Long getLong(String value, long defaultValue, Long min, Long max)
{
if (value == null)
return defaultValue;
long v = defaultValue;
try
{
v = Long.parseLong(value);
if (min != null && v < min)
return defaultValue;
if (max != null && v > max)
return defaultValue;
return v;
}
catch (Throwable t)
{
return defaultValue;
}
}
/**
* Special case of getLong(String value, long defaultValue, Long min, Long max) in that this method only trys to
* parse the object as a Long and will return Long.MAX_VALUE in any case in which it can not be parsed as a Long. If
* the given object is a String, then it is cast to a String before parsing otherwise the value that is parsed is
* equivalent to value.toString();
*
* @param value
* @return
*/
public static final Long getLong(Object value)
{
if (value == null)
return Long.MAX_VALUE;
long v = Long.MAX_VALUE;
try
{
v = Long.parseLong(value instanceof String ? (String) value : value.toString());
return v;
}
catch (Throwable t)
{
return Long.MAX_VALUE;
}
}
/**
* Special case of getLong(String value, long defaultValue, Long min, Long max) in that this method only trys to
* parse the object as a Long and will return Long.MAX_VALUE in any case in which it can not be parsed as a Long. If
* the given object is a String, then it is cast to a String before parsing otherwise the value that is parsed is
* equivalent to value.toString();
*
* @param value
* @return
*/
public static final Integer getInteger(Object value)
{
if (value == null)
return Integer.MAX_VALUE;
int v = Integer.MAX_VALUE;
try
{
v = Integer.parseInt(value instanceof String ? (String) value : value.toString());
return v;
}
catch (Throwable t)
{
return Integer.MAX_VALUE;
}
}
public static final Short getShort(Object value)
{
if (value == null)
return Short.MAX_VALUE;
short v = Short.MAX_VALUE;
try
{
v = Short.parseShort(value instanceof String ? (String) value : value.toString());
return v;
}
catch (Throwable t)
{
return Short.MAX_VALUE;
}
}
public static final Float getFloat(Object value)
{
if (value == null)
return Float.MAX_VALUE;
float v = Float.MAX_VALUE;
try
{
v = Float.parseFloat(value instanceof String ? (String) value : value.toString());
return v;
}
catch (Throwable t)
{
return Float.MAX_VALUE;
}
}
public static final Double getDouble(Object value)
{
if (value == null)
return Double.MAX_VALUE;
double v = Double.MAX_VALUE;
try
{
v = Double.parseDouble(value instanceof String ? (String) value : value.toString());
return v;
}
catch (Throwable t)
{
return Double.MAX_VALUE;
}
}
public static final boolean equals(Short v1, Short v2)
{
if (v1 == v2)
return true;
if (v1 == null || v2 == null)
return false;
return v1.intValue() == v2.intValue();
}
public static final boolean equals(Integer v1, Integer v2)
{
return eval(v1, Operators.EQUAL, v2);
}
/**
* Useful method to check if an Integer object is null or set to
* some default value.
*
* @param v1 Integer object which could be null or contain a value
* @param v2 the primitive int value from which we want to equate to.
*
* @return true if v1 is null or v1 = v2.
*/
public static final boolean isNullOrEquals(Integer v1, int v2)
{
return (v1 == null || v1.intValue() == v2);
}
/**
* Predicate operation to evaluate parameter <code>v1</code>.
* If v1 is null, return false;
* Other wise, use the operator and v2, evaluate the expression
* as being true or false.
*
* @param v1 Integer object used as operand1 (if null, method evaluate to false)
* @param op comparison operator
* @param v2 Integer object used as operand2 (if null, method evaluate to false)
* @return
*
*/
public static final boolean eval(Integer v1, Operators op, Integer v2)
{
if (v1 == null || v2 == null)
return false;
int o1 = v1.intValue();
int o2 = v2.intValue();
if (op == Operators.EQUAL)
return o1 == o2;
if (op == Operators.NOT_EQUAL)
return o1 != o2;
if (op == Operators.LESS_THAN)
return o1 < o2;
if (op == Operators.LESS_THAN_OR_EQUAL)
return o1 <= o2;
if (op == Operators.GREATER_THAN)
return o1 > o2;
if (op == Operators.GREATER_THAN_OR_EQUAL)
return o1 >= o2;
return false;
}
/**
* Predicate operation to evaluate parameter <code>v1</code>.
* If v1 is null, return false;
* Other wise, use the range operator and lower and upper ranges to
* evaluate the expression as being true or false.
*
* lower and upper bounds are inclusive in the comparison.
*
* @param v1 Integer object used as operand1 (if null, method evaluate to false)
* @param op comparison operator
* @param lower Integer object used as lower bound value (if null, method evaluate to false)
* @param upper Integer object used as upper bound value (if null, method evaluate to false)
* @return
*
*/
public static final boolean eval(Integer v1, RangeOperators op, Integer lower, Integer upper)
{
if (v1 == null || lower == null || upper == null)
return false;
int ov = v1.intValue();
int lv = lower.intValue();
int uv = upper.intValue();
return (op == RangeOperators.BETWEEN) ? ov >= lv && ov <= uv : !(ov >= lv && ov <= uv);
}
/**
* Predicate operation to evaluate parameter <code>v1</code>.
* If v1 is null, return false;
* Other wise, use the range operator and lower and upper ranges to
* evaluate the expression as being true or false.
*
* lower and upper bounds are inclusive in the comparison.
*
* @param v1 Integer object used as operand1 (if null, method evaluate to false)
* @param op comparison operator
* @param lower Integer object used as lower bound value (if null, method evaluate to false)
* @param upper Integer object used as upper bound value (if null, method evaluate to false)
* @return
*
*/
public static final boolean eval(Long v1, RangeOperators op, Long lower, Long upper)
{
if (v1 == null || lower == null || upper == null)
return false;
long ov = v1.longValue();
long lv = lower.longValue();
long uv = upper.longValue();
return (op == RangeOperators.BETWEEN) ? ov >= lv && ov <= uv : !(ov >= lv && ov <= uv);
}
/**
* Predicate operation to evaluate parameter <code>v1</code>.
* If v1 is null, return false;
* Other wise, use the operator and v2, evaluate the expression
* as being true or false.
*
* @param v1 Integer object used as operand1 (if null, method evaluate to false)
* @param op comparison operator
* @param v2 Integer object used as operand2 (if null, method evaluate to false)
* @return
*
*/
public static final boolean eval(Long v1, Operators op, Long v2)
{
if (v1 == null || v2 == null)
return false;
long o1 = v1.longValue();
long o2 = v2.longValue();
if (op == Operators.EQUAL)
return o1 == o2;
if (op == Operators.NOT_EQUAL)
return o1 != o2;
if (op == Operators.LESS_THAN)
return o1 < o2;
if (op == Operators.LESS_THAN_OR_EQUAL)
return o1 <= o2;
if (op == Operators.GREATER_THAN)
return o1 > o2;
if (op == Operators.GREATER_THAN_OR_EQUAL)
return o1 >= o2;
return false;
}
/**
* Useful method to check if an Integer object is null or set to
* some default value.
*
* @param v1 Integer object which could be null or contain a value
* @param v2 the primitive int value from which we want to equate to.
*
* @return true if v1 is null or v1 = v2.
*/
public static final boolean isNullOrEquals(Long v1, long v2)
{
return (v1 == null || v1.longValue() == v2);
}
public static final boolean equals(Long v1, Long v2)
{
return eval(v1,Operators.EQUAL,v2);
}
public static final boolean equals(Float v1, Float v2)
{
if (v1 == v2)
return true;
if (v1 == null || v2 == null)
return false;
return v1.floatValue() == v2.floatValue();
}
public static final boolean equals(Double v1, Double v2)
{
if (v1 == v2)
return true;
if (v1 == null || v2 == null)
return false;
return v1.doubleValue() == v2.doubleValue();
}
public static final String encode32(Long value)
{
return encodeBaseX(value, 32);
}
public static final String encodeBaseX(Long value, int radix)
{
return (value == null) ? Strings.EMPTY : Long.toString(value, radix).toUpperCase();
}
/**
* Convert a number to a String. If the given number object is null, then return the defaultValue. If the
* defaultValue is null then Strings.EMPTY is returned.
*
* @param someNumber
* @param defaultValue
* @return
*/
public static final String toString(Number someNumber, String defaultValue)
{
if (defaultValue == null)
defaultValue = Strings.EMPTY;
return (someNumber == null) ? defaultValue : someNumber.toString();
}
/**
* Convert a number to a String. If the given number object is null, then return the defaultValue. If the
* defaultValue is null then Strings.EMPTY is returned.
*
* @param someNumber
* @param defaultValue
* @return
*/
public static final String toString(Number someNumber)
{
return toString(someNumber, Strings.EMPTY);
}
/**
* Convert a number to a String. If the given number object is null, then return the defaultValue. If the
*
* @param someNumber
* @param defaultValue
* @return
*/
public static final String toString(Number someNumber, int defaultValue)
{
return someNumber == null ? String.valueOf(defaultValue) : toString(someNumber, null);
}
}
| [
"scott@primary"
] | scott@primary |
b41f601afb42bb1e663e29cb51f0a45da9b9e643 | 87d9be85ab23f5633135743e6809de93b36cccba | /AutomaGREat/app/src/main/java/automa/great/ufc/br/automagreat/model/listeners/ContextListener.java | fdceac2b1ce10ab9d00755c0b61555151a505ce9 | [] | no_license | IoTGroup/ProjetoIoT | 1a856dbb0b0437af2208196131e9a1afb3190e8c | 1daa05731a5e4d5cc40d5de6a98f60cab2ffb6c5 | refs/heads/master | 2021-01-25T05:15:21.820596 | 2015-12-08T15:29:52 | 2015-12-08T15:29:52 | 42,950,581 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 168 | java | package automa.great.ufc.br.automagreat.model.listeners;
public interface ContextListener{
void onContextReady(String data);
public String getContextKey();
}
| [
"[email protected]"
] | |
f1efa684f0409b1b7355328c608b6ccf3efec88e | f5868db1bcbe9e4185d07de7ae9fece14ecfa3b7 | /src/com/sabel/array/Auto/Auto.java | f7d0082cea251292ccca2320dab02501a58bbef4 | [] | no_license | marcokiefer/UebungIntelliJ | 6302ca2f6ec5c1c2b11e887a81355e009def61c8 | affe887af5201ff7c52b8ec5a9522fd830bc25ad | refs/heads/master | 2018-09-03T15:42:36.561323 | 2018-06-04T07:37:32 | 2018-06-04T07:37:32 | 116,789,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 610 | java | package com.sabel.array.Auto;
public class Auto {
private String kennzeichen;
private int ps;
public Auto() {
}
public Auto(String kennzeichen, int ps) {
this.kennzeichen = kennzeichen;
this.ps = ps;
}
public String getKennzeichen() {
return kennzeichen;
}
public void setKennzeichen(String kennzeichen) {
this.kennzeichen = kennzeichen;
}
public int getPs() {
return ps;
}
public void setPs(int ps) {
this.ps = ps;
}
public void druckeInfo(){
System.out.println(kennzeichen);
}
}
| [
"[email protected]"
] | |
2e1704740199cb68a78597bcd43a544b92b53c79 | 7a14ac621c265cdaea3934c0eebf81c9e8495ea3 | /src/main/java/com/pd/core/patterns/behavioral/strategy/example/payment/PaypalStrategy.java | 6585b1bda22d9f1e249627a746f568b1c1c3425e | [] | no_license | dunejaparas/CoreJava | 12d864a8828880751deb48f87e2eef866c52d6b8 | ff113f6ae3c76d9717e0a67b9e5e038257a109bc | refs/heads/master | 2021-01-16T18:03:10.644420 | 2015-09-05T23:59:26 | 2015-09-05T23:59:26 | 33,132,791 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | package com.pd.core.patterns.behavioral.strategy.example.payment;
/**
*
* Now we will have to create concrete implementations of algorithms for payment
* using credit/debit card or through paypal.
*
*
*
*/
public class PaypalStrategy implements PaymentStrategy {
private final String emailId;
private final String password;
public PaypalStrategy(final String email, final String pwd) {
this.emailId = email;
this.password = pwd;
}
@Override
public void pay(final int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
/**
* Now our algorithms are ready and we can implement Shopping Cart and payment
* method will require input as Payment strategy.
*/
| [
"[email protected]"
] | |
55ef6fd307fe01a5d0b5ffaa31c6d4df5ad06d48 | 19d3c4a325757e1c1e1a3dd1c823d2503da96c31 | /Assignmnet-7/Person.java | cc61ea80faa507a307f8e6f06a31210b84549c91 | [] | no_license | agitcelik/Intermediate_Programming-JAVA | 11852b0a665ddad0a04ae4d30eba8fbbc8ae436c | b2017aeb087dd90fbae081781bb5313d5d5ee8f3 | refs/heads/master | 2021-09-07T15:15:28.440146 | 2018-02-24T20:41:37 | 2018-02-24T20:41:37 | 122,777,897 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,372 | java |
public class Person {//Beginning of the Class.
private String name;//Given type String name
private int age;//Given type int age
public Person(){//No argument constructor.
}
public Person(String n,int age){//Two argument constructors. To identify Person.
this.age=age;
this.name=n;
}
public String getName() {//To get name that given into the Test class.
return name;//This method must return due to String type used.
}
public void setName(String name) {//Setting name to change with different variables into the Test class.
this.name = name;//In this method this. must be used due to void
}
public int getAge() {//To get age that given into the Test class.
return age;//This method must return due to int type used.
}
public void setAge(int age) {//Setting age to change with different variables into the Test class.
if(age<=18){//if the age is under and equals to 18. Program gives us a message.
System.out.println("Age of 18 and under that age is not allowed to drive Truck");
}//End of the if block
else//due to one line of code we do not have to use bracket points.
this.age=age;//In this method this. must be used due to void
}
public String toString(){//To print age and name with toString method.
return String.format("%s ,age of the owner is: %s",name, age);//String format is exactly as same as printf method.
}
}//End of the Person Class.
| [
"[email protected]"
] | |
df95ff4b86c1c34cfb1a55e0d9022fa8789cb5e3 | 54f3319834fdddfdc3ce4238c227ee05be122877 | /Demo2020010911/src/main/java/net/javaci/Demo20200109/CustomerDao.java | 63d517550f97194e23d6cd872a52569232d71ddd | [] | no_license | alicoskun43/demo20200109 | 11a5965cd3da24f7f0c84a3ce52069737e8d7828 | 4f08756ce23c5718820bee498b0ad85c6815a75b | refs/heads/master | 2023-03-08T01:45:09.703976 | 2021-02-23T16:08:56 | 2021-02-23T16:08:56 | 341,594,309 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package net.javaci.Demo20200109;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CustomerDao extends JpaRepository<Customer, Long> {
}
| [
"[email protected]"
] | |
c880dc0ff37df0294ecb90c6c90eb75de8bd8136 | a7136873623657a3480298549f153bd7138b6319 | /src/main/java/toktok/render/Renderer.java | 68343a00f1fc4dbb7c837d1e5a260fc566096196 | [] | no_license | jkischkel/toktok | 45248c9ccadba5a32641b474c2744644571d79bd | ce4f216fc8f31f264e1d9847e7041684f1ca37ca | refs/heads/master | 2020-06-09T01:44:09.563635 | 2013-10-05T17:51:28 | 2013-10-05T17:51:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149 | java | package toktok.render;
/**
* @author Jan Kischkel
*/
public enum Renderer implements NothingRenderer, TextRenderer, JsonRenderer {
instance
}
| [
"[email protected]"
] | |
54f600d08a4d26bf18c03d9d4d6d24dadc7f9f05 | 2bf86995d03cc077fe33e254d5fe989a134cf836 | /src/main/java/com/bookshop/dao/SearchMapper.java | cb1fea7e58d7a95c424cb3effc6ff30220d5d044 | [] | no_license | zhj6666/bookshop | 06b72ac038c08e274b4cd9f92ce77699a52aeabd | fa3a558fecd4c522ad0222957bbc7f29b750d872 | refs/heads/master | 2022-12-23T15:29:26.845145 | 2019-05-29T15:16:59 | 2019-05-29T15:16:59 | 189,250,213 | 1 | 0 | null | 2022-12-16T11:17:18 | 2019-05-29T15:16:25 | Java | UTF-8 | Java | false | false | 399 | java | package com.bookshop.dao;
import com.bookshop.beans.Book;
import com.bookshop.beans.SearchResultsPaging;
import java.util.List;
public interface SearchMapper {
//分页查询
List<Book> paging(SearchResultsPaging searchResultsPaging);//查询列表
int count(SearchResultsPaging searchResultsPaging);//查询列表数
//根据书的id查找书
Book searchBookById(int id);
}
| [
"[email protected]"
] | |
a3312f7bc2ae3d1328f5aab8c59b726c55897ec4 | 5c9c739112418ce82654c95b934e059c663c9d82 | /src/main/java/tr/net/rota/aeyacin/rotamobil/model/sbt/signalr/MessageLocation.java | 75f8d39cbc9f608784062000f9c045ba147cb0d4 | [] | no_license | cakmakridvan/RotaMobile | e6fa3893214ecb9503b0709d818f6b9de2097697 | 229f3c38a482e9004c1f15e9f50b0de3226d67e8 | refs/heads/master | 2022-02-26T11:29:59.012676 | 2019-09-18T11:46:10 | 2019-09-18T11:46:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 651 | java | package tr.net.rota.aeyacin.rotamobil.model.sbt.signalr;
/**
* Created by ayacin on 23.03.2017.
*/
public class MessageLocation {
public String R2;//= lt.IMEI;
public String R3;//= vehicle.Plate;
public String R4;//= vehicle.Tag;
public int R5;//= vehicle.CompanyID;
public String R6;//= vehicle.VehicleImageName;
public String R11;//= lt.DateTime;
public String R12;//= lt.LocalDateTime;
public int R13;//= lt.Speed;
public double R14;//= lt.Latitude;
public double R15;//= lt.Longitude;
public int R16;//= lt.SatelliteCount;
public int R17;//= lt.Angle;
public String R18;//= DateTime.Now;
}
| [
"[email protected]"
] | |
a75c344ced069819b805a44c2adce79c89deb633 | 5190b15ed8b736bca0bf825e71c206853b4b1f77 | /recommend_movie_show/src/main/java/mapper/RectabMapper.java | b553b6ffb1e749f67ed908d267ccee4a0419f42b | [] | no_license | pangxljc/recommend_mv | b94c4a595753af707563965af422ac8590857a43 | c4b06f155dba5411478838b76b92cb4c6f2d0b6f | refs/heads/master | 2020-03-12T21:04:46.523676 | 2018-05-30T07:33:51 | 2018-05-30T07:33:51 | 130,820,397 | 0 | 0 | null | 2018-05-30T07:33:52 | 2018-04-24T08:17:27 | CSS | UTF-8 | Java | false | false | 651 | java | package mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import po.Rectab;
import po.RectabExample;
public interface RectabMapper {
int countByExample(RectabExample example);
int deleteByExample(RectabExample example);
int insert(Rectab record);
int insertSelective(Rectab record);
List<Rectab> selectByExample(RectabExample example);
int updateByExampleSelective(@Param("record") Rectab record, @Param("example") RectabExample example);
int updateByExample(@Param("record") Rectab record, @Param("example") RectabExample example);
void update(Rectab rectab);
} | [
"[email protected]"
] | |
e5263ff517aa597e383146eb2ddb8778a2810436 | b617660d40e2dfc1726dd36a1cdf7d97dbc1c16e | /src/main/java/de/hubrick/challenge/zarutsky/domain/Employee.java | ab304ab17f8e28892bfd9e2c6bfade6a8cb62036 | [] | no_license | AntonZarutsky/hubrick-challenge | aac92a679d4448cec75914b0b2ca2fb977d10f08 | a2d18080816117999afacb87c80c130dda1e74a8 | refs/heads/master | 2021-01-22T09:47:00.875497 | 2016-09-20T08:40:59 | 2016-09-20T08:40:59 | 68,687,480 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,347 | java | package de.hubrick.challenge.zarutsky.domain;
import java.math.BigDecimal;
import java.util.Objects;
public class Employee {
private String name;
private Gender gender;
private BigDecimal income;
private Department department;
private int age;
private Employee(Builder builder) {
// Here can also be validation on wrong parameters / missing values.
this.age = builder.age;
this.department = builder.department;
this.name = builder.name;
this.gender = builder.gender;
this.income = builder.income;
}
public Department getDepartment() {
return department;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public Gender getGender() {
return gender;
}
public BigDecimal getIncome() {
return income;
}
public static Employee.Builder builder() {
return new Builder();
}
// I used to use builder if model object contains 5+ fields. Handy to work with it.
public static class Builder {
private Builder() { }
private Department department;
private int age;
private String name;
private Gender gender;
private BigDecimal income;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder gender(Gender gender) {
this.gender = gender;
return this;
}
public Builder income(BigDecimal income) {
this.income = income;
return this;
}
public Builder department(Department department) {
this.department = department;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Employee build(){
return new Employee(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Employee)) {
return false;
}
Employee employee = (Employee) o;
return Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
| [
"[email protected]"
] | |
f0d0f16e0cf185278084cd6642618b93799bab06 | b7ed63d645d5462e4e6f850ea5e97418462716b9 | /bldj-android/src/com/bldj/lexiang/view/IconPagerAdapter.java | f0c8be8f4a20ff89792ee0d0ae5252a11991ef00 | [] | no_license | pengweiqiang/bldj | 31127352e1e3fef37622c05c8c40036df20bd2a2 | 85036e1ca2627fd37063928c246b95c0c58dfea7 | refs/heads/master | 2022-08-13T18:56:44.149914 | 2022-07-14T06:38:21 | 2022-07-14T06:38:21 | 102,273,995 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package com.bldj.lexiang.view;
public interface IconPagerAdapter {
/**
* Get icon representing the page at {@code index} in the adapter.
*/
int getIconResId(int index);
// From PagerAdapter
int getCount();
}
| [
"pengweiqiang@5782cfdc-cac2-4cb0-8122-00ee8e001a98"
] | pengweiqiang@5782cfdc-cac2-4cb0-8122-00ee8e001a98 |
10c140b1042c8f336c50717a1a621e0dc92d58dd | e530f4a9ef5acefc4c8b0bd7bb7b22323a391e73 | /app/src/main/java/oscar/riksdagskollen/Util/Twitter/TwitterAuthRequest.java | d40b3b13680191c68bdc98094f4ec557758cab5c | [
"MIT"
] | permissive | OAndell/Riksdagskollen | 4740f1e6ec9874fe43c6b3408f5e39e896534ea2 | 415179784d1e4ae8a0708ae62c774064b193eaba | refs/heads/master | 2021-07-15T07:24:47.722267 | 2021-07-05T17:41:11 | 2021-07-05T17:41:11 | 126,734,001 | 35 | 3 | MIT | 2021-06-30T16:13:01 | 2018-03-25T19:48:46 | Java | UTF-8 | Java | false | false | 862 | java | package oscar.riksdagskollen.Util.Twitter;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class TwitterAuthRequest extends JsonObjectRequest {
private String apiKey;
public TwitterAuthRequest(int method, String url, String apiKey, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
this.apiKey = apiKey;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> authHeader = new HashMap<>();
authHeader.put("Authorization", "Basic " + apiKey);
return authHeader;
}
}
| [
"[email protected]"
] | |
4d20d0261a20a2669fb482dcd10d9428d3c8335b | 1d3ed942e2de38cf263fb1c9218da6d0c4746e03 | /src/main/java/org/rcsb/assembly/GraphTest.java | 15c0e1ec1e6cd11d42967a51713732a64c1de767 | [] | no_license | josemduarte/assembly | e0e684e2e1963a0c16d181c9927623531e8291cf | be2fc6be092162dd897da66bc7e0fe8f72abe32d | refs/heads/master | 2020-12-31T02:23:17.632450 | 2015-01-23T14:56:32 | 2015-01-23T14:56:32 | 29,736,459 | 1 | 0 | null | 2015-01-23T14:38:53 | 2015-01-23T14:38:53 | null | UTF-8 | Java | false | false | 2,461 | java | package org.rcsb.assembly;
import java.awt.Dimension;
import javax.swing.JFrame;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.Pair;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
public class GraphTest {
public static void main(String[] args) {
UndirectedSparseGraph<ChainVertex, InterfaceEdge> graph = new UndirectedSparseGraph<ChainVertex, InterfaceEdge>();
ChainVertex v1 = new ChainVertex("A", 1);
ChainVertex v2 = new ChainVertex("B", 1);
ChainVertex v3 = new ChainVertex("C", 1);
graph.addVertex(v1);
graph.addVertex(v2);
graph.addVertex(v3);
ChainVertex fake1 = new ChainVertex("A", 1);
ChainVertex fake2 = new ChainVertex("B", 1);
InterfaceEdge e1 = new InterfaceEdge(1);
InterfaceEdge e2 = new InterfaceEdge(2);
graph.addEdge(e1, fake1,fake2);
graph.addEdge(e2, v2, v3);
Pair<ChainVertex> ends = graph.getEndpoints(e1);
System.out.format("v1 %s first %s fake1%n", v1 == ends.getFirst() ? "==" : "!=", ends.getFirst() == fake1 ? "==" : "!=");
System.out.format("v2 %s second %s fake2%n", v2 == ends.getSecond() ? "==" : "!=", ends.getSecond() == fake2 ? "==" : "!=");
ends = graph.getEndpoints(e2);
System.out.format("v2 %s first %s fake2%n", v2 == ends.getFirst() ? "==" : "!=", ends.getFirst() == fake2 ? "==" : "!=");
System.out.format("Graph has %d vertices and %d edges.%n",graph.getVertexCount(),graph.getEdgeCount());
// Visualize
Layout<ChainVertex, InterfaceEdge> layout = new CircleLayout<ChainVertex, InterfaceEdge>(graph);
layout.setSize(new Dimension(300,300)); // sets the initial size of the space
// The BasicVisualizationServer<V,E> is parameterized by the edge types
BasicVisualizationServer<ChainVertex, InterfaceEdge> vv =
new BasicVisualizationServer<ChainVertex, InterfaceEdge>(layout);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<ChainVertex>());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<InterfaceEdge>());
vv.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size
JFrame frame = new JFrame("Simple Graph View");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
}
| [
"[email protected]"
] | |
764e025f382297a9dab71e8b3b9a633ac860d09a | cf3593cc024ca40f95cbd96b5524e7c572ec8f2b | /Washing machine[TCS NQT].java | 5a260955c58d233a995a8da37081c26795f16ce1 | [] | no_license | nivedha-ravi/Code-and-play | 9ee145dd04526c26fb3d92586a7f21c8c8c52567 | 986fa248e8df276ec994effb30c7fd60680fecb3 | refs/heads/master | 2023-04-15T08:39:53.336632 | 2021-05-04T17:03:24 | 2021-05-04T17:03:24 | 305,116,494 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,666 | java | /*
The program must accept an integer representing the weight of the clothes to be washed in a washing machine.
There are 3 water levels in the washing mechanism which are given below.
- Low Water Level: The estimated time is 25 minutes, where the approximate weight is between 1 gram to 2000 grams (both inclusive).
- Medium Water Level: The estimated time is 35 minutes, where the approximate weight is between 2001 grams and 4000 grams (both inclusive).
- High Water Level: The estimated time is 45 minutes, where the approximate weight is above 4000 grams.
The maximum capacity of the machine is 7000 grams.
The program must print the estimated time for the given weight of clothes W as the output.
If the weight is more than 7000 grams, the program must print the string value "OVERLOADED" as the output.
If the weight is 0, the program must print 0 as the output. For all other values of W, the program must print "INVALID INPUT" as the output.
*/
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int level=in.nextInt();
if(level>=1 && level<=2000)
{
System.out.print("25");
}
else if(level>2000 && level<=4000)
{
System.out.print("35");
}
else if(level>4000 && level<=7000)
{
System.out.print("45");
}
else if(level>7000)
{
System.out.print("OVERLOADED");
}
else if(level==0)
{
System.out.print("0");
}
else
{
System.out.print("INVALID INPUT");
}
}
}
| [
"[email protected]"
] | |
0271efa1033c8d67886d77e03bbbfa6d821e58e2 | 2fdb936a5284bb2ddfbd56db51a0024aa0149773 | /duobao-service/src/main/java/com/duobao/payment/strategy/wcPaymetnTools/PaymentTools.java | f26b0adc61a7ea4ef20246a54bcc1d0e0a7f6353 | [] | no_license | xuerenlv/yougou | 7ee6627f41d6aff8cff84e0bae8f1746fc7a08ca | e58b24ea4fc9119e014c2994ddae998849e9c7fa | refs/heads/master | 2023-03-19T06:49:26.874411 | 2016-12-16T06:10:10 | 2016-12-16T06:10:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,145 | java | package com.duobao.payment.strategy.wcPaymetnTools;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.lijing.wechatpay.util.ssl.ClientCustomSSL;
public class PaymentTools
{
public PaymentTools()
{
}
protected static String createSign(SortedMap parameters, String KEYAPI)
{
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
for(Iterator it = es.iterator(); it.hasNext();)
{
java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(v != null && !"".equals(v) && !"sign".equals(k) && !"key".equals(k))
if("prepay_id".equals(k))
sb.append((new StringBuilder("package=")).append(v).append("&").toString());
else
sb.append((new StringBuilder(String.valueOf(k))).append("=").append(v).append("&").toString());
}
sb.append((new StringBuilder("key=")).append(KEYAPI).toString());
return PayMD5.MD5Encode(sb.toString(), "UTF-8");
}
protected static String Signature(SortedMap parameters, String KEYAPI)
{
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb2.append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n<xml>");
sb2.append("\n");
Set es = parameters.entrySet();
for(Iterator it = es.iterator(); it.hasNext(); sb2.append("\n"))
{
java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
sb.append(k);
sb.append('=');
sb.append(v);
sb.append('&');
sb2.append((new StringBuilder("<")).append(k).append(">").toString());
sb2.append(v);
sb2.append((new StringBuilder("</")).append(k).append(">").toString());
}
sb.append("key=");
sb.append(KEYAPI);
String packageSign = null;
packageSign = createSign(parameters, KEYAPI);
sb2.append("<sign><![CDATA[");
sb2.append(packageSign);
sb2.append("]]></sign>");
sb2.append("\n</xml>");
try
{
return new String(sb2.toString().getBytes(), "UTF-8");
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
public static String getServerIP()
{
String serverip = "";
try
{
Enumeration netInterfaces = null;
for(netInterfaces = NetworkInterface.getNetworkInterfaces(); netInterfaces.hasMoreElements();)
{
NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
for(Enumeration ips = ni.getInetAddresses(); ips.hasMoreElements();)
{
InetAddress ip = (InetAddress)ips.nextElement();
if(ip.isSiteLocalAddress())
{
serverip = ip.getHostAddress();
break;
}
}
}
}
catch(Exception ex)
{
serverip = "192.168.200.200";
}
return serverip;
}
public static Date policyHesitation(String dateTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Calendar ca = Calendar.getInstance();
try
{
ca.setTime(sdf.parse(dateTime));
ca.add(6, 10);
}
catch(ParseException e)
{
e.printStackTrace();
}
return ca.getTime();
}
protected static String reqWechat(String req_URL, String param, String cret, String mch_id)
{
String respXML = null;
try
{
if(req_URL.equals(RERUND_URL))
respXML = ClientCustomSSL.doClientCustomSSL(req_URL, param, cret, mch_id);
else
respXML = HttpUtils.postApache(req_URL, param);
}
catch(Exception e)
{
e.printStackTrace();
}
return respXML;
}
public static String getTimeStamp()
{
return Long.toString((new Date()).getTime() / 1000L);
}
public static String getPackage(String prepay_id)
{
return (new StringBuilder("prepay_id=")).append(prepay_id).toString();
}
public static String businessOrderNumber()
{
return (new StringBuilder(String.valueOf((new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date())))).append(getcurrentTimeMillis()).append(PayMD5.nonceStrNumber()).toString();
}
public static String getcurrentTimeMillis()
{
return String.valueOf(System.currentTimeMillis()).substring(6, 13);
}
protected static String sbString(String prepay_id)
{
return prepay_id.substring(0, 10);
}
public static boolean isTime(String dateTime)
{
return (new Date()).before(policyHesitation(dateTime));
}
public static String getUnitCount(String money)
{
int count = Integer.parseInt(money.substring(0, money.length() - 3));
return String.valueOf(count / 1000);
}
public static String getStringTime(Date dateTime)
{
return getFormat().format(dateTime);
}
public static Date getDateTime(String dateTime)
{
Date date = null;
try
{
date = getFormat().parse(dateTime);
}
catch(ParseException e)
{
e.printStackTrace();
}
return date;
}
public static SimpleDateFormat getFormat()
{
return new SimpleDateFormat("yyyy-MM-dd");
}
public static String ChangeSex(String sex)
{
return sex != "M" ? "1" : "0";
}
public static String getStringTime(String dateTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try
{
date = sdf.parse(dateTime);
}
catch(ParseException e)
{
e.printStackTrace();
}
return sd.format(date);
}
public static String getStringDate(String dateTime)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try
{
date = sdf.parse(dateTime);
}
catch(ParseException e)
{
e.printStackTrace();
}
return sd.format(date);
}
public static String notify_urlSUCCESS()
{
return "<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>";
}
public static String notify_urlFail()
{
return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg></return_msg></xml>";
}
protected static String fail(String msg)
{
return (new StringBuilder("<xml><return_code><![CDATA[FAIL]]></return_code>\n<return_msg><![CDATA[")).append(msg).append("]]></return_msg>").append("</xml>").toString();
}
private static String RERUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
}
/*
DECOMPILATION REPORT
Decompiled from: C:\Users\Administrator\.m2\repository\fakepath\wechatpay\1.1\wechatpay-1.1.jar
Total time: 29 ms
Jad reported messages/errors:
Exit status: 0
Caught exceptions:
*/ | [
"[email protected]"
] | |
e0b64b4306c5b530cd4b990ca6de760fffda1058 | 837c40b9b8ffb033be70a3746b4e484175ae682f | /src/main/java/Painting.java | 0e5c82503539f2bdbd55e44aaf3cea7da300fcbc | [] | no_license | MHD22/intelliJ_Git_Demo | 7d64aae1e2602bac6f0e1da1aeb379a5b6fb5bda | 01e706114e6d2e3a80fc2c312c278eeb36ed330b | refs/heads/main | 2023-02-18T22:18:52.552555 | 2021-01-04T22:15:45 | 2021-01-04T22:15:45 | 326,763,592 | 0 | 0 | null | 2021-01-04T22:08:14 | 2021-01-04T17:48:16 | Java | UTF-8 | Java | false | false | 817 | java | public class Painting implements Item, Checkable {
String itemName="Painting";
String keyName="";
boolean isThereKey;
public Painting(boolean isThereKey, String keyName ) {
this.isThereKey = isThereKey;
this.keyName = keyName;
}
public boolean isThereKey() {
return this.isThereKey;
}
public String getKeyName() {
return keyName;
}
@Override
public String look() {
return itemName;
}
@Override
public void check(Player player) {
if(isThereKey){
player.keysWithPlayer.add(this.keyName);
isThereKey=false;
System.out.println("The (" +keyName+ ") key was acquired");
}
else{
System.out.println("Nothing behind this Painting.");
}
}
}
| [
"[email protected]"
] | |
4db25b80fb8a3ee6218b690d91a5166c677f8442 | 57df873a3072ea22b7d1997ce3ee6d4154d67093 | /Brute Force/NM1_SB.java | 16a4d2ea42e6edc67f31b45974862633ebad5ace | [] | no_license | heunnajo/Algorithm | 3f0dee28a3da781be7633ae53672b1b8463f77cb | 4f39568d11b98306209fe6d5773c5eea5975a6ec | refs/heads/main | 2023-07-15T00:27:39.674140 | 2021-08-30T09:30:46 | 2021-08-30T09:30:46 | 300,517,260 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 746 | java | import java.util.Scanner;
public class NM1_SB {
static boolean[] c = new boolean[10];
static int[] a = new int[10];
static StringBuilder go(int index,int n,int m) {
if(index == m) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<m;i++) {
sb.append(a[i]);
if(i != m-1) sb.append(" ");
}
sb.append("\n");
return sb;
}
StringBuilder ans = new StringBuilder();
for(int i=1;i<=n;i++) {
if(c[i])continue;
c[i] = true; a[index] = i;
ans.append(go(index+1,n,m));
c[i] = false;
}
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
System.out.print(go(0,n,m));
}
}
| [
"[email protected]"
] | |
b52b3dde4cbe09a77886bbf301346e8c6bde01d2 | 5661578c8e2cc1e2b9b350cca4b1b2499973824c | /springcloud-provider-user/src/main/java/com/jk/SpringcloudProviderUserApplication.java | 5cb169ad4700bc50311dc83f76fee26ff5ef07a3 | [] | no_license | zyl1011/springcloud | a6b5838fd538bfb1435fb50c96ef63e20df6f826 | f04be29063a61d419593d9f230ec812c320d8eea | refs/heads/master | 2022-05-01T22:01:29.110930 | 2019-11-08T11:04:51 | 2019-11-08T11:04:51 | 220,447,225 | 0 | 0 | null | 2022-03-31T18:57:12 | 2019-11-08T10:50:38 | HTML | UTF-8 | Java | false | false | 432 | java | package com.jk;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringcloudProviderUserApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudProviderUserApplication.class, args);
}
} | [
"[email protected]"
] | |
58def8c9b63b4c55c3a21d3bc7d26634262d68cf | 53712b823b389742649122b401d4e27d15024c7d | /src/test/java/com/in6k/twitter/AppTests.java | 9f7f8914b30abaecc5b21c0fe03db153fb047d73 | [] | no_license | IhorMakovoz/twitter | 8de2aff289a81c1b8d1744d7ce14509215e98f37 | fb12e80b9e668493bf8be09b37b6bd5ffc255c12 | refs/heads/master | 2016-09-07T04:00:41.443450 | 2013-10-17T12:32:04 | 2013-10-17T12:32:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,485 | java | package com.in6k.twitter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml")
public class AppTests {
private MockMvc mockMvc;
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void simple() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("hello"));
}
}
| [
"[email protected]"
] | |
c8b89628fc7c1e96423840da92df33d67f2544c3 | 5490ecaa3adfad0b10a5b6f8922f7a642a4ef47e | /src/com/talis/labs/pagerank/mapreduce/InitializePageRanksMapper.java | c9a877e17c5e7297517e549cba548da69092056a | [] | no_license | huangyueranbbc/hadoop05_pagerank | 87b61de9808407260cbb4840e69840121d7165aa | 84de906b1c04d2e327cba15c62cfaaf4daba4c45 | refs/heads/master | 2021-01-02T22:20:18.461380 | 2017-08-20T06:39:49 | 2017-08-20T06:39:49 | 99,320,272 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,194 | java | /*
* Copyright © 2011 Talis Systems Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.talis.labs.pagerank.mapreduce;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class InitializePageRanksMapper extends Mapper<LongWritable, Text, Text, Text> {
private double pagerank;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
long count = Long.parseLong(context.getConfiguration().get("pagerank.count"));// 需要统计的网页总数
pagerank = 1.0 / count; // 默认初始时,每个网页的初始PR值 1.0/网页总数
}
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer st = new StringTokenizer(value.toString()); // 读取每行数据 转为StringTokenizer对象
Text page = null;
StringBuffer sb = new StringBuffer();
boolean first = true;
Set<String> links = new HashSet<String>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (first) {
page = new Text(token);
sb.append(pagerank).append("\t"); // current pagerank 当前PR值 = 1.0 / count
sb.append(pagerank).append("\t"); // previous pagerank 之前计算的PR值 = 1.0 / count
first = false;
} else {
// to remove duplicated links and self-references
if ((links.add(token)) && (!page.equals(token))) {
sb.append(token).append("\t");
}
}
}
context.write(page, new Text(sb.toString()));
}
}
| [
"[email protected]"
] | |
e4ac8424ff94c6e099f2afd7ce69bec2024746a1 | fa35c5e85df7c23fca14930aaa01ae513fa9f322 | /ESI/src/main/java/com/talentica/esi/lb/RandomLoadBalancer.java | b6f1b698bd1c3e2097365a8fb8e1b2b5cd4d2be1 | [] | no_license | sushantap/ESI | 737f09f7d5fcabe42244a493e553f4f416649a2b | 0cde819a95773ca99729133ea78bcac7377d430a | refs/heads/master | 2021-01-22T07:02:47.335986 | 2014-03-21T09:04:15 | 2014-03-21T09:04:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,041 | java | package com.talentica.esi.lb;
import java.util.Random;
import com.talentica.esi.cache.Cache;
import com.talentica.esi.config.EsiServerResources;
import com.talentica.esi.config.PageLetConfig;
public class RandomLoadBalancer implements LoadBalancer{
private final Cache lbCache;
private final Random random;
public RandomLoadBalancer(EsiServerResources esiServerResources) {
this.random = new Random();
this.lbCache = esiServerResources.getCache();
}
@Override
public String getServer(PageLetConfig pageLetConfig) {
Object[] servers = pageLetConfig.getServers().toArray();
int randomOffset = this.random.nextInt(pageLetConfig.getServers().size());
String server = (String) servers[randomOffset];
int previousOffset = this.lbCache.getLBServerOffset(pageLetConfig);
if(previousOffset == randomOffset){
++randomOffset;
if(randomOffset >= servers.length){
randomOffset = 0;
}
}
server = (String) servers[randomOffset];
this.lbCache.putLBServerOffset(pageLetConfig, randomOffset);
return server;
}
}
| [
"[email protected]"
] | |
9333d8fb60f5385a6e0fdf8d2f14b319b245cfcf | 45ab7f186743597bcb5aecacea4feb3c0fd3d312 | /algorithms/dynamic_programming/longest_common_substring/DeletionDistance.java | 4893f798d5271d2fdb11b091a6e84bf11145acfc | [] | no_license | shubhamgupta2901/datastructures-and-algorithms | 5cecdb93e5adf412f3b0b7970c30f60d704333bf | da5c18ed33fac274f97c43c64feced0ca9ff0a4b | refs/heads/master | 2021-06-23T19:05:22.274058 | 2021-06-18T14:50:37 | 2021-06-18T14:50:37 | 225,032,691 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,674 | java | package algorithms.dynamic_programming.longest_common_substring;
/**
* This question comes in two patterns:
*
* 1. Deletion Distance:
* The deletion distance of two strings is the minimum number of characters you need to delete in the two strings
* in order to get the same string.
* For instance, the deletion distance between "heat" and "hit" is 3:
* By deleting 'e' and 'a' in "heat", and 'i' in "hit", we get the string "ht" in both cases.
* We cannot get the same string from both strings by deleting 2 letters or fewer.
* Given the strings str1 and str2, write an efficient function deletionDistance that
* returns the deletion distance between them. Explain how your function works,
* and analyze its time and space complexities.
*
* 2. Minimum Deletions & Insertions to Transform a String into another
* Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters.
* Write a function to calculate the count of the minimum number of deletion and insertion operations.
*
* Example 1:
* Input: s1 = "abc"
* s2 = "fbc"
* Output: 1 deletion and 1 insertion.
* Explanation: We need to delete {'a'} and insert {'f'} to s1 to transform it into s2.
*
* Example 2:
* Input: s1 = "abdca"
* s2 = "cbda"
* Output: 2 deletions and 1 insertion.
* Explanation: We need to delete {'a', 'c'} and insert {'c'} to s1 to transform it into s2.
*
* Example 3:
* Input: s1 = "passport"
* s2 = "ppsspt"
* Output: 3 deletions and 1 insertion
* Explanation: We need to delete {'a', 'o', 'r'} and insert {'p'} to s1 to transform it into s2.
*
* Both the problems are variations of {@link LongestCommonSubsequence} only.
* DeletionDistance: The "deletion distance" between two strings is just the total length of the strings
* minus twice the length of the LCS.
* i.e deletion distance = str1.length() + str2.length() - 2*lcs(str1, str2)
*
* Minimum Deletions & Insertions to Transform a String into another:
* 1. To transform str1 into str2, we need to delete everything from str1 which is not part of LCS,
* so minimum deletions we need to perform from str1 => str1.length() - lcs(str1, str2)
* 2. We need to insert everything in str1 which is present in str2 but not part of LCS,
* so minimum insertions we need to perform in str1 => str2.length() - lcs(str1,str2)
* so, Insertions + Deletions = str1.length() + str2.length() - 2*lcs(str1, str2)
*/
public class DeletionDistance {
/**
* Approach 1: Top Down DP + Memoization
* Time complexity Brute force: O(2^(M+N)
* Space Complexity Brute force : O(M+N)
*
* Time Complexity Memoized DP: O(M*N)
* Space Complexity Memoized DP: O(M*N)
*/
private int deletionDistanceApproach1(String str1, String str2){
Integer[][] cache = new Integer[str1.length()][str2.length()];
int lcs = lcsHelper(str1, str2, 0, 0, cache);
return str1.length() + str2.length() - 2 * lcs;
}
private int lcsHelper(String str1, String str2, int i, int j, Integer[][] cache){
if(i == str1.length() || j == str2.length())
return 0;
if(cache[i][j] != null)
return cache[i][j];
if(str1.charAt(i) == str2.charAt(j))
return 1 + lcsHelper(str1, str2, i+1, j+1,cache);
int lcs1 = lcsHelper(str1, str2, i+1, j,cache);
int lcs2 = lcsHelper(str1, str2, i, j+1,cache);
cache[i][j] = Math.max(lcs1, lcs2);
return cache[i][j];
}
/**
* Approach 2: Bottom up Dp
* Time Complexity: O(M*N)
* Space complexity: O(M*N)
*/
private int deletionDistanceApproach2(String str1, String str2){
int m = str1.length();
int n = str2.length();
int[][] table = new int[m][n];
//bottom case:
if(str1.charAt(m-1) == str2.charAt(n-1))
table[m-1][n-1] = 1;
//bottom case:
for(int j = n-2; j>=0; j--){
if(table[m-1][j+1] == 1 || str1.charAt(m-1) == str2.charAt(j))
table[m-1][j] = 1;
}
//bottom case:
for(int i = m-2; i>=0; i--){
if(table[i+1][n-1] == 1|| str1.charAt(i) == str2.charAt(n-2))
table[i][n-1] = 1;
}
//fill table bottom up
for(int i = m-2; i>=0; i--){
for(int j = n-2; j>=0; j--){
if(str1.charAt(i)== str2.charAt(j))
table[i][j] = 1 + table[i+1][j+1];
else table[i][j] = Math.max(table[i+1][j], table[i][j+1]);
}
}
//return str1.length() + str2.length - 2* lcs(str1, str2)
return m + n - 2*table[0][0];
}
}
| [
"[email protected]"
] | |
3f0f13d9eed1cd7e336d8e3a246a6247f0db46cf | fc92a7dbdc5316d9a3e3ded58b0f0cf19ec785e0 | /week-8/src/chapter18/Edit1.java | 7111106884daf2bfc90597100d73a20ef6ff8ba6 | [] | no_license | rollingball211/Java_Study | 424b1c823faa011439dd6b93c1b01c62a48405af | 8fe79fea1807e59a425115501b830b394272547b | refs/heads/main | 2023-06-11T09:56:07.434119 | 2021-07-02T07:34:43 | 2021-07-02T07:34:43 | 334,901,503 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,089 | java | package chapter18;
public class Edit1 {
/*
자바에서 데이터는 스트림을 통해 입출력됨.
스트림은 단일 방향으로 연속적으로 흘러가는 것을 말함.
데이터를 입력받을 떄 =>InputStream (키보드,파일,네트워크상의 프로그램..)
프로그램이 데이터를 보낼 떄 =>OutputStream (모니터,파일.네트워크상의 프로그램)
스트림 클래스
1.byteStream
Input&OutputStream
2.문자기반 스트림
Reader
Writer
보조 스트림
다른 스트림과 연결되어 여러 가지 편리한 기능을 제공해주는 스트림을 말함
자체적으로 입출력을 수행할수 없기때문에 입/출력 소스와 바로 연결되는 스트림들에 연결되어 입출력 수행
문자변환,객체 입출력 등의 기능 제공.
InputStreamReader
바이트 입력 스트림에 연결되어 문자입력 스트림인 Reader로 변환시킴
Reader reader = new InputStreamReader(byte input stream);
콘솔 / 파일을 위한 스트림도 reader타입으로 변환 가능
InputStream is = system.in;
FileInputStream fis= new FileInputStream();
Reader reader = new InputStreamReader(is/fis);
OutputStreamWriter
바이트 출력 스트림에 연결되어 문자 출력 스트림인 Writer로 변환.
Writer writer = new OutputStreamWriter();
성능 향상 보조 스트림
메모리 버퍼와 작업해 실행 성능을 향상시킴.
버퍼는 데이터가 쌓이기를 기다렸다가 꽉 차게 되면 데이터를 한꺼번에 하드디스크로 보냄으로써 출력횟수 줄임
바이트기반은 Buffered Input/Output Stream이 있고
문자 기반 스트림에는 BufferedReader/Writer가 있음.
BufferedReader/ BufferedInputStream
문자 / 바이트 입력 스트림에 연결되어 버퍼를 제공해줌.
자신의 내부 버퍼 크기만큼 데이터를 미리 읽고 버퍼에 저장해놓음.
바이트는 최대 8192, 문자는 최대 8192문자까지 저장가능
BufferedWritter/ BufferedOutputStream
프로그램에서 전송한 데이터를 내부에 쌓아 두었다가 버퍼가 꽉 차면,
버퍼의 모든 데이터를 한꺼번에 보냄.
출력 작업을 마친 뒤에는 flush()메소드를 호출해 버퍼에서 잔류하고 있는 데이터를 보내게 해야함.
기본 타입 입출력 보조 스트림
DataInputStream / DataOutputStream
사용하면 기본 데이터 타입으로 입출력 가능.
데이터 타입의 크기가 모두 다르므로 outputStream으로 출력한 데이터를다시 읽어와야할 때는출력한 순서와 동일한 순서로 읽어와야함.
프린터 보조 스트림
PrintStream/PrintWriter
출력 스트림과 연결됨. Writer은 문자출력 스트림과 연결됨.
PrintStream ps = new PrintStream(byte 출력);
PrintWriter pw = new PrintWriter(문자출력);
객체 입출력 보조 스트림
자바는 메모리에 생성된 객체를 파일 또는 네트워크로 출력 가능.
객체는 문자가 아님=> 바이트 기반 스트림으로 출력해야함.
객체를 출력하기 위해서는 데이터(필드값)을 일렬로 늘어선 연속적인 바이트로 변경해야함
=>객체의 직렬화
입력 스트림으로부터 읽어들인 연속적인 바이트를 객체로 복원하는것을 역직렬화라고 함.
ObjectInputStream / ObjectOutputStream
직렬화가 가능한 클래스(Serializable)
자바는 Serializable 인터페이스를 구현한 클래스만 직렬화 할수 있도록 제한함.
객체를 직렬화할때 변환되는건 필드기 때문에 역직렬화 할떄도 필드의 값만 복원됨.
static or transient가 붙어있다면 직렬화 x
자식만 직렬화가 되있고 부모의 필드를 직렬화시키고 싶을 떄
부모 클래스가 Serilalizable 클래스를 구현하도록 함
or 자식 클래스에서 writeObject()와 readObject()메소드를 선언해 부모객체의 필드를 출력시킴.
*/
}
| [
"[email protected]"
] | |
7ef70a7dfb950814e2479f76d1f43ea80a200ade | 06c4a8306a7446a91c717627549adabe0065d0b5 | /android-design/src/test/java/com/lily/design/ExampleUnitTest.java | 200ba4718a95912b0de47fe90a9f9626e2047005 | [
"Apache-2.0"
] | permissive | rapeflower/AndroidStudy | 7069008125432006682c357bd04b8760ef65a9c7 | 908e383d9ecfac28f9e417e07bfa4df8d8c1e19b | refs/heads/master | 2021-01-21T16:15:52.481956 | 2019-08-16T02:47:44 | 2019-08-16T02:47:44 | 95,403,894 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 308 | java | package com.lily.design;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
861ac47ee3af398d58632b87a12ad61e923be673 | 315d7629ff6470f6752f9b6f97c125cb0a93681f | /src/omtg2sql/omtg/classes/OMTGCardinality.java | a4dac2c0058155505efedeb7a234058a7db8cd81 | [
"MIT"
] | permissive | lizardoluis/omtg2sql | 2430b70d0a962d676b6fc3fb01e551f262756e82 | e5208b4b0d73c65d3daa1045106b9356c93ece7f | refs/heads/master | 2020-12-03T05:26:49.371559 | 2016-03-07T17:16:59 | 2016-03-07T17:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,385 | java | package omtg2sql.omtg.classes;
import java.util.Scanner;
public class OMTGCardinality {
public static final String ONE_TO_ONE = "(1,1)";
public static final String ONE_TO_MANY = "(1,n)";
public static final String MANY_TO_ONE = "(n,1)";
public static final String MANY_TO_MANY = "(n,n)";
public static final int PARTIAL = 0;
public static final int TOTAL = 1;
private String min;
private String max;
private int participation;
public OMTGCardinality(String cardString) {
Scanner in = new Scanner(cardString);
in.useDelimiter(",");
this.min = in.next();
this.max = in.next();
if (min.equals("0"))
this.participation = 0; //partial
else this.participation = 1; //total
}
public OMTGCardinality(String min, String max) {
this.min = min;
this.max = max;
if (min.equals("0"))
this.participation = 0; //partial
else this.participation = 1; //total
}
public int getParticipation() {
return participation;
}
public String getMin() {
return min;
}
public String getMax() {
return max;
}
public boolean isEqual(OMTGCardinality card) {
if ((min.equals(card.getMin()) && max.equals(card.getMax())) ||
(min.equals(card.getMax()) && max.equals(card.getMin()))) {
return true;
}
return false;
}
public String toString() {
return "(" + min + "," + max + ")";
}
} | [
"[email protected]"
] | |
3da632bdb8737396fcd1d6bfe21005d2390bb89c | 41320c833d5ce2de98b07133d20f6b320958d73b | /src/main/java/Pair.java | 1a185fb37347ae82aea326c675714c0c062b4079 | [] | no_license | SamNechipurenko/HashMapSoftindex | 6b755ed18ab5b5cf034b69bb45f6e94640affa9c | 353537d99017b86041f871cd46ff7bbdc3ea7cea | refs/heads/master | 2021-03-10T17:52:33.386441 | 2020-03-11T04:51:06 | 2020-03-11T04:51:06 | 246,463,804 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 443 | java | public class Pair {
private int key;
private Long value;
public Pair() {
}
public Pair(int key, Long value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
| [
"[email protected]"
] | |
d0324e1c259343f6f644f30455c36df7759bfdb9 | 660b7f33a24d0de8bc42294bfbaf04db72f89267 | /src/main/java/chap15/chap15_7/chap15_7_1/ReturnGenericType.java | 1d557b789a82f40cff565f7879c34c998d12fa60 | [] | no_license | zhouqifen/think_java | 2ea93c074f5070ce23b10e7ed583683ae0117cd7 | 67b500c76d07f259b109939f8cba79088a12de29 | refs/heads/master | 2020-05-27T21:44:27.128073 | 2019-06-28T10:18:56 | 2019-06-28T10:18:56 | 188,798,026 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package chap15.chap15_7.chap15_7_1;
/**
* @Author: zhouqifen
* @Date:2019/6/21 17:15
* @Desc 当希望代码能跨多个类工作时,使用泛型才会有所帮助
* 类型参数在有用的泛型代码中应用比简单的类替换要更复杂
*/
public class ReturnGenericType<T> {
private T obj;
public ReturnGenericType(T x){
obj = x;
}
public T get(){
return obj;
}
}
| [
"zhouqfen213"
] | zhouqfen213 |
c9d6a87f8e07cc7f33ee4f42fc0794a09e371347 | ce3244ae892636d3c29db1454efe799c153b509c | /src/main/java/hampus/olsson/hvsz/com/example/demo/controllers/api/SquadMemberController.java | 5cb1e90981a1a67e43e000e130bb785ac4f466fe | [] | no_license | Heso113/hvszdbtemp | 14319fc571b58b52fbb7096aecab263502b8fde3 | 2782645276f8a4f34d29d9f9db7255e8dcea7c02 | refs/heads/main | 2023-01-22T07:46:24.332078 | 2020-12-03T09:49:48 | 2020-12-03T09:49:48 | 318,145,843 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,882 | java | package hampus.olsson.hvsz.com.example.demo.controllers.api;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import hampus.olsson.hvsz.com.example.demo.models.tables.Game;
import hampus.olsson.hvsz.com.example.demo.models.tables.Player;
import hampus.olsson.hvsz.com.example.demo.models.tables.Squad;
import hampus.olsson.hvsz.com.example.demo.models.tables.SquadMember;
import hampus.olsson.hvsz.com.example.demo.repositories.SquadMemberRepository;
@RestController
public class SquadMemberController {
@Autowired
SquadMemberRepository squadMemberRepository;
@GetMapping("/api/fetch/squadmember/all")
public ResponseEntity<ArrayList<SquadMember>> getAllUsers() {
ArrayList<SquadMember> squadMembers = (ArrayList<SquadMember>)squadMemberRepository.findAll();
System.out.println("Fetched all squad members");
return new ResponseEntity<>(squadMembers, HttpStatus.OK);
}
@PostMapping("/api/create/squadmember/{gameId}/{squadId}/{playerId}")
public ResponseEntity<SquadMember> addSquadMember(@RequestBody SquadMember newSquadMember, @PathVariable Integer gameId,
@PathVariable Integer squadId, @PathVariable Integer playerId) {
HttpStatus response = HttpStatus.CREATED;
newSquadMember.setGame(new Game(gameId));
newSquadMember.setSquad(new Squad(squadId));
newSquadMember.setPlayer(new Player(playerId));
squadMemberRepository.save(newSquadMember);
System.out.println("SquadMember CREATED with id: " + newSquadMember.getSquadMemberId());
return new ResponseEntity<>(newSquadMember, response);
}
@DeleteMapping("/api/delete/squadmember/{squadMemberId}")
public ResponseEntity<String> deleteSquadMember(@PathVariable Integer squadMemberId) {
String message = "";
HttpStatus response;
SquadMember squadMember = squadMemberRepository.findById(squadMemberId).orElse(null);
if(squadMember != null) {
squadMemberRepository.deleteById(squadMemberId);
System.out.println("SquadMember DELETED with id: " + squadMember.getSquadMemberId());
message = "SUCCESS";
response = HttpStatus.OK;
} else {
message = "FAILED";
response = HttpStatus.NOT_FOUND;
}
return new ResponseEntity<>(message, response);
}
}
| [
"[email protected]"
] | |
1bb3641f0f3885accfee69d0050c7ad955ef3ab8 | ebb0b0fdd6fdf01d30aa15acb1375ae77ba377e4 | /xyzbank-cucumber-project/src/test/java/com/bank/cucumber/Hooks.java | 5c3974bdf4a88862b9c35b05a4da037d1828f806 | [] | no_license | Rugnoronthemove/homework-25.04.2020-Cucumber-Projects | a07fee972760bde9204a255992712e308a05c860 | 4ef76e87a0de25acba0fd4304cc1fdee1a5d4e53 | refs/heads/master | 2023-04-14T13:16:17.058260 | 2020-04-29T22:20:43 | 2020-04-29T22:20:43 | 259,781,703 | 0 | 0 | null | 2021-04-26T20:13:44 | 2020-04-29T00:13:14 | Java | UTF-8 | Java | false | false | 1,840 | java | package com.bank.cucumber;
import com.bank.basepage.BasePage;
import com.bank.browserselector.BrowserSelector;
import com.bank.loadproperty.LoadProperty;
import com.bank.utility.Utility;
import com.cucumber.listener.Reporter;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Hooks extends BasePage {
BrowserSelector browserSelector = new BrowserSelector();
LoadProperty loadProperty = new LoadProperty();
String baseUrl = loadProperty.getProperty("baseUrl");
String browser = loadProperty.getProperty("browser");
//Annotation from cucumber.api.java //if selected from junit will get null pointer exception
@Before
public void openBrowser() {
browserSelector.selectBrowser(browser);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
//inserts Author into the Extent report
Reporter.assignAuthor("Prime Testing", "Batch 3");
}
//Annotation from cucumber.api.java //if selected from junit will get null pointer exception
//if Scenario is failing to take screenshot adding parameter as Scenario from cucumber
@After
public void tearDown(Scenario scenario) {
if (scenario.isFailed()) {
//declaring variable for screenShotPath & getting method from utility, replacing spaces" " in Scenario with "_"
String screenShotPath = Utility.getScreenshot(driver, scenario.getName().replace(" ", "_"));
try {
Reporter.addScreenCaptureFromPath(screenShotPath);
} catch (IOException e) {
e.printStackTrace();
}
}
// driver.quit();
}
}
| [
"[email protected]"
] | |
81bcdbd1fb3478cb7f903935db6122d64ffe723a | 68c0cd463d7e7860a362a3de2d1545d0ab449fcf | /backendWithDb/WebAppWithDb/src/main/java/se/kth/mobdev/ruontime/service/StatisticsService.java | 890a5e39f8f90540ba74d111d8116ecf0e271619 | [] | no_license | Anaskhall/rUonTime-Android | a90756171b3cb3f2d718eb8225ca41bfc139a8d3 | 3bf3c67ae7aab5c4b738c4487fa836244b079233 | refs/heads/master | 2021-01-20T00:40:21.946693 | 2014-03-05T11:04:45 | 2014-03-05T11:04:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,157 | java | /**
*
*/
package se.kth.mobdev.ruontime.service;
import java.util.List;
import se.kth.mobdev.ruontime.model.Statistics;
import se.kth.mobdev.ruontime.persistence.PersistenceFactory;
import se.kth.mobdev.ruontime.persistence.model.CheckIn;
import se.kth.mobdev.ruontime.persistence.model.User;
/**
* @author Jasper
*
*/
public class StatisticsService {
public Statistics getUserStatistics(User user) {
List<CheckIn> checkInsForUser = PersistenceFactory.getCheckinDao().getCheckInsForUser(user.getUserName());
Statistics statistics = new Statistics(checkInsForUser);
//aggregate information:
int aggregatedLate = 0;
int noOfFirst = 0;
int noOfLast = 0;
for(CheckIn check: checkInsForUser) {
aggregatedLate += check.getMinutesLate();
if(check.isFirstToShowUp())
noOfFirst++;
if(check.isLastToShowUp())
noOfLast++;
}
double avgLate = (aggregatedLate * 1.0)/checkInsForUser.size();
statistics.setAggregatedLate(aggregatedLate);
statistics.setAvgLate(avgLate);
statistics.setNoOfFirst(noOfFirst);
statistics.setNoOfLast(noOfLast);
return statistics;
}
}
| [
"[email protected]"
] | |
37ddb0400061fa4b1fb93a33ec55669ab2aeb533 | 4e324ac5ef3237edfbb35e3b58a2914e458ece8b | /aliyun_video/src/main/java/com/online/edu/videoservice/service/VideoService.java | 976e913820421e8354e8d30375636c202aa2c29c | [] | no_license | MapToSend/xuechen_edu | 5df8832e66cb8401e184b60ddd174d2669b20883 | bf649f3a43495d602cf2a12a1f1e404b625399b9 | refs/heads/master | 2022-07-05T00:22:26.833191 | 2019-12-14T10:24:08 | 2019-12-14T10:24:08 | 228,003,731 | 0 | 0 | null | 2022-06-29T17:50:47 | 2019-12-14T10:23:42 | Java | UTF-8 | Java | false | false | 230 | java | package com.online.edu.videoservice.service;
import org.springframework.web.multipart.MultipartFile;
public interface VideoService {
public String uploadVideo(MultipartFile file);
Boolean deleteVideo(String videoId);
}
| [
"[email protected]"
] | |
39848736738d705c2ccb8650f75545b5837bb8de | 483fb1e501d825906c8b0ab8acff4b71d17f9e0a | /123180086_RESPONSI_A/src/View/vHome.java | 0975df6a0d258ea5617f53f7617f93bc0595b59d | [] | no_license | vaniazer/123180086_RESPONSI_A | f8a8d3d9885d036d34bdc9dfeb8102dd6620c53b | cf7ac8d59ffe2936f6311f5b649b2646cb1d7ee9 | refs/heads/master | 2022-08-03T02:49:02.228829 | 2020-05-19T16:38:04 | 2020-05-19T16:38:04 | 265,302,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,719 | java | package View;
import javax.swing.*;
import java.awt.*;
public class vHome extends JFrame {
JLabel lLogo = new JLabel();
String path = new String("src/Gambar/home.png");
ImageIcon imageIcon = new ImageIcon(path);
Image image = imageIcon.getImage();
Image newImage = image.getScaledInstance(700,400,Image.SCALE_SMOOTH);
ImageIcon logo = new ImageIcon(newImage);
Font font = new Font("Serif",Font.BOLD, 20);
Font font1 = new Font("Monospaced", Font.CENTER_BASELINE,12);
public JButton btnLogout = new JButton("Logout");
public JButton btnPinjam = new JButton("PINJAM");
public JButton btnTampil = new JButton("TAMPIL");
public JButton btnAboutUs = new JButton("ABOUT US");
public vHome(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("PERPUSTAKAAN");
setVisible(true);
setLayout(null);
setSize(700,420);
setResizable(true);
setLocationRelativeTo(null);
getContentPane().setBackground(Color.BLACK);
add(lLogo);
lLogo.setBounds(0,0,700,400);
lLogo.setIcon(logo);
add(btnLogout);
btnLogout.setBounds(560,10,100,20);
add(btnPinjam);
btnPinjam.setBounds(130,110,140,40);
btnPinjam.setFont(font);
add(btnTampil);
btnTampil.setBounds(130,180,140,40);
btnTampil.setFont(font);
add(btnAboutUs);
btnAboutUs.setBounds(130,250,140,40);
btnAboutUs.setFont(font);
}
}
| [
"[email protected]"
] | |
05f312ae9ec07f472f3da4a51da3df31f4f353c9 | ce6aedf1a56b576ed290fa771b967e4fd758e9f2 | /src/main/java/net/novaborn/smtp/command/RequireAuthCommandWrapper.java | 441249fb8fe79e2386abcfd4a16e73f443768ca6 | [] | no_license | oliverfun/smtp- | c2cd926a354981d22d1a9561d69c01da9285462e | 4665d4705417a9b6cb6c12c7e9e342ca2cf22f67 | refs/heads/master | 2023-03-23T12:00:55.013808 | 2020-11-07T10:51:25 | 2020-11-07T10:51:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,546 | java | package net.novaborn.smtp.command;
import net.novaborn.smtp.server.Command;
import net.novaborn.smtp.server.SmtpSession;
import java.io.IOException;
public class RequireAuthCommandWrapper implements Command
{
private Command wrapped;
/**
* @param wrapped the wrapped command (not null)
*/
public RequireAuthCommandWrapper(Command wrapped)
{
this.wrapped = wrapped;
}
/**
* {@inheritDoc}
*/
// public String execute(String preState, String commandString, Channel channel, ServerConfig serverConfig, CommandHandler commandHandler)
// throws IOException
// {
// String isLogin = (String)channel.attr(AttributeKey.valueOf("isLogin")).get();
// if (!(serverConfig.isAuthenticated=="true") || isLogin=="true")
// return wrapped.execute(preState,commandString, channel,serverConfig,commandHandler);
// else
// channel.writeAndFlush("530 5.7.0 Authentication required\r\n");
// return preState;
// }
@Override
public SmtpSession execute(String commandString, SmtpSession smtpSession) throws IOException {
if(smtpSession.isLogin()||!(smtpSession.getServerConfig().isAuthenticated)){
return wrapped.execute(commandString,smtpSession);
}
else{
smtpSession.Write("530 5.7.0 Authentication required\r\n");
return smtpSession;
}
}
/**
* {@inheritDoc}
*/
public String getName()
{
return wrapped.getName();
}
}
| [
"[email protected]"
] | |
71e3764fe01873e27b5b68a0c0dbef76243c18f0 | 474f1f1da5f8e76ec4c42f164e70cfd5bcd3c322 | /src/main/java/com/mykid/platform/web/controller/system/LoginController.java | 45ecdd293b10c7eba656d620bae7e570a1efbd50 | [
"Apache-2.0"
] | permissive | fifthangel/kid-platform | 1fb3d33172d5fd683573d15db0c520d0a494ef3e | 0fe4164beeb482040c9e82529d42dff65115044d | refs/heads/master | 2022-09-04T18:30:42.446766 | 2020-02-27T13:57:20 | 2020-02-27T13:57:20 | 216,469,183 | 0 | 0 | Apache-2.0 | 2022-09-01T23:14:41 | 2019-10-21T03:22:25 | Java | UTF-8 | Java | false | false | 4,377 | java | package com.mykid.platform.web.controller.system;
import com.mykid.platform.common.annotation.Limit;
import com.mykid.platform.common.controller.BaseController;
import com.mykid.platform.common.entity.PlatformResponse;
import com.mykid.platform.common.exception.PlatformException;
import com.mykid.platform.common.utils.CaptchaUtil;
import com.mykid.platform.common.utils.MD5Util;
import com.mykid.platform.pojo.entity.LoginLog;
import com.mykid.platform.service.ILoginLogService;
import com.mykid.platform.pojo.entity.User;
import com.mykid.platform.service.IUserService;
import com.wf.captcha.base.Captcha;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author MrBird
*/
@Validated
@RestController
public class LoginController extends BaseController {
@Autowired
private IUserService userService;
@Autowired
private ILoginLogService loginLogService;
@PostMapping("login")
@Limit(key = "login", period = 60, count = 20, name = "登录接口", prefix = "limit")
public PlatformResponse login(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password,
@NotBlank(message = "{required}") String verifyCode,
boolean rememberMe, HttpServletRequest request) throws PlatformException {
if (!CaptchaUtil.verify(verifyCode, request)) {
throw new PlatformException("验证码错误!");
}
password = MD5Util.encrypt(username.toLowerCase(), password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
super.login(token);
// 保存登录日志
LoginLog loginLog = new LoginLog();
loginLog.setUsername(username);
loginLog.setSystemBrowserInfo();
this.loginLogService.saveLoginLog(loginLog);
return new PlatformResponse().success();
}
@PostMapping("regist")
public PlatformResponse regist(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password) throws PlatformException {
User user = userService.findByName(username);
if (user != null) {
throw new PlatformException("该用户名已存在");
}
this.userService.regist(username, password);
return new PlatformResponse().success();
}
@GetMapping("index/{username}")
public PlatformResponse index(@NotBlank(message = "{required}") @PathVariable String username) {
// 更新登录时间
this.userService.updateLoginTime(username);
Map<String, Object> data = new HashMap<>();
// 获取系统访问记录
Long totalVisitCount = this.loginLogService.findTotalVisitCount();
data.put("totalVisitCount", totalVisitCount);
Long todayVisitCount = this.loginLogService.findTodayVisitCount();
data.put("todayVisitCount", todayVisitCount);
Long todayIp = this.loginLogService.findTodayIp();
data.put("todayIp", todayIp);
// 获取近期系统访问记录
List<Map<String, Object>> lastSevenVisitCount = this.loginLogService.findLastSevenDaysVisitCount(null);
data.put("lastSevenVisitCount", lastSevenVisitCount);
User param = new User();
param.setUsername(username);
List<Map<String, Object>> lastSevenUserVisitCount = this.loginLogService.findLastSevenDaysVisitCount(param);
data.put("lastSevenUserVisitCount", lastSevenUserVisitCount);
return new PlatformResponse().success().data(data);
}
@GetMapping("images/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
CaptchaUtil.outPng(110, 34, 4, Captcha.TYPE_ONLY_NUMBER, request, response);
}
}
| [
"[email protected]"
] | |
9082d816ce17da26f1749e913895152c46f3f9f6 | e63112f59af96a4fdf9899381ed62a2f00960f5e | /C01W02-find-gene-assignment/src/Part4.java | b22be5c261500a06f938ba00770082ac51160d79 | [] | no_license | EnduranceCode/JavaCourseraDuke | 356c38b2c211f1832dcc036e587134e72d93bf2e | ca31d50fb8ae82a709aa0cd316613434ade8e837 | refs/heads/master | 2021-06-16T22:16:01.537468 | 2021-02-19T23:27:00 | 2021-02-19T23:27:00 | 163,318,585 | 2 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,349 | java | import edu.duke.URLResource;
public class Part4 {
public String findYoutubeURL() {
/* Track the result of the search */
String result = "";
/* Get the given URL Resource */
URLResource urlResource = new URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
/* Read the file in the given URL, word by word */
for (String word : urlResource.words()) {
/* Set the word to lower case */
String lowerCaseWord = word.toLowerCase();
/* Get the index of "youtube.com" in the word */
int indexYoutubeCom = lowerCaseWord.indexOf("youtube.com");
/* Check if "youtube.com" is present in the word */
if (indexYoutubeCom != -1) {
/*
* "youtube.com" is included in the word, so we look for the full URL,
* Starting with the beginning of the URL
*/
int startIndex = lowerCaseWord.lastIndexOf('\"', indexYoutubeCom) + 1;
/* Then we look for the end of the URL */
int endIndex = lowerCaseWord.indexOf('\"', indexYoutubeCom);
/* We get the URL and add it to the result string */
result += word.substring(startIndex, endIndex) + "\n";
}
}
return result;
}
public static void main(String[] args) {
Part4 part4 = new Part4();
System.out.println("Youtube Video's URL found:\n" + part4.findYoutubeURL());
}
}
| [
"[email protected]"
] | |
706155ccb63537f890b8929f0b7e4a5958994770 | ce29435b8b6bc3c095aef1e80132423fc947c74f | /src/quintwong/mapper/HeroMapper.java | bfc6b4188f6ba8d30daf2c0889a103c1cb24af20 | [] | no_license | wangqgcn/mybatis | 834ecc7811284a1f5df1f9f0804a86775ef9d2cf | b5c464cb77befb4bd0f53349257adf4003e8a1b4 | refs/heads/master | 2023-04-05T10:33:50.468391 | 2021-04-12T17:26:29 | 2021-04-12T17:26:29 | 357,281,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,550 | java | package quintwong.mapper;
import quintwong.pojo.Hero;
import quintwong.pojo.HeroExample;
import java.util.List;
public interface HeroMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
int insert(Hero record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
int insertSelective(Hero record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
List<Hero> selectByExample(HeroExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
Hero selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(Hero record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table hero
*
* @mbg.generated
*/
int updateByPrimaryKey(Hero record);
} | [
"[email protected]"
] | |
69489fafb567d7d46410fcbc29de01162b3ce89e | 926da11a2f285ee8386339192b2f5e34331ed419 | /fourteenproject.java | 8f6415ffa0480898f7637f2baf9caf9285a8a624 | [] | no_license | SunsetUzuki/tic-tac-toe | 6a4609c8cbfa4a930c7ec939cdfa7efdb815335b | 97755ed6b583bfd8bf76bd345dccbb2625d4e071 | refs/heads/master | 2021-05-12T01:41:26.408972 | 2018-01-15T17:46:13 | 2018-01-15T17:46:13 | 117,565,855 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,877 | java | package by.itstep;
import java.util.Scanner;
/**
* Created by st on 11.12.2017.
*/
public class fourteenproject {
public static void main3(String[] args) {
int[] a = new int[10];
for (int x = 0; x < a.length; x++) {
a[x] = x + 1;
}
printArray(a);
// int []pari=Pari(a);
// printArray(pari);
printArray(Sme(a, 1));
}
public static void fillByRandom(int a[], int max) {
for (int i = 0; i < a.length; i++)
a[i] = (int) (Math.random() * max);
}
public static void fillByValue(int a[], int value) {
for (int i = 0; i < a.length; i++)
a[i] = value;
}
public static void printArray(int a[]) {
for (int i = 0; i < a.length; i++)
System.out.printf("[%d]=%d ", i, a[i]);
System.out.println();
}
public static int[] copyAndMultiply(int[] sourceArray, int m) {
int[] newArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++)
newArray[i] = sourceArray[i] * m;
return newArray;
}
public static int[] Pari(int p[]) {
for (int i = 0; i < p.length - 1; i = i + 2) {
int x = p[i + 1];
p[i + 1] = p[i];
p[i] = x;
}
return p;
}
public static int[] Sme(int b[], int n) {
int x;
for (int i = 0; i < n; i++) {
x = b[b.length - 1];
for (int nn = b.length - 1; nn > 1; nn--) {
b[nn] = b[nn - 1];
}
b[0] = x;
}
return b;
}
public static void main2(String[] args) {
int[] a = new int[10];
fillByRandom(a, 100);
printArray(a);
int n = 3 % a.length;
int[] buffer = new int[n];
for (int i = 0; i < n; i++)
buffer[i] = a[a.length - n + i];
printArray(buffer);
for (int i = a.length - 1; i >= n; i--)
a[i] = a[i - n];
for (int i = 0; i < n; i++)
a[i] = buffer[i];
printArray(a);
}
public static void main6(String[] args) {
int[] x = new int[10];
fillByRandom(x, 100);
printArray(x);
int max = 0;
int currentCount = 0;
int indexOfFirst = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 == 0)
currentCount++;
else {
if (currentCount > max) {
max = currentCount;
indexOfFirst = i - max;
}
currentCount = 0;
}
}
System.out.println(max);
while (x[indexOfFirst] % 2 == 0) {//for (int i=indexOfFirst; i<indexOfFirst+max;i++) system/out/print(x[i]+" "); s
System.out.print(x[indexOfFirst] + " ");
indexOfFirst++;
}
}
public static void main7(String[] args) {
int x;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Введите число от 0 до 10");
System.out.println("Введите 100 для выхода");
x = sc.nextInt();
switch (x) {
case 1:
System.out.println("Один");
break;
case 2:
System.out.println("Два");
break;
case 3:
System.out.println("Три");
break;
case 4:
System.out.println("Четыре");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("Число больше 4х, меньше 10ти");
break;
default:
System.out.println("Что за число?");
}
} while (x != 100);
}
public static void main4(String[] args) {
int[] a = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 10);
for (int j = 0; j < i; j++) {
while (a[i] == a[j]) {
a[i] = (int) (Math.random() * 10);
j = 0;
}
}
}
printArray(a);
}
public static void main(String[] args) {
final int SIZE = 12;
final int RANDOM_LIMIT = 12;
int[] x = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
x[i] = (int) (Math.random() * RANDOM_LIMIT);
for (int j = 0; j < i; j++) {
if (x[i] == x[j]) {
i--;
break;
}
}
}printArray(x);
}
}
| [
"[email protected]"
] | |
5782c25bb46e1c2ce4a11a71b69df975ee771c61 | 6ecaaf02caaf3285d0c84ca3db03f5e8124ec7c4 | /src/main/java/com/verwaltungsplatform/service/TeacherServiceImpl.java | f753e2ffecf6ea486ab841af5e6becdb8482a19f | [] | no_license | Team1-Uni-Passau/Verwaltungsplattform-Schule-Backend | 833cc15f3a8d4996344fd07d1815285658cd5400 | 17a8de1be84137c46c62adc0961aeb311b2d044c | refs/heads/master | 2023-03-02T11:38:56.316876 | 2021-01-17T17:40:26 | 2021-01-17T17:40:26 | 313,601,855 | 0 | 0 | null | 2021-01-15T11:33:37 | 2020-11-17T11:44:20 | Java | UTF-8 | Java | false | false | 79 | java | package com.verwaltungsplatform.service;
public class TeacherServiceImpl {
}
| [
"[email protected]"
] | |
5a9904d31fd888388d0e4c9f42b860ecd88a77ac | 1aef4669e891333de303db570c7a690c122eb7dd | /src/main/java/com/alipay/api/domain/AlipayEcoCmsCdataUploadModel.java | 0a6338dfe1db978fffe4e0d85675e73c811c5363 | [
"Apache-2.0"
] | permissive | fossabot/alipay-sdk-java-all | b5d9698b846fa23665929d23a8c98baf9eb3a3c2 | 3972bc64e041eeef98e95d6fcd62cd7e6bf56964 | refs/heads/master | 2020-09-20T22:08:01.292795 | 2019-11-28T08:12:26 | 2019-11-28T08:12:26 | 224,602,331 | 0 | 0 | Apache-2.0 | 2019-11-28T08:12:26 | 2019-11-28T08:12:25 | null | UTF-8 | Java | false | false | 4,090 | java | package com.alipay.api.domain;
import java.util.Date;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 上传投放消息
*
* @author auto create
* @since 1.0, 2016-09-21 11:31:27
*/
public class AlipayEcoCmsCdataUploadModel extends AlipayObject {
private static final long serialVersionUID = 5782951614883492959L;
/**
* 属性-消息投放的单个行业页面(如教育的某个幼儿园)
*/
@ApiField("attribute")
private String attribute;
/**
* 类目-消息投放的行业平台(教育、车主、医疗等)
*/
@ApiField("category")
private String category;
/**
* 消息失效时间,标准时间格式:yyyy-MM-dd HH:mm:ss
*/
@ApiField("exp_time")
private Date expTime;
/**
* 商户消息唯一流水,类目范围内唯一,标识此消息唯一ID,若重复上传通过此判断
*/
@ApiField("merch_id")
private String merchId;
/**
* 操作数据,自定义,使用方需知晓
若需要同步域内时:
如果只需要支付宝这边利用数据直接完成某个功能(通知),则使用此参数传输数据.,根据不同的scene_code,op_code,channel,version共同确定参数是否可以为空,接入时由支付宝确定参数格式。
*/
@ApiField("op_data")
private String opData;
/**
* 消息数据,json格式,内容由模板参数列表定义.
{"占位符":"参数值","占位符2":"参数值"…}
若需要同步域内时:
场景的数据表示. json 数组
格式,根据不同的scene_code,
op_code,channel,version共同确定
参数是否可以为空,接入时由支付宝确定
参数格式。
*/
@ApiField("scene_data")
private String sceneData;
/**
* 消息生效时间,标准时间格式:yyyy-MM-dd HH:mm:ss
*/
@ApiField("start_time")
private Date startTime;
/**
* 是否需要同步域内,设定模板时需支持;
若需要特殊可选均是必填
*/
@ApiField("syn")
private Boolean syn;
/**
* 消息模板的版本,由开放生态分配
*/
@ApiField("t_v")
private String tV;
/**
* 消息模板ID,需要预先设定模板才能进行消息投放,由开放生态协商分配
*/
@ApiField("tamplate_id")
private Long tamplateId;
/**
* 投放目标对象,自定义.
若需要同步到域内:
场景覆盖的目标人群标识,单个用户是支付宝的userId,多个用户userId 使用英文半角逗号隔开,最多200个如果是群组,使用支付宝分配的群组ID.
*/
@ApiField("target_id")
private String targetId;
public String getAttribute() {
return this.attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public Date getExpTime() {
return this.expTime;
}
public void setExpTime(Date expTime) {
this.expTime = expTime;
}
public String getMerchId() {
return this.merchId;
}
public void setMerchId(String merchId) {
this.merchId = merchId;
}
public String getOpData() {
return this.opData;
}
public void setOpData(String opData) {
this.opData = opData;
}
public String getSceneData() {
return this.sceneData;
}
public void setSceneData(String sceneData) {
this.sceneData = sceneData;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Boolean getSyn() {
return this.syn;
}
public void setSyn(Boolean syn) {
this.syn = syn;
}
public String gettV() {
return this.tV;
}
public void settV(String tV) {
this.tV = tV;
}
public Long getTamplateId() {
return this.tamplateId;
}
public void setTamplateId(Long tamplateId) {
this.tamplateId = tamplateId;
}
public String getTargetId() {
return this.targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
}
| [
"[email protected]"
] | |
196370d91ca661bfe59bbd806b6af65caeceb782 | 5cebcdf3c154784a60324f71e8513c71d5f2f1cc | /src/comparators/PanelWidthComparator.java | e312a69bd5611a6bf0cc4c863947a4b455b57d8a | [] | no_license | grezxune/hilltop-woods-creations-2.0 | b66ab2d724957afe6e26ea97d3235ecf10bc3e3c | 162c447a97452c0555efdbb494c90c32a6566d85 | refs/heads/master | 2020-07-22T05:50:32.362886 | 2017-06-14T15:14:39 | 2017-06-14T15:14:39 | 94,344,308 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 736 | java | /*****************************
******************************
*
* File: PanelWidthComparator.java
*
* Project: Hilltop Woods Creations 2.0
*
* Author: Tommy Trzebiatowski
*
* Description:
*
* Comments: 3/1/2013
*
*****************************
*****************************/
package comparators;
import java.util.Comparator;
import newDoorSystem.CabinetOpening;
public class PanelWidthComparator implements Comparator< CabinetOpening >
{
public int compare( CabinetOpening door1, CabinetOpening door2 )
{
//double doorOnePanelWidth = door1.getPanelWidth();
//double doorTwoPanelWidth = door2.getPanelWidth();
//return Double.compare( doorOnePanelWidth, doorTwoPanelWidth );
return 0;
}
} | [
"[email protected]"
] | |
bd5acb982261a8550a6b935163f33c50a60db5c2 | 9b8a1e7d4f3dea4296e3bfab54e2ed3972c1dec2 | /src/main/java/designpattern/iterator/transition/PancakeHouseMenu.java | eeade95f08b0462b21390c671937f90c2cf24484 | [] | no_license | zhsirhello/javas | fba899a8b4065ed218b92b791dd1dd5481d9fc40 | 28e410aad7df30641c33cd2439666bbf93b7a0ed | refs/heads/master | 2022-10-15T11:10:32.703565 | 2022-02-17T09:44:09 | 2022-02-17T09:44:09 | 163,251,708 | 0 | 0 | null | 2022-01-07T22:40:21 | 2018-12-27T05:37:30 | Java | UTF-8 | Java | false | false | 1,092 | java | package designpattern.iterator.transition;
import java.util.ArrayList;
import java.util.Iterator;
public class PancakeHouseMenu implements Menu {
ArrayList<MenuItem> menuItems;
public PancakeHouseMenu() {
menuItems = new ArrayList<MenuItem>();
addItem("K&B's Pancake Breakfast",
"Pancakes with scrambled eggs, and toast",
true,
2.99);
addItem("Regular Pancake Breakfast",
"Pancakes with fried eggs, sausage",
false,
2.99);
addItem("Blueberry Pancakes",
"Pancakes made with fresh blueberries, and blueberry syrup",
true,
3.49);
addItem("Waffles",
"Waffles, with your choice of blueberries or strawberries",
true,
3.59);
}
public void addItem(String name, String description,
boolean vegetarian, double price)
{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
menuItems.add(menuItem);
}
public ArrayList<MenuItem> getMenuItems() {
return menuItems;
}
public Iterator<MenuItem> createIterator() {
return menuItems.iterator();
}
// other menu methods here
}
| [
"[email protected]"
] | |
27f03c6b58fc2178afd88de3159f4f1d0de16b17 | ab08369680595aad6fa22e35c8353649952b8dc7 | /src/main/java/test/db/DBManager.java | d64170f83ca94973445a53b2c658163946bbc91d | [] | no_license | ikvwar7/test | 0a996ad58c107e3d868b7150bea8545835f77927 | 9ce5d2b448abec84f31cc8beca04a1c57de6e56f | refs/heads/master | 2020-04-29T19:29:19.660802 | 2019-03-19T08:41:21 | 2019-03-19T08:41:21 | 176,352,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,391 | java | package test.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.domain.Result;
import test.domain.actions.object.DemandObject;
import test.domain.actions.object.NewProductObject;
import test.domain.actions.object.PurchaseOpbject;
import test.domain.actions.object.SalesReportObject;
import java.sql.*;
public class DBManager {
private static final Logger logger = LoggerFactory.getLogger(DBManager.class);
private final String DRIVER_NAME = "org.h2.Driver";
private final String DB_URL = "jdbc:h2:mem:";
private static Connection conn;
private final String PURCHASE = "PURCHASE";
public static DBManager getDBManager() {
return new DBManager();
}
private DBManager() {
if (conn == null)
conn = createH2Connection();
}
private Connection createH2Connection() {
try {
Class.forName(DRIVER_NAME);
return DriverManager.getConnection(DB_URL);
} catch (ClassNotFoundException | SQLException e) {
System.exit(-1);
return null;
}
}
public void creteTables() {
String createActionTable = "CREATE TABLE IF NOT EXISTS Action(" +
"id NUMBER auto_increment ," +
"name Varchar(200)," +
"amount NUMBER," +
"action_kind VARCHAR(20)," +
"date DATE ," +
"price DOUBLE," +
"PRIMARY KEY(id))";
try {
Statement createTable = conn.createStatement();
createTable.execute(createActionTable);
String createProductTable = "CREATE TABLE IF NOT EXISTS Product(" +
"name Varchar(200))";
createTable.execute(createProductTable);
String createSaleTable = "CREATE TABLE IF NOT EXISTS Profit(" +
"name Varchar(200)," +
"profit DOUBLE," +
"sale_date DATE)";
createTable.execute(createSaleTable);
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
}
public void dropTables() {
String dropActionTable = "DROP TABLE IF EXISTS Action";
try {
Statement dropTable = conn.createStatement();
dropTable.execute(dropActionTable);
String dropProductTable = "DROP TABLE IF EXISTS Product";
dropTable.execute(dropProductTable);
String dropSaleTable = "DROP TABLE IF EXISTS Profit";
dropTable.execute(dropSaleTable);
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
}
public Result addProduct(NewProductObject newProductObject) {
String name = newProductObject.getName();
try {
if (isProductExist(name)) return new Result("ERROR");
String insertProduct = "Insert into product (name) Values(?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertProduct);
preparedStatement.setString(1, name);
preparedStatement.executeUpdate();
logger.debug("Add new product {}", newProductObject);
return new Result("OK");
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
return new Result("ERROR");
}
public Result purchase(PurchaseOpbject purchaseOpbject) {
try {
String name = purchaseOpbject.getName();
int amount = purchaseOpbject.getAmount();
Date date = Date.valueOf(purchaseOpbject.getDate());
Double price = purchaseOpbject.getPrice();
if (!isProductExist(name)) return new Result("ERROR");
if (!isDateValid(date, name)) return new Result("ERROR");
String insertPurchase = "Insert into Action (name, amount, action_kind, date, price) " +
"Values (?, ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(insertPurchase);
statement.setString(1, name);
statement.setInt(2, amount);
statement.setString(3, PURCHASE);
statement.setDate(4, date);
statement.setDouble(5, price);
statement.executeUpdate();
logger.debug("Purchase product {}", purchaseOpbject);
return new Result("OK");
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
return new Result("ERROR");
}
public Result demand(DemandObject demandObject) {
try {
String name = demandObject.getName();
int amount = demandObject.getAmount();
Date date = Date.valueOf(demandObject.getDate());
Double price = demandObject.getPrice();
if (!isProductExist(name)) return new Result("ERROR");
if (!isAmountValid(amount, date)) return new Result("ERROR");
double profit = demand(amount, date, price);
insetIntoSaleTable(name, profit, date);
logger.debug("Demand product {}", demandObject);
return new Result("OK");
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
return new Result("ERROR");
}
public Result salesReport(SalesReportObject salesReportObject) {
try {
String name = salesReportObject.getName();
Date date = Date.valueOf(salesReportObject.getDate());
String selectProfit = "SELECT SUM(profit) FROM Profit WHERE name = ? and sale_date <= ?";
PreparedStatement statement = conn.prepareStatement(selectProfit);
statement.setString(1, name);
statement.setDate(2, date);
ResultSet profit = statement.executeQuery();
double salesReport = 0;
while (profit.next()) {
salesReport = profit.getDouble(1);
}
logger.debug("SalesReport {}", salesReportObject);
return new Result(Double.toString(salesReport));
} catch (SQLException ex) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
return new Result("ERROR");
}
/**
* проверяет продавали ли товар с указанным именем раньше введённой даты
*/
private boolean isDateValid(Date date, String name) throws SQLException {
String selectMinDate = "SELECT MIN(date) FROM Action WHERE name = ?";
PreparedStatement stat = conn.prepareStatement(selectMinDate);
stat.setString(1, name);
ResultSet minDate = stat.executeQuery();
Date min = null;
while (minDate.next()) {
if (minDate.getDate(1) == null) return true;
min = minDate.getDate(1);
}
return !date.before(min);
}
private boolean isAmountValid(int amount, Date date) throws SQLException {
String selectAmount = "SELECT SUM(amount) FROM Action WHERE action_kind = 'PURCHASE' and date < ?";
PreparedStatement statement = conn.prepareStatement(selectAmount);
statement.setDate(1, date);
ResultSet amountSet = statement.executeQuery();
while (amountSet.next()) {
if (amountSet.getInt(1) < amount) return false;
}
return true;
}
private boolean isProductExist(String name) throws SQLException {
String selectProduct = "Select * FROM Product WHERE name = ?";
PreparedStatement statement = conn.prepareStatement(selectProduct);
statement.setString(1, name);
ResultSet productSet = statement.executeQuery();
return productSet.isBeforeFirst();
}
private double demand(int amount, Date date, double price) throws SQLException {
String selectPurchase = "SELECT * FROM Action WHERE action_kind = 'PURCHASE' and date < ?";
PreparedStatement purchaseStatement = conn.prepareStatement(selectPurchase);
purchaseStatement.setDate(1, date);
Statement updateDbStatments = conn.createStatement();
double revenue = 0;
int amountToSale = 0;
ResultSet purhaseSet = purchaseStatement.executeQuery();
while (purhaseSet.next()) {
conn.setAutoCommit(false);
int id = purhaseSet.getInt(1);
amountToSale += purhaseSet.getInt(3);//число проданных товаров
if (amount - amountToSale >= 0) {
revenue += purhaseSet.getInt(3) * purhaseSet.getDouble(6);//amount * price
String update = "DELETE FROM Action WHERE id = " + id;
updateDbStatments.addBatch(update);
if (amount == amountToSale) break;
} else if (amount - amountToSale < 0) {//если поле amount в строке не 0, надо обновить его
revenue += (amount - amountToSale + purhaseSet.getInt(3)) * purhaseSet.getDouble(6);
String update = "UPDATE Action SET amount = " + (amountToSale - amount) + "WHERE id = " + id;
updateDbStatments.addBatch(update);
break;
}
}
updateDbStatments.executeBatch();
conn.commit();
double profit = price * amount - revenue;
return profit;
}
private void insetIntoSaleTable(String name, double profit, Date saleDate) throws SQLException {
String intoSale = "INSERT INTO Profit (name, profit, sale_date) VALUES (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(intoSale);
statement.setString(1, name);
statement.setDouble(2, profit);
statement.setDate(3, saleDate);
statement.executeUpdate();
}
} | [
"[email protected]"
] | |
1ecc8dfae6899af5a11bd788dd10ec1165ee25a7 | 7b74527c03af2c0aa909d936a45315faae70264b | /impl/shim/sqoop/src/test/java/org/pentaho/big/data/impl/shim/sqoop/SqoopServiceFactoryLoaderTest.java | c0ca48df782523b1393e3a64c0b4041d7604597b | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | LoseYourself/big-data-plugin-8.0 | 22d7a9a24f3d2f1ddf27d62287b65a41bbd38da8 | 0cc7b301bc59d6da1507f90df66464efc3de96d0 | refs/heads/master | 2020-03-14T21:03:43.191289 | 2018-05-04T02:06:32 | 2018-05-04T02:06:32 | 131,788,250 | 4 | 2 | Apache-2.0 | 2018-05-17T05:43:32 | 2018-05-02T02:36:06 | Java | UTF-8 | Java | false | false | 5,164 | java | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.impl.shim.sqoop;
import com.google.common.primitives.Primitives;
import com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingServiceTracker;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.osgi.framework.BundleContext;
import org.pentaho.big.data.api.cluster.service.locator.NamedClusterServiceFactory;
import org.pentaho.di.core.hadoop.HadoopConfigurationBootstrap;
import org.pentaho.hadoop.shim.ConfigurationException;
import org.pentaho.hadoop.shim.HadoopConfiguration;
import org.pentaho.hadoop.shim.spi.HadoopShim;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
* Created by bryan on 2/26/16.
*/
public class SqoopServiceFactoryLoaderTest {
private BundleContext bundleContext;
private ShimBridgingServiceTracker shimBridgingServiceTracker;
private HadoopConfigurationBootstrap hadoopConfigurationBootstrap;
private SqoopServiceFactoryLoader sqoopServiceFactoryLoader;
@Before
public void setup() throws ConfigurationException {
bundleContext = mock( BundleContext.class );
shimBridgingServiceTracker = mock( ShimBridgingServiceTracker.class );
hadoopConfigurationBootstrap = mock( HadoopConfigurationBootstrap.class );
sqoopServiceFactoryLoader =
new SqoopServiceFactoryLoader( bundleContext, shimBridgingServiceTracker, hadoopConfigurationBootstrap );
verify( hadoopConfigurationBootstrap ).registerHadoopConfigurationListener( sqoopServiceFactoryLoader );
}
@Test
public void testTwoArgConstructor() throws ConfigurationException {
assertNotNull( new SqoopServiceFactoryLoader( bundleContext, shimBridgingServiceTracker ) );
}
@Test
public void testOnConfigurationOpenNull() {
sqoopServiceFactoryLoader.onConfigurationOpen( null, false );
verifyNoMoreInteractions( shimBridgingServiceTracker );
}
@Test
public void testOnConfigurationOpenSuccess()
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
IllegalAccessException {
HadoopConfiguration hadoopConfiguration = mock( HadoopConfiguration.class );
when( hadoopConfiguration.getHadoopShim() ).thenReturn( mock( HadoopShim.class ) );
ClassLoader classLoader = hadoopConfiguration.getHadoopShim().getClass().getClassLoader();
ArgumentCaptor<Class[]> clazzArgumentCaptor = ArgumentCaptor.forClass( Class[].class );
ArgumentCaptor<Object[]> argsArgumentCaptor = ArgumentCaptor.forClass( Object[].class );
sqoopServiceFactoryLoader.onConfigurationOpen( hadoopConfiguration, true );
verify( shimBridgingServiceTracker ).registerWithClassloader( eq( hadoopConfiguration ), eq(
NamedClusterServiceFactory.class ), eq( SqoopServiceFactoryImpl.class.getCanonicalName() ), eq( bundleContext ),
eq( classLoader ), clazzArgumentCaptor.capture(), argsArgumentCaptor.capture() );
Class[] parameterTypes = clazzArgumentCaptor.getValue();
Constructor<SqoopServiceFactoryImpl> constructor =
SqoopServiceFactoryImpl.class.getConstructor( parameterTypes );
assertNotNull( constructor );
Object[] objects = argsArgumentCaptor.getValue();
assertEquals( parameterTypes.length, objects.length );
for ( int i = 0; i < objects.length; i++ ) {
assertTrue( Primitives.wrap( parameterTypes[ i ] ).isInstance( objects[ i ] ) );
}
}
@Test
public void testOnConfigurationFailure() {
sqoopServiceFactoryLoader.onConfigurationOpen( mock( HadoopConfiguration.class ), false );
verifyNoMoreInteractions( shimBridgingServiceTracker );
}
@Test
public void testOnConfigurationClose() {
HadoopConfiguration hadoopConfiguration = mock( HadoopConfiguration.class );
sqoopServiceFactoryLoader.onConfigurationClose( hadoopConfiguration );
verify( shimBridgingServiceTracker ).unregister( hadoopConfiguration );
}
@Test
public void testOnClassLoaderAvailable() {
sqoopServiceFactoryLoader.onClassLoaderAvailable( getClass().getClassLoader() );
verifyNoMoreInteractions( shimBridgingServiceTracker, hadoopConfigurationBootstrap );
}
}
| [
"[email protected]"
] | |
d3f82fc1c1c0197ab5f8b249226bb8ee96776008 | 575dbcda56d3ffa4ca5159db6f1fd7f257dd2306 | /Tema6/Ejercicio05.java | becf05021e14797eb54cbd96548a61b923154ed7 | [] | no_license | SilviaHidalgo/Programacion | 32c0552c9f4916f6a5a3d1394c4c704a26dde654 | 7bbea3e0c4c4c41bc60095f4953415d6c19d3648 | refs/heads/master | 2020-08-03T17:28:56.379903 | 2019-12-11T20:04:28 | 2019-12-11T20:04:28 | 210,793,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 691 | java | public class Ejercicio05{
public static void main (String[] args){
int num;
int max = 100;
int min = 199;
int suma = 0;
int media = 0;
for(int i=0;i<50;i++){
num = (int)(Math.random()*100)+100;
System.out.print(num+" ");
suma = suma + num;
if(num<min){
min = num;
}
if(num>max){
max = num;
}
}
media = suma /50;
System.out.println("");
System.out.print("El numero mínimo es: "+min+"\n");
System.out.print("El numero máxima es: "+max+"\n");
System.out.print("La media es: "+media);
}
}
| [
"[email protected]"
] | |
1ad9d23c66db6f05f93957b3d1bfb08b353769c4 | ee63930722137539e989a36cdc7a3ac235ca1932 | /app/src/main/java/com/yksj/consultation/sonDoc/chatting/avchat/infra/Handlers.java | 827053b51e177eed25238850c2b7841415fc62c0 | [] | no_license | 13525846841/SixOneD | 3189a075ba58e11eedf2d56dc4592f5082649c0b | 199809593df44a7b8e2485ca7d2bd476f8faf43a | refs/heads/master | 2020-05-22T07:21:27.829669 | 2019-06-05T09:59:58 | 2019-06-05T09:59:58 | 186,261,515 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,016 | java | package com.yksj.consultation.sonDoc.chatting.avchat.infra;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;
import java.util.HashMap;
public final class Handlers {
public static final String DEFAULT_TAG = "Default";
private static Handlers instance;
public static synchronized Handlers sharedInstance() {
if (instance == null) {
instance = new Handlers();
}
return instance;
}
private static Handler sharedHandler;
/**
* get shared handler for main looper
* @param context
* @return
*/
public static final Handler sharedHandler(Context context) {
/**
* duplicate handlers !!! i don't care
*/
if (sharedHandler == null) {
sharedHandler = new Handler(context.getMainLooper());
}
return sharedHandler;
}
/**
* get new handler for main looper
* @param context
* @return
*/
public static final Handler newHandler(Context context) {
return new Handler(context.getMainLooper());
}
private Handlers() {
}
/**
* get new handler for a background default looper
* @return
*/
public final Handler newHandler() {
return newHandler(DEFAULT_TAG);
}
/**
* get new handler for a background stand alone looper identified by tag
* @param tag
* @return
*/
public final Handler newHandler(String tag) {
return new Handler(getHandlerThread(tag).getLooper());
}
private final HashMap<String, HandlerThread> threads = new HashMap<String, HandlerThread>();
private final HandlerThread getHandlerThread(String tag) {
HandlerThread handlerThread = null;
synchronized (threads) {
handlerThread = threads.get(tag);
if (handlerThread == null) {
handlerThread = new HandlerThread(nameOfTag(tag));
handlerThread.start();
threads.put(tag, handlerThread);
}
}
return handlerThread;
}
private final static String nameOfTag(String tag) {
return "HT-" + (TextUtils.isEmpty(tag) ? DEFAULT_TAG : tag);
}
}
| [
"[email protected]"
] | |
5653b79f65a6d198e86cbd1a920e89054ad08f01 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/反混淆后/src/main/java/com/tencent/p177mm/plugin/appbrand/jsapi/p306g/C19394e.java | 2097761e3b35038d7f54ca8dca57f6c994d289a6 | [] | no_license | xsren/AndroidReverseNotes | 9631a5aabc031006e795a112b7ac756a8edd4385 | 9202c276fe9f04a978e4e08b08e42645d97ca94b | refs/heads/master | 2021-04-07T22:50:51.072197 | 2019-07-16T02:24:43 | 2019-07-16T02:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,529 | java | package com.tencent.p177mm.plugin.appbrand.jsapi.p306g;
import android.graphics.Color;
import com.facebook.internal.ServerProtocol;
import com.google.firebase.analytics.FirebaseAnalytics.C8741b;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.p177mm.plugin.appbrand.jsapi.C2241c;
import com.tencent.p177mm.plugin.appbrand.jsapi.p306g.p307a.C10406b;
import com.tencent.p177mm.plugin.appbrand.jsapi.p306g.p307a.C10406b.C10427r;
import com.tencent.p177mm.plugin.appbrand.jsapi.p306g.p307a.C10406b.C10427r.C10403b;
import com.tencent.p177mm.plugin.appbrand.jsapi.p306g.p307a.C10406b.C10427r.C10428a;
import com.tencent.p177mm.plugin.appbrand.p1219d.C19162a;
import com.tencent.p177mm.plugin.appbrand.p1219d.C33139b;
import com.tencent.p177mm.plugin.appbrand.p328r.C42668g;
import com.tencent.p177mm.plugin.mmsight.segment.FFmpegMetadataRetriever;
import com.tencent.p177mm.sdk.platformtools.C4990ab;
import com.tencent.p177mm.sdk.platformtools.C5046bo;
import com.tencent.ttpic.util.VideoMaterialUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: com.tencent.mm.plugin.appbrand.jsapi.g.e */
public final class C19394e extends C42517a {
public static final int CTRL_INDEX = 133;
public static final String NAME = "addMapMarkers";
/* renamed from: a */
public final void mo5994a(C2241c c2241c, JSONObject jSONObject, int i) {
AppMethodBeat.m2504i(93842);
super.mo5994a(c2241c, jSONObject, i);
if (jSONObject == null) {
C4990ab.m7412e("MicroMsg.JsApiAddMapMarkers", "data is null");
c2241c.mo6107M(i, mo73394j("fail:invalid data", null));
AppMethodBeat.m2505o(93842);
return;
}
C4990ab.m7417i("MicroMsg.JsApiAddMapMarkers", "data:%s", jSONObject);
C10406b f = mo67990f(c2241c, jSONObject);
if (f == null) {
C4990ab.m7412e("MicroMsg.JsApiAddMapMarkers", "mapView is null, return");
c2241c.mo6107M(i, mo73394j("fail:mapview is null", null));
AppMethodBeat.m2505o(93842);
return;
}
int by;
C4990ab.m7417i("MicroMsg.JsApiAddMapMarkers", "clear:%b", Boolean.valueOf(jSONObject.optBoolean("clear", true)));
if (jSONObject.optBoolean("clear", true)) {
f.aDZ();
}
if (jSONObject.has("markers")) {
JSONArray jSONArray;
try {
jSONArray = new JSONArray(jSONObject.optString("markers"));
} catch (JSONException e) {
jSONArray = null;
}
if (jSONArray != null) {
int i2 = 0;
while (true) {
int i3 = i2;
if (i3 >= jSONArray.length()) {
break;
}
JSONObject jSONObject2;
try {
jSONObject2 = (JSONObject) jSONArray.get(i3);
} catch (JSONException e2) {
C4990ab.printErrStackTrace("MicroMsg.JsApiAddMapMarkers", e2, "", new Object[0]);
jSONObject2 = null;
}
if (jSONObject2 != null) {
JSONObject jSONObject3;
C10427r c10427r = new C10427r();
String optString = jSONObject2.optString("id");
float f2 = C5046bo.getFloat(jSONObject2.optString("latitude"), 0.0f);
double d = (double) f2;
double d2 = (double) C5046bo.getFloat(jSONObject2.optString("longitude"), 0.0f);
c10427r.latitude = d;
c10427r.longitude = d2;
String optString2 = jSONObject2.optString("iconPath");
float a = C42668g.m75553a(jSONObject2, "width", 0.0f);
float a2 = C42668g.m75553a(jSONObject2, "height", 0.0f);
if (!C5046bo.isNullOrNil(optString2)) {
if (c2241c.mo5936B(C33139b.class) != null) {
c10427r.hNN = ((C33139b) c2241c.mo5936B(C33139b.class)).mo22120b(c2241c, optString2);
c10427r.hOb = a;
c10427r.hOc = a2;
}
}
c10427r.rotate = (float) jSONObject2.optDouble(FFmpegMetadataRetriever.METADATA_KEY_VIDEO_ROTATION, 0.0d);
c10427r.alpha = (float) jSONObject2.optDouble("alpha", 1.0d);
c10427r.data = jSONObject2.optString("data");
c10427r.hOd = jSONObject2.optString("ariaLabel");
if (jSONObject2.has("anchor")) {
try {
jSONObject3 = new JSONObject(jSONObject2.optString("anchor"));
} catch (JSONException e3) {
jSONObject3 = null;
}
if (jSONObject3 != null) {
c10427r.mo21941K((float) jSONObject3.optDouble(VideoMaterialUtil.CRAZYFACE_X, 0.5d), (float) jSONObject3.optDouble(VideoMaterialUtil.CRAZYFACE_Y, 1.0d));
} else {
c10427r.mo21941K(0.5f, 1.0f);
}
}
c10427r.zIndex = jSONObject2.optInt("zIndex", 0);
String optString3 = jSONObject2.optString("label");
if (!C5046bo.isNullOrNil(optString3)) {
try {
jSONObject3 = new JSONObject(optString3);
} catch (JSONException e4) {
jSONObject3 = null;
}
if (jSONObject3 != null) {
optString2 = jSONObject3.optString(C8741b.CONTENT);
by = C42668g.m75559by(jSONObject3.optString("color", "#000000"), Color.parseColor("#000000"));
int optInt = jSONObject3.optInt("fontSize", 12);
int a3 = C42668g.m75555a(jSONObject3, "anchorX", C42668g.m75555a(jSONObject3, VideoMaterialUtil.CRAZYFACE_X, 0));
int a4 = C42668g.m75555a(jSONObject3, "anchorY", C42668g.m75555a(jSONObject3, VideoMaterialUtil.CRAZYFACE_Y, 0));
int optInt2 = jSONObject3.optInt("borderRadius", 0);
int f3 = C42668g.m75563f(jSONObject3, "borderWidth");
int Ee = C42668g.m75551Ee(jSONObject3.optString("borderColor"));
c10427r.hOf = new C10403b(optString2, by, optInt, a3, a4, C42668g.m75559by(jSONObject3.optString("bgColor", ""), Color.parseColor("#000000")), optInt2, f3, Ee, jSONObject3.optString("textAlign", ""), C42668g.m75555a(jSONObject3, "padding", 0));
}
}
optString3 = jSONObject2.optString("callout");
if (!C5046bo.isNullOrNil(optString3)) {
try {
jSONObject3 = new JSONObject(optString3);
} catch (JSONException e5) {
jSONObject3 = null;
}
if (jSONObject3 != null) {
c10427r.hOe = new C10428a(jSONObject3.optString(C8741b.CONTENT), C42668g.m75559by(jSONObject3.optString("color", "#000000"), Color.parseColor("#000000")), jSONObject3.optInt("fontSize", 12), jSONObject3.optInt("borderRadius", 0), C42668g.m75559by(jSONObject3.optString("bgColor", "#000000"), Color.parseColor("#000000")), C42668g.m75563f(jSONObject3, "borderWidth"), C42668g.m75551Ee(jSONObject3.optString("borderColor")), C42668g.m75555a(jSONObject3, "padding", 0), C42668g.m75559by(jSONObject3.optString("shadowColor", "#000000"), Color.parseColor("#000000")), jSONObject3.optInt("shadowOpacity"), jSONObject3.optInt("shadowOffsetX"), jSONObject3.optInt("shadowOffsetY"), jSONObject3.optInt(ServerProtocol.DIALOG_PARAM_DISPLAY, 0), jSONObject3.optString("textAlign", ""));
}
}
String optString4 = jSONObject2.optString("buildingId");
optString2 = jSONObject2.optString("floorName");
c10427r.buildingId = optString4;
c10427r.floorName = optString2;
C10406b c10406b = f;
String str = optString;
C10427r c10427r2 = c10427r;
c10406b.mo21893a(str, c10427r2, (C19162a) c2241c.mo5936B(C19162a.class));
}
i2 = i3 + 1;
}
} else {
C4990ab.m7412e("MicroMsg.JsApiAddMapMarkers", "markersArray is null, return");
c2241c.mo6107M(i, mo73394j("fail:internal error", null));
AppMethodBeat.m2505o(93842);
return;
}
}
C2241c c2241c2 = c2241c;
by = i;
mo67989a(c2241c2, by, mo73394j("ok", null), true, f.aDU());
AppMethodBeat.m2505o(93842);
}
}
| [
"[email protected]"
] | |
390d7fd85c249a32b2d27240c1a09b8b53d27b74 | 4dd0ed043c99469b4d638820755435ed908633d0 | /src/main/java/com/shinnlove/wechatpay/http/consts/HttpRequestHeaderConst.java | 1927c561c8d9d4e904826fa61d86237a17e50246 | [
"Apache-2.0"
] | permissive | H6yV7Um/wechatpay | c2f67e7a1f382c4e567d3d0d670a3cd119548499 | 64431b5cf42d794767ba83233f69ed3681ebf9a1 | refs/heads/master | 2020-03-22T13:08:40.828010 | 2018-07-07T13:23:34 | 2018-07-07T13:23:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,665 | java | /**
* Alipay.com Inc.
* Copyright (c) 2004-2018 All Rights Reserved.
*/
package com.shinnlove.wechatpay.http.consts;
/**
* Http请求中有的字段常量。
*
* 一个HTTP请求如:
*
* ==========================Request Headers==========================
* Accept: application/json,text/plain;charset=UTF-8
* Accept-Encoding:gzip,deflate
* Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
* Connection:keep-alive
* Content-Type:application/json;charset=UTF-8
* Cookie:_b_s=chensheng.zcs;_b_n=113505;buservice_domain_id=KOUBEI_SALESCRM;IS_INNER_LOGIN=1;UM_distinctid=164174aef2039c-0768eb31a428b8-33667f07-13c680-164174aef21d29;zone=GZ00B;ZAUTH_REST_LOGIN_INFO=7b22666f7277617264223a302c226970223a2231302e3230392e31392e3832222c226c6f67696e4e616d65223a226368656e7368656e672e7a6373222c226c6f67696e54696d65223a313532393633393935323833312c22746f6b656e223a2232373565366562342d393938362d343336662d613261382d333665643635363939343435222c2275726c223a22687474703a2f2f31302e3230392e31392e38322f2f726573742f6765744c6f67696e5573657241757468732e6a736f6e227d;ALIPAYJSESSIONID=GZ00SlixdekHrX3dXUMtTPvAoxkvYFfindecisionGZ00;session.cookieNameId=ALIPAYBUMNGJSESSIONID;ALIPAYBUMNGJSESSIONID=GZ003NhJdOUJkeqSsET3RXdfvTXihrantbuserviceGZ00;ctoken=wfX1NpGsSe4xoaj8;sso.global.authtoken=sso.global.authtoken;_l_n=106809;JSESSIONID=3230D52FDEE91AFB6D16AA4943E6B806
* Host:instasset-zth-2.gz00b.dev.alipay.net
* Referer:http://instasset-zth-2.gz00b.dev.alipay.net/index.htm
* User-Agent:Mozilla/5.0(Macintosh;Intel Mac OS X 10_12_5)AppleWebKit/537.36(KHTML,like Gecko)Chrome/66.0.3359.139Safari/537.36
* ===================================================================
*
* @author shinnlove.jinsheng
* @version $Id: HttpRequestHeaderConst.java, v 0.1 2018-07-04 下午2:07 shinnlove.jinsheng Exp $$
*/
public class HttpRequestHeaderConst {
private HttpRequestHeaderConst() {
}
/** 客户端可以接收的类型,如:application/json,text/plain,charset=UTF-8 */
public static final String ACCEPT = "Accept";
/** 支持的编码方式:如:gzip, deflate。可以支持压缩 */
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String ACCEPT_CHARSET = "Accept-Charset";
/** 客户端能接收的语言类型,如:zh-CN,zh;q=0.9,en;q=0.8 */
public static final String ACCEPT_LANGUAGE = "Accept-Language";
public static final String ACCEPT_RANGES = "Accept-Ranges";
public static final String AUTHORIZATION = "Authorization";
/** 可以设置为keep-alive */
public static final String CONNECTION = "Connection";
/** 内容类型,如:application/json;charset=UTF-8 */
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String CACHE_CONTROL = "Cache-Control";
/** 请求头中携带的cookie,一般为浏览器产生于使用,key=value; key2=value2; 注意空格和分号,下划线优选 */
public static final String COOKIE = "Cookie";
public static final String DATE = "Date";
public static final String EXPECT = "Expect";
public static final String FROM = "From";
public static final String HOST = "Host";
public static final String IF_MATCH = "If-Match";
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String IF_NONE_MATCH = "If-None-Match";
public static final String IF_RANGE = "If-Range";
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String KEEP_ALIVE = "Keep-Alive";
public static final String MAX_FORWARDS = "Max-Forwards";
public static final String PRAGMA = "Pragma";
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String RANGE = "Range";
/** 从哪个来源发起的请求,一般用于跨域验证 */
public static final String REFERER = "Referer";
public static final String TE = "TE";
/** WebSocket类型使用 */
public static final String UPGRADE = "Upgrade";
/** 当使用浏览器访问时,不同浏览器、版本会携带不同用户请求头 */
public static final String USER_AGENT = "User-Agent";
public static final String VIA = "Via";
public static final String WARNING = "Warning";
} | [
"[email protected]"
] | |
b00301cf85431a348eba0cf630152e682bf18729 | 851cab09c5ec8f4474b80ee7070f3acd026f8173 | /MobileApp/src/edu/athens/tennesseevalleyoldtimefiddlersconvention/Info2Activity.java | 8efe9b821beef2e4dda8e2e09282a95776853f14 | [] | no_license | TNValleyFiddlersConvention/fiddlers | 47a2c904f444803eb3d39bb2a6a559b0e4571a01 | e6a90c7fc1f888ed55d64b5ae593e4deadb7a255 | refs/heads/master | 2021-01-23T11:40:42.181423 | 2015-12-03T00:23:49 | 2015-12-03T00:23:49 | 39,043,212 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 662 | java | package edu.athens.tennesseevalleyoldtimefiddlersconvention;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
public class Info2Activity extends Activity {
// Open up the layout for the Info activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info2);
}
// Go back to Home Screen
public void OnClickHome(View view) {
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
}
}
| [
"[email protected]"
] | |
2f6fb125f777e4866f339e588929cd4802fdf5d4 | 93eeaf363fca53b97f1afb2c7f0381ccc4278d2c | /app/src/main/java/com/hanul/team1/triplan/ysh/Fn2Fragment.java | 2df6eec5acf70ac5641e8a4834446a2f55fd69aa | [] | no_license | MagneticGang/teamTriplan | 129932b7fe5bbf0a66d36176bf093b0426ced51a | 769378086e343a88f811ab283d260a09fa7dbddb | refs/heads/master | 2020-04-04T22:41:32.105769 | 2018-11-26T03:21:06 | 2018-11-26T03:21:06 | 156,332,363 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package com.hanul.team1.triplan.ysh;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hanul.team1.triplan.R;
public class Fn2Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.sh_fragment_fn2, container, false);
return rootView;
}
}
| [
"[email protected]"
] | |
e639539cc3ce1fb921e72e744c30d078f6b3ba98 | ba2eef5e3c914673103afb944dd125a9e846b2f6 | /AL-Game/src/com/aionemu/gameserver/network/aion/serverpackets/SM_ICON_INFO.java | 261dd07a341e62aa09731d2587513e367d3d34af | [] | no_license | makifgokce/Aion-Server-4.6 | 519d1d113f483b3e6532d86659932a266d4da2f8 | 0a6716a7aac1f8fe88780aeed68a676b9524ff15 | refs/heads/master | 2022-10-07T11:32:43.716259 | 2020-06-10T20:14:47 | 2020-06-10T20:14:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,299 | java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion.serverpackets;
import com.aionemu.gameserver.network.aion.AionConnection;
import com.aionemu.gameserver.network.aion.AionServerPacket;
/**
* @author xTz
*/
public class SM_ICON_INFO extends AionServerPacket {
private int buffId;
private boolean display;
public SM_ICON_INFO(int buffId, boolean display) {
this.buffId = buffId;
this.display = display;
}
@Override
protected void writeImpl(AionConnection con) {
writeC(buffId);
writeC(display ? 1 : 0);
}
}
| [
"Falke_34@080676fd-0f56-412f-822c-f8f0d7cea3b7"
] | Falke_34@080676fd-0f56-412f-822c-f8f0d7cea3b7 |
928041592cf3afa4d65223daa2d70706093c5cb5 | 1b1e7e5ff2b6f07aaddb6820a431d8e4f62d2e3a | /src/exercises/Ex7.java | 3cb271a55551fb308cf24b7d2f1ec2be889ec818 | [] | no_license | arekm3/ZDJAVAPOL33 | ebe80cefbbf18a9043161ef5867480f1e27df8d1 | bafbc25410ce120fd8984b5a86d51d76ced2636e | refs/heads/master | 2022-12-07T20:07:07.753954 | 2020-09-04T22:12:33 | 2020-09-04T22:12:33 | 291,434,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 496 | java | package exercises;
import java.util.Arrays;
public class Ex7 {
public static void getArithmeticSequence(int lenght, int firstNumber, int incrementValue) {
int[] array = new int[lenght];
for (int i = 0; i < lenght; i++) {
array[i] = firstNumber;
firstNumber = firstNumber + incrementValue;
}
System.out.println(Arrays.toString(array));
}
public static void main(String[] args) {
getArithmeticSequence(5,2,3) ;
}
}
| [
"[email protected]"
] | |
a1fb071fe448ea77f2455ba8c73ba9c9d1681766 | 2078d6ddbbd20109aaed614a5bbc0d7cf16b770e | /Week_08/saturday/common/src/main/java/account/api/AccountService.java | 37d4fa976c9e94614e578bb0a76c17722cf38a0b | [] | no_license | Zhoutzzz/JAVA-000 | 45ad1f42238e3860858e7b5e243d25a7f98eaaa2 | daf21f72163890274f40f8ebe2b7282887bb981c | refs/heads/main | 2023-02-25T02:15:48.774665 | 2021-02-03T07:54:09 | 2021-02-03T07:54:09 | 303,139,271 | 0 | 0 | null | 2020-10-11T14:29:29 | 2020-10-11T14:29:28 | null | UTF-8 | Java | false | false | 1,710 | java |
package account.api;
import account.dto.AccountDTO;
import account.dto.AccountNestedDTO;
import account.entity.AccountDO;
import org.dromara.hmily.annotation.Hmily;
/**
* The interface Account service.
*
* @author xiaoyu
*/
public interface AccountService {
/**
* 扣款支付
*
* @param accountDTO 参数dto
*/
@Hmily
boolean payment(AccountDTO accountDTO);
/**
* Mock try payment exception.
*
* @param accountDTO the account dto
*/
@Hmily
boolean mockTryPaymentException(AccountDTO accountDTO);
/**
* Mock try payment timeout.
*
* @param accountDTO the account dto
*/
@Hmily
boolean mockTryPaymentTimeout(AccountDTO accountDTO);
/**
* Payment tac boolean.
*
* @param accountDTO the account dto
* @return the boolean
*/
@Hmily
boolean paymentTAC(AccountDTO accountDTO);
/**
* Test payment boolean.
*
* @param accountDTO the account dto
* @return the boolean
*/
boolean testPayment(AccountDTO accountDTO);
/**
* 扣款支付
*
* @param accountNestedDTO 参数dto
* @return true boolean
*/
@Hmily
boolean paymentWithNested(AccountNestedDTO accountNestedDTO);
/**
* Payment with nested exception boolean.
*
* @param accountNestedDTO the account nested dto
* @return the boolean
*/
@Hmily
boolean paymentWithNestedException(AccountNestedDTO accountNestedDTO);
/**
* 获取用户账户信息
*
* @param userId 用户id
* @return AccountDO account do
*/
AccountDO findByUserId(String userId);
}
| [
"[email protected]"
] | |
53ad223d6e05be2f2d901f2d71ee06c15b93118b | b6aff174e41b9af796c73fe95d9748ccc7cdddf7 | /clients/dev-simulator/src/main/java/com/iris/ipcd/client/commands/SetParameterValue.java | c6ebd048c7fca041752a4fed4fac06e08f70bd8a | [
"Apache-2.0"
] | permissive | theocdgeek/arcusipcd | d5c8d5fcbe4bf754ed739fbeb190f3c61afa8b2a | 5f76c98251d1f49bfe96957a02050ffaa2d04950 | refs/heads/master | 2020-05-03T18:59:37.767180 | 2019-03-15T21:00:45 | 2019-03-15T21:00:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.iris.ipcd.client.commands;
public class SetParameterValue extends AbstractCommand {
@Override
public Commands getType() {
return Commands.SetParameterValue;
}
}
| [
"[email protected]"
] | |
3d625e297a169ed4ca8e9842effda8a4c70e92ae | c955bdb6d07ca4ee0d7ef3ec1e6a195fdec58753 | /src/test/java/com/tree/BinaryTreeLevelOrderTraversalII.java | ca8d6ea8a1ef026044e6d8a1837c2b7051e7dd88 | [] | no_license | sulei945/t2 | 2e0f294a8308193c9eb3f1c54341170ae9b39b12 | a030fd709bd6cddd37ed7efa3f3f5d04690e2c92 | refs/heads/master | 2021-09-16T18:23:37.905197 | 2018-06-23T05:13:41 | 2018-06-23T05:13:41 | 119,341,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,353 | java | package com.tree;
import java.util.*;
/**
* Created by zhangwei on 18-5-28.
* 二叉树的层次遍历 II
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
*/
public class BinaryTreeLevelOrderTraversalII {
//beats 86.29%
public List<List<Integer>> myLevelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null) return result;
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
LinkedList<List<Integer>> llr = new LinkedList<List<Integer>>();
list.add(root);
while (!list.isEmpty()){
int size = list.size();
List<Integer> rl = new ArrayList<Integer>(size);
llr.offer(rl);
for (int i=0; i<size; i++){
TreeNode tn = list.poll();
rl.add(tn.val);
if(tn.left != null){
list.offer(tn.left);
}
if(tn.right != null){
list.offer(tn.right);
}
}
}
while (!llr.isEmpty()){
result.add(llr.removeLast());
}
return result;
}
//return List<List<Integer>>, 可以是LinkedList<ArrayList<>>
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) return Collections.emptyList();
LinkedList<List<Integer>> traversals = new LinkedList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
int numNodesAtLevel = queue.size();
List<Integer> levelTraversal = new ArrayList<Integer>();
for (int i = 0; i < numNodesAtLevel; i++) {
TreeNode node = queue.poll();
levelTraversal.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
traversals.addFirst(levelTraversal);
}
return traversals;
}
}
| [
"[email protected]"
] | |
8d2b16680d8348406603c5db5754935b3f6aa206 | 1e211e4b2deba797e935d4f9a45647105d17fb8e | /src/parmaguerrabot/images/Images.java | abf7a1fdedc61eec70c5ba5bbe47f50656ae287b | [] | no_license | Rooouge/ParmaGuerraBot | 50b63c3c0d49384824ae69d9cbe837eb9621050b | 838ed21d9e2d58b5addc58a7baa167ad6340dbf4 | refs/heads/master | 2022-10-22T03:27:52.754394 | 2020-06-09T15:07:18 | 2020-06-09T15:07:18 | 264,501,400 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 442 | java | package parmaguerrabot.images;
import javax.swing.ImageIcon;
public class Images {
public static final ImageIcon MAP_IMAGE = new ImageIcon("res/images/map.png");
public static final ImageIcon BORDER_LAYER = new ImageIcon("res/images/border_layer.png");
public static ImageIcon getTerritoryImage(String territoryName) {
return new ImageIcon("res/images/territories/" + territoryName.toLowerCase().replace(' ', '_') + ".png");
}
}
| [
"[email protected]"
] | |
6387553310d2fbba56d4639d1c32d969774d05d5 | 9c2474ca41f06b3636577c84c7e07b5b95351226 | /FinalModifications/SRModel.java | 5a7af4cea864ffcbd07f7d7383061318f3d596df | [] | no_license | Chuddington/COMP329AssignmentTwo | a1987d6078504087166eef580f0623270dcb0149 | fa09a040943b4b9084bec6314303e23710633673 | refs/heads/master | 2021-01-10T18:20:17.265878 | 2015-12-16T15:07:02 | 2015-12-16T15:07:02 | 46,421,766 | 1 | 1 | null | 2015-12-16T13:16:38 | 2015-11-18T13:51:02 | Java | UTF-8 | Java | false | false | 14,120 | java | /*
* File Purpose: Mapping class for the robot - contains 2D array and current
* Robot position
* Author/s : Michael Chadwick
* Student IDs : 200882675
*/
import lejos.nxt.*;
import lejos.nxt.addon.ColorHTSensor;
import lejos.util.Delay;
//class used to model/map the world
public class SRModel {
//Global Variables
//actual value-changing variables
public static int xLimit; //number of cells on the X axis
public static int yLimit; //number of cells on the Y axis
//cPos and map use the top down perspective. This is important when
//reading the ultrasonic scan methods
public static int[][] map ; //robot's interpretation of the arena
public static int[] cPos ; //stores the X and Y axis of the robot
//class/object variables
public static SRMov moveO;
public static UltrasonicSensor us = new UltrasonicSensor(SensorPort.S3);
public static ColorHTSensor cs = new ColorHTSensor( SensorPort.S4);
//constants
public static final int UNKNOWN_ID = 6; //cell with 'fog of war'
public static final int SCANNED_ID = 5; //scanned with US but not entered
public static final int EMPTY_ID = 4; //cell the robot has entered
public static final int OBSTACLE_ID = 9; //cell with an obstacle
public static final int RED_VIC = 0; //cell with red 'victim'
public static final int BLU_VIC = 1; //cell with blue 'victim'
public static final int GRN_VIC = 2; //cell with green 'victim'
//constructor
SRModel(int x, int y) {
xLimit = x ; //length of the X axis
yLimit = y ; //length of the Y axis
map = new int[x][y]; //generate the correct size map
populateMap() ; //method to fill with UNKNOWN_ID
cPos = new int[2] ; //array to store current robot position
cPos[0] = 0 ; //X axis position
cPos[1] = 0 ; //Y axis position
us.continuous(); //ultrasonic sensor continually pings
}
//constructor including Movement object
SRModel(int x, int y, SRMov m) {
this(x, y); //run base constructor
moveO = m ; //add moveObj variable
}
//method to fill the map with 'fog of war'
public static void populateMap() {
for(int loop1 = 0; loop1 < xLimit; ++loop1) {
for(int loop2 = 0; loop2 < yLimit; ++loop2) {
map[loop1][loop2] = UNKNOWN_ID;
}
}
map[0][0] = EMPTY_ID;
}
//method to scan ahead only - used in SRMain.explore() for faster traversal
public static boolean scanAhead(int d) {
int dest = 0; //store distance to object
Motor.A.rotateTo(0) ; //rotate to front
Delay.msDelay(200) ; //wait for accurate reading
dest = us.getDistance(); //scan
Delay.msDelay(50) ; //wait for reading to be confirmed
if(dest < d) { //if obstacle is in the 'next' cell
return true ; //set true when an obstacle is there
} else {
return false; //set false when an obstacle is not
}
}
//method to scan around the robot - left, ahead and right
public static boolean[] scanAll(int d) {
boolean[] results = new boolean[3]; //stores the boolean results
int dest = 0; //stores distance to object
Motor.A.rotateTo(0) ; //rotate to front
Delay.msDelay(200) ; //wait for accurate reading
dest = us.getDistance(); //scan
Delay.msDelay(50) ; //wait for reading to be confirmed
if(dest < d) { //if directly ahead
results[1] = true ; //set true when an obstacle is there
} else {
results[1] = false; //set false when an obstacle is not
}
Motor.A.rotateTo(-650) ; //rotate to left
Delay.msDelay(200) ;
dest = us.getDistance(); //scan
Delay.msDelay(50) ;
if(dest < d) { //if directly ahead
results[0] = true ; //set left value to true
} else {
results[0] = false; //set left value to false
}
Motor.A.rotateTo(650) ; //rotate to right
Delay.msDelay(200) ;
dest = us.getDistance(); //scan
Delay.msDelay(50) ;
if(dest < d) { //if directly ahead
results[2] = true ; //set right value to true
} else {
results[2] = false; //set right value to false
}
Motor.A.rotateTo(0) ; //rotate to front
return results;
}
//method to check whether an edge of the arena is to the left of the robot
public static boolean scanLimitLeft(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
if( (cPos[0] - 1) == -1) { //decremented X axis is the left of robot
return true; //arena edge is found
} else {
//update correct map position with scanned, empty cell
map[cPos[0] - 1][cPos[1] ] = SCANNED_ID;
return false;
}
case(2): //when facing right
if( (cPos[1] + 1) == yLimit) {
return true;
} else {
map[cPos[0] ][cPos[1] + 1] = SCANNED_ID;
return false;
}
case(3): //when facing down
if( (cPos[0] + 1) == xLimit) {
return true;
} else {
map[cPos[0] + 1][cPos[1] ] = SCANNED_ID;
return false;
}
case(4): //when facing left
if( (cPos[1] - 1) == -1) {
return true;
} else {
map[cPos[0] ][cPos[1] - 1] = SCANNED_ID;
return false;
}
}
return false;
}
//method to check whether an edge of the arena is in front of the robot
//very similar to the scanLimitLeft() method
public static boolean scanLimitUp(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
if( (cPos[1] + 1) == yLimit) {
return true;
} else {
map[cPos[0] ][cPos[1] + 1] = SCANNED_ID;
return false;
}
case(2): //when facing right
if( (cPos[0] + 1) == xLimit) {
return true;
} else {
map[cPos[0] + 1][cPos[1] ] = SCANNED_ID;
return false;
}
case(3): //when facing down
if( (cPos[1] - 1) == -1) {
return true;
} else {
map[cPos[0] ][cPos[1] - 1] = SCANNED_ID;
return false;
}
case(4): //when facing left
if( (cPos[0] - 1) == -1) {
return true;
} else {
map[cPos[0] - 1][cPos[1] ] = SCANNED_ID;
return false;
}
}
return false;
}
//method to check whether an edge of the arena is to the right of the robot
//very similar to the scanLimitLeft() method
public static boolean scanLimitRight(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
if( (cPos[0] + 1) == xLimit) {
return true;
} else {
map[cPos[0] + 1][cPos[1] ] = SCANNED_ID;
return false;
}
case(2): //when facing right
if( (cPos[1] - 1) == -1) {
return true;
} else {
map[cPos[0] ][cPos[1] - 1] = SCANNED_ID;
return false;
}
case(3): //when facing down
if( (cPos[0] - 1) == -1) {
return true;
} else {
map[cPos[0] - 1][cPos[1] ] = SCANNED_ID;
return false;
}
case(4): //when facing left
if( (cPos[1] + 1) == yLimit) {
return true;
} else {
map[cPos[0] ][cPos[1] + 1] = SCANNED_ID;
return false;
}
}
return false;
}
//method to set the cell at the left of the robot to be an obstacle
public static void obstacleAtLeft(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
map[cPos[0] - 1][cPos[1] ] = OBSTACLE_ID;
break;
case(2): //when facing right
map[cPos[0] ][cPos[1] + 1] = OBSTACLE_ID;
break;
case(3): //when facing down
map[cPos[0] + 1][cPos[1] ] = OBSTACLE_ID;
break;
case(4): //when facing left
map[cPos[0] ][cPos[1] - 1] = OBSTACLE_ID;
break;
}
}
//method to set the cell ahead of the robot to be an obstacle
public static void obstacleAtUp(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
map[cPos[0] ][cPos[1] + 1] = OBSTACLE_ID;
break;
case(2): //when facing right
map[cPos[0] + 1][cPos[1] ] = OBSTACLE_ID;
break;
case(3): //when facing down
map[cPos[0] ][cPos[1] - 1] = OBSTACLE_ID;
break;
case(4): //when facing left
map[cPos[0] - 1][cPos[1] ] = OBSTACLE_ID;
break;
}
}
//method to set the cell at the right of the robot to be an obstacle
public static void obstacleAtRight(int f) {
switch(f) { //f = facing in movement object
case(1): //when facing up
map[cPos[0] + 1][cPos[1] ] = OBSTACLE_ID;
break;
case(2): //when facing right
map[cPos[0] ][cPos[1] - 1] = OBSTACLE_ID;
break;
case(3): //when facing down
map[cPos[0] - 1][cPos[1] ] = OBSTACLE_ID;
break;
case(4): //when facing left
map[cPos[0] ][cPos[1] + 1] = OBSTACLE_ID;
break;
}
}
//checks whether the robot can move into the cell in front of itself
//It knows by only being able to move into cells it has either scanned or
//moved into previously.
public static boolean canMove(int[] cp, int f) {
switch(f) {
case(1): //facing up
if( (map[cp[0] ][cp[1] + 1] < UNKNOWN_ID) && (cp[1] + 1 != yLimit) ) {
return true ; //true if scanned, empty or has a victim in cell
} else {
return false; //false if cell is not scanned or has an obstacle
}
case(2): //facing right
if( (map[cp[0] + 1][cp[1] ] < UNKNOWN_ID) && (cp[0] + 1 != xLimit) ) {
return true ;
} else {
return false;
}
case(3): //facing down
if( (map[cp[0] ][cp[1] - 1] < UNKNOWN_ID) && (cp[1] - 1 != -1) ) {
return true ;
} else {
return false;
}
case(4): //facing left
if( (map[cp[0] - 1][cp[1] ] < UNKNOWN_ID) && (cp[0] - 1 != -1) ) {
return true ;
} else {
return false;
}
}
return false;
}
//method to check if the target cell (such as in moveTo() ) contains an
//obstacle - meaning it is impossible to move into the target cell
public static boolean obsAtTarget(int x, int y) {
if(map[x][y] == OBSTACLE_ID) {
return true ;
} else {
return false;
}
}
//method to implement the scan results into the map[][].
//r[x] is from the scanAll() method output; f = SRMov.facing
public static void impScan(boolean[] r, int f) {
if(r[0] && !scanLimitLeft(f) ) {
obstacleAtLeft(f) ;
}
if(r[1] && !scanLimitUp(f) ) {
obstacleAtUp(f) ;
}
if(r[2] && !scanLimitRight(f) ) {
obstacleAtRight(f);
}
}
//method to implement the scan results into the map[][].
//variant used when only scanAhead() is called
public static void impScan(boolean r, int f) {
if(r && !scanLimitUp(f) ) {
obstacleAtUp(f);
}
}
//method to create a local copy of the movement object
//this method might not be used during this program
public static void setMovementObject(SRMov m) {
moveO = m;
}
//method to obtain the local copy of the movement object
//this method might not be used - is useful in updating the movement object
public static SRMov getMovementObject() {
return moveO;
}
//method to return a string for Jason; outputs victim colour
public String getColour() {
int colour = cs.getColorID(); //scan colour
String literal = "";
StringBuilder sb = new StringBuilder();
//create initial string for all cases
sb.append("victim(");
if(colour == 0) { //red victim
//literal = String.format("victim(%d,%d,%d)", RED_VIC, cPos[0], cPos[1] );
/*Used a string builder to create literal as the above commented out code refused to work*/
sb.append(RED_VIC);
sb.append(",");
sb.append(cPos[0]);
sb.append(",");
sb.append(cPos[1]);
sb.append(")");
//add victim to map
map[cPos[0] ][cPos[1] ] = RED_VIC;
} else if (colour == 2) { //blue victim
//translate colour ID 2 to 1 as blue has higher priority
//create literal
sb.append(BLU_VIC);
sb.append(",");
sb.append(cPos[0]);
sb.append(",");
sb.append(cPos[1]);
sb.append(")");
//add victim to map
map[cPos[0] ][cPos[1] ] = BLU_VIC;
} else if (colour == 1) { //green victim
//translate colour ID 1 to 2 as green has lower priority
//create literal
sb.append(GRN_VIC);
sb.append(",");
sb.append(cPos[0]);
sb.append(",");
sb.append(cPos[1]);
sb.append(")");
//add victim to map
map[cPos[0] ][cPos[1] ] = GRN_VIC;
} else {
map[cPos[0] ][cPos[1] ] = EMPTY_ID; //set cell to empty & traversed
//send colour to agent - agent deals with error checking
//create literal
sb.append(colour);
sb.append(",");
sb.append(cPos[0]);
sb.append(",");
sb.append(cPos[1]);
sb.append(")");
}
//create string
literal = sb.toString();
return literal;
}
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.