blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
128c17d2e7bbf8898bdae4388c454e3d9da4f041 | 80ff81f4cec37518791b58b2f4729dca1fe05c8d | /src/org/opengts/war/track/Track.java | b5352f095d32ef05593b8427ea0794a082581417 | []
| no_license | rodrigo102195/dyds2017-opengts | 23fb44e907f91009a75dce0edb7f3a93add16578 | bc59dfb9021d0d07df4dbced84170a2ec0090156 | refs/heads/master | 2021-01-21T16:45:18.389302 | 2017-05-20T19:31:10 | 2017-05-20T19:31:10 | 91,904,733 | 0 | 0 | null | 2017-05-20T17:18:55 | 2017-05-20T17:18:54 | null | UTF-8 | Java | false | false | 94,162 | java | // ----------------------------------------------------------------------------
// Copyright 2007-2016, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/03/30 Martin D. Flynn
// -Added support for 'User' login (in addition to 'Account' login)
// 2007/05/20 Martin D. Flynn
// -Added support for "admin" user
// -Added check for login to authorized host domain
// 2007/06/03 Martin D. Flynn
// -Added I18N support
// 2007/06/13 Martin D. Flynn
// -Added support for browsers with disabled cookies
// 2007/07/27 Martin D. Flynn
// -Now set per-thread runtime properties for locale and 'From' email address.
// 2007/01/10 Martin D. Flynn
// -Added customizable 'BASE_URI()' method
// 2008/02/27 Martin D. Flynn
// -Added methods '_resolveFile' and '_writeFile' to resolve Image/JavaScript files.
// 2008/05/14 Martin D. Flynn
// -Added runtime property for enabling cookie support
// 2008/09/01 Martin D. Flynn
// -Added support for User 'getFirstLoginPageID()'
// 2009/02/20 Martin D. Flynn
// -"RELOAD:XML" now also reloads the runtime config file.
// 2009/09/23 Martin D. Flynn
// -An encoded hash of the password is now saved as a session attribute
// 2009/10/02 Martin D. Flynn
// -Added support for creating pushpin markers with embedded text.
// 2009/12/16 Martin D. Flynn
// -Added support to "ZONEGEOCODE" handler to allow using the GeocodeProvider
// defined in the 'private.xml' file.
// 2010/09/09 Martin D. Flynn
// -Added support for forwarding 'http' to 'https' (see "forwardToSecureAccess")
// 2010/11/29 Martin D. Flynn
// -Look up main domain when subdomain is specified (see PrivateLabelLoader.getPrivateLabel)
// 2012/10/16 Martin D. Flynn
// -Check "PROP_track_updateLastLoginTime_[user|account]" before updating lastLoginTime.
// 2013/08/27 Martin D. Flynn
// -Added support for returning to SysAdmin/Manager originator (if applicable)
// 2016/01/04 Martin D. Flynn
// -Added support for User.isExpired() [2.6.1-B45]
// 2016/04/01 Martin D. Flynn
// -Added support for User.isSuspended() [2.6.2-B50]
// ----------------------------------------------------------------------------
package org.opengts.war.track;
import java.util.*;
import java.io.*;
import java.net.*;
import java.math.*;
import java.security.*;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.RenderedImage;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.geocoder.*;
import org.opengts.db.*;
import org.opengts.db.tables.*;
import org.opengts.war.tools.*;
import org.opengts.war.track.page.AccountLogin;
import org.opengts.war.track.page.TrackMap;
public class Track
extends CommonServlet
implements Constants
{
// ------------------------------------------------------------------------
// TODO:
// - HttpSessionBindingListener (interface) // Only applicable to HttpSession setAttribute/removeAttribute
// void valueBound(HttpSessionBindingEvent event)
// void valueUnbound(HttpSessionBindingEvent event)
// - HttpSessionListener (interface)
// void sessionCreated(HttpSessionEvent se)
// void sessionDestroyed(HttpSessionEvent se)
private static class TrackSessionListener
implements HttpSessionListener
{
private int sessionCount = 0;
public TrackSessionListener() {
this.sessionCount = 0;
}
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
synchronized (this) {
this.sessionCount++;
}
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
synchronized (this) {
this.sessionCount--;
}
}
public int getSessionCount() {
int count = 0;
synchronized (this) {
count = this.sessionCount;
}
return count;
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/* Debug: display incoming request */
private static boolean DISPLAY_REQUEST = false;
public static void setDisplayRequest(boolean display)
{
DISPLAY_REQUEST = display;
}
// ------------------------------------------------------------------------
/* these must match the data response values in "jsmap.js" */
public static final String DATA_RESPONSE_LOGOUT = "LOGOUT";
public static final String DATA_RESPONSE_ERROR = "ERROR";
public static final String DATA_RESPONSE_PING_OK = "PING:OK";
public static final String DATA_RESPONSE_PING_ERROR = "PING:ERROR";
// ------------------------------------------------------------------------
/* global enable cookies */
private static boolean REQUIRE_COOKIES = true;
// ------------------------------------------------------------------------
// Commands
public static final String COMMAND_DEVICE_LIST = "devlist";
// ------------------------------------------------------------------------
// custom page requests
public static final String PAGE_LOGINFRAME = "LOGINFRAME";
public static final String PAGE_RELOAD = "RELOAD:XML";
public static final String PAGE_COPYRIGHT = "COPYRIGHT";
public static final String PAGE_VERSION = "VERSION";
public static final String PAGE_RUNSTATE = "RUNSTATE";
public static final String PAGE_STATISTICS = "STATISTICS";
public static final String PAGE_REVERSEGEOCODE = "REVERSEGEOCODE";
public static final String PAGE_GEOCODE = "ZONEGEOCODE";
public static final String PAGE_AUTHENTICATE = "AUTHENTICATE";
public static final String PAGE_RULE_EVAL = "RULE_EVAL";
public static final String PAGE_DEBUG_PUSHPINS = "DEBUG_PUSHPINS";
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private static long InitializedTime = 0L;
/* get initialized time */
public static long GetInitializedTime()
{
return InitializedTime;
}
/* static initializer */
static {
/* initialize DBFactories */
// -- should already have been called by 'RTConfigContextListener'
DBConfig.servletInit(null);
/* pre-init Base URI var */
RequestProperties.TRACK_BASE_URI();
/* enable cookies? "track.requireCookies" */
if (RTConfig.hasProperty(DBConfig.PROP_track_requireCookies)) {
REQUIRE_COOKIES = RTConfig.getBoolean(DBConfig.PROP_track_requireCookies,true);
}
/* initialized */
InitializedTime = DateTime.getCurrentTimeSec();
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static String GetBaseURL(RequestProperties reqState)
{
return WebPageAdaptor.EncodeMakeURL(reqState, RequestProperties.TRACK_BASE_URI());
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private static final String DIRECTORY_CSS = "/css/";
private static final String DIRECTORY_JS = "/js/";
private static final String DIRECTORY_IMAGES = "/images/";
private static final String DIRECTORY_OPT = "/opt/";
private static boolean trackRootDirInit = false;
private static File trackRootDir = null;
/* resolve the specified file relative to the configFile directory */
protected static File _resolveFile(String fileName)
{
/* initialize trackRootDir */
if (!trackRootDirInit) {
trackRootDirInit = true;
trackRootDir = RTConfig.getServletContextPath(); // may return null
}
/* have a directory? */
if (trackRootDir == null) {
Print.logWarn("No Servlet Context Path!");
return null;
}
/* have a file? */
if (StringTools.isBlank(fileName)) {
Print.logWarn("Specified file name is blank/null");
return null;
}
/* remove prefixing '/' from filename */
if (fileName.startsWith("/")) {
fileName = fileName.substring(1);
}
/* assemble file path */
File filePath = new File(trackRootDir, fileName);
if (!filePath.isFile()) {
Print.logInfo("File not found: " + filePath);
return null;
}
/* return resolved file */
return filePath;
}
/* write the specified file to the output stream */
protected static void _writeFile(HttpServletResponse response, File file)
throws IOException
{
//Print.logInfo("Found file: " + file);
/* content mime type */
CommonServlet.setResponseContentType(response, HTMLTools.getMimeTypeFromExtension(FileTools.getExtension(file)));
/* copy file to output */
OutputStream output = response.getOutputStream();
InputStream input = null;
try {
input = new FileInputStream(file);
FileTools.copyStreams(input, output);
} catch (IOException ioe) {
Print.logError("Error writing file: " + file + " " + ioe);
} finally {
if (input != null) { try{input.close();}catch(IOException err){/*ignore*/} }
}
output.close();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// GET/POST entry point
/* clear all session attributes, except HOST_PROPERTIES */
private static void clearSessionAttributes(HttpServletRequest request)
{
RTProperties hp = (RTProperties)AttributeTools.getSessionAttribute(request, CommonServlet.HOST_PROPERTIES, null);
AttributeTools.clearSessionAttributes(request); // invalidate
if (hp != null) {
AttributeTools.setSessionAttribute(request, CommonServlet.HOST_PROPERTIES, hp);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// GET/POST entry point
/* GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
this._doWork_wrapper(false, request, response);
} catch (Throwable th) {
Print.logException("Unexpected error",th);
}
}
/* POST request */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
this._doWork_wrapper(true, request, response);
} catch (Throwable th) {
Print.logException("Unexpected error",th);
}
}
/* handle POST/GET request */
private void _doWork_wrapper(boolean isPost, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
AttributeTools.parseRTP(request);
AttributeTools.parseMultipartFormData(request);
/* get PrivateLabel instance for this URL */
PrivateLabel privLabel = null;
URL requestURL = null;
String requestHostName = null;
String requestUrlPath = null;
try {
requestURL = new URL(request.getRequestURL().toString());
requestHostName = requestURL.getHost();
requestUrlPath = requestURL.getPath();
privLabel = (PrivateLabel)PrivateLabelLoader.getPrivateLabelForURL(requestURL);
} catch (MalformedURLException mfue) {
// invalid URL? (unlikely to occur)
Print.logWarn("Invalid URL? " + request.getRequestURL());
privLabel = (PrivateLabel)PrivateLabelLoader.getDefaultPrivateLabel();
}
/* PrivateLabel not found, look for other options */
if (privLabel == null) {
Print.logError("PrivateLabel not defined or contains errors!");
CommonServlet.setResponseContentType(response, HTMLTools.MIME_HTML()); // MIME_PLAIN());
PrintWriter out = response.getWriter();
String pageName = AttributeTools.getRequestString(request, CommonServlet.PARM_PAGE, "");
out.println("<HTML>");
/*
if (pageName.equals(PAGE_RELOAD)) {
RTConfig.reload();
PrivateLabelLoader.loadPrivateLabelXML();
out.println("RELOADED ...");
} else
*/
if (BasicPrivateLabelLoader.hasParsingErrors()) {
out.println("ERROR encountered:<br>");
out.println("'private.xml' contains syntax/parsing errors<br>");
out.println("(see log files for additional information)<br>");
out.println("<br>");
out.println("Please contact the System Administrator<br>");
} else
if (!BasicPrivateLabelLoader.hasDefaultPrivateLabel()) {
out.println("The specified URL is not allowed on this server:<br>");
out.println("(Unrecognized URL and no default Domain has been defined)<br>");
} else {
// should not occur
out.println("ERROR encountered:<br>");
out.println("Invalid 'private.xml' configuration<br>");
out.println("<br>");
out.println("Please contact the System Administrator<br>");
}
out.println("</HTML>");
out.close();
return;
}
/* overriding host properties? */
RTProperties hostProps = null;
// -- check for "&lfid=" host properties id
String hostPropID = AttributeTools.getRequestString(request, CommonServlet.HOST_PROPERTIES_ID, null); // "lfid"/"laf"?
if (StringTools.isBlank(hostPropID)) {
// -- get previous host properties
hostProps = (RTProperties)AttributeTools.getSessionAttribute(request, CommonServlet.HOST_PROPERTIES, null);
} else
if (hostPropID.equalsIgnoreCase(CommonServlet.DEFAULT_HOST_PROPERTIES_ID) ||
hostPropID.equalsIgnoreCase("x") ) {
// -- explicit reset to default
hostProps = null;
AttributeTools.setSessionAttribute(request, CommonServlet.HOST_PROPERTIES, null); // clear
} else {
// -- get specified host properties from ID
hostProps = Resource.getPrivateLabelPropertiesForHost(hostPropID, null); // may return null
if (hostProps != null) {
hostProps.setString(CommonServlet.HOST_PROPERTIES_ID, hostPropID);
}
AttributeTools.setSessionAttribute(request, CommonServlet.HOST_PROPERTIES, hostProps); // clears if null
}
// -- if no explicit host properties, try resources
if (hostProps == null) {
//Print.logInfo("Looking up host properties by host/url: " + requestHostName + ", " + requestUrlPath);
hostProps = Resource.getPrivateLabelPropertiesForHost(requestHostName, requestUrlPath);
}
// -- found?
//if (hostProps != null) { Print.logInfo("Found host/url host properties"); }
/* check for DebugPushpins */
boolean debugPP = false;
if (AttributeTools.hasRequestAttribute(request,EventData.DEBUG_PUSHPINS)) {
debugPP = AttributeTools.getRequestBoolean(request,EventData.DEBUG_PUSHPINS, false);
AttributeTools.setSessionBoolean(request, EventData.DEBUG_PUSHPINS[0], debugPP);
} else
if (AttributeTools.getSessionBoolean(request,EventData.DEBUG_PUSHPINS,false)) {
debugPP = true;
}
if (debugPP) {
if (hostProps == null) {
hostProps = new RTProperties();
}
hostProps.setBoolean(EventData.DEBUG_PUSHPINS[0], true);
Print.logInfo("Debugging Pushpins ...");
} else {
//Print.logInfo("Not Debugging Pushpins ...");
}
/* display PrivateLabel */
try {
privLabel.pushRTProperties();
if (hostProps != null) {
RTConfig.pushThreadProperties(hostProps);
}
this._doWork(isPost, request, response, privLabel);
} finally {
//if (hostProps != null) {
// RTConfig.popThreadProperties(hostProps);
//}
//privLabel.popRTProperties();
RTConfig.popAllThreadProperties();
}
}
/* handle POST/GET request */
private void _doWork(
boolean isPost, HttpServletRequest request,
HttpServletResponse response,
PrivateLabel privLabel)
throws ServletException, IOException
{
/* URL query string */
String requestURL = StringTools.trim(request.getRequestURL().toString());
String queryString = StringTools.trim(request.getQueryString());
/* was logged-in from SysAdmin? */
// cache beore session attributes are cleared
boolean saLogin = RequestProperties.isLoggedInFromSysAdmin(request,privLabel);
String saAcctID = saLogin? AttributeTools.getSessionString(request,Constants.PARM_SA_RELOGIN_ACCT,"") : null;
String saUserID = saLogin? AttributeTools.getSessionString(request,Constants.PARM_SA_RELOGIN_USER,"") : null;
long saLoginTS = saLogin? AttributeTools.getSessionLong( request,Constants.PARM_SA_RELOGIN_SESS,0L) : 0L;
/* secure (SSL) only? */
boolean isSecure = request.isSecure();
if (!isSecure && privLabel.getBooleanProperty(PrivateLabel.PROP_Track_forwardToSecureAccess,false)) {
if (StringTools.startsWithIgnoreCase(requestURL,"http:")) {
// Create new URL
URIArg uri = new URIArg(requestURL);
uri.setProtocol("https");
int uriPort = uri.getPort();
if (uriPort == 8080) {
uri.setPort(8443);
} else
if (uriPort == 80) {
uri.setPort(443);
}
// append query string
String secureURL = uri.toString();
if (!StringTools.isBlank(queryString)) {
secureURL += "?" + queryString;
}
// Write forward HTML:
// <html>
// <meta HTTP-EQUIV="refresh" CONTENT="1; URL=http://example.com/link.html"></meta>
// </html>
Print.logInfo("HTTPS Forward: " + secureURL);
CommonServlet.setResponseContentType(response, HTMLTools.MIME_HTML());
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<META HTTP-EQUIV=\"refresh\" CONTENT=\"1; URL="+secureURL+"\"></META>");
out.println("</HTML>");
out.close();
return;
} else {
// nut secure, but URL does not start with "http:"
Print.logError("Access is not secure, however link is not prefixed with 'http'!");
return;
}
}
/* response character set */
////response.setCharacterEncoding("UTF-8");
/* action request */
String pageName = AttributeTools.getRequestString(request, CommonServlet.PARM_PAGE , ""); // query only
String cmdName = AttributeTools.getRequestString(request, CommonServlet.PARM_COMMAND , ""); // query only ("page_cmd")
String cmdArg = AttributeTools.getRequestString(request, CommonServlet.PARM_ARGUMENT, ""); // query only
/* adjust page request */
if (cmdName.equals(Constants.COMMAND_LOGOUT) || pageName.equals(PAGE_LOGIN)) {
Track.clearSessionAttributes(request); // start with a clean slate
pageName = PAGE_LOGIN;
}
/* currently logged-in account/user */
String loginAcctID = (String)AttributeTools.getSessionAttribute(request, Constants.PARM_ACCOUNT , ""); // session only
String loginUserID = (String)AttributeTools.getSessionAttribute(request, Constants.PARM_USER , ""); // session only
boolean isLoggedIn = !StringTools.isBlank(loginAcctID);
/* account/user */
String userEmail = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_USEREMAIL, ""); // session or query
String accountID = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_ACCOUNT , ""); // session or query
String userID = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_USER , ""); // session or query
String enteredPass = AttributeTools.getRequestString (request, Constants.PARM_PASSWORD , null); // query only
String entEncPass = AttributeTools.getRequestString (request, Constants.PARM_ENCPASS , null); // query only
/* DemoLogin? */
if (StringTools.isBlank(accountID) && requestURL.endsWith(Constants.DEFAULT_DEMO_LOGIN_URI)) {
accountID = Account.GetDemoAccountID();
userID = "";
enteredPass = null;
entEncPass = null;
Print.logInfo("Demo Login ["+accountID+"] ...");
}
/* validate AccountID/UserID */
// the following prevents HTML/JavaScript injection via "accountID" or "userID"
if ((privLabel == null) || privLabel.globalValidateIDs()) {
//Print.logInfo("Validating account/user IDs");
if (!AccountRecord.isValidID(accountID)) {
accountID = "";
}
if (!AccountRecord.isValidID(userID)) {
userID = "";
}
} else {
Print.logWarn("account/user ID validation disabled!!");
}
/* encoded password */
if (!StringTools.isBlank(entEncPass)) {
// already have encoded password
enteredPass = null; // clear entered password in favor of previously encoded password
} else {
entEncPass = Account.encodePassword(privLabel,enteredPass); // may be null
if (entEncPass == null) { entEncPass = ""; }
}
/* store/restore password (PARM_ENCPASS) */
if (StringTools.isBlank(entEncPass)) {
// blank password, check for restore
// (this doesn't really provide the feature expected. what is wanted is an auto-re-login
// if the session expires, but the following cannot provide that since if the session has
// expired, the 'PARM_RESTOREPW' attribute will also be gone.)
if (AttributeTools.getSessionBoolean(request,Constants.PARM_RESTOREPW,false)) {
//entEncPass = (String)AttributeTools.getSessionAttribute(request, Constants.PARM_ENCPASS, "");
}
} else {
// non-blank password, check to see if we should indicate to subsequently reload the pwd from the session
if (queryString.indexOf("&password=") > 0) {
// the password was explicity specified on the query string
// TODO: this should really indicate that the "password=x" should always be included on
// the subsequent URL traversal links (this is currently not supported).
AttributeTools.setSessionBoolean(request, Constants.PARM_RESTOREPW, true); // save in session
// Should this indicate that the password should be stored in a client cookie?
}
}
/* session cached group/device/driver */
String groupID = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_GROUP , "");
String deviceID = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_DEVICE, "");
String driverID = (String)AttributeTools.getRequestAttribute(request, Constants.PARM_DRIVER, "");
// -- the following prevents HTML/JavaScript injection
if ((privLabel == null) || privLabel.globalValidateIDs()) {
if (!AccountRecord.isValidID(groupID,false/*strict?*/)) {
groupID = "";
}
if (!AccountRecord.isValidID(deviceID,false/*strict?*/)) {
deviceID = "";
}
if (!AccountRecord.isValidID(driverID,false/*strict?*/)) {
driverID = "";
}
} else {
Print.logWarn("group/device/driver ID validation disabled!!");
}
/* log-in ip address */
String ipAddr = request.getRemoteAddr();
// Options for looking up an AccountID/UserID
// 1) "accountID"/"userID" explicitly supplied.
// 2) "accountID" supplied, UserID implied (blank)
// 3) "userEmail" supplied, from which AccountID/UserID is implied
/* debug info */
if (DISPLAY_REQUEST || RTConfig.isDebugMode()) {
try {
URL url = new URL(requestURL);
Print.logInfo("Request : " + (isPost?"POST":"GET"));
Print.logInfo("URL Path: " + url.getPath());
Print.logInfo("URL File: " + url.getFile());
} catch (MalformedURLException mfue) {
//
}
Print.logInfo("Context Path: " + request.getContextPath());
Print.logInfo("[" + ipAddr + "] URL: " + requestURL + " " + queryString);
for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
String key = e.nextElement();
String val = request.getParameter(key);
Print.logInfo("Request Key:" + key + ", Value:" + val);
}
}
/* check for file resource requests */
String servletPath = request.getServletPath();
if ((servletPath != null) && (
servletPath.startsWith(DIRECTORY_CSS) ||
servletPath.startsWith(DIRECTORY_JS) ||
servletPath.startsWith(DIRECTORY_IMAGES) ||
servletPath.startsWith(DIRECTORY_OPT)
)) {
// -- If this occurs, it means that the servlet context redirected a request
// - for a file resource to this servlet. We attempt here to find the requested
// - file, and write it to the output stream.
File filePath = Track._resolveFile(servletPath);
if (filePath != null) {
// -- file was found, write it to the output stream
Print.logInfo("Serving file: " + filePath);
Track._writeFile(response, filePath);
} else {
// -- the file was not found
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("Invalid file specification");
out.close();
}
return;
}
// -- initialize the RequestProperties
RequestProperties reqState = new RequestProperties();
reqState.setBaseURI(RequestProperties.TRACK_BASE_URI());
reqState.setHttpServletResponse(response);
reqState.setHttpServletRequest(request);
reqState.setIPAddress(ipAddr);
reqState.setCommandName(cmdName);
reqState.setCommandArg(cmdArg);
reqState.setCookiesRequired(REQUIRE_COOKIES); /* enable cookies? */
/* locale override */
String localeStr = AttributeTools.getRequestString(request, Constants.PARM_LOCALE, null); // query only
if (StringTools.isBlank(localeStr)) {
localeStr = (String)AttributeTools.getSessionAttribute(request, Constants.PARM_LOCALE, ""); // session only
}
reqState.setLocaleString(localeStr);
/* store the RequestProperties instance in the current request to allow access from TagLibs */
request.setAttribute(PARM_REQSTATE, reqState);
/* content only? (obsolete?) */
int contentOnly = 0;
if (AttributeTools.hasRequestAttribute(request,PARM_CONTENT)) {
// -- key explicitly specified in the request (obsolete)
contentOnly = AttributeTools.getRequestInt(request,PARM_CONTENT, 0);
AttributeTools.setSessionInt(request,PARM_CONTENT,contentOnly); // save in session
} else {
// -- get last value stored in the session
contentOnly = AttributeTools.getSessionInt(request,PARM_CONTENT, 0);
}
reqState.setPageFrameContentOnly(contentOnly != 0);
/* invalid url (no private label defined for this URL host) */
if (privLabel == null) {
// -- This would be an abnormal situation, English should be acceptable here
if (pageName.equals(PAGE_AUTHENTICATE)) {
Track._writeAuthenticateXML(response, false);
} else {
String invalidURL = "Invalid URL";
Track.writeErrorResponse(reqState, invalidURL);
}
return;
}
reqState.setPrivateLabel(privLabel);
I18N i18n = privLabel.getI18N(Track.class);
String bplName = privLabel.getName();
long nowTimeSec = DateTime.getCurrentTimeSec();
/* authentication request */
boolean authRequest = (pageName.equals(PAGE_AUTHENTICATE) &&
privLabel.getBooleanProperty(PrivateLabel.PROP_Track_enableAuthenticationService,false));
/* display Version info */
if (pageName.equals(PAGE_COPYRIGHT)) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println(org.opengts.Version.getInfo());
out.close();
return;
}
/* display Version */
if (pageName.equals(PAGE_VERSION)) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println(org.opengts.Version.getVersion());
out.close();
return;
}
/* display run-state */ // 2.5.2-B40
// -- This feature is used for testing the run status of the servlet container
if (pageName.equals(PAGE_RUNSTATE)) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("OK");
// -- TODO: other runtime status could be displayed here
out.close();
return;
}
/* reload PrivateLabel XML */
// -- This allow making changes directly within the "$CATALINA_HOME/webapps/track/"
// - to various 'private.xml' or runtime config files (ie. custom.conf, etc), then
// - force a reload of the changes without having to start/stop Tomcat. Any currently
// - logged-in users will still remain logged-in.
// - WARNING: This has been known to fail in some cases and not properly reload the
// - runtime configuration files. This should only be used for development purposes.
/*
if (pageName.equals(PAGE_RELOAD)) {
RTConfig.reload();
PrivateLabelLoader.loadPrivateLabelXML();
if (cmdName.equalsIgnoreCase("short")) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("RELOADED");
out.close();
} else {
Track.writeMessageResponse(reqState, "PrivateLabel XML reloaded"); // English only
}
return;
}
*/
/* special "loginFrame" request */
if (requestURL.endsWith(RequestProperties._HTML_LOGIN_FRAME) ||
requestURL.endsWith(RequestProperties._HTML_LOGIN) ||
pageName.equalsIgnoreCase(PAGE_LOGINFRAME) ) {
String indexJSP = "/jsp/loginFrame.jsp";
Print.logInfo("Dispatching to " + indexJSP);
RequestDispatcher rd = request.getRequestDispatcher(indexJSP);
if (rd != null) {
try {
rd.forward(request, response);
return;
} catch (ServletException se) {
Print.logException("JSP error: " + indexJSP, se);
// continue below
}
} else {
Print.logError("******* RequestDispatcher not found for URI: " + indexJSP);
}
}
/* custom text marker */
// Example:
// Marker?icon=/images/pp/label47_fill.png&fr=3,2,42,13,8&text=Demo2&rc=red&fc=yellow
// Options:
// icon=<PathToImageIcon> - icon URI (relative to "/track/")
// frame=<XOffset>,<YOffset>,<Width>,<Height>,<FontPt> - frame definition
// fill=<FillColor> - frame background color
// border=<BorderColor> - frame border color
// text=<ShortText> - string text
// arrow=<Heading> - double heading
if (isLoggedIn && requestURL.endsWith(Constants.DEFAULT_MARKER_URI)) { // make sure someone is logged-in
// -- box28_white.png : 3,2,21,16,8
// -- label47_fill.png : 3,2,42,13,9
String icon = StringTools.blankDefault(AttributeTools.getRequestString(request,PushpinIcon.MARKER_ARG_ICON,""),"/images/pp/label47_fill.png");
PushpinIcon.TextIcon imageTI = null;
if (icon.startsWith("#")) {
PushpinIcon.TextIcon ti = PushpinIcon.GetTextIcon(icon.substring(1));
if (ti != null) {
imageTI = new PushpinIcon.TextIcon(ti); // clone
} else {
Print.logWarn("TextIcon not found: " + icon);
}
} else {
File iconPath = Track._resolveFile(icon);
if (iconPath != null) {
String frS = AttributeTools.getRequestString(request, PushpinIcon.MARKER_ARG_FRAME, "");
String fs[] = StringTools.split(frS,',');
int fr[] = StringTools.parseInt(fs,0);
int X = ((fr != null) && (fr.length > 0) && (fr[0] > 0))? fr[0] : 0; // X-Offset [ 1]
int Y = ((fr != null) && (fr.length > 1) && (fr[1] > 0))? fr[1] : 2; // Y-Offset [14]
int W = ((fr != null) && (fr.length > 2) && (fr[2] > 0))? fr[2] : 42; // Width [29]
int H = ((fr != null) && (fr.length > 3) && (fr[3] > 0))? fr[3] : 13; // Height [ 9]
int Fpt = ((fr != null) && (fr.length > 4) && (fr[4] > 0))? fr[4] : 9; // FontSize [10]
String Fnm = ((fs != null) && (fs.length > 5) && !StringTools.isBlank(fs[5]))? fs[5] : null; // FontName [SanSerif]
imageTI = new PushpinIcon.TextIcon(iconPath, X, Y, W, H, Fpt, Fnm);
} else {
Print.logWarn("Unable to resolve file: " + icon);
}
}
if (imageTI == null) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("Invalid icon: " + icon);
out.close();
return;
}
// -- colors
{
Color fillC = ColorTools.parseColor(AttributeTools.getRequestString(request,PushpinIcon.MARKER_ARG_FILL_COLOR ,""),(Color)null);
Color bordC = ColorTools.parseColor(AttributeTools.getRequestString(request,PushpinIcon.MARKER_ARG_BORDER_COLOR,""),(Color)null);
Color foreC = ColorTools.parseColor(AttributeTools.getRequestString(request,PushpinIcon.MARKER_ARG_COLOR ,""),(Color)null);
if (fillC != null) { imageTI.setFillColor(fillC); }
if (bordC != null) { imageTI.setBorderColor(bordC); }
if (foreC != null) { imageTI.setForegroundColor(foreC); }
}
// -- render image with text
String text = AttributeTools.getRequestString(request, PushpinIcon.MARKER_ARG_TEXT , "");
double arrow = AttributeTools.getRequestDouble(request, PushpinIcon.MARKER_ARG_ARROW, -1.0);
RenderedImage image = imageTI.createImage(text, arrow);
if (image != null) {
response.setContentType(HTMLTools.MIME_PNG());
OutputStream out = response.getOutputStream();
ImageIO.write(image, "png", out);
out.close();
} else {
Print.logError("Unable to render image: " + icon);
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("Unable to render: " + icon);
out.close();
}
return;
}
/* return EventData attachment */
// Example:
// Attach.jpg?d=DEVICE&ts=TIMSTAMP&sc=STATUSCODE
// Options:
// d=<Device> - device
// ts=<Timestamp> - timestamp
// sc=<StatusCode> - status code
int att = isLoggedIn? requestURL.indexOf(Constants.DEFAULT_ATTACH_URI+".") : -1; // make sure someone is logged-in
if (att >= 0) {
String ext = requestURL.substring(att + (Constants.DEFAULT_ATTACH_URI+".").length());
String acc = loginAcctID;
String dev = AttributeTools.getRequestString(request, "d" , "");
long ts = AttributeTools.getRequestLong (request, "ts", 0L);
int sc = AttributeTools.getRequestInt (request, "sc", StatusCodes.STATUS_NONE);
// get EventData record
EventData ev = null;
try {
EventData.Key evKey = new EventData.Key(acc, dev, ts, sc);
ev = evKey.exists()? evKey.getDBRecord(true) : null;
} catch (DBException dbe) {
Print.logError("Unable to update EventData with attachment: " + dbe);
}
// EventData record not found
if (ev == null) {
// EventData not found
Print.logError("EventData record not found: " + acc + "," + dev + "," + ts + "," + sc);
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("EventData record not found.");
out.close();
return;
}
// EventData record does not contain an attachment
if (!ev.hasAttachData()) {
// no attachment (empty response)
String mimeType = HTMLTools.getMimeTypeFromExtension(ext, HTMLTools.MIME_PLAIN());
response.setContentType(mimeType);
OutputStream out = response.getOutputStream();
// write nothing (empty response)
out.close();
return;
}
// return EventData attachment
String attachType = ev.getAttachType();
byte attachData[] = ev.getAttachData();
String mimeType = HTMLTools.getMimeTypeFromExtension(ext, attachType);
response.setContentType(mimeType);
OutputStream out = response.getOutputStream();
out.write(attachData);
out.close();
return;
}
/* statistics */
if (pageName.equals(PAGE_STATISTICS) && !cmdName.equals("") && !cmdArg.equals("")) {
try{
MethodAction ma = new MethodAction(DBConfig.PACKAGE_OPT_AUDIT_ + "Statistics", "getStats", String.class, String.class);
String stats = (String)ma.invoke(cmdName, cmdArg);
if (stats != null) {
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println(stats);
out.close();
return;
}
} catch (Throwable th) {
// ignore
//Print.logException("Statistics",th);
}
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
PrintWriter out = response.getWriter();
out.println("");
out.close();
return;
}
/* offline? */
String glbOflMsg = PrivateLabel.GetGlobalOfflineMessage();
String ctxOflMsg = PrivateLabel.GetContextOfflineMessage();
boolean isOffline = (glbOflMsg != null) || ((ctxOflMsg != null) && !AccountRecord.isSystemAdminAccountID(accountID));
if (isOffline || pageName.equals(PAGE_OFFLINE)) {
if (isOffline) {
Print.logWarn("Domain Offline: " + request.getRequestURL());
}
Track.clearSessionAttributes(request);
String offlineMsg = (ctxOflMsg != null)? ctxOflMsg : glbOflMsg;
pageName = PAGE_OFFLINE;
WebPage offlinePage = privLabel.getWebPage(pageName); // may return null
if (offlinePage != null) {
reqState.setPageName(pageName);
reqState.setPageNavigationHTML(offlinePage.getPageNavigationHTML(reqState));
offlinePage.writePage(reqState, offlineMsg);
} else {
if (StringTools.isBlank(offlineMsg)) {
offlineMsg = i18n.getString("Track.offline","The system is currently offline for maintenance\nPlease check back later.");
}
Track.writeMessageResponse(reqState, offlineMsg);
}
return;
}
/* explicit logout? */
if (pageName.equals(PAGE_LOGIN)) {
// -- check for SysAdmin/Manager Accounts-Login return
try {
for (;;) {
// -- Originally logged-in from SysAdnin/Manager? (EXPERIMENTAL)
// - Used to support returning to the "System Accounts" page if the
// - SysAdmin/Manager had logged-in to this account using the "Login"
//- button on the "System Accounts" page.
if (!saLogin) {
// -- not logged-in from SysAdmin/Manager
//Print.logInfo("Not logged in from SysAdmin/Manager");
break;
} else
if (StringTools.isBlank(saAcctID)) {
// -- not logged-in from SysAdmin/Manager
Print.logWarn("Originator SysAdmin/Manager AccountID id blsnk");
break;
}
// -- return enabled?
if (!privLabel.isSystemAccountsLoginReturnEnabled(saAcctID)) {
// -- return from SysAccountsLogin not enabled
//Print.logWarn("SysAdmin/Manager Account login return disabled");
break;
}
// -- return timeout
long rtnTimeoutSec = privLabel.getSystemAccountsLoginReturnTimeout(saAcctID);
if ((rtnTimeoutSec > 0L) && ((saLoginTS + rtnTimeoutSec) < DateTime.getCurrentTimeSec())) {
// timeout
Print.logWarn("SysAdmin/Manager Account login return timeout");
break;
}
// -- get account
Account saAcct = Account.getAccount(saAcctID);
if (saAcct == null) {
Print.logWarn("Account not found: " + saAcctID);
break;
}
// -- get user
User saUser = null;
if (!StringTools.isBlank(saUserID)) {
saUser = User.getUser(saAcct, saUserID);
if ((saUser == null) && !User.isAdminUser(saUserID)) {
Print.logWarn("User not found: " + saAcctID + "/" + saUserID);
break; // UserID specified, but not found
}
}
// -- get password
String saPasswd = (saUser != null)?
saUser.getDecodedPassword(null) :
saAcct.getDecodedPassword(null);
// -- construct URL
URIArg url = new URIArg(reqState.getBaseURI());
url.addArg(Constants.PARM_ACCOUNT , saAcctID);
url.addArg(Constants.PARM_USER , saUserID);
url.addArg(Constants.PARM_PASSWORD, StringTools.blankDefault(saPasswd,""));
url.addArg(CommonServlet.PARM_PAGE, Constants.PAGE_SYSADMIN_ACCOUNTS);
Print.logInfo("ReLogin URL: " + url);
// -- dispatch
RequestDispatcher rd = request.getRequestDispatcher(url.toString());
rd.forward(request, response);
return;
}
} catch (Throwable th) {
Print.logError("Unable to dispatch to '"+saAcctID+"' login: " + th);
}
// -- standard logout
if (!loginAcctID.equals("")) {
Print.logInfo("Logout: " + loginAcctID);
}
String pleaseLogin = i18n.getString("Track.pleaseLogin","Please Login"); // UserErrMsg
Track._displayLogin(reqState, pleaseLogin, false);
return;
}
/* get requested page */
WebPage trackPage = privLabel.getWebPage(pageName); // may return null
if (trackPage != null) {
reqState.setPageName(pageName);
}
/* check for page that does not require a login */
if ((trackPage != null) && !trackPage.isLoginRequired()) {
reqState.setPageNavigationHTML(trackPage.getPageNavigationHTML(reqState));
trackPage.writePage(reqState, "");
return;
}
// --- verify that user is logged in
// -- If not logged-in, the login page will be displayed
/* email id */
String emailID = null;
if (privLabel.getAllowEmailLogin()) {
String email = !StringTools.isBlank(userEmail)? userEmail : userID;
if (email.indexOf("@") > 0) {
emailID = email;
} else
//if (!privLabel.getAccountLogin() && Account.isSystemAdminAccountID(email))
if (!privLabel.getAccountLogin() && StringTools.isBlank(accountID)) {
// -- TODO: may want to make this a configurable option
emailID = null;
accountID = email;
if (!privLabel.getUserLogin() /*&& StringTools.isBlank(userID)*/) {
userID = User.getAdminUserID(); // TODO: default account user?
}
}
}
/* account-id not specified */
if (StringTools.isBlank(accountID)) {
String dftAcctID = privLabel.getDefaultLoginAccount(); // may be blank
if (!StringTools.isBlank(dftAcctID)) {
accountID = dftAcctID;
} else
if (!privLabel.getAccountLogin() || !StringTools.isBlank(emailID)) {
// -- attempt to look up account/user from user contact email address
try {
// -- look up in User table
User user = User.getUserForContactEmail(null,emailID);
if (user != null) {
emailID = null;
accountID = user.getAccountID();
userID = user.getUserID();
// -- account/user revalidated below ...
Print.logInfo("Found contact email User: " + emailID + " ==> " + accountID + "/" + userID);
} else {
// -- not in User table, try Account table
java.util.List<String> acctList = Account.getAccountIDsForContactEmail(emailID);
if (!ListTools.isEmpty(acctList)) {
emailID = null;
accountID = acctList.get(0);
userID = User.getAdminUserID();
Print.logInfo("Found contact email Account: " + emailID + " ==> " + accountID + "/" + userID);
} else {
Print.logWarn("User Email address not found: " + emailID);
}
}
} catch (Throwable th) { // DBException
// -- ignore
Print.logError("EMail lookup error: ["+emailID+"] " + th);
}
}
if (StringTools.isBlank(accountID)) { // still blank?
// -- This is NOT an error, only an indication that the account session may have expired!
//Print.logInfo("[%s] Account/User not logged in (session expired?) ...", privLabel.getName());
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else
if ((trackPage instanceof TrackMap) &&
(cmdName.equals(TrackMap.COMMAND_MAP_UPDATE) ||
cmdName.equals(TrackMap.COMMAND_DEVICE_PING) ) ) {
// -- A map has requested an update, and the user is not logged-in
PrintWriter out = response.getWriter();
CommonServlet.setResponseContentType(response, HTMLTools.MIME_PLAIN());
out.println(DATA_RESPONSE_LOGOUT);
} else {
String enterAcctPass = i18n.getString("Track.enterAccount","Please enter Login/Authentication"); // UserErrMsg
Track._displayLogin(reqState, enterAcctPass, false);
}
return;
}
} else
if (!StringTools.isBlank(emailID)) {
// -- attempt to look up user from account and contact email address
try {
User user = User.getUserForContactEmail(accountID,emailID);
if (user != null) {
emailID = null;
userID = user.getUserID();
// -- account/user revalidated below ...
} else {
Print.logWarn("User Email address not found: " + accountID + "/" + emailID);
}
} catch (Throwable th) { // DBException
// -- ignore
Print.logError("EMail lookup error: " + th);
}
}
/* login from "sysadmin"? */
String relogin = AttributeTools.getRequestString(request, Constants.PARM_SA_RELOGIN, "");
if (!StringTools.isBlank(relogin)) {
AttributeTools.setSessionAttribute(request, Constants.PARM_SA_RELOGIN, relogin);
}
boolean isSysadminRelogin = RequestProperties.isLoggedInFromSysAdmin(request,privLabel);
/* load account */
Account account = null;
try {
account = Account.getAccount(accountID);
if (account == null) {
Print.logInfo("Account does not exist: " + accountID);
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
String invLoginText = reqState.getShowPassword()?
i18n.getString("Track.invalidLoginPass","Invalid Login/Password") : // UserErrMsg
i18n.getString("Track.invalidLogin","Invalid Login"); // UserErrMsg
Track._displayLogin(reqState, invLoginText, true);
}
Print.logInfo("Login[Failed]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
} else
if (!account.isActive() && !isSysadminRelogin) {
Print.logInfo("Account is inactive: " + accountID);
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track._displayLogin(reqState, i18n.getString("Track.inactiveAccount","Inactive Account"), true); // UserErrMsg
}
Print.logInfo("Login[Inactive]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
} else
if (account.isExpired() && !isSysadminRelogin) {
Print.logInfo("Account has expired: " + accountID);
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track._displayLogin(reqState, i18n.getString("Track.expiredAccount","Expired Account"), true); // UserErrMsg
}
Print.logInfo("Login[Inactive]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
} else
if (account.isSuspended() && !isSysadminRelogin) {
long suspendTime = account.getSuspendUntilTime();
Print.logInfo("Account is suspended: " + accountID + " (until "+(new DateTime(suspendTime))+")");
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track._displayLogin(reqState, i18n.getString("Track.suspendedAccount","Please contact Administrator"), true); // UserErrMsg
}
Print.logInfo("Login[Suspended]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
}
// -- check that the Account is authorized for this host domain
if (privLabel.isRestricted() && !isSysadminRelogin) {
String acctDomain = account.getPrivateLabelName();
String domainName = privLabel.getDomainName();
String hostName = privLabel.getHostName(); // never null (may be PrivateLabel.DEFAULT_HOST)
for (;;) {
if (!StringTools.isBlank(acctDomain)) {
if ((domainName != null) && acctDomain.equals(domainName)) {
break; // account domain matches alias name
} else
if ((hostName != null) && acctDomain.equals(hostName)) {
break; // account domain matches host name
} else
if (acctDomain.equals(BasicPrivateLabel.ALL_HOSTS)) {
break; // account domain explicitly states it is valid in all domains
}
}
// -- if we get here, we've failed the above tests
Print.logInfo("Account not authorized for this host: " + accountID + " ==> " + hostName);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track._displayLogin(reqState, i18n.getString("Track.invalidHost","Invalid Login Host"), true); // UserErrMsg
}
return;
}
}
} catch (DBException dbe) {
// -- Internal error
Track.clearSessionAttributes(request);
Print.logException("Error reading Account: " + accountID, dbe);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track.writeErrorResponse(reqState, i18n.getString("Track.errorAccount","Error reading Account"));
}
return;
}
/* default to 'admin' user */
if (StringTools.isBlank(userID)) {
userID = account.getDefaultUser();
if (StringTools.isBlank(userID)) {
userID = (privLabel != null)? privLabel.getDefaultLoginUser() : User.getAdminUserID();
}
}
/* different account (or not yet logged in) */
boolean wasLoggedIn = (loginAcctID.equals(accountID) && loginUserID.equals(userID));
if (!wasLoggedIn && !isSysadminRelogin) {
// -- clear old session variables and continue
Track.clearSessionAttributes(request);
}
/* validate account/user/password */
User user = null;
Account failedAccount = null;
User failedUser = null;
try {
/* lookup specified UserID */
boolean loginOK = true;
user = User.getUser(account, userID);
if (user != null) {
// -- we found a valid user
//Print.logInfo("Found User: " + userID);
} else
if (User.isAdminUser(userID)) {
// -- logging in as the 'admin' user, and we don't have an explicit user record
//Print.logInfo("Explicit Admin user not found: " + userID);
} else {
Print.logInfo("Invalid User: " + accountID + "/" + userID);
failedAccount = account;
account = null;
loginOK = false;
}
// -- if we found the account/user, check the password (if not already logged in)
if (loginOK && !wasLoggedIn) {
if (user != null) {
// -- standard password check
boolean validLogin = false;
if (user.isSuspended()) { // [2.6.2-B50]
long suspendTime = user.getSuspendUntilTime();
Print.logInfo("User is suspended: " + accountID+"/"+userID + " (until "+(new DateTime(suspendTime))+")");
validLogin = false;
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
Track._displayLogin(reqState, i18n.getString("Track.suspendedUser","Please contact Administrator"), true); // UserErrMsg
}
Print.logInfo("Login[Suspended]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
} else
if (enteredPass != null) {
String decPass = enteredPass;
validLogin = user.checkPassword(privLabel,decPass,true/*suspend*/);
} else
if (entEncPass != null) {
// -- TODO: should support checking MD5 encoded passwords
String decPass = Account.decodePassword(privLabel,entEncPass); // may be null
validLogin = user.checkPassword(privLabel,decPass,true/*suspend*/);
} else {
validLogin = false;
}
if (!validLogin) {
Print.logInfo("Invalid Password for User: " + accountID + "/" + userID);
failedAccount = account;
account = null;
failedUser = user;
user = null;
loginOK = false;
}
} else {
// -- standard password check (virtual "admin" user)
boolean validLogin = false;
if (enteredPass != null) {
String decPass = enteredPass;
validLogin = account.checkPassword(privLabel,decPass,true/*suspend*/);
} else
if (entEncPass != null) {
// -- TODO: should support checking MD5 encoded passwords
String decPass = Account.decodePassword(privLabel,entEncPass); // may be null
validLogin = account.checkPassword(privLabel,decPass,true/*suspend*/);
} else {
validLogin = false;
}
if (!validLogin) {
Print.logInfo("Invalid Password for Account: " + accountID);
failedAccount = account;
account = null;
loginOK = false;
}
}
}
/* invalid account, user, or password, displays the same error */
if (!loginOK) {
// -- login failed
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else
if (AccountRecord.isSystemAdminAccountID(accountID) && StringTools.isBlank(enteredPass)) {
String enterAcctPass = i18n.getString("Track.enterAccount","Please enter Login/Authentication"); // UserErrMsg
Track._displayLogin(reqState, enterAcctPass, false);
} else
if (request.getParameter(AttributeTools.ATTR_RTP) != null) {
String enterAcctPass = i18n.getString("Track.enterAccount","Please enter Login/Authentication"); // UserErrMsg
Track._displayLogin(reqState, enterAcctPass, false);
} else {
String invLoginText = reqState.getShowPassword()?
i18n.getString("Track.invalidLoginPass","Invalid Login/Password") : // UserErrMsg
i18n.getString("Track.invalidLogin","Invalid Login"); // UserErrMsg
Track._displayLogin(reqState, invLoginText, true);
}
Print.logInfo("Login[Failed]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
// -- audit login failed
Audit.userLoginFailed(accountID, userID, ipAddr, bplName);
// -- count login failures for possible suspension
if (failedUser != null) {
failedUser.suspendOnLoginFailureAttempt(false);
} else
if (failedAccount != null) {
failedAccount.suspendOnLoginFailureAttempt(false);
}
return;
}
/* inactive/expired user */
if (user == null) {
// -- assume "admin" user
} else
if (!user.isActive()) {
Print.logInfo("User is inactive: " + accountID + "/" + userID);
account = null;
user = null;
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
String inactiveUser = i18n.getString("Track.inactiveUser","Inactive User"); // UserErrMsg
Track._displayLogin(reqState, inactiveUser, true);
}
Print.logInfo("Login[Inactive]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
} else
if (user.isExpired()) {
Print.logInfo("User is expired: " + accountID + "/" + userID);
account = null;
user = null;
Track.clearSessionAttributes(request);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
String expiredUser = i18n.getString("Track.expiredUser","Expired User"); // UserErrMsg
Track._displayLogin(reqState, expiredUser, true);
}
Print.logInfo("Login[Expired]: Domain="+bplName + " Account="+accountID + " User="+userID + " Time="+nowTimeSec + " IPAddr="+ipAddr);
return;
}
/* log login message */
if (!wasLoggedIn) {
// -- Account/User was not previously logged-in
if (account.isSystemAdmin()) {
Print.logInfo("Login SysAdmin: " + accountID + "/" + userID + " [From " + ipAddr + "]");
} else {
Print.logInfo("Login Account/User: " + accountID + "/" + userID + " [From " + ipAddr + "]");
}
// -- display memory usage on first login for each user
OSTools.printMemoryUsage();
}
/* save current context user in Account */
account.setCurrentUser(user);
} catch (DBException dbe) {
// -- Internal error
Track.clearSessionAttributes(request);
Print.logException("Error reading Account/User: " + accountID + "/" + userID, dbe);
if (authRequest) {
Track._writeAuthenticateXML(response, false);
} else {
String errorAccount = i18n.getString("Track.errorUser","Error reading Account/User");
Track.writeErrorResponse(reqState, errorAccount);
}
return;
}
reqState.setCurrentAccount(account); // never null
reqState.setCurrentUser(user); // may be null
// --------------------------------------------
// -- login successful after this point
/* account specific Look&Feel ID */
// -- Resource.getPrivateLabelPropertiesForHost
{
RTProperties acctLafProps = null;
// -- first try account specific lafID
//if (account.hasLookAndFeelID()) {
// acctLafProps = Resource.getPrivateLabelPropertiesForHost(account.getLookAndFeelID(), null);
//}
// -- check for account resource lafID
if (acctLafProps == null) {
acctLafProps = Resource.getPrivateLabelPropertiesForHost("-"+accountID, null);
}
// -- set Account LAF props if found
if (acctLafProps != null) {
RTConfig.pushThreadProperties(acctLafProps);
}
}
/* Authenticate test */
// -- experimental
if (authRequest) {
Track._writeAuthenticateXML(response, true);
return;
}
/* password expired? */
boolean passwordExpired = false;
if (user != null) {
// -- logged in via User password
passwordExpired = user.hasPasswordExpired();
} else {
// -- logged in via Account password
passwordExpired = account.hasPasswordExpired();
}
/* set SESSION_ACCOUNT/SESSION_USER */
RTProperties sessionProps = new RTProperties();
String sessionAcctID = account.getAccountID();
String sessionUserID = (user != null)? user.getUserID() : User.getAdminUserID();
sessionProps.setString(RTKey.SESSION_ACCOUNT , sessionAcctID);
sessionProps.setString(RTKey.SESSION_USER , sessionUserID);
sessionProps.setString(RTKey.SESSION_IPADDRESS, ipAddr);
RTConfig.pushThreadProperties(sessionProps);
/* save locale override (after "clearSessionAttributes") */
if (!StringTools.isBlank(localeStr)) {
AttributeTools.setSessionAttribute(request, Constants.PARM_LOCALE, localeStr);
RTProperties localeProps = sessionProps; // new RTProperties();
localeProps.setString(RTKey.SESSION_LOCALE, localeStr); // SESSION_USER?
localeProps.setString(RTKey.LOCALE , localeStr);
//RTConfig.pushThreadProperties(localeProps);
//Print.logInfo("PrivateLabel Locale: " + localeStr + " [" + privLabel.getLocaleString() + "]");
}
/* Account temporary properties? */
{
RTProperties tempRTP = Resource.getTemporaryProperties(account);
if (tempRTP != null) {
RTConfig.pushThreadProperties(tempRTP);
}
}
/* Reverse Geocode */
if (pageName.equals(PAGE_REVERSEGEOCODE) && !reqState.isDemoAccount() &&
RTConfig.getBoolean("enableReverseGeocodeTest",false)) {
String rgCache[] = null;
ReverseGeocodeProvider rgp = privLabel.getReverseGeocodeProvider();
if (rgp != null) {
boolean cache = AttributeTools.getRequestBoolean(request, "cache", false); // from query only
String gpStr = AttributeTools.getRequestString(request, "gp", "0/0"); // from query only
GeoPoint gp = new GeoPoint(gpStr);
ReverseGeocode rg = rgp.getReverseGeocode(gp, localeStr, cache);
String charSet = StringTools.getCharacterEncoding();
Print.logInfo("ReverseGeocode: ["+charSet+"]\n"+rg);
rgCache = new String[] { gp.toString(), rg.getFullAddress() };
Track.writeMessageResponse(reqState, "ReverseGeocode: ["+charSet+"]\n"+rg); // English only
} else {
Track.writeMessageResponse(reqState, "ReverseGeocodeProvider not available"); // English only
}
// -- Save last cached geocode
AttributeTools.setSessionAttribute(request, Constants.LAST_REVERSEGEOCODE, rgCache);
return;
}
/* Address/PostalCode Geocode */
if (pageName.equals(PAGE_GEOCODE)) {
//Print.logInfo("Found 'PAGE_GEOCODE' request ...");
String rgCache[] = null; // { "Address", "Country", "Latitude/Longitude" }
GeoPoint rgPoint = null;
String rgAddrs = null;
String gpXML = null;
// -- PrivateLabel.PROP_ZoneInfo_enableGeocode
String addr = AttributeTools.getRequestString(request, "addr", ""); // zip/address
String country = AttributeTools.getRequestString(request, "country", "");
GeocodeProvider geocodeProv = privLabel.getGeocodeProvider();
if (geocodeProv != null) {
GeoPoint gp = geocodeProv.getGeocode(addr, country);
//Print.logInfo("GeocodeProvider ["+geocodeProv.getName()+"] "+addr+" ==> " + gp);
if ((gp != null) && gp.isValid()) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<geocode>\n");
sb.append(" <lat>").append(gp.getLatitude() ).append("</lat>\n");
sb.append(" <lng>").append(gp.getLongitude()).append("</lng>\n");
sb.append("</geocode>\n");
gpXML = sb.toString();
rgAddrs = addr;
rgPoint = gp;
rgCache = new String[] { addr, country, gp.toString() };
} else {
// -- no GeoPoint found
gpXML = "";
Print.logInfo("No Geocode point found ...");
}
} else
if (StringTools.isBlank(addr)) {
// -- zip/address not specified
gpXML = "";
Print.logInfo("Address not specified ...");
} else
if (StringTools.isNumeric(addr)) {
// -- all numeric, US zip code only
int timeoutMS = 5000;
String zip = addr;
gpXML = org.opengts.geocoder.geonames.GeoNames.getPostalCodeLocation_xml(zip, country, timeoutMS);
// -- already included "<?xml version="1.0" encoding="UTF-8" standalone="no"?>"
// - TODO: extract GeoPoint
Print.logInfo("Geonames zip geocode ...");
} else {
// -- city, state
int timeoutMS = 5000;
String a[] = StringTools.split(addr,',');
if (ListTools.isEmpty(a)) {
gpXML = "";
} else
if (a.length >= 2) {
String state = a[a.length - 1];
String city = a[a.length - 2];
gpXML = org.opengts.geocoder.geonames.GeoNames.getCityLocation_xml(city, state, country, timeoutMS);
// -- already included "<?xml version="1.0" encoding="UTF-8" standalone="no"?>"
// - TODO: extract GeoPoint
} else {
String state = "";
String city = a[0];
gpXML = org.opengts.geocoder.geonames.GeoNames.getCityLocation_xml(city, state, country, timeoutMS);
// -- already included "<?xml version="1.0" encoding="UTF-8" standalone="no"?>"
// - TODO: extract GeoPoint
}
Print.logInfo("Geonames city/state geocode ...");
}
// -- Save last cached geocode
if (rgCache == null) {
Print.logInfo("No cached GeoPoint for address: "+rgAddrs);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_CACHE , null);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_ADDRESS , null);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_LATITUDE , null);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_LONGITUDE, null);
} else {
Print.logInfo("Geocode: "+rgAddrs+" ==> " + rgPoint);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_CACHE , rgCache);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_ADDRESS , rgAddrs);
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_LATITUDE , rgPoint.getLatitudeString(null,null));
AttributeTools.setSessionAttribute(request, Constants.LAST_GEOCODE_LONGITUDE, rgPoint.getLongitudeString(null,null));
}
// -- write Geocode XML to client
CommonServlet.setResponseContentType(response, HTMLTools.MIME_XML(), StringTools.CharEncoding_UTF_8);
PrintWriter out = response.getWriter();
out.println(
!StringTools.isBlank(gpXML)? gpXML :
("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<geonames></geonames>\n"));
out.close();
return;
}
/* Check Rule Trigger */
if (pageName.equals(PAGE_RULE_EVAL)) {
Object result = null;
String ruleID = AttributeTools.getRequestString(request, Constants.PARM_RULE, "");
if (StringTools.isBlank(ruleID)) {
// -- undefined
} else
if (ruleID.startsWith("@")) {
// -- pre-defined function
if (ruleID.equalsIgnoreCase("@devnotify")) {
// -- account (not null)
// -- user (may be null)
try {
long ageSec = -1L;
long sinceTime = (ageSec >= 0L)? (DateTime.getCurrentTimeSec() - ageSec) : 1L; // 1 ==> Jan 1, 1970 12:01am
result = account.hasDeviceLastNotifySince(sinceTime,user)? "1" : "0";
} catch (DBException dbe) {
Print.logError("Account/Device DBException: " + accountID + " [" + dbe);
result = null;
}
} else {
// -- undefined
}
} else
if (Device.hasRuleFactory()) {
RuleFactory ruleFact = Device.getRuleFactory();
String selector = ruleFact.getRuleSelector(account, ruleID);
if (!StringTools.isBlank(selector)) {
try {
Object r = ruleFact.evaluateSelector(selector, account);
result = (r != null)? r : "";
} catch (RuleParseException rpe) {
Print.logException("Rule Selector: " + selector, rpe);
result = null;
}
} else {
// -- undefined
}
} else {
// -- undefined
}
// -- write Rule match state XML to client
CommonServlet.setResponseContentType(response, HTMLTools.MIME_XML(), StringTools.CharEncoding_UTF_8);
PrintWriter out = response.getWriter();
//Print.logInfo("Rule selector result: " + result);
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
if (result != null) {
out.println("<Result>"+result+"</Result>");
} else {
out.println("<Result/>");
}
out.close();
return;
}
/* do we have a 'trackPage'? */
if (trackPage == null) {
// -- occurs when 'pageName' is either blank or invalid
/* check user preference for first page after login */
if (!wasLoggedIn && (user != null) && user.hasFirstLoginPageID()) {
pageName = user.getFirstLoginPageID();
} else {
//pageName = PAGE_MENU_TOP;
pageName = privLabel.getStringProperty(PrivateLabel.PROP_Track_firstLoginPageID,PAGE_MENU_TOP);
}
/* get page */
trackPage = privLabel.getWebPage(pageName); // should not be null
if (trackPage == null) {
if (pageName.equals(PAGE_MENU_TOP)) {
Print.logError("[CRITICAL] Missing required page specification: '%s'", pageName);
String invalidPage = i18n.getString("Track.invalidPage","Unrecognized page requested: {0}",pageName);
Track.writeErrorResponse(reqState, invalidPage);
return;
} else {
Print.logError("Invalid page requested [%s], defaulting to '%s'", pageName, PAGE_MENU_TOP);
pageName = PAGE_MENU_TOP;
trackPage = privLabel.getWebPage(pageName);
if (trackPage == null) {
Print.logError("[CRITICAL] Missing required page specification: '%s'", pageName);
String invalidPage = i18n.getString("Track.invalidPage","Unrecognized page requested: {0}",pageName);
Track.writeErrorResponse(reqState, invalidPage);
return;
}
}
}
reqState.setPageName(pageName);
}
/* invalid page for ACL? */
if (!privLabel.hasReadAccess(user,trackPage.getAclName())) {
String userName = (user != null)? user.getUserID() : (User.getAdminUserID() + "?");
String aclName = trackPage.getAclName();
//Print.logWarn("User=%s, ACL=%s, Access=%s", userName, aclName, reqState.getAccessLevel(aclName));
String unauthPage = i18n.getString("Track.unauthPage","Unauthorized page requested: {0}",pageName);
Track.writeErrorResponse(reqState, unauthPage);
return;
}
/* default selected device group (if any) */
//if (StringTools.isBlank(groupID)) {
// groupID = DeviceGroup.DEVICE_GROUP_ALL;
//}
/* default selected device (if any) */
if ((user != null) && !StringTools.isBlank(deviceID)) {
try {
if (!user.isAuthorizedDevice(deviceID)) {
deviceID = null;
}
} catch (DBException dbe) {
deviceID = null;
}
}
if (!StringTools.isBlank(deviceID)) {
reqState.setSelectedDeviceID(deviceID, true);
} else {
try {
if (user != null) {
deviceID = user.getDefaultDeviceID(false); // already authorized
} else {
OrderedSet<String> d = Device.getDeviceIDsForAccount(accountID, null, false, 1);
deviceID = !ListTools.isEmpty(d)? d.get(0) : null;
}
} catch (DBException dbe) {
deviceID = null;
}
reqState.setSelectedDeviceID(deviceID, false);
}
/* default selected group (if any) */
if (User.isAdminUser(user)) {
// -- admin user
OrderedSet<String> g = reqState.getDeviceGroupIDList(true/*include'ALL'*/);
if (StringTools.isBlank(groupID)) {
groupID = !ListTools.isEmpty(g)? g.get(0) : DeviceGroup.DEVICE_GROUP_ALL;
} else
if (!ListTools.contains(g,groupID)) {
Print.logWarn("DeviceGroup list does not contain ID '%s'", groupID);
groupID = !ListTools.isEmpty(g)? g.get(0) : DeviceGroup.DEVICE_GROUP_ALL;
} else {
// -- groupID is fine as-is
}
} else {
// -- specific user
OrderedSet<String> g = reqState.getDeviceGroupIDList(true/*include'ALL'*/);
if (StringTools.isBlank(groupID)) {
groupID = !ListTools.isEmpty(g)? g.get(0) : null;
} else
if (!ListTools.contains(g,groupID)) {
Print.logWarn("DeviceGroup list does not contain ID '%s'", groupID);
groupID = !ListTools.isEmpty(g)? g.get(0) : null;
} else {
// -- groupID is fine as-is
}
}
reqState.setSelectedDeviceGroupID(groupID);
/* default selected driver (if any) */
if (!StringTools.isBlank(driverID)) {
reqState.setSelectedDriverID(driverID, true);
}
/* Account/User checks out, marked as logged in */
AttributeTools.setSessionAttribute(request, Constants.PARM_ACCOUNT , accountID);
AttributeTools.setSessionAttribute(request, Constants.PARM_USER , userID);
AttributeTools.setSessionAttribute(request, Constants.PARM_ENCPASS , entEncPass);
/* save preferred/selected device/group */
AttributeTools.setSessionAttribute(request, Constants.PARM_GROUP , groupID);
AttributeTools.setSessionAttribute(request, Constants.PARM_DEVICE , deviceID);
AttributeTools.setSessionAttribute(request, Constants.PARM_DRIVER , driverID);
/* make sure we have session sequence ID cached */
AttributeTools.GetSessionSequence(request);
/* login from "sysadmin"? */
//String relogin = AttributeTools.getRequestString(request, Constants.PARM_SA_RELOGIN, "");
//if (!StringTools.isBlank(relogin)) {
// AttributeTools.setSessionAttribute(request, Constants.PARM_SA_RELOGIN, relogin);
//}
//boolean isSysadminRelogin = RequestProperties.isLoggedInFromSysAdmin(request,privLabel);
/* set login times */
if (!wasLoggedIn) {
// -- new login for this account/user
boolean updLastLogin_user = RTConfig.getBoolean(DBConfig.PROP_track_updateLastLoginTime_user ,true);
boolean updLastLogin_account = RTConfig.getBoolean(DBConfig.PROP_track_updateLastLoginTime_account,true);
// -- last login time is now
long lastLoginTime = nowTimeSec;
// -- Last User login time
if (updLastLogin_user && (user != null)) {
// -- save prior login time [2.6.2-B59]
long priorUserLoginTime = user.getLastLoginTime();
AttributeTools.setSessionLong(request, Constants.PRIOR_USER_LOGIN, priorUserLoginTime);
if (!saLogin) { // [2.6.2-B59] !saLogin
// -- update last user login, and NOT login from sysadmin
try {
user.setLastLoginTime(lastLoginTime);
user.update(User.FLD_lastLoginTime); // anything else?
} catch (DBException dbe) {
Print.logException("Error saving LastLoginTime for user: " + accountID + "/" + userID, dbe);
// -- continue
}
}
}
// -- Last Account login time
if (updLastLogin_account) {
// -- save prior login time [2.6.2-B59]
long priorAccountLoginTime = account.getLastLoginTime();
AttributeTools.setSessionLong(request, Constants.PRIOR_ACCOUNT_LOGIN, priorAccountLoginTime);
// -- update last account login, and NOT login from sysadmin
if (!saLogin) { // [2.6.2-B59] !saLogin
try {
account.setLastLoginTime(lastLoginTime);
account.update(Account.FLD_lastLoginTime);
} catch (DBException dbe) {
Print.logException("Error saving LastLoginTime for account: " + accountID, dbe);
// -- continue
}
}
}
// -- audit login successful
Audit.userLoginOK(accountID, userID, ipAddr, bplName);
}
/* dispatch to page */
reqState.setPageNavigationHTML(trackPage.getPageNavigationHTML(reqState));
trackPage.writePage(reqState, "");
return;
}
/* display authentication state */
private static void _writeAuthenticateXML(
HttpServletResponse response,
boolean state)
throws IOException
{
CommonServlet.setResponseContentType(response, HTMLTools.MIME_XML(), StringTools.CharEncoding_UTF_8);
PrintWriter out = response.getWriter();
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.print("<authenticate>");
out.print(state?"true":"false");
out.print("</authenticate>");
out.print("\n");
out.close();
}
/* display login */
private static void _displayLogin(
RequestProperties reqState,
String msg,
boolean alert)
throws IOException
{
PrivateLabel privLabel = reqState.getPrivateLabel();
WebPage loginPage = privLabel.getWebPage(PAGE_LOGIN);
if ((loginPage instanceof AccountLogin) && ((AccountLogin)loginPage).hasCustomLoginURL()) {
HttpServletResponse response = reqState.getHttpServletResponse();
HttpServletRequest request = reqState.getHttpServletRequest();
String loginURL = ((AccountLogin)loginPage).getCustomLoginURL();
CommonServlet.setResponseContentType(response, HTMLTools.MIME_HTML());
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<META HTTP-EQUIV=\"refresh\" CONTENT=\"1; URL="+loginURL+"\"></META>");
out.println("</HTML>");
out.close();
} else
if (loginPage != null) {
reqState.setPageName(PAGE_LOGIN);
reqState.setPageNavigationHTML(loginPage.getPageNavigationHTML(reqState));
if (alert) {
reqState._setLoginErrorAlert();
}
//Print.logInfo("Writing login page ... " + StringTools.className(loginPage));
loginPage.writePage(reqState, msg);
} else {
Print.logError("Login page '"+PAGE_LOGIN+"' not found!");
I18N i18n = privLabel.getI18N(Track.class);
String noLogin = i18n.getString("Track.noLogin","Login page not available");
Track.writeErrorResponse(reqState, noLogin);
}
}
// ------------------------------------------------------------------------
// Simple error response
/* write message to stream */
public static void writeMessageResponse(
final RequestProperties reqState,
final String msg)
throws IOException
{
PrivateLabel privLabel = reqState.getPrivateLabel();
WebPage loginPage = privLabel.getWebPage(PAGE_LOGIN);
if (loginPage != null) {
//reqState.setPageName(PAGE_LOGIN);
reqState.setPageNavigationHTML(loginPage.getPageNavigationHTML(reqState));
} else {
//Print.logWarn("Login page not found.");
}
HTMLOutput HTML_CONTENT = new HTMLOutput(CommonServlet.CSS_MESSAGE, "") { // Content
public void write(PrintWriter out) throws IOException {
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(Track.class);
String baseURL = WebPageAdaptor.EncodeURL(reqState,new URIArg(RequestProperties.TRACK_BASE_URI()));
out.println(StringTools.replace(msg,"\n",StringTools.HTML_BR));
out.println("<hr>");
out.println("<a href=\"" + baseURL + "\">" + i18n.getString("Track.back","Back") + "</a>");
}
};
CommonServlet.writePageFrame(
reqState,
null,null, // onLoad/onUnload
HTMLOutput.NOOP, // Style sheets
HTMLOutput.NOOP, // JavaScript
null, // Navigation
HTML_CONTENT); // Content
}
/* write error response to stream */
public static void writeErrorResponse(
RequestProperties reqState,
String errMsg)
throws IOException
{
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(Track.class);
String error = i18n.getString("Track.error","ERROR:");
Track.writeMessageResponse(reqState, error + "\n" + errMsg);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/* debug: test page */
public static void main(String argv[])
throws IOException
{
//RTConfig.setCommandLineArgs(argv);
TimeZone tz = null;
DateTime fr = new DateTime(tz, 2008, RTConfig.getInt("m",6), 1);
DateTime to = new DateTime(tz, 2008, RTConfig.getInt("m",7), 1);
String acctId = "opendmtp";
String devId = "mobile";
// OutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter out = new PrintWriter(baos);
//writePage_Map(
// out,
// privLabel,
// acctId,
// devId, new String[] { devId },
// fr, to,
// Account.GetDefaultTimeZone(),
// lastEvent);
out.close(); // close (flush PrintWriter)
String s = new String(baos.toByteArray());
System.err.print(s);
}
}
| [
"Rodrigo@Rodrigo"
]
| Rodrigo@Rodrigo |
20aa67aca8d93ba1ba3ed14d4e07a52f9867d6f6 | 60feada88a66bf1c9a68a74ecf588c5dc9d42e1a | /src/main/java/com/bookerdimaio/scrabble/web/rest/AccountResource.java | 30a7ff96592af259e813a32b537640baf5c8edf1 | []
| no_license | cmavelis/scr-gate | a877c40aec4ec2c8cd97856289407905b020677a | be55a73622ac8bd0fd12e9b8ec88fc201eb6231a | refs/heads/master | 2022-12-24T22:32:37.880800 | 2019-08-22T16:18:40 | 2019-08-22T16:18:40 | 204,721,722 | 0 | 0 | null | 2022-12-16T05:03:16 | 2019-08-27T14:30:35 | TypeScript | UTF-8 | Java | false | false | 7,566 | java | package com.bookerdimaio.scrabble.web.rest;
import com.bookerdimaio.scrabble.domain.User;
import com.bookerdimaio.scrabble.repository.UserRepository;
import com.bookerdimaio.scrabble.security.SecurityUtils;
import com.bookerdimaio.scrabble.service.MailService;
import com.bookerdimaio.scrabble.service.UserService;
import com.bookerdimaio.scrabble.service.dto.PasswordChangeDTO;
import com.bookerdimaio.scrabble.service.dto.UserDTO;
import com.bookerdimaio.scrabble.web.rest.errors.*;
import com.bookerdimaio.scrabble.web.rest.vm.KeyAndPasswordVM;
import com.bookerdimaio.scrabble.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private static class AccountResourceException extends RuntimeException {
private AccountResourceException(String message) {
super(message);
}
}
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
private final UserRepository userRepository;
private final UserService userService;
private final MailService mailService;
public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) {
this.userRepository = userRepository;
this.userService = userService;
this.mailService = mailService;
}
/**
* {@code POST /register} : register the user.
*
* @param managedUserVM the managed user View Model.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
*/
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
if (!checkPasswordLength(managedUserVM.getPassword())) {
throw new InvalidPasswordException();
}
User user = userService.registerUser(managedUserVM, managedUserVM.getPassword());
mailService.sendActivationEmail(user);
}
/**
* {@code GET /activate} : activate the registered user.
*
* @param key the activation key.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated.
*/
@GetMapping("/activate")
public void activateAccount(@RequestParam(value = "key") String key) {
Optional<User> user = userService.activateRegistration(key);
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this activation key");
}
}
/**
* {@code GET /authenticate} : check if the user is authenticated, and return its login.
*
* @param request the HTTP request.
* @return the login if the user is authenticated.
*/
@GetMapping("/authenticate")
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
/**
* {@code GET /account} : get the current user.
*
* @return the current user.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned.
*/
@GetMapping("/account")
public UserDTO getAccount() {
return userService.getUserWithAuthorities()
.map(UserDTO::new)
.orElseThrow(() -> new AccountResourceException("User could not be found"));
}
/**
* {@code POST /account} : update the current user information.
*
* @param userDTO the current user information.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found.
*/
@PostMapping("/account")
public void saveAccount(@Valid @RequestBody UserDTO userDTO) {
String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found"));
Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) {
throw new EmailAlreadyUsedException();
}
Optional<User> user = userRepository.findOneByLogin(userLogin);
if (!user.isPresent()) {
throw new AccountResourceException("User could not be found");
}
userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(),
userDTO.getLangKey(), userDTO.getImageUrl());
}
/**
* {@code POST /account/change-password} : changes the current user's password.
*
* @param passwordChangeDto current and new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect.
*/
@PostMapping(path = "/account/change-password")
public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) {
if (!checkPasswordLength(passwordChangeDto.getNewPassword())) {
throw new InvalidPasswordException();
}
userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword());
}
/**
* {@code POST /account/reset-password/init} : Send an email to reset the password of the user.
*
* @param mail the mail of the user.
* @throws EmailNotFoundException {@code 400 (Bad Request)} if the email address is not registered.
*/
@PostMapping(path = "/account/reset-password/init")
public void requestPasswordReset(@RequestBody String mail) {
mailService.sendPasswordResetMail(
userService.requestPasswordReset(mail)
.orElseThrow(EmailNotFoundException::new)
);
}
/**
* {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
*
* @param keyAndPassword the generated key and the new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset.
*/
@PostMapping(path = "/account/reset-password/finish")
public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {
if (!checkPasswordLength(keyAndPassword.getNewPassword())) {
throw new InvalidPasswordException();
}
Optional<User> user =
userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey());
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this reset key");
}
}
private static boolean checkPasswordLength(String password) {
return !StringUtils.isEmpty(password) &&
password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH &&
password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH;
}
}
| [
"[email protected]"
]
| |
7df7157f1854359f59ab75a0b8996125d2f027bd | dda1ec3135f07a166feee115aa66bf60a630fbf9 | /src/com/ecwork/great/common/Ref.java | c43777388dd4d48b99fd46b12adda96321f1834b | []
| no_license | ecsark/great | a0a2dead3b177af0877dab8328cc71cd0686a599 | e44f1f02f1f694cde430a96e692625229797eccf | refs/heads/master | 2021-01-22T10:02:37.106760 | 2014-02-18T03:23:51 | 2014-02-18T03:23:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 167 | java | package com.ecwork.great.common;
/**
* User: ecsark
* Date: 2/11/14
* Time: 2:08 PM
*/
public final class Ref {
public static final int TYPE_UNDEFINED = 0;
}
| [
"[email protected]"
]
| |
86aa5126043644e070e9e2b7d8acc0f3d1ffbb5a | abe0810e22ecc6fb0138e8b8f1849ed324bd9229 | /imno/src/kr/btms/btms_control.java | 291d41267f8723c37726fa4c3e06b8ad87978689 | []
| no_license | imimnono/imimnono | 80888eb28f96799c3fa2c3e00931faf81dda137b | 75639695b6f78c7e6102f24da48187db6c800c6e | refs/heads/master | 2023-01-20T03:12:42.187960 | 2020-11-12T08:03:16 | 2020-11-12T08:03:16 | 307,278,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,882 | java | package kr.btms;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class btms_control
*/
@WebServlet("/btms_control")
public class btms_control extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public btms_control() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
RequestDispatcher dsp = request.getRequestDispatcher("login.jsp");
dsp.forward(request, response);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"USER506-06@DESKTOP-S3KOM5P"
]
| USER506-06@DESKTOP-S3KOM5P |
4e67f152dc81bb66e3d7a54223b51e644bab02f9 | ee54576ff8996536f2f753e71221f768c478efb2 | /src/main/java/io/github/pascalgrimaud/testjhipsteronline/config/CloudDatabaseConfiguration.java | 3998ade32d0f53e2e8316a4f7695ec55c8606740 | []
| no_license | pascalgrimaud/TestJhipsterOnlineGateway | 6e3777f9430ce02d28871137f8c4925e31b06dd5 | 810f9c5d256ddb8116b348cc3d7d58f1e62488f4 | refs/heads/master | 2021-01-01T15:28:45.538925 | 2017-07-18T17:51:02 | 2017-07-18T17:51:02 | 97,627,598 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 789 | java | package io.github.pascalgrimaud.testjhipsteronline.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
@Bean
public DataSource dataSource(CacheManager cacheManager) {
log.info("Configuring JDBC datasource from a cloud provider");
return connectionFactory().dataSource();
}
}
| [
"[email protected]"
]
| |
ad2e41c79fdd317d31a24315ef9a5c79d22cbb2e | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/22/22_6caad68434a7ed0c1dd2c04a408d0120751df500/ClusterConnectionControl2Test/22_6caad68434a7ed0c1dd2c04a408d0120751df500_ClusterConnectionControl2Test_t.java | 38afea3c503089aebc274729ebe987329568cdf3 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 8,951 | java | /*
* Copyright 2009 Red Hat, Inc.
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.hornetq.tests.integration.management;
import static org.hornetq.tests.util.RandomUtil.randomBoolean;
import static org.hornetq.tests.util.RandomUtil.randomPositiveInt;
import static org.hornetq.tests.util.RandomUtil.randomPositiveLong;
import static org.hornetq.tests.util.RandomUtil.randomString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
import org.hornetq.core.config.Configuration;
import org.hornetq.core.config.TransportConfiguration;
import org.hornetq.core.config.cluster.BroadcastGroupConfiguration;
import org.hornetq.core.config.cluster.ClusterConnectionConfiguration;
import org.hornetq.core.config.cluster.DiscoveryGroupConfiguration;
import org.hornetq.core.config.cluster.QueueConfiguration;
import org.hornetq.core.config.impl.ConfigurationImpl;
import org.hornetq.core.management.ClusterConnectionControl;
import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
import org.hornetq.core.server.HornetQ;
import org.hornetq.core.server.HornetQServer;
import org.hornetq.integration.transports.netty.NettyAcceptorFactory;
import org.hornetq.integration.transports.netty.NettyConnectorFactory;
import org.hornetq.integration.transports.netty.TransportConstants;
import org.hornetq.utils.Pair;
import org.hornetq.utils.json.JSONArray;
import org.hornetq.utils.json.JSONObject;
/**
* A BridgeControlTest
*
* @author <a href="[email protected]">Jeff Mesnil</a>
*
* Created 11 dec. 2008 17:38:58
*
*/
public class ClusterConnectionControl2Test extends ManagementTestBase
{
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
private HornetQServer server_0;
private HornetQServer server_1;
private MBeanServer mbeanServer_1;
private int port_1 = TransportConstants.DEFAULT_PORT + 1000;
private ClusterConnectionConfiguration clusterConnectionConfig_0;
private String clusterName = "cluster";
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
public void testNodes() throws Exception
{
ClusterConnectionControl clusterConnectionControl_0 = createManagementControl(clusterConnectionConfig_0.getName());
assertTrue(clusterConnectionControl_0.isStarted());
Map<String, String> nodes = clusterConnectionControl_0.getNodes();
assertEquals(0, nodes.size());
server_1.start();
long start = System.currentTimeMillis();
while (true)
{
nodes = clusterConnectionControl_0.getNodes();
if (nodes.size() != 1 && System.currentTimeMillis() - start < 30000)
{
Thread.sleep(100);
}
else
{
break;
}
}
assertEquals(1, nodes.size());
String remoteAddress = nodes.values().iterator().next();
assertTrue(remoteAddress.endsWith(":" + port_1));
}
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
@Override
protected void setUp() throws Exception
{
super.setUp();
String discoveryName = randomString();
String groupAddress = "231.7.7.7";
int groupPort = 9876;
Map<String, Object> acceptorParams_1 = new HashMap<String, Object>();
acceptorParams_1.put(TransportConstants.PORT_PROP_NAME, port_1);
TransportConfiguration acceptorConfig_1 = new TransportConfiguration(NettyAcceptorFactory.class.getName(), acceptorParams_1);
TransportConfiguration connectorConfig_1 = new TransportConfiguration(NettyConnectorFactory.class.getName(),
acceptorParams_1);
TransportConfiguration connectorConfig_0 = new TransportConfiguration(NettyConnectorFactory.class.getName());
QueueConfiguration queueConfig = new QueueConfiguration(randomString(), randomString(), null, false);
clusterConnectionConfig_0 = new ClusterConnectionConfiguration(clusterName,
queueConfig.getAddress(),
randomPositiveLong(),
randomBoolean(),
randomBoolean(),
randomPositiveInt(),
discoveryName);
List<Pair<String, String>> connectorInfos = new ArrayList<Pair<String, String>>();
connectorInfos.add(new Pair<String, String>("netty", null));
BroadcastGroupConfiguration broadcastGroupConfig = new BroadcastGroupConfiguration(discoveryName,
null,
-1,
groupAddress,
groupPort,
250,
connectorInfos);
DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration(discoveryName,
groupAddress,
groupPort,
ClientSessionFactoryImpl.DEFAULT_DISCOVERY_REFRESH_TIMEOUT);
Configuration conf_1 = new ConfigurationImpl();
conf_1.setSecurityEnabled(false);
conf_1.setJMXManagementEnabled(true);
conf_1.setClustered(true);
conf_1.getAcceptorConfigurations().add(acceptorConfig_1);
conf_1.getConnectorConfigurations().put("netty", connectorConfig_1);
conf_1.getQueueConfigurations().add(queueConfig);
conf_1.getDiscoveryGroupConfigurations().put(discoveryName, discoveryGroupConfig);
conf_1.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
Configuration conf_0 = new ConfigurationImpl();
conf_0.setSecurityEnabled(false);
conf_0.setJMXManagementEnabled(true);
conf_0.setClustered(true);
conf_0.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
conf_0.getConnectorConfigurations().put("netty", connectorConfig_0);
conf_0.getClusterConfigurations().add(clusterConnectionConfig_0);
conf_0.getDiscoveryGroupConfigurations().put(discoveryName, discoveryGroupConfig);
conf_0.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
mbeanServer_1 = MBeanServerFactory.createMBeanServer();
server_1 = HornetQ.newHornetQServer(conf_1, mbeanServer_1, false);
server_0 = HornetQ.newHornetQServer(conf_0, mbeanServer, false);
server_0.start();
}
@Override
protected void tearDown() throws Exception
{
server_0.stop();
server_1.stop();
server_0 = null;
server_1 = null;
MBeanServerFactory.releaseMBeanServer(mbeanServer_1);
mbeanServer_1 = null;
super.tearDown();
}
protected ClusterConnectionControl createManagementControl(String name) throws Exception
{
return ManagementControlHelper.createClusterConnectionControl(name, mbeanServer);
}
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| [
"[email protected]"
]
| |
ccb75e3ee152d9122c2b0e3ebea2dd592d770185 | eba216fa612e1eeeb70602837a183cdc7ee67413 | /src/main/java/com/aripd/project/lgk/model/EmployeeworkinghourReportModel.java | f172cff83e906ce9ea85d04148b428f9a90ea5f5 | []
| no_license | 2325407504/lokman | 45ba72e96861c76c6f1ee797e9f9faede0b69289 | 41b726205b5429521c6b2cafadfdb6adbd8799be | refs/heads/master | 2016-09-10T12:06:22.200780 | 2013-08-01T10:55:07 | 2013-08-01T10:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 611 | java | package com.aripd.project.lgk.model;
import java.util.Date;
public class EmployeeworkinghourReportModel {
private Date date;
private Integer qualified;
private Integer used;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getQualified() {
return qualified;
}
public void setQualified(Integer qualified) {
this.qualified = qualified;
}
public Integer getUsed() {
return used;
}
public void setUsed(Integer used) {
this.used = used;
}
}
| [
"[email protected]"
]
| |
1cf99ad6c3632712a758cc57709b86ca2db2a06a | 8aeb36e0dd28acf43dd4b32f8cba5bf66a6f0bf4 | /VendingMachineSpringDI/src/main/java/com/sg/vendingmachine/App.java | 89aad9d62851a22f000d765629d7c48da631801c | []
| no_license | shaehamm/VendingMachine | 33143cbf0e345d30b5d818033cd623fa5942f32d | fcfa1d667423e155fb82a971d1ae1a5e864179f3 | refs/heads/master | 2022-11-24T02:25:51.421744 | 2020-07-29T19:30:54 | 2020-07-29T19:30:54 | 283,585,292 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,243 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sg.vendingmachine;
import com.sg.vendingmachine.controller.VendingMachineController;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;
/**
*
* @author codedchai
*/
public class App {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext appContext =
new AnnotationConfigApplicationContext();
appContext.getEnvironment().getPropertySources().addFirst
(new ResourcePropertySource(new ClassPathResource("application.properties")));
appContext.scan("com.sg.vendingmachine");
appContext.refresh();
VendingMachineController controller =
appContext.getBean("vendingMachineController",
VendingMachineController.class);
//runs the program
controller.run();
}
}
| [
"[email protected]"
]
| |
da8257432e17dd0ad6340abc7653cad053e86d39 | 7e4a0c6f5714a7b0c52a682350e24cd1d74d52bc | /src/main/java/com/elearning/controller/pub/EosOperatorController.java | dbc619b33673b37ac5ff84cdaa99cc237cb54b9e | []
| no_license | guoshenshen/mygitworktest | 3cd5698f853fd8a8a289e0f4b6b394774ffed86a | 467779c19dc6aed2efea133526a467953f8d8f54 | refs/heads/master | 2022-12-17T10:00:41.931982 | 2020-03-20T14:45:36 | 2020-03-20T14:45:36 | 248,735,256 | 0 | 0 | null | 2022-12-16T03:07:40 | 2020-03-20T11:07:42 | JavaScript | UTF-8 | Java | false | false | 4,080 | java | package com.elearning.controller.pub;
import com.elearning.common.Constants;
import com.elearning.common.ServiceResponse;
import com.elearning.pojo.pub.EosOperator;
import com.elearning.pojo.systemManage.Tenant;
import com.elearning.service.pub.IEosOperatorService;
import com.elearning.service.systemManage.ITenantService;
import com.elearning.vo.BasicUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
@Controller
@RequestMapping("/eosOperator/")
public class EosOperatorController {
@Autowired
private IEosOperatorService eosOperatorService;
@Autowired
private ITenantService tenantService;
@RequestMapping("getEosOperatorServiceByID.do")
@ResponseBody
public ServiceResponse getEosOperatorServiceByID(Integer ID, Model model){
EosOperator eosOperator = eosOperatorService.selectByPrimaryKey(ID);
return ServiceResponse.createBySuccess(eosOperator);
}
//判断用户是否已经登录,并返回最基本信息(当前平台tenantId,tenantName,若用户已经登录,则返回该用户的基本信息userForm
@RequestMapping("hasLogined.do")
@ResponseBody
public ServiceResponse hasLogined(HttpServletRequest request){
Map<String,Object> resultMap = new HashMap<>();
// 获取当前登录租户平台信息
Integer currentTenantId = Constants.tenantId;
if(currentTenantId == null || currentTenantId == 0){
currentTenantId = 6;
}
Tenant currentTenant = this.tenantService.findById(currentTenantId);
resultMap.put("tenantId",currentTenantId);
resultMap.put("tenantName",currentTenant.getTenantName());
// 如果用户登录则获取当前用户基本信息
EosOperator eosoperator = (EosOperator)request.getSession().getAttribute(Constants.USERINFO_KEY);
if (eosoperator != null) {
List<Integer> operatorIds = new ArrayList<>();
operatorIds.add(eosoperator.getOperatorId());
List<BasicUserVo> userForms = this.eosOperatorService.findBasicUserInfoById(operatorIds, currentTenantId);
if (userForms != null && userForms.size() > 0) {
resultMap.put("userForm",userForms.get(0));
}
Tenant operatorTenant = this.tenantService.findById(eosoperator.getTenantId());
if (operatorTenant.getWorkingStatus() == null || operatorTenant.getWorkingStatus().equals((short) 0)) {
resultMap.put("showVersionChange",false);
} else {
if (operatorTenant.getIsRedirectToPortalWeb().equals(1) && (currentTenantId == 1000 || currentTenant.getIsRedirectToPortalWeb().equals(1))) {
resultMap.put("showVersionChange",true);
} else {
resultMap.put("showVersionChange",false);
}
}
resultMap.put("userTenant",eosoperator.getTenantId());
}
return ServiceResponse.createBySuccess(resultMap);
}
/**
* 判断当前操作人员是否处于在线状态
* @param request
* @return
*/
@RequestMapping("ifOnline.do")
@ResponseBody
public ServiceResponse ifOnline(HttpServletRequest request){
Map<String,Object> resultMap = new HashMap<>();
if (request.getSession().getAttribute(Constants.USERINFO_KEY) != null) {
EosOperator operator = (EosOperator) request.getSession().getAttribute(Constants.USERINFO_KEY);
resultMap.put("operatorId",operator.getOperatorId());
} else {
resultMap.put("operatorId",-1);
}
return ServiceResponse.createBySuccess(resultMap);
}
}
| [
"[email protected]"
]
| |
fdf79cd66cf920edc42d01dda8951a9213300f04 | 01d1894d308871e68adc97af2897606057131114 | /src/main/java/tr/com/tandempartner/tandem/entity/user/LanguageOption.java | 85b7065f0f609253bc15e2085ad40c68da18c6e3 | []
| no_license | EnginAkin/ChatSee | e8bd04581111d340e34d7212b18396663fddd350 | 2d10d026615cbbeb4719bbd694b9f83a53696126 | refs/heads/main | 2023-09-01T03:52:45.864038 | 2021-09-12T18:17:22 | 2021-09-12T18:17:22 | 405,607,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 428 | java | package tr.com.tandempartner.tandem.entity.user;
import java.io.Serializable;
public enum LanguageOption implements Serializable{
EN("EN","English"),
TR("TR","Turkish"),
DEU("DEU","Deutch"),
FR("FR","FRENCH");
LanguageOption(String code, String name) {
}
LanguageOption(String code) {
LanguageOption.valueOf(code);
}
LanguageOption getLanguageOption(String code){
return LanguageOption.valueOf(code);
}
}
| [
"[email protected]"
]
| |
65841907edd38fb9244a95c90ad5e61177e098f9 | 19c34f0707020dbe15afbbf1e4e3759aec6e15af | /order-management-orders/src/main/java/com/ordermanagement/orders/extservice/OrderItemClient.java | 621f6f98c3cbae296221d86935fc7a32afa6a200 | []
| no_license | Abinash4656/order-management | 2d851a8bdfef2bf9ebd53fae41f71f88e45a353b | 1d2766aa8f25a7c0e08f935a23bc7c2476f47e7c | refs/heads/master | 2022-12-14T22:32:52.046618 | 2020-08-30T17:57:55 | 2020-08-30T17:57:55 | 291,516,214 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package com.ordermanagement.orders.extservice;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.ordermanagement.orders.requestatributes.ItemRequest;
@FeignClient(url = "http://localhost:8080",name = "ITEMS")
public interface OrderItemClient {
@GetMapping(value = "/items")
public List<ItemResponse> getAllItems();
@PostMapping(value = "/items")
public String saveItems(List<ItemRequest> ItemRequests);
@GetMapping(value = "/item/{productId}")
public ItemResponse getItemById(@PathVariable(value = "productId") Integer productId);
}
| [
"[email protected]"
]
| |
c5f8045d06ccbc9678d9c25e013ccda29b1b7a48 | 85f32f2267b3d5e7846a028e00ce1bc13b5e22d3 | /Unique Paths/src/Main.java | 073b0ec2bfbc8ce7209c3c3c90973f49f72db649 | []
| no_license | ChiJiuJiu/JAVA | 85b0c01304fbbf20d6ec078911bbf740656d6a9d | 3891af9a3a38501cfab59c9c49907d1512ffb138 | refs/heads/master | 2021-06-16T17:51:05.105267 | 2019-09-13T02:43:36 | 2019-09-13T02:43:36 | 141,991,992 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,165 | java | <<<<<<< HEAD
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
//动态规划
class Solution {
public int uniquePaths(int m, int n) {
int i,j;
int [][] a = new int[n][m];
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
if(i == 0 || j == 0)
a[i][j] = 1;
else
a[i][j] = a[i-1][j] + a[i][j-1];
}
}
return a[n-1][m-1];
}
}
//优化版本 组合数
class Solution2 {
public int uniquePaths(int m, int n) {
double dom = 1;
double dedom = 1;
int small = m<n? m-1:n-1;
int big = m<n? n-1:m-1;
for(int i=1;i<=small;i++)
{
dedom *= i;
dom *= small+big+1-i;
}
return (int)(dom/dedom);
// ---------------------
// 作者:Code_Ganker
// 来源:CSDN
// 原文:https://blog.csdn.net/linhuanmars/article/details/22126357
// 版权声明:本文为博主原创文章,转载请附上博文链接!
}
=======
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
//动态规划
class Solution {
public int uniquePaths(int m, int n) {
int i,j;
int [][] a = new int[n][m];
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
if(i == 0 || j == 0)
a[i][j] = 1;
else
a[i][j] = a[i-1][j] + a[i][j-1];
}
}
return a[n-1][m-1];
}
}
//优化版本 组合数
class Solution2 {
public int uniquePaths(int m, int n) {
double dom = 1;
double dedom = 1;
int small = m<n? m-1:n-1;
int big = m<n? n-1:m-1;
for(int i=1;i<=small;i++)
{
dedom *= i;
dom *= small+big+1-i;
}
return (int)(dom/dedom);
// ---------------------
// 作者:Code_Ganker
// 来源:CSDN
// 原文:https://blog.csdn.net/linhuanmars/article/details/22126357
// 版权声明:本文为博主原创文章,转载请附上博文链接!
}
>>>>>>> a8a83698f7e43fa083c63e8090a315f562686894
} | [
"[email protected]"
]
| |
1624951af2cfea18266132ba7e7042c3e282a841 | cd98bdda22d3c2f1f59bb0504782fd4a27c71c6c | /addressbook-web-tests/src/test/java/ru/training/addressbook/tests/ContactAddToGroupTest.java | 657886114b9c74a194aba28ccfa268afb31ea7f2 | [
"Apache-2.0"
]
| permissive | e-davydenkova/Java_training | bc0a0e3872812ac8fbeb786346f0489a5f840521 | ec715440127b1e5fce22286e7204c64da248806d | refs/heads/master | 2021-09-06T14:04:47.117085 | 2018-02-07T09:32:52 | 2018-02-07T09:32:52 | 112,183,513 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,425 | java | package ru.training.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.training.addressbook.model.ContactData;
import ru.training.addressbook.model.Contacts;
import ru.training.addressbook.model.GroupData;
import ru.training.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactAddToGroupTest extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
if (app.db().contacts().size() == 0) {
app.goTo().homePage();
app.contact().create(new ContactData().withFirstName("First name"), true);
}
if (app.db().groups().size() == 0) {
app.goTo().groupPage();
app.group().create(new GroupData().withName("test1"));
}
Boolean canAdd = false;
for (ContactData c : app.db().contacts()) {
if (c.getGroups().size() < app.db().groups().size()) {
canAdd = true;
break;
}
}
if (!canAdd) {
app.goTo().groupPage();
app.group().create(new GroupData().withName("test2"));
}
}
@Test
public void testContactAddToGroup() {
Contacts contacts = app.db().contacts();
Groups groupsDB = app.db().groups();
ContactData modifiedContact = new ContactData();
// ContactData modifiedContact = app.db().contacts().iterator().next();
for (ContactData c : contacts) {
if (c.getGroups().size() < groupsDB.size()) {
modifiedContact = c;
break;
}
}
Assert.assertFalse(modifiedContact.getId() == Integer.MAX_VALUE, "All contacts are connected to all groups");
Contacts before = app.db().contacts();
GroupData groupAddTo = new GroupData();
for (GroupData group : groupsDB) {
if (!modifiedContact.getGroups().contains(group)) {
groupAddTo = group;
app.goTo().homePage();
app.contact().addToGroup(modifiedContact, groupAddTo.getName());
break;
}
}
Contacts after = app.db().contacts();
assertThat(after, equalTo(before.without(modifiedContact).withAdded(modifiedContact.inGroup(groupAddTo))));
}
}
| [
"[email protected]"
]
| |
cad58d69b228480adc7213c70f7fa6d7711cedd3 | 2c0eda1138061c878aaa5b8831e8556d332b2a63 | /src/com/edu/fireeyes/adapter/CompanyBaseInformListViewAdapter.java | e095646c9865dc23c47bcdd651c32ebc18e91172 | [
"Apache-2.0"
]
| permissive | cf0566/FireEyes | 67debfb095132030bec5457e38bb7a1fbf701fee | 284f5b2140cb20ab8243642ef357aecf3d42948f | refs/heads/master | 2021-01-10T13:31:42.834244 | 2016-01-26T11:33:06 | 2016-01-26T11:33:06 | 49,318,081 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,568 | java | package com.edu.fireeyes.adapter;
import java.util.ArrayList;
import java.util.List;
import com.edu.fireeyes.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class CompanyBaseInformListViewAdapter extends BaseAdapter{
private static final int TYPE_TTTLE = 0;
private static final int TYPE_CONTENT= 1;
private static final int TYPE_COUNT = 2;
private List<String> datas = new ArrayList<String>();
private Context context;
public CompanyBaseInformListViewAdapter(Context context) {
this.context = context;
}
public void setDatas(List<String> datas){
this.datas = datas;
}
// @Override
// public int getItemViewType(int position) {
//
// if (data.get(position).getType().equals("title")) {
// return TYPE_TTTLE;
// }else{
// return TYPE_CONTENT;
// }
//
// }
//
// @Override
// public int getViewTypeCount() {
// return TYPE_COUNT;
// }
//
@Override
public int getCount() {
return datas == null ? 0 :datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
// if (type == TYPE_TTTLE) {
// convertView = View.inflate(context,R.layout.item_company_base_inform_listview_title, null);
// holder.tvTitle = (TextView) convertView.findViewById(R.id.item_company_base_inform_listview_tv_title);
// }else if (type == TYPE_CONTENT){
convertView = View.inflate(context,R.layout.item_company_base_inform_listview_context, null);
holder.tvContent = (TextView) convertView.findViewById(R.id.item_company_base_inform_listview_tv_name);
holder.etContent = (EditText) convertView.findViewById(R.id.item_company_base_inform_listview_et_content);
// }
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// if (type == TYPE_TTTLE) {
// holder.tvTitle.setText("小测试");
// }else if (type == TYPE_CONTENT) {
holder.tvContent.setText(datas.get(position));
// }
return convertView;
}
class ViewHolder{
TextView tvContent,tvTitle;
EditText etContent;
}
}
| [
"[email protected]"
]
| |
5260720f8b6b73d410ddfc314cfcc6a6409bcad7 | 548319494133d9e25b32a7ae010a7b5ab066c832 | /app/src/main/java/com/just/test/activity/DistinguishErCode.java | fbd599e69de24e8c896965f1639461ebd1a44ce1 | []
| no_license | xinshengBoy/JavaTest1 | c7b1509190ca000dc5a9d5fde4764ccfd47808c9 | 25280bf4c1b08f16ea3e4a35d9f5a671c436ef06 | refs/heads/master | 2022-11-19T00:54:21.458811 | 2020-07-17T02:46:25 | 2020-07-17T02:46:25 | 280,298,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,059 | java | package com.just.test.activity;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.bolex.pressscan.ScanTools;
import com.just.test.R;
import com.just.test.widget.MyActionBar;
import net.lemonsoft.lemonbubble.LemonBubble;
/**
* 长按识别二维码
* 参考网址:http://p.codekk.com/detail/Android/BolexLiu/PressScanCode
* https://github.com/BolexLiu/PressScanCode
* compile 'com.github.BolexLiu:PressScanCode:v1.0.0'
* Created by admin on 2017/6/3.
*/
public class DistinguishErCode extends Activity {
private EditText et_distinguish;
private ImageView iv_distinguish;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_distinguish_ercode);
//// TODO: 2016/12/21 actionbar
LinearLayout headerLayout = (LinearLayout) findViewById(R.id.headerLayout);
Bundle bundle = new Bundle();
bundle.putBoolean("back", true);
bundle.putString("leftText", null);
bundle.putString("title", " 长按识别二维码");
bundle.putBoolean("rightImage", false);
bundle.putString("rightText", null);
MyActionBar.actionbar(this, headerLayout, bundle);
initView();
}
private void initView(){
et_distinguish = (EditText)findViewById(R.id.et_distinguish);
Button btn_distinguish_check = (Button) findViewById(R.id.btn_distinguish_check);
iv_distinguish = (ImageView)findViewById(R.id.iv_distinguish);
btn_distinguish_check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String input = et_distinguish.getText().toString();
if (input.equals("")){
LemonBubble.showError(DistinguishErCode.this,"请输入内容",1000);
return;
}
LemonBubble.showRoundProgress(DistinguishErCode.this, "加载中");
createErCode(input);
}
});
//使用方法
iv_distinguish.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
ScanTools.scanCode(view, new ScanTools.ScanCall() {
@Override
public void getCode(String s) {
LemonBubble.showRight(DistinguishErCode.this,s,5000);
}
});
return true;
}
});
}
private void createErCode(String msg){
Bitmap bitmap = QRCode.createQRImage(msg);
iv_distinguish.setImageBitmap(bitmap);
LemonBubble.hide();
}
@Override
protected void onDestroy() {
super.onDestroy();
LemonBubble.forceHide();
}
}
| [
"[email protected]"
]
| |
e79af78ffe9e1a6afa57f66940d8c831f329d1e6 | fab5327dd092b90ebb5c6116116f7d338319c85f | /app/src/androidTest/java/minhasanotacoes/studio/com/minhasanotacoes/ExampleInstrumentedTest.java | 8a66869e6f52645bbcda944e2c093cad7f5b9d59 | []
| no_license | leopdonato/MinhasAnotacoes | a9cbf1a6052d71ae060353f579cd5240d633fc62 | 19525199f7c1726c409ab5d4f85db6ea0bf57d7e | refs/heads/master | 2020-04-01T05:38:55.960610 | 2018-10-13T20:50:07 | 2018-10-13T20:50:07 | 152,913,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 768 | java | package minhasanotacoes.studio.com.minhasanotacoes;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("minhasanotacoes.studio.com.minhasanotacoes", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
ee5c276269ea903c8a9b7fee46c5bd1592b6d414 | 98d3af9d3cac9891567daeca5f60b20c7f179fe8 | /DBDiscos/app/src/main/java/com/example/jmalberola/dbdiscos/MainActivity.java | 5f563f79d0d94442f271a5a02f6e391965b0baf0 | []
| no_license | AlejandroSantacatalinaP/Android | acb806e30955ad0ebf84f7ed7594213d6970d70f | 70963e725933f06e071291f7616bebcfcd7270b4 | refs/heads/master | 2020-06-13T07:08:20.571704 | 2016-01-29T08:44:44 | 2016-01-29T08:44:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,329 | java | package com.example.jmalberola.dbdiscos;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
private MyDBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter = new MyDBAdapter(this);
dbAdapter.open();
dbAdapter.insertarDisco("Redeemer of Souls", 2014);
dbAdapter.insertarDisco("Land of the Free", 1995);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
]
| |
1229442f313d4947ef8dd01243dfb780eb1be0fc | 2bf5795edd9031c0da7909724839a16147176ffc | /test/system/SpaceTest.java | a822d6e477a244eafd5696d04f9828f16e2a7b46 | []
| no_license | guys79/QA_ASS2 | e2f559fe1787c7d13cbdff8f12d6bab2ffcec5dd | b46624c673a31abf7cae132cc584c69191587e39 | refs/heads/master | 2020-11-30T01:55:08.220277 | 2019-12-31T14:13:22 | 2019-12-31T14:13:22 | 230,267,905 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,671 | java | package system;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.junit.Assert.*;
/**
* This class is responsible to test the Space class
*/
public class SpaceTest {
private Random rand;//The random variable
private final int BOUND = 100; //The maximal random number
/**
* This function will initialize the Random variable
*/
@Before
public void initialize() {
rand = new Random();
}
/**
* This function checks the creation of a Space instance
*/
@Test
public void checkCreation()
{
int size = rand.nextInt(this.BOUND) + 1;
Space space = new Space(size);
assertEquals(size,space.countFreeSpace());
Leaf [] blocks = space.getAlloc();
assertEquals(size,blocks.length);
}
/**
* This function will check the countFreeSpace function
* This function will create multiple instances of files in variety of sizes
* And will check the number of free space after each allocation
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void allocFreeSpace() throws OutOfSpaceException {
//For a random number of iterations
int iter = rand.nextInt(this.BOUND) + 1;
int [] sizes = new int[iter];
int spaceSize =0;
//Create random file sizes
for(int k= 0;k<sizes.length;k++) {
sizes[k] = rand.nextInt(this.BOUND) + 1;
spaceSize+=sizes[k];
}
Leaf leaf;
String fileName = "fileName";
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
int sum = 0;
//Check the allocation of the random files
for(int i=0;i<iter;i++) {
leaf = new Leaf(fileName, sizes[i]);
sum +=sizes[i];
assertEquals(space.countFreeSpace(), spaceSize - sum);
}
}
/**
* This function will check the allocation procedure
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void allocCheck() throws OutOfSpaceException {
//For a random number of iterations
int iter = rand.nextInt(this.BOUND) + 1;
int [] sizes = new int[iter];
int spaceSize =0;
//Create random file sizes
for(int k= 0;k<sizes.length;k++) {
sizes[k] = rand.nextInt(this.BOUND) + 1;
spaceSize+=sizes[k];
}
Leaf leaf;
String fileName = "fileName";
spaceSize = spaceSize + 1 +rand.nextInt(BOUND);
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
//Check the allocation of the random files
for(int i=0;i<iter;i++) {
leaf = new Leaf(fileName, sizes[i]);
Leaf[] blocks = space.getAlloc();
int count = 0;
for (int j = 0; j < blocks.length; j++) {
if (blocks[j] == leaf)
count++;
}
assertEquals(count, sizes[i]);
}
}
/**
* This function will check the case when we will try to allocate space when there is no more
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test(expected = OutOfSpaceException.class)
public void allocCheckWhenFull() throws OutOfSpaceException {
try {
int fileSize = this.rand.nextInt(this.BOUND) + 1;
int spaceSize = 2 * fileSize - fileSize / 2 - 1;
String fileName = "fileName";
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
Leaf leaf;
try {
leaf = new Leaf(fileName, fileSize);
} catch (Exception e) {
assertTrue(false);
}
leaf = new Leaf(fileName, fileSize);
}
catch(Exception e)
{
if(e instanceof OutOfSpaceException)
throw e;
assertTrue(false);
}
}
/**
* This function will assignn the given root tree as the parent of all the random files this function will create
* @param root - The root Tree
* @return - The random files
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
private RandomLeafCreation allocRandomFiles(Tree root) throws OutOfSpaceException {
RandomLeafCreation randomLeafCreation = allocRandomFiles();
Set<Leaf> files= randomLeafCreation.getFiles().keySet();
for(Leaf file : files)
{
file.parent = root;
}
return randomLeafCreation;
}
/**
* This function creates and returns files in different sizes
* @return - The files
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
private RandomLeafCreation allocRandomFiles() throws OutOfSpaceException {
//For a random number of iterations
int iter = rand.nextInt(this.BOUND) + 1;
int [] sizes = new int[iter];
Leaf [] files = new Leaf[iter];
int spaceSize =0;
//Create random file sizes
for(int k= 0;k<sizes.length;k++) {
sizes[k] = rand.nextInt(this.BOUND) + 1;
spaceSize+=sizes[k];
}
Leaf leaf;
String fileName = "fileName";
spaceSize = spaceSize + 1 +rand.nextInt(BOUND);
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
int sum = 0;
//Check the allocation of the random files
for(int i=0;i<iter;i++) {
leaf = new Leaf(fileName, sizes[i]);
files[i] = leaf;
Leaf[] blocks = space.getAlloc();
int count = 0;
for (int j = 0; j < blocks.length; j++) {
if (blocks[j] == leaf)
count++;
}
assertEquals(count, sizes[i]);
}
return new RandomLeafCreation(files,sizes,space);
}
/**
* This function will check the countFreeSpace function after the use of Dealloc
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void deallocFreeSpace() throws OutOfSpaceException {
Tree root = new Tree("root");
RandomLeafCreation randomLeafCreation = allocRandomFiles(root);
HashMap<Leaf,Integer> files = randomLeafCreation.getFiles();
Space space = randomLeafCreation.getSpace();
int freeSpace = space.countFreeSpace();
int spaceSize;
for(Map.Entry<Leaf,Integer> file : files.entrySet())
{
space.Dealloc(file.getKey());
spaceSize = space.countFreeSpace();
assertEquals(freeSpace + file.getValue(),spaceSize);
freeSpace = spaceSize;
}
FileSystem.fileStorage = null;
}
/**
* This function will check the dealloc function (normal behavior)
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void deallocCheck() throws OutOfSpaceException {
Tree root = new Tree("root");
RandomLeafCreation randomLeafCreation = allocRandomFiles(root);
HashMap<Leaf,Integer> files = randomLeafCreation.getFiles();
Space space = randomLeafCreation.getSpace();
Leaf [] allocs;
for(Map.Entry<Leaf,Integer> file : files.entrySet())
{
space.Dealloc(file.getKey());
allocs = space.getAlloc();
for(int j=0;j<allocs.length;j++)
{
assertTrue(allocs[j] != file.getKey());
}
}
FileSystem.fileStorage = null;
}
/**
* This function checks the behavior of the dealloc function when empty
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void deallocCheckWhenEmpty() throws OutOfSpaceException {
int fileSize = rand.nextInt(this.BOUND) + 1;
Tree root = new Tree("root");
int spaceSize = fileSize;
String fileName = "fileName";
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
Leaf leaf = new Leaf(fileName,fileSize);
leaf.parent = root;
assertEquals(0,space.countFreeSpace());
space.Dealloc(leaf);
assertEquals(spaceSize,space.countFreeSpace());
Leaf [] prev = space.getAlloc().clone();
space.Dealloc(leaf);
Leaf [] after = space.getAlloc().clone();
assertEquals(spaceSize,space.countFreeSpace());
for(int i=0;i<prev.length;i++)
{
assertEquals(after[i],prev[i]);
}
FileSystem.fileStorage = null;
}
/**
* This function will check the behavior of the Alloc and Dealloc when used on after the other
* @throws OutOfSpaceException - In the process of creating the files an OutOfSpaceException might be thrown
*/
@Test
public void allocAndDealloc() throws OutOfSpaceException {
int fileSize = rand.nextInt(100);
int spaceSize = fileSize+1;
Tree root = new Tree("root");
FileSystem.fileStorage = new Space(spaceSize);
Space space = FileSystem.fileStorage;
String name = "fileName";
Leaf file1 = new Leaf(name,fileSize);
file1.parent = root;
space.Dealloc(file1);
Leaf file2 = new Leaf(name+"2",fileSize);
file2.parent = root;
space.Dealloc(file1);
Leaf [] allocs = space.getAlloc();
int count =0;
for(int i=0;i<allocs.length;i++) {
if (allocs[i] == file2)
count++;
}
assertEquals(count,fileSize);
assertEquals(spaceSize-fileSize,space.countFreeSpace());
}
/**
* This function will reset the space instance
*/
@After
public void clean()
{
FileSystem.fileStorage = null;
}
/**
* This class contains the information of random files and their sizes (as well as the space)
*/
private static class RandomLeafCreation
{
private HashMap<Leaf,Integer> files;//The files - sizes dictionary
private Space space;//The space
/**
* The contructor of the class
* @param files - The files
* @param sizes - The sizes of the files
* @param space - The space
*/
public RandomLeafCreation(Leaf [] files,int []sizes, Space space)
{
this.files = new HashMap<>();
for(int i=0;i<sizes.length;i++)
{
this.files.put(files[i],sizes[i]);
}
this.space = space;
}
/**
* This function will return the file - size dictionary
* @return - The file - size dictionary
*/
public HashMap<Leaf, Integer> getFiles() {
return files;
}
/**
* This function will return the space
* @return - The space
*/
public Space getSpace() {
return space;
}
}
} | [
"[email protected]"
]
| |
544fdfc4360069496eec64f48d9615c64d116934 | 61a33968f488eed97f9facafd84a415dfbdf5488 | /src/MODEL/Pedido.java | c7b299f6e648576284c297b4ae0028f02cd38b21 | []
| no_license | Brendo-Ricardo/arqdsis | a9307708331931cbcf8c5cce0100cd3242c6d605 | 7bd7ae799e21b7837517eec40aa1e85d10f0c0ec | refs/heads/master | 2021-01-18T16:12:25.707830 | 2017-04-06T18:52:23 | 2017-04-06T18:52:23 | 86,726,738 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 2,076 | java | package MODEL;
import DAO.PedidoDAO;
public class Pedido {
private int id;
private String descrição;
private double preço;
private int quantidadeVendidas;
public Pedido(int id, String descrição, double preço, int quantidadeVendidas) {
this.id = id;
this.descrição = descrição;
this.preço = preço;
this.quantidadeVendidas = quantidadeVendidas;
}
//GET AND SET - ID
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//GET AND SET - DESCRIÇÃO
public String getDescrição() {
return descrição;
}
public void setDescrição(String descrição) {
this.descrição = descrição;
}
//GET AND SET- PREÇO
public double getPreço() {
return preço;
}
public void setPreço(double preço) {
this.preço = preço;
}
//GET AND SET - QUANTIDADE.VENDIDAS
public int getQuantidadeVendidas() {
return quantidadeVendidas;
}
public void setQuantidadeVendidas(int quantidadeVendidas) {
this.quantidadeVendidas = quantidadeVendidas;
}
//MÉTODO CRIAR
public void criar() {
PedidoDAO dao = new PedidoDAO();
PedidoTO to = new PedidoTO();
to.setId(id);
to.setDescrição(descrição);
to.setPreço(preço);
to.setQuantidadeVendidas(quantidadeVendidas);
dao.incluir(to);
}
//MÉTODO ATUALIZAR
public void atualizar() {
PedidoDAO dao = new PedidoDAO();
PedidoTO to = new PedidoTO();
to.setId(id);
to.setDescrição(descrição);
to.setPreço(preço);
to.setQuantidadeVendidas(quantidadeVendidas);
dao.atualizar(to);
}
//MÉTODO EXCLUIR
public void excluir() {
PedidoDAO dao = new PedidoDAO();
PedidoTO to = new PedidoTO();
to.setId(id);
dao.excluir(to);
}
//MÉTODO CARREGAR
public void carregar() {
PedidoDAO dao = new PedidoDAO();
PedidoTO to = dao.carregar(id);
descrição = to.getDescrição();
preço = to.getPreço();
quantidadeVendidas = to.getQuantidadeVendidas();
}
@Override
public String toString() {
return "Pedido [id=" + id + ", descrição=" + descrição + ", preço=" + preço + ", quantidadeVendidas=" + quantidadeVendidas + "]";
}
} | [
"[email protected]"
]
| |
19e34c8a1d29083ad084da4f8eb7afc5e508985f | 69debdf0e42ba363581fa9a69830796941b83edc | /workspace/Vjezbe25052015/src/Task3.java | ece2abab45267cc56599e248c301e12d99d33502 | []
| no_license | GordanMasic/bitCampMiniMac | fa13533f70a9bc25a43e7b1229e30888ede3c5a1 | 378414b1eb4dac312341390761fbc9ee14d950ab | refs/heads/master | 2020-06-06T09:51:12.029226 | 2015-08-03T15:19:00 | 2015-08-03T15:19:00 | 37,205,105 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java |
public class Task3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numbers = 100;
int sum = 0;
int num = 1;
while (num <= numbers){
sum += num;
num++;
}
System.out.println(sum);
}
}
| [
"[email protected]"
]
| |
0e732c6894e1f3bc8dcc0524992b11453289c729 | 9e31f5865ab809e565baed2f45273ba064ec11a5 | /src/main/java/com/vermeg/bookstore/service/UserDetailsServiceImpl.java | b0f303a5ad48c8a7fa7d3ae846f66991115b4b56 | []
| no_license | Ihebf/bookstore_springboot | c9d52ccf3f647723220cec8945f517e31b707659 | bb01321ae4bce729cd55aa9466876b981bc3b62e | refs/heads/main | 2023-02-28T15:37:14.393999 | 2021-02-05T11:02:44 | 2021-02-05T11:02:44 | 316,909,990 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,848 | java | package com.vermeg.bookstore.service;
import com.vermeg.bookstore.entities.User;
import com.vermeg.bookstore.repository.UserRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> userOptional = userRepository.findByUsername(username);
User user = userOptional
.orElseThrow(() -> new UsernameNotFoundException("No user found with username: "+ username));
return new org.springframework.security
.core.userdetails.User(user.getUsername(), user.getPassword(),
true, true, true,
true, getAuthorities("USER",user));
}
private Collection<? extends GrantedAuthority> getAuthorities(String role,User user) {
return Arrays.stream(user.getRoles().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
}
| [
"[email protected]"
]
| |
522a3bc7d070579a4ad7d5114304e060fd8c9255 | 128616b5903e03eb1afe6746b21e54fe2459f58a | /pierchem-app/src/test/java/com/s14014/tau/selenium/SeleniumTest.java | 8f2a19a21acbf748c6d9c378dcb73d714404b2f2 | [
"MIT"
]
| permissive | Sinnlos/PierwiastkiChemiczne | 298977f7756acc101d077eca42bf5eb8e3faa87f | 9c18936af4d3cc7b8d127aa521aee9455aff5634 | refs/heads/master | 2021-01-24T07:43:31.818653 | 2018-06-19T15:01:05 | 2018-06-19T15:01:05 | 122,963,754 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,167 | java | package com.s14014.tau.selenium;
/*
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class SeleniumTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private WebElement unexpectedPineapple;
private StringBuffer verificationErrors = new StringBuffer();
private String firstName1 = "Adam";
private String lastName1 = "Nowak";
private String email1 = "[email protected]";
private String passwd1 = "superhaslo";
private String address1 = "Oak 34";
private String city1 = "Las Vegas";
private String state1 = "21";
private String zip1 = "11111";
private String country1 = "21";
private String phone1 = "987654321";
private String alias1 = "address";
private String firstName2 = "Adam#$";
private String lastName2 = "Nowak";
private String email2;
private String passwd2 = "supe";
private String address2 = "Oak 34";
private String city2 = "Las Vegas";
private String state2 = "21";
private String zip2 = "11111";
private String country2 = "21";
private String phone2 = "";
private String alias2 = "address";
public String mailRandom(String email2){
int c;
Random rand = new Random();
c = rand.nextInt(30000);
email2 = (firstName1 + lastName1 + c);
return email2;
}
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
baseUrl = "http://automationpractice.com/index.php";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private void register() {
driver.findElement(By.id("submitAccount")).click();
}
public void signInCreateAccount() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Sign in")).click();
driver.findElement(By.id("email_create")).clear();
driver.findElement(By.id("email_create")).sendKeys(email1);
driver.findElement(By.id("SubmitCreate")).click();
if(checkIfErrorExist("#create_account_error") == true){
int c;
Random rand = new Random();
c = rand.nextInt(30000);
email2 = (firstName1 + lastName1 + c);
driver.findElement(By.id("email_create")).clear();
driver.findElement(By.id("email_create")).sendKeys(email2 + "@wp.pl");
driver.findElement(By.id("SubmitCreate")).click();
}
}
public void fillingInfo() throws Exception {
driver.findElement(By.id("customer_firstname")).clear();
driver.findElement(By.id("customer_firstname")).sendKeys(firstName2);
driver.findElement(By.id("customer_lastname")).clear();
driver.findElement(By.id("customer_lastname")).sendKeys(lastName2);
driver.findElement(By.id("passwd")).clear();
driver.findElement(By.id("passwd")).sendKeys(passwd2);
driver.findElement(By.id("address1")).clear();
driver.findElement(By.id("address1")).sendKeys(address2);
driver.findElement(By.id("city")).clear();
driver.findElement(By.id("city")).sendKeys(city2);
WebElement element1 = driver.findElement(By.id("id_state"));
Select s1 = new Select(element1);
s1.selectByValue(state2);
WebElement element2 = driver.findElement(By.id("id_country"));
Select s2 = new Select(element2);
s2.selectByValue(country2);
driver.findElement(By.id("postcode")).clear();
driver.findElement(By.id("postcode")).sendKeys(zip2);
driver.findElement(By.id("phone_mobile")).clear();
driver.findElement(By.id("phone_mobile")).sendKeys(phone2);
driver.findElement(By.id("alias")).clear();
driver.findElement(By.id("alias")).sendKeys(alias2);
register();
if (checkIfErrorExist("#center_column > div > ol > li") == true) {
String alertText = driver.findElement(By.cssSelector("#center_column > div")).getText();
assertTrue(alertText.contains("firstname"));
if (alertText.contains("firstname")) {
driver.findElement(By.id("customer_firstname")).clear();
driver.findElement(By.id("customer_firstname")).sendKeys(firstName1);
}
if (alertText.contains("passwd")) {
driver.findElement(By.id("passwd")).clear();
driver.findElement(By.id("passwd")).sendKeys(passwd1);
}
if (alertText.contains("You must register at least one phone number.")) {
driver.findElement(By.id("phone_mobile")).clear();
driver.findElement(By.id("phone_mobile")).sendKeys(phone1);
}
register();
}
}
@Test
public void test() throws Exception {
signInCreateAccount();
fillingInfo();
ifSignedIn();
signOut();
}
private boolean checkIfErrorExist(String cssSelector) throws Exception {
Thread.sleep(3000);
return driver.findElement(By.cssSelector(cssSelector)).isDisplayed();
}
public void ifSignedIn(){
WebElement text = driver.findElement(By.linkText(firstName1 + " " + lastName1));
assertNotNull(text);
}
public void signOut(){
driver.findElement(By.linkText("Sign out")).click();
}
}
*/
| [
"[email protected]"
]
| |
cce7d319e5ae4a342afe92f32bcac30fae9fd00c | 7703dc419f53baec5fa8c7744a6759c557f79f78 | /Git/GMProjects/driverGuard/src/test/java/com/gm/NGIDataAccessorTest.java | 6e08a6278131ddcb6d887c7c859e36a7579a2774 | []
| no_license | caprice/myAndroidCommLib | 1a380d4104594947af7b82cecaab514f68fd2b64 | 9d842e2fa8cb483385b0f3871e4f99c5b3b7b8fb | refs/heads/master | 2016-09-06T14:20:10.329683 | 2015-03-13T07:29:46 | 2015-03-13T07:30:27 | 32,125,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,106 | java | package com.gm;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import com.gm.driverGuard.dao.NGIDataAccessor;
import com.gm.driverGuard.entity.DateSummary;
import com.gm.driverGuard.entity.MetricObject;
import com.gm.driverGuard.entity.NGIData;
import com.gm.driverGuard.entity.NGITriggerData;
import com.gm.driverGuard.entity.TripSummaryObject;
import com.gm.driverGuard.entity.Vehicle;
import com.gm.driverGuard.helper.CassandraSessionHelper;
public class NGIDataAccessorTest extends TestCase{
private ApplicationContext context;
private NGIDataAccessor dataAccessor;
private CassandraSessionHelper sessionHelper;
@Override
public void setUp(){
context=new ClassPathXmlApplicationContext(new String[]{
"spring/applicationContext.xml"
});
dataAccessor=(NGIDataAccessor)context.getBean("ngiDataAccessor");
sessionHelper=(CassandraSessionHelper)context.getBean("cassandraSessionHelper");
}
@Override
public void tearDown(){
((CassandraSessionHelper)context.getBean("cassandraSessionHelper")).close();
((ClassPathXmlApplicationContext)context).close();
}
public void testInsertData(){
Date startDate=DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
int rand=Math.abs(new Random(new Date().getTime()).nextInt());
String metricName="metric_"+rand;
String vin="vin_"+rand;
//insert metric
dataAccessor.addMetric(new MetricObject(rand,metricName,-1,"%",0,"example metric"));
try{
dataAccessor.getMetricId(metricName);
}catch(DataAccessException e){
assertTrue(false);
}
//insert vehicle
dataAccessor.addVehicle(new Vehicle(rand,vin));
try{
dataAccessor.getIDByVin(vin);
}catch(DataAccessException e){
assertTrue(false);
}
//insert data
dataAccessor.insertData(metricName, vin, new Date(), new BigDecimal(1.0f),null,null);
dataAccessor.insertData(metricName, vin, new Date(), new BigDecimal(2.0f),null,null);
dataAccessor.insertData(metricName, vin, new Date(), new BigDecimal(3.0f),null,null);
List<NGIData> resultData=new ArrayList<NGIData>();
dataAccessor.getDataSeries(metricName,vin,startDate,startDate,resultData);
assertTrue(resultData.size()==3);
System.out.println("result NGI data:"+resultData);
}
public void testInsertTrigger(){
Date startDate=DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
int rand=Math.abs(new Random(new Date().getTime()).nextInt());
String metricName="metric_"+rand;
String triggerType="trigger_"+(rand+1);
String vin="vin_"+rand;
//insert metric
dataAccessor.addMetric(new MetricObject(rand,metricName,-1,"%",0,"example metric"));
try{
dataAccessor.getMetricId(metricName);
}catch(DataAccessException e){
assertTrue(false);
}
//insert trigger type
dataAccessor.addMetric(new MetricObject(rand+1,triggerType,-1,"%",0,"example trigger"));
try{
dataAccessor.getMetricId(triggerType);
}catch(DataAccessException e){
assertTrue(false);
}
//insert vehicle
dataAccessor.addVehicle(new Vehicle(rand,vin));
try{
dataAccessor.getIDByVin(vin);
}catch(DataAccessException e){
assertTrue(false);
}
//insert data
Map<String,BigDecimal> triggerData=new HashMap<String,BigDecimal>();
triggerData.put(metricName, new BigDecimal(1.0f));
dataAccessor.insertTriggerData(vin, new Date(), triggerType, triggerData);
List<NGITriggerData> resultData=new ArrayList<NGITriggerData>();
dataAccessor.getTriggerDataSeries(vin, startDate, startDate, triggerType, resultData);
assertTrue(resultData.size()==1);
System.out.println("result trigger data:"+resultData);
}
public void testGetTripSummary(){
Date startDate=DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
int rand=Math.abs(new Random(new Date().getTime()).nextInt());
String metricName="metric_"+rand;
String vin="vin_"+rand;
//insert metric
dataAccessor.addMetric(new MetricObject(rand,metricName,-1,"%",0,"example metric"));
try{
dataAccessor.getMetricId(metricName);
}catch(DataAccessException e){
assertTrue(false);
}
//insert vehicle
dataAccessor.addVehicle(new Vehicle(rand,vin));
try{
dataAccessor.getIDByVin(vin);
}catch(DataAccessException e){
assertTrue(false);
}
Map<Integer,BigDecimal> data=new HashMap<Integer,BigDecimal>();
data.put(rand, new BigDecimal(1.0f));
//insert summary data
sessionHelper.insert("INSERT INTO ngi.trip_summary(vin_id,trip_id,trip_stime,trip_etime,values) VALUES(?,?,?,?,?)",
rand,1,startDate,new Date(),data
);
List<TripSummaryObject> resultData=new ArrayList<TripSummaryObject>();
dataAccessor.getTripSummary(vin, startDate, startDate, resultData);
assertTrue(resultData.size()==1);
System.out.println("result Trip data:"+resultData);
}
public void testDataTimeSummary(){
Date startDate=DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
Date startMonth=DateUtils.truncate(new Date(), java.util.Calendar.MONTH);
Date startYear=DateUtils.truncate(new Date(), java.util.Calendar.YEAR);
int rand=Math.abs(new Random(new Date().getTime()).nextInt());
String metricName="metric_"+rand;
String vin="vin_"+rand;
//insert metric
dataAccessor.addMetric(new MetricObject(rand,metricName,-1,"%",0,"example metric"));
try{
dataAccessor.getMetricId(metricName);
}catch(DataAccessException e){
assertTrue(false);
}
//insert vehicle
dataAccessor.addVehicle(new Vehicle(rand,vin));
try{
dataAccessor.getIDByVin(vin);
}catch(DataAccessException e){
assertTrue(false);
}
Map<Integer,BigDecimal> data=new HashMap<Integer,BigDecimal>();
data.put(rand, new BigDecimal(1.0f));
//insert data summary
sessionHelper.insert("INSERT INTO ngi.data_time_summary(vin_id,summary_type,summary_date,values) VALUES(?,?,?,?)",
rand,0,startDate,data
);
sessionHelper.insert("INSERT INTO ngi.data_time_summary(vin_id,summary_type,summary_date,values) VALUES(?,?,?,?)",
rand,1,startMonth,data
);
sessionHelper.insert("INSERT INTO ngi.data_time_summary(vin_id,summary_type,summary_date,values) VALUES(?,?,?,?)",
rand,2,startYear,data
);
List<DateSummary> resultData=new ArrayList<DateSummary>();
dataAccessor.getDateSummary(vin, startDate, startDate, NGIDataAccessor.DATA_SUMMARY_TYPE_DAY, new ArrayList<String>(), resultData);
assertTrue(resultData.size()==1);
System.out.println("data summary by date:"+resultData);
resultData.clear();
dataAccessor.getDateSummary(vin, startMonth, startMonth, NGIDataAccessor.DATA_SUMMARY_TYPE_MONTH, new ArrayList<String>(), resultData);
assertTrue(resultData.size()==1);
System.out.println("data summary by month:"+resultData);
resultData.clear();
dataAccessor.getDateSummary(vin, startYear, startYear, NGIDataAccessor.DATA_SUMMARY_TYPE_YEAR, new ArrayList<String>(), resultData);
assertTrue(resultData.size()==1);
System.out.println("data summary by year:"+resultData);
}
public void testGetCrossAnalysisResult(){
Date startDate=DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH);
Date startMonth=DateUtils.truncate(new Date(), java.util.Calendar.MONTH);
Date lastMonth=DateUtils.addMonths(startMonth, -1);
Date startYear=DateUtils.truncate(new Date(), java.util.Calendar.YEAR);
Date lastYear=DateUtils.addYears(startYear, -1);
int rand=Math.abs(new Random(new Date().getTime()).nextInt());
String vin="vin_"+rand;
//insert vehicle
dataAccessor.addVehicle(new Vehicle(rand,vin));
try{
dataAccessor.getIDByVin(vin);
}catch(DataAccessException e){
assertTrue(false);
}
//insert last year cross analysis data
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,lastYear,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_YEAR,rand,1,new BigDecimal(100),new BigDecimal(200),100
);
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,lastYear,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_YEAR,rand,2,new BigDecimal(200),new BigDecimal(200),100
);
//insert last month cross analysis data
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,lastMonth,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_MONTH,rand,1,new BigDecimal(100),new BigDecimal(200),100
);
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,lastMonth,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_MONTH,rand,2,new BigDecimal(200),new BigDecimal(200),100
);
//insert for today
//insert last month cross analysis data
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,startDate,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_DAY,rand,1,new BigDecimal(100),new BigDecimal(200),100
);
sessionHelper.insert("INSERT INTO ngi.data_cross_analysis(vin_id,summary_sdate,summary_type,cross_type,idx,value_x,value_y,samples) VALUES(?,?,?,?,?,?,?,?)",
rand,startDate,NGIDataAccessor.CROSS_ANALYSIS_DATA_TYPE_DAY,rand,2,new BigDecimal(200),new BigDecimal(200),100
);
Map<BigDecimal,BigDecimal> resultData=new HashMap<BigDecimal,BigDecimal>();
dataAccessor.crossAnalysis(vin, lastYear, startDate, rand, resultData);
assertTrue(resultData.size()==2);
System.out.println("result Cross Analysis data:"+resultData);
}
}
| [
"[email protected]"
]
| |
47e3aaa237fa813ed78b2cbbd0352da938095e4b | 6050f2b8aaaec6a6eebfff5ece4e31b859915fc9 | /src/util/Func.java | 7ecdc322b02a02a32d2bde6344089bdd38f917d9 | [
"MIT"
]
| permissive | TzuChieh/Photon | ad5c113e821212824ffc1f0a049d715975403f55 | 000ba675fc7d2a6c97123db1b3d1e0430244eef9 | refs/heads/master | 2020-05-21T13:52:59.207086 | 2019-03-30T07:30:21 | 2019-03-30T07:30:21 | 52,543,101 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,805 | java | // The MIT License (MIT)
//
// Copyright (c) 2016 Tzu-Chieh Chang (as known as D01phiN)
//
// 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 util;
import math.Vector3f;
public class Func
{
public static int clamp(int value, int lowerBound, int upperBound)
{
return Math.max(lowerBound, Math.min(value, upperBound));
}
public static float clamp(float value, float lowerBound, float upperBound)
{
return Math.max(lowerBound, Math.min(value, upperBound));
}
public static Vector3f min(Vector3f value1, Vector3f value2)
{
return new Vector3f(Math.min(value1.x, value2.x), Math.min(value1.y, value2.y), Math.min(value1.z, value2.z));
}
public static float squared(float var)
{
return var * var;
}
}
| [
"[email protected]"
]
| |
6edafb7f6b4af74900c7246870d878c74a0ecee9 | 7f536326b0b787b4df315ac3539cc1d1e43d325b | /src/org/droidpersistence/util/DroidUtils.java | 0ff0bcc4be4cccfd92824c4678d2268a006912d9 | []
| no_license | linconcp/LoginPersistente | 82447313855324051be477e52bb096aeaf336e1c | 8a65c72fe05a1612dcbb45e892f6c8ab2bf6c869 | refs/heads/master | 2021-01-21T02:27:42.177180 | 2013-12-09T13:26:28 | 2013-12-09T13:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 847 | java | package org.droidpersistence.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DroidUtils {
public static Date convertStringToDate(String date){
Date result = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
result = format.parse(date);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static String convertDateToString(Date date){
String result = "";
//SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
result = format.format(date);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
| [
"[email protected]"
]
| |
1a9c4cce68f5f54e3e7876dedfd3cf1f64f19865 | c8dc0ebd2cd46c99db299c464be168af758d7f4d | /src/main/java/jabara/wicket/ValidatorUtil.java | a76f7c0b42d5909fe6a45abb1244dc5f46ed910d | []
| no_license | jabaraster/jabara-wicket | f0f5024d81b2acb9879aa92d519063ae976a65f9 | e0f1a212461d932703d2b8c32c296ebc8562bcd6 | refs/heads/master | 2021-01-10T10:25:40.073839 | 2015-03-04T16:16:07 | 2015-03-04T16:16:07 | 8,442,999 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,303 | java | /**
*
*/
package jabara.wicket;
import jabara.general.ArgUtil;
import jabara.general.ExceptionUtil;
import jabara.general.NotFound;
import java.io.Serializable;
import java.lang.reflect.Field;
import javax.persistence.metamodel.Attribute;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.validator.StringValidator;
/**
* @author jabaraster
*/
public final class ValidatorUtil {
private ValidatorUtil() {
//
}
/**
* 文字列入力用コンポーネントの基本的な入力チェックを追加します. <br>
* 対象のフィールドにアノテーション{@link Size}が付与されている必要があります. <br>
* アノテーション{@link NotNull}が付与されている場合、{@link FormComponent#setRequired(boolean)}にtrueがセットされます. <br>
* <br>
* 現在の仕様では、型Tの<strong>サブクラス</strong>のフィールドに対して処理出来ません. <br>
* フィールドが定義されている型そのもののClassオブジェクトを指定するようにして下さい. <br>
*
* @param pComponent Wicketの入力コンポーネント.
* @param pCheckTargetObjectType チェック対象オブジェクトの型.
* @param pPropertyName チェック対象プロパティ.
* @return 追加したチェックに関する情報.
*/
public static ValidatorInfo setSimpleStringValidator( //
final FormComponent<String> pComponent //
, final Class<?> pCheckTargetObjectType //
, final String pPropertyName) {
ArgUtil.checkNull(pComponent, "pComponent"); //$NON-NLS-1$
ArgUtil.checkNull(pCheckTargetObjectType, "pCheckTargetObjectType"); //$NON-NLS-1$
ArgUtil.checkNullOrEmpty(pPropertyName, "pPropertyName"); //$NON-NLS-1$
final boolean required = isRequired(pCheckTargetObjectType, pPropertyName);
final Size size = getSizeAnnotation(pCheckTargetObjectType, pPropertyName);
pComponent.setRequired(required);
if (size != null) {
pComponent.add(createStringValidator(size));
}
return new ValidatorInfo(required, size);
}
/**
* {@link #setSimpleStringValidator(FormComponent, Class, String)}と同じ効果です.
*
* @param <T> チェック対象オブジェクトの型.
* @param pComponent Wicketの入力コンポーネント.
* @param pCheckTargetObjectType チェック対象オブジェクトの型.
* @param pPropertyName チェック対象プロパティ.
* @return 追加したチェックに関する情報.
*/
public static <T> ValidatorInfo setSimpleStringValidator( //
final FormComponent<String> pComponent //
, final Class<T> pCheckTargetObjectType //
, final Attribute<T, String> pPropertyName) {
ArgUtil.checkNull(pComponent, "pComponent"); //$NON-NLS-1$
ArgUtil.checkNull(pCheckTargetObjectType, "pCheckTargetObjectType"); //$NON-NLS-1$
ArgUtil.checkNull(pPropertyName, "pPropertyName"); //$NON-NLS-1$
return setSimpleStringValidator(pComponent, pCheckTargetObjectType, pPropertyName.getName());
}
private static <T> IValidator<String> createStringValidator(final Size pSize) {
return new StringValidator(Integer.valueOf(pSize.min()), Integer.valueOf(pSize.max()));
}
private static Field getField(final Class<?> pCheckTargetObjectType, final String pPropertyName) {
try {
return pCheckTargetObjectType.getDeclaredField(pPropertyName);
} catch (final NoSuchFieldException e) {
throw ExceptionUtil.rethrow(e);
}
}
private static <T> Size getSizeAnnotation(final Class<T> pCheckTargetObjectType, final String pPropertyName) {
final Field field = getField(pCheckTargetObjectType, pPropertyName);
return field.getAnnotation(Size.class);
}
private static <T> boolean isRequired(final Class<T> pCheckTargetObjectType, final String pPropertyName) {
final Field field = getField(pCheckTargetObjectType, pPropertyName);
return field.isAnnotationPresent(NotNull.class);
}
/**
* @author jabaraster
*/
public static class ValidatorInfo implements Serializable {
private static final long serialVersionUID = -5292946437870881954L;
private final boolean required;
private final Size size;
/**
* @param pRequired -
* @param pSize -
*/
public ValidatorInfo(final boolean pRequired, final Size pSize) {
this.required = pRequired;
this.size = pSize;
}
/**
* @return sizeを返す.
* @throws NotFound -
*/
public Size getSize() throws NotFound {
if (this.size == null) {
throw NotFound.GLOBAL;
}
return this.size;
}
/**
* @return requiredを返す.
*/
public boolean isRequired() {
return this.required;
}
}
}
| [
"[email protected]"
]
| |
c56854832d1fa307dfcffe8bf13b796e14a619bb | e456cb4a09c9159586024a156c008dc28c3698f2 | /src/com/projectrixor/rixor/scrimmage/player/commands/SetTeamCommand.java | 1703f6e0a9b3d803fe2b40dd1ee4cc0371ed688b | [
"MIT"
]
| permissive | matita01/Rixor | 8e199adf71f55faebd6b89625ea9d8960d7563b0 | 870d5044ecff2baee1bea62ed34f09d6b6f07c60 | refs/heads/master | 2021-01-22T16:53:25.125521 | 2014-03-09T22:26:15 | 2014-03-09T22:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,885 | java | package com.projectrixor.rixor.scrimmage.player.commands;
import com.projectrixor.rixor.scrimmage.Scrimmage;
import com.projectrixor.rixor.scrimmage.map.Map;
import com.projectrixor.rixor.scrimmage.map.MapTeam;
import com.projectrixor.rixor.scrimmage.player.Client;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SetTeamCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdl, String[] args) {
if(sender instanceof Player) {
if(!Client.getClient((Player) sender).isRanked()) {
sender.sendMessage(ChatColor.RED + "No permission!");
return false;
}
}
Map map = Scrimmage.getRotation().getSlot().getMap();
if(args.length < 2) {
sender.sendMessage(ChatColor.RED + "/setteam <team> <new name>");
return false;
}
MapTeam team = map.getTeam(args[0]);
String name = "";
int i = 1;
while(i < args.length) {
name += " " + args[i];
i++;
}
name = name.substring(1);
team.setDisplayName(name, true);
/*sender.sendMessage(team.getColor() + team.getName() + ChatColor.GRAY + " has been changed to " + team.getColor() + team.getDisplayName() + ChatColor.GRAY + ".");*/
for (Player Online : Bukkit.getOnlinePlayers()) {
if (Client.getClient((Player) Online).isRanked()) {
Online.sendMessage(ChatColor.WHITE + "[" + ChatColor.GOLD + "A" + ChatColor.WHITE + "] " + (Client.getClient((Player) sender).getStars()) + (Client.getClient((Player) sender).getTeam().getColor()) + sender.getName() + ChatColor.WHITE + " has changed " + team.getColor() + team.getName() + ChatColor.WHITE + " to " + team.getColor() + team.getDisplayName() + ChatColor.WHITE + ".");
}
}
return false;
}
}
| [
"[email protected]"
]
| |
920b4759c85a9c2301bd3343e134dff5989b2a6e | 9a44333cf802aadd2ad1f4b64c5af3c0b2e09f6d | /src/main/java/com/bulingbuu/common/http/util/Base64.java | e1610c1221a26761b2ce6a4f7f6d64a131c81f35 | []
| no_license | NineF/HttpClient | 1863f2b524f9e777ff257bb4b6c2b4c304babc85 | 473217e0f1d3e1382dd6af9f0c7eaa9b0cbe60ed | refs/heads/master | 2020-03-22T12:57:16.370442 | 2018-07-07T10:03:49 | 2018-07-07T10:03:49 | 140,072,926 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,803 | java | package com.bulingbuu.common.http.util;
import java.io.CharArrayWriter;
import java.io.IOException;
public class Base64 {
static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
public static char[] encode(byte[] content) {
CharArrayWriter cw = new CharArrayWriter(4 * content.length / 3);
int idx = 0;
int x = 0;
for (int i = 0; i < content.length; ++i) {
if (idx == 0)
x = (content[i] & 0xFF) << 16;
else if (idx == 1)
x |= (content[i] & 0xFF) << 8;
else {
x |= content[i] & 0xFF;
}
if (++idx == 3) {
cw.write(alphabet[(x >> 18)]);
cw.write(alphabet[(x >> 12 & 0x3F)]);
cw.write(alphabet[(x >> 6 & 0x3F)]);
cw.write(alphabet[(x & 0x3F)]);
idx = 0;
}
}
if (idx == 1) {
cw.write(alphabet[(x >> 18)]);
cw.write(alphabet[(x >> 12 & 0x3F)]);
cw.write(61);
cw.write(61);
}
if (idx == 2) {
cw.write(alphabet[(x >> 18)]);
cw.write(alphabet[(x >> 12 & 0x3F)]);
cw.write(alphabet[(x >> 6 & 0x3F)]);
cw.write(61);
}
return cw.toCharArray();
}
public static byte[] decode(char[] message) throws IOException {
byte[] buff = new byte[4];
byte[] dest = new byte[message.length];
int bpos = 0;
int destpos = 0;
for (int i = 0; i < message.length; ++i) {
int c = message[i];
if ((c != 10) && (c != 13) && (c != 32)) {
if (c == 9)
continue;
if ((c >= 65) && (c <= 90)) {
buff[(bpos++)] = (byte) (c - 65);
} else if ((c >= 97) && (c <= 122)) {
buff[(bpos++)] = (byte) (c - 97 + 26);
} else if ((c >= 48) && (c <= 57)) {
buff[(bpos++)] = (byte) (c - 48 + 52);
} else if (c == 43) {
buff[(bpos++)] = 62;
} else if (c == 47) {
buff[(bpos++)] = 63;
} else if (c == 61) {
buff[(bpos++)] = 64;
} else {
throw new IOException("Illegal char in base64 code.");
}
if (bpos == 4) {
bpos = 0;
if (buff[0] == 64)
break;
if (buff[1] == 64)
throw new IOException("Unexpected '=' in base64 code.");
int v;
if (buff[2] == 64) {
v = (buff[0] & 0x3F) << 6 | buff[1] & 0x3F;
dest[(destpos++)] = (byte) (v >> 4);
break;
}
if (buff[3] == 64) {
v = (buff[0] & 0x3F) << 12 | (buff[1] & 0x3F) << 6
| buff[2] & 0x3F;
dest[(destpos++)] = (byte) (v >> 10);
dest[(destpos++)] = (byte) (v >> 2);
break;
}
v = (buff[0] & 0x3F) << 18 | (buff[1] & 0x3F) << 12
| (buff[2] & 0x3F) << 6 | buff[3] & 0x3F;
dest[(destpos++)] = (byte) (v >> 16);
dest[(destpos++)] = (byte) (v >> 8);
dest[(destpos++)] = (byte) v;
}
}
}
byte[] res = new byte[destpos];
System.arraycopy(dest, 0, res, 0, destpos);
return res;
}
} | [
"[email protected]"
]
| |
8fe9d7b2f488268e4e2849830dd9fa4d89df4b9b | f7cc8938ccf25a514c6a6ccdfb4dcc49f80b5c12 | /microvibe-booster/booster-core/src/main/java/io/microvibe/booster/core/base/entity/UpdateUserRecordable.java | b2d777548816082e0c1a658fc9ce944808381cc8 | [
"Apache-2.0"
]
| permissive | microsignal/vibe | 6f8b8d91aa6fa0dfc7020ca023ea8c3cb0d82e37 | 4b3e2d5b5a6f3b3e021276b7e496d6eaa1b7b665 | refs/heads/master | 2021-09-25T13:07:16.911688 | 2018-10-22T05:14:14 | 2018-10-22T05:14:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 204 | java | package io.microvibe.booster.core.base.entity;
import java.io.Serializable;
public interface UpdateUserRecordable<ID extends Serializable> {
ID getUpdateUser();
void setUpdateUser(ID updateUser);
}
| [
"[email protected]"
]
| |
c1342b80a96a67c39cc0cd339d2b95213faf8f8f | adc2299fa37ce1325aadffc0f2b2a6d85a8a8f89 | /day06/src/com/banyuan/practice/p06/p06.java | ecaffc4df99d037d129d631dc220fe3475ea8f5c | []
| no_license | weizhang668/JavaEE | c3293db4ecd06392805f05d31c947e6bcc796efb | af3b83ecc1074f42a66718523fe7da5aec96482f | refs/heads/master | 2021-07-23T23:10:39.813256 | 2019-11-29T07:10:13 | 2019-11-29T07:10:13 | 224,757,437 | 0 | 0 | null | 2020-10-13T17:50:16 | 2019-11-29T01:51:47 | Java | UTF-8 | Java | false | false | 1,604 | java | package com.banyuan.practice.p06;
/**
* @Auther: 张伟
* @Date: 2019/10/30
* @Description: com.banyuan.practice.p06
* @version: 1.0
*/
/*题目
*String st1="aa,bb,cc"; //根据逗号来截取
String st3="aa bb cc";// 根据空格来截取
String st4="D:\\EclipseWorkSpace\\Day12\\src\\zhengze\\ZhengZeDemo5.java"; //根据 \\ 截取
得到截取之后的数据。
*/
public class p06 {
public static void main(String[] args) {
String st1="aa,bb,cc";
//根据逗号来截取
//st1.split(",");
for (String s:st1.split(",")){
System.out.println(s);
}
String st3="aa bb cc";
// 根据空格来截取
/*
* Java 增强 for 循环
Java5 引入了一种主要用于数组的增强型 for 循环。
Java 增强 for 循环语法格式如下:
for(声明语句 : 表达式)
{
//代码句子
}
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
* */
for (String s3:st3.split("\\s+")) {
System.out.println(s3);
}
String st4="D:\\EclipseWorkSpace\\Day12\\src\\zhengze\\ZhengZeDemo5.java";
//根据 \\ 截取得到截取之后的数据。
for (String s4:st4.split("\\\\")){
System.out.println(s4);
}
}
}
| [
"[email protected]"
]
| |
876e1deca26797b5a7f40f729db105b24be4c7d4 | 8f95ef6e4469e73f38b54f099e0c1493b3e63e3f | /vendas/src/androidTest/java/joaquimneto/com/alimec/vendas/ApplicationTest.java | 5d68e88540d5e98fbb29b8c47a2f4fd3b4de4f3f | []
| no_license | Joaquimmnetto/FrenteAlimec-Android | 2280b62e96857f815ef30c5cc732e4b6b1734746 | 5c8ed687436eb5f7706c9fade9b95d0a697470f4 | refs/heads/master | 2020-04-16T14:44:52.218475 | 2016-06-11T02:33:12 | 2016-06-11T02:33:12 | 33,778,827 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 360 | java | package joaquimneto.com.alimec.vendas;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
]
| |
83dcc7989be5db71d4e539e926f849ecfd24e59a | 5cc7b300b223dcfdc70ab74ad20be4c28df0c9c1 | /apps-movie-fun-code-mdn-circuitbreaker/components/blobstore/src/main/java/org/superbiz/moviefun/blobstore/Blob.java | 21b7182ad888136aacaa9a3242ee6be9c3b36f96 | []
| no_license | RemyahDevi/homeassignment | a210342bd8afa662da9f114c2c5f1aa78391ce3b | 9934db408294835d7f3647da70be73182977d0c3 | refs/heads/master | 2021-08-31T14:36:15.911215 | 2017-12-21T18:14:58 | 2017-12-21T18:14:58 | 115,033,378 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 406 | java | package org.superbiz.moviefun.blobstore;
import java.io.InputStream;
public class Blob {
public final String name;
public final InputStream inputStream;
public final String contentType;
public Blob(String name, InputStream inputStream, String contentType) {
this.name = name;
this.inputStream = inputStream;
this.contentType = contentType;
}
}
| [
"[email protected]"
]
| |
d149ac736dc7a3f3b46826fb52d1406f109159df | bacc5e296eba2b8d00050bb2d7b3a3003085cbfe | /src/main/java/com/vinterdo/deusexmachina/inventory/ContainerGrayMatterFabricator.java | 6d412e481bdeed011b360af889b981bc71444ba2 | []
| no_license | vinterdo/DeusExMachina | fff724859959337660b603de8fba59931f86a61e | 0c01c9ed8c36210e44033ff142d922bc6837bf2a | refs/heads/master | 2021-01-20T18:40:00.664283 | 2016-02-01T16:00:29 | 2016-02-01T16:00:29 | 36,866,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,092 | java | package com.vinterdo.deusexmachina.inventory;
import com.vinterdo.deusexmachina.init.ModItems;
import com.vinterdo.deusexmachina.tileentity.TEGrayMatterFabricatorMaster;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class ContainerGrayMatterFabricator extends ContainerDEM<TEGrayMatterFabricatorMaster>
{
public ContainerGrayMatterFabricator(InventoryPlayer playerInv, TEGrayMatterFabricatorMaster _te)
{
super(_te);
te = _te;
this.addSlotToContainer(new Slot(te, 0, 25, 14));
this.addSlotToContainer(new Slot(te, 1, 25, 56));
this.addSlotToContainer(new SlotOutput(te, 2, 80, 56));
addPlayerSlots(playerInv, 8, 84);
}
@Override
protected boolean mergeStackToContainer(ItemStack itemstack1)
{
if (itemstack1.getItem() == ModItems.steelIngot)
{
if (!this.mergeItemStack(itemstack1, 0, 1, false))
return true;
} else if (itemstack1.getItem() == ModItems.essence)
{
if (!this.mergeItemStack(itemstack1, 1, 2, false))
return true;
}
return false;
}
}
| [
"[email protected]"
]
| |
ddb8adfb3e08d51416f0e62e9fcd8d8ee7eb2fd1 | f0c79738dd3cdc9267f8cd50042cf0d1b8b9b0a8 | /holiday-manager-web/src/main/java/jp/co/genuine/hm/model/group/GroupList.java | 7bd07f4168e5e31c19ae2b5790a87ec99ece9044 | []
| no_license | genuine-dev/holiday-manager | d990257f9f6040cadadaf81a61e15be1bf14f4eb | 2aa5a05fd62c2c91d60b93ac2f73104ac3971d53 | refs/heads/master | 2023-03-07T07:52:16.354148 | 2022-12-29T22:47:22 | 2022-12-29T22:47:22 | 206,788,141 | 0 | 1 | null | 2022-12-29T22:47:23 | 2019-09-06T12:22:22 | JavaScript | UTF-8 | Java | false | false | 489 | java | package jp.co.genuine.hm.model.group;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_EMPTY)
public class GroupList {
private List<Group> groups;
public GroupList() {
}
public GroupList(List<Group> groups) {
this.groups = groups;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
| [
"[email protected]"
]
| |
c3b83049ba44230797660e411f5e84b118756891 | 9126e6db99b575e432bcac9fdf655282b530d19a | /src/ua/artcode/week2/day2/game/Sword.java | 5ab7825960258bce30bd55cba49e7c3fc9a0454b | []
| no_license | DimitrN/ACO3my | ac56c58e9feb49f2f23c58e70ff3187a234ee605 | d5214fb10ef04ee02b64aae4aa8796330151bca6 | refs/heads/master | 2020-05-26T21:10:13.099309 | 2014-12-27T14:26:21 | 2014-12-27T14:26:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 292 | java | package ua.artcode.week2.day2.game;
/**
* Created with IntelliJ IDEA.
* User: КЕП
* Date: 18.11.14
* Time: 20:25
* To change this template use File | Settings | File Templates.
*/
public class Sword extends Weapon {
@Override
public int use() {
return 30;
}
}
| [
"[email protected]"
]
| |
942857a9dd87f8ffb50c8bbdf9c942d0e09baaa7 | 87f7f6794fd73308e2027de6d0784307b74038f1 | /src/main/java/cc/nuvu/technical/test/backend/services/UserService.java | 24517cd3b0ae1ac995634fa495360f11acca728e | []
| no_license | Angel-Villasmil/Nuvu-Technical-Test.Backend | 69f2683abadf322487f2fe7bfaf13184086a41a6 | 3451d0b41e1ce18cbfc3cca2d85e30edb35dd052 | refs/heads/main | 2023-05-01T20:21:48.722312 | 2021-05-04T12:26:10 | 2021-05-04T12:26:10 | 361,900,867 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,725 | java | package cc.nuvu.technical.test.backend.services;
import java.util.ArrayList;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.*;
import cc.nuvu.technical.test.backend.models.UserModel;
import cc.nuvu.technical.test.backend.repositories.UserRepository;
import cc.nuvu.technical.test.backend.security.Crypto;
@Service
public class UserService {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Autowired
UserRepository userRepository;
public ArrayList<UserModel> findAllUser(){
return (ArrayList<UserModel>) userRepository.findAll();
}
public Optional<UserModel> findUserById(Long id){
return userRepository.findById(id);
}
public UserModel saveUser(UserModel user){
user.setPassword(Crypto.encrypt(user.getPassword()));
return userRepository.save(user);
}
public String deleteUser(Long id){
if (userRepository.findById(id).isPresent()){
userRepository.deleteById(id);
return "Usuario eliminado correctamente.";
}
return "Error! El usuario no existe.";
}
public String updateUser(UserModel userToUpdate){
if (userRepository.findById(userToUpdate.getId()).isPresent()){
userToUpdate.setPassword(Crypto.encrypt(userToUpdate.getPassword()));
userRepository.save(userToUpdate);
return "Usuario modificado.";
}
return "Error al modificar el Usuario.";
}
public boolean validateUser(String user, String pasword) {
UserModel userModel = userRepository.getValidUser(user, Crypto.encrypt(pasword));
if (userModel != null) return true;
else return false;
}
}
| [
"[email protected]"
]
| |
8561279ea9c217ef8cf306f28cd5b974d2201306 | 38cd56e14f1c2190b76bc344eac3ac0a79c2c5d5 | /app/src/androidTest/java/myhello/helloworld/myhelloworld/ApplicationTest.java | 72257ca4b16c317cb7a698c00f1e59c40b181c9d | []
| no_license | githubshare/MyHelloworld | afbeb2ee80ed10d0dc24f4eb3a9f00191e4a0b95 | fb80eea28c750c156839b97e2558d6deb82eed5b | refs/heads/master | 2021-01-01T05:07:12.019416 | 2016-05-16T17:45:11 | 2016-05-16T17:45:11 | 58,951,011 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package myhello.helloworld.myhelloworld;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
]
| |
d78794574706e3f3700374911871417475b320ca | 5b166ef6d918644254bdaa24365762d63be4e3e2 | /app/src/main/java/com/fmi/bot/FullList.java | 6ac3b2e86e8d6f8940dfefd583cb1e5a982d8a6c | []
| no_license | iulia-purcaru/AndroidProject | a9dc106bdff063242293431e542ad945a36a905f | 0db6cddca0a5e394d6414f3bf5354362e0e8ed25 | refs/heads/master | 2023-01-22T15:53:47.498623 | 2020-12-07T13:47:37 | 2020-12-07T13:47:37 | 305,184,873 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,466 | java | package com.fmi.bot;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.SearchView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class FullList extends AppCompatActivity {
private FullListAdapter adapter;
private List<ModalClass> exampleList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulllist);
fillExampleList();
setUpRecyclerView();
}
private void fillExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new ModalClass(R.drawable.ic_dress,"Dress"));
exampleList.add(new ModalClass(R.drawable.ic_shoe,"Shoe"));
exampleList.add(new ModalClass(R.drawable.ic_pants,"Pants"));
exampleList.add(new ModalClass(R.drawable.ic_cap,"Cap"));
exampleList.add(new ModalClass(R.drawable.ic_tshirt,"T-Shirt"));
exampleList.add(new ModalClass(R.drawable.ic_tie,"Tie"));
}
private void setUpRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
adapter = new FullListAdapter(exampleList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
} | [
"[email protected]"
]
| |
ed28d69b09b588b5b2c709f07d12f96bf693e611 | 6d2dcd390bf4694af25f3191fb0e6adc11abdd3f | /app/src/main/java/com/yangll/bishe/happyweather/adapter/OnItemRemoveListener.java | 924288c486439c0d359e58e98b6b561aecf9cc9c | []
| no_license | miss1/HappyWeather | 84831a6380daf4d728662b5bbeb7ea6716ea9244 | 0861357cc5b04aefc1499115d4a5dadd0d24971a | refs/heads/master | 2021-06-23T20:28:31.855834 | 2021-06-05T14:39:10 | 2021-06-05T14:39:10 | 74,372,735 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 254 | java | package com.yangll.bishe.happyweather.adapter;
import android.view.View;
/**
* Created by Administrator on 2017/3/27.
*/
public interface OnItemRemoveListener {
void onItemClick(View view, int position);
void onDeleteClick(int position);
}
| [
"[email protected]"
]
| |
7b6f8355226cca72035aef5b6ffe81af4db68c2b | f2f233dc8ddcc6a5d5021e6b66d3690fde174a74 | /app/src/main/java/com/myclothershopapp/fragmment/ProductSpecificationFragment.java | 3e3f99b481e5f073630db4d8d643bc1e31f33bf7 | []
| no_license | chanh12012001/Clothers-Shop-App | 9d254d96c610f75ba92c4b1848365fcc9350fa62 | 90c4b42d4d6313b1e5d959b2bf073d8ae88a24ff | refs/heads/main | 2023-06-13T06:42:01.594664 | 2021-07-11T20:09:48 | 2021-07-11T20:09:48 | 351,673,945 | 0 | 0 | null | 2021-07-11T20:09:49 | 2021-03-26T05:37:25 | Java | UTF-8 | Java | false | false | 1,703 | java | package com.myclothershopapp.fragmment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.myclothershopapp.R;
import com.myclothershopapp.adapter.ProductSpecificationAdapter;
import com.myclothershopapp.model.ProductSpecificationModel;
import java.util.List;
public class ProductSpecificationFragment extends Fragment {
public ProductSpecificationFragment() {
// Required empty public constructor
}
private RecyclerView productSpecificationRecyclerView;
public List<ProductSpecificationModel> productSpecificationModelList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product_specification, container, false);
productSpecificationRecyclerView = view.findViewById(R.id.product_specification_recyclerview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(view.getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
productSpecificationRecyclerView.setLayoutManager(linearLayoutManager);
ProductSpecificationAdapter productSpecificationAdapter = new ProductSpecificationAdapter(productSpecificationModelList);
productSpecificationRecyclerView.setAdapter(productSpecificationAdapter);
productSpecificationAdapter.notifyDataSetChanged();
return view;
}
}
| [
"[email protected]"
]
| |
5890bb2a76a22bf9d83489b7d6948cd20b7b7f17 | 495e06a5482c04d312fc351a1eaaefe1dedeeb3d | /app/src/main/java/com/justApp/RadioPlayer/data/repository/local/LocalSource.java | e2b954584d975ba7be91bce6bce5f7d29dfc4496 | []
| no_license | putnik-busy/RadioPlayer | cc833b7f0a7f585664f9c522a17cc210c6476e66 | 3cb87a41dfb2536e2709557d223ec6565e4dffd8 | refs/heads/master | 2021-01-16T17:38:22.171251 | 2017-09-01T08:46:39 | 2017-09-01T08:46:39 | 90,381,388 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,309 | java | package com.justApp.RadioPlayer.data.repository.local;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import com.justApp.RadioPlayer.data.pojo.Category;
import com.justApp.RadioPlayer.data.pojo.Image;
import com.justApp.RadioPlayer.data.pojo.NowPlaying;
import com.justApp.RadioPlayer.data.pojo.Station;
import com.justApp.RadioPlayer.data.pojo.Stream;
import com.justApp.RadioPlayer.data.pojo.Thumb;
import com.justApp.RadioPlayer.data.repository.DataSource;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import static dagger.internal.Preconditions.checkNotNull;
/**
* @author Sergey Rodionov
*/
public class LocalSource implements DataSource {
private static LocalSource INSTANCE;
private DbHelper mDbHelper;
private LocalSource(@NonNull Context context) {
checkNotNull(context);
mDbHelper = new DbHelper(context);
}
public static LocalSource getInstance(@NonNull Context context) {
if (INSTANCE == null) {
INSTANCE = new LocalSource(context);
}
return INSTANCE;
}
@Override
public Observable<List<Station>> getStations() {
List<Station> stationList = new ArrayList<>();
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + TableColumns.StationEntry.TABLE_NAME +
" INNER JOIN " + TableColumns.ImageEntry.TABLE_NAME +
" ON (" + TableColumns.StationEntry.TABLE_NAME + "." + TableColumns.StationEntry._ID + " = " +
TableColumns.ImageEntry.TABLE_NAME + "." + TableColumns.ImageEntry.COLUMN_STATION_ID + ")" +
" INNER JOIN " + TableColumns.ThumbEntry.TABLE_NAME +
" ON (" + TableColumns.StationEntry.TABLE_NAME + "." + TableColumns.ImageEntry._ID + " = " +
TableColumns.ThumbEntry.TABLE_NAME + "." + TableColumns.ThumbEntry.COLUMN_IMAGE_ID +
")";
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
while (c.moveToNext()) {
stationList.add(getStationFromCursor(c));
}
}
if (c != null) {
c.close();
}
db.close();
if (stationList.isEmpty()) {
return Observable.empty();
}
return Observable.just(stationList);
}
private Station getStationFromCursor(Cursor c) {
Station station = new Station();
station.setId(c.getInt(c.getColumnIndex(TableColumns.StationEntry.COLUMN_ID)));
station.setName(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_NAME)));
station.setCountry(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_COUNTRY)));
station.setImage(getImageFromCursor(c));
station.setSlug(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_SLUG)));
station.setWebsite(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_WEBSITE)));
station.setTwitter(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_TWITTER)));
station.setFacebook(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_FACEBOOK)));
station.setTotalListeners(c.getInt(c.getColumnIndex(TableColumns.StationEntry
.COLUMN_TOTAL_LISTENER)));
station.setCategories(getCategoryStationList());
station.setStreams(getStreamStationList());
station.setCreatedAt(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_CREATED_AT)));
station.setUpdatedAt(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_UPDATED_AT)));
station.setLastUpdate(c.getString(c.getColumnIndex(TableColumns.StationEntry.COLUMN_LAST_UPDATE)));
return station;
}
private Image getImageFromCursor(Cursor c) {
Image image = new Image();
image.setUrl(c.getString(c.getColumnIndex(TableColumns.ImageEntry.COLUMN_URL)));
image.setThumb(getThumbFromCursor(c));
image.setIdStation(c.getInt(c.getColumnIndex(TableColumns.ImageEntry.COLUMN_STATION_ID)));
return image;
}
private Thumb getThumbFromCursor(Cursor c) {
Thumb thumb = new Thumb();
thumb.setUrl(c.getString(c.getColumnIndex(TableColumns.ThumbEntry.COLUMN_URL)));
thumb.setIdImage(c.getInt(c.getColumnIndex(TableColumns.ThumbEntry.COLUMN_IMAGE_ID)));
return thumb;
}
private List<Category> getCategoryStationList() {
List<Category> categoryList = new ArrayList<>();
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + TableColumns.CategoryEntry.TABLE_NAME;
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
while (c.moveToNext()) {
categoryList.add(getCategoryStationListFromCursor(c));
}
}
if (c != null) {
c.close();
}
return categoryList;
}
private Category getCategoryStationListFromCursor(Cursor c) {
Category category = new Category();
category.setId(c.getInt(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_ID)));
category.setTitle(c.getString(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_TITLE)));
category.setDescription(c.getString(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_DESCRIPTION)));
category.setSlug(c.getString(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_SLUG)));
category.setAncestry(c.getString(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_ANCESTRY)));
category.setIdStation(c.getInt(c.getColumnIndex(TableColumns.CategoryEntry.COLUMN_STATION_ID)));
return category;
}
private List<Stream> getStreamStationList() {
List<Stream> streamList = new ArrayList<>();
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + TableColumns.StreamEntry.TABLE_NAME;
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
while (c.moveToNext()) {
streamList.add(getStreamStationListFromCursor(c));
}
}
if (c != null) {
c.close();
}
return streamList;
}
private Stream getStreamStationListFromCursor(Cursor c) {
Stream stream = new Stream();
stream.setStream(c.getString(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_STREAM)));
stream.setBitrate(c.getInt(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_BITRATE)));
stream.setContentType(c.getString(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_CONTENT_TYPE)));
stream.setListeners(c.getInt(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_LISTENERS)));
stream.setStatus(c.getInt(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_STATUS)));
stream.setIdStation(c.getInt(c.getColumnIndex(TableColumns.StreamEntry.COLUMN_STATION_ID)));
return stream;
}
private NowPlaying getNowPlayingFromCursor(Cursor c) {
NowPlaying nowPlaying = new NowPlaying();
nowPlaying.setStationId(c.getInt(c.getColumnIndex(TableColumns.NowPlayingStationEntry.COLUMN_STATION_ID)));
return nowPlaying;
}
@Override
public Observable<Station> getStation(@NonNull Integer id) {
Station station = new Station();
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + TableColumns.StationEntry.TABLE_NAME +
" INNER JOIN " + TableColumns.ImageEntry.TABLE_NAME +
" ON (" + TableColumns.StationEntry.TABLE_NAME + "." + TableColumns.StationEntry._ID + " = " +
TableColumns.ImageEntry.TABLE_NAME + "." + TableColumns.ImageEntry.COLUMN_STATION_ID + ")" +
" INNER JOIN " + TableColumns.ThumbEntry.TABLE_NAME +
" ON (" + TableColumns.StationEntry.TABLE_NAME + "." + TableColumns.ImageEntry._ID + " = " +
TableColumns.ThumbEntry.TABLE_NAME + "." + TableColumns.ThumbEntry.COLUMN_IMAGE_ID + ")" +
"WHERE (" + TableColumns.StationEntry.TABLE_NAME + "." + TableColumns.StationEntry.COLUMN_ID + " = " +
String.valueOf(id) + ")";
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
while (c.moveToNext()) {
station = getStationFromCursor(c);
}
}
if (c != null) {
c.close();
}
db.close();
if (station == null) {
return Observable.empty();
}
return Observable.just(station);
}
@Override
public void saveStations(@NonNull List<Station> stationList) {
checkNotNull(stationList);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values;
int stationListSize = stationList.size();
long currentTime = System.currentTimeMillis();
for (int i = 0; i < stationListSize; i++) {
values = addStation(stationList.get(i), currentTime);
long idStationRow = db.insert(TableColumns.StationEntry.TABLE_NAME, null, values);
values.clear();
values = addImage(stationList.get(i), idStationRow);
long idImageRow = db.insert(TableColumns.ImageEntry.TABLE_NAME, null, values);
values.clear();
values = addThumb(stationList.get(i), idImageRow);
db.insert(TableColumns.ThumbEntry.TABLE_NAME, null, values);
values.clear();
List<Stream> streamList = stationList.get(i).getStreams();
int sizeStreamList = streamList.size();
for (int j = 0; j < sizeStreamList; j++) {
values = addStream(streamList.get(j), idStationRow);
db.insert(TableColumns.StreamEntry.TABLE_NAME, null, values);
values.clear();
}
List<Category> categoryList = stationList.get(i).getCategories();
int sizeCategoryList = categoryList.size();
for (int k = 0; k < sizeCategoryList; k++) {
values = addCategory(categoryList.get(k), idStationRow);
db.insert(TableColumns.CategoryEntry.TABLE_NAME, null, values);
values.clear();
}
}
db.close();
}
private ContentValues addStation(Station station, long currentTime) {
ContentValues cv = new ContentValues();
cv.put(TableColumns.StationEntry.COLUMN_ID, station.getId());
cv.put(TableColumns.StationEntry.COLUMN_NAME, station.getName());
cv.put(TableColumns.StationEntry.COLUMN_COUNTRY, station.getCountry());
cv.put(TableColumns.StationEntry.COLUMN_SLUG, station.getSlug());
cv.put(TableColumns.StationEntry.COLUMN_WEBSITE, station.getWebsite());
cv.put(TableColumns.StationEntry.COLUMN_TWITTER, station.getTwitter());
cv.put(TableColumns.StationEntry.COLUMN_FACEBOOK, station.getFacebook());
cv.put(TableColumns.StationEntry.COLUMN_TOTAL_LISTENER, station.getTotalListeners());
cv.put(TableColumns.StationEntry.COLUMN_CREATED_AT, station.getCreatedAt());
cv.put(TableColumns.StationEntry.COLUMN_UPDATED_AT, station.getUpdatedAt());
cv.put(TableColumns.StationEntry.COLUMN_LAST_UPDATE, currentTime);
return cv;
}
private ContentValues addImage(Station station, long idStationRow) {
ContentValues cv = new ContentValues();
Image image = station.getImage();
cv.put(TableColumns.ImageEntry.COLUMN_URL, image.getUrl());
cv.put(TableColumns.ImageEntry.COLUMN_STATION_ID, idStationRow);
return cv;
}
private ContentValues addThumb(Station station, long idImageRow) {
ContentValues cv = new ContentValues();
Thumb thumb = station.getImage().getThumb();
cv.put(TableColumns.ThumbEntry.COLUMN_URL, thumb.getUrl());
cv.put(TableColumns.ThumbEntry.COLUMN_IMAGE_ID, idImageRow);
return cv;
}
private ContentValues addStream(Stream stream, long idStationRow) {
ContentValues cv = new ContentValues();
cv.put(TableColumns.StreamEntry.COLUMN_STREAM, stream.getStream());
cv.put(TableColumns.StreamEntry.COLUMN_BITRATE, stream.getBitrate());
cv.put(TableColumns.StreamEntry.COLUMN_CONTENT_TYPE, stream.getContentType());
cv.put(TableColumns.StreamEntry.COLUMN_LISTENERS, stream.getListeners());
cv.put(TableColumns.StreamEntry.COLUMN_STATUS, stream.getStatus());
cv.put(TableColumns.StreamEntry.COLUMN_STATION_ID, idStationRow);
return cv;
}
private ContentValues addCategory(Category category, long idStationRow) {
ContentValues cv = new ContentValues();
cv.put(TableColumns.CategoryEntry.COLUMN_ID, category.getId());
cv.put(TableColumns.CategoryEntry.COLUMN_TITLE, category.getTitle());
cv.put(TableColumns.CategoryEntry.COLUMN_DESCRIPTION, category.getDescription());
cv.put(TableColumns.CategoryEntry.COLUMN_SLUG, category.getSlug());
cv.put(TableColumns.CategoryEntry.COLUMN_ANCESTRY, (String) category.getAncestry());
cv.put(TableColumns.CategoryEntry.COLUMN_STATION_ID, idStationRow);
return cv;
}
private ContentValues addNowPlayingStation(NowPlaying nowPlaying) {
ContentValues cv = new ContentValues();
cv.put(TableColumns.NowPlayingStationEntry.COLUMN_STATION_ID, nowPlaying.getStationId());
return cv;
}
@Override
public void refreshStations(@NonNull List<Station> stationList) {
checkNotNull(stationList);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values;
int stationListSize = stationList.size();
long currentTime = System.currentTimeMillis();
for (int i = 0; i < stationListSize; i++) {
Station station = stationList.get(i);
values = addStation(station, currentTime);
long idStationRow = db.update(TableColumns.StationEntry.TABLE_NAME, values,
TableColumns.StationEntry.COLUMN_ID + " =?",
new String[]{String.valueOf(station.getId())});
values.clear();
values = addImage(station, idStationRow);
long idImageRow = db.update(TableColumns.ImageEntry.TABLE_NAME, values,
TableColumns.ImageEntry.COLUMN_STATION_ID + " =?",
new String[]{String.valueOf(idStationRow)});
values.clear();
values = addThumb(station, idImageRow);
db.update(TableColumns.ThumbEntry.TABLE_NAME, values,
TableColumns.ThumbEntry.COLUMN_IMAGE_ID + " =?",
new String[]{String.valueOf(station.getImage().getThumb().getIdImage())});
values.clear();
List<Stream> streamList = station.getStreams();
int sizeStreamList = streamList.size();
for (int j = 0; j < sizeStreamList; j++) {
Stream stream = streamList.get(j);
values = addStream(stream, idStationRow);
db.update(TableColumns.StreamEntry.TABLE_NAME, values,
TableColumns.StreamEntry.COLUMN_STATION_ID + " =?",
new String[]{String.valueOf(stream.getIdStation())});
values.clear();
}
List<Category> categoryList = station.getCategories();
int sizeCategoryList = categoryList.size();
for (int k = 0; k < sizeCategoryList; k++) {
Category category = categoryList.get(k);
values = addCategory(category, idStationRow);
db.update(TableColumns.CategoryEntry.TABLE_NAME, values,
TableColumns.CategoryEntry.COLUMN_STATION_ID + " =?",
new String[]{String.valueOf(category.getIdStation())});
values.clear();
}
}
db.close();
}
@Override
public long getLastUpdate() {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
long lastUpdate = -1;
String sql = "SELECT " + TableColumns.StationEntry.COLUMN_LAST_UPDATE + " FROM " +
TableColumns.StationEntry.TABLE_NAME;
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
lastUpdate = c.getLong(c.getColumnIndex(TableColumns.StationEntry.COLUMN_LAST_UPDATE));
}
if (c != null) {
c.close();
}
db.close();
return lastUpdate;
}
@Override
public void saveNowPlaying(@NonNull NowPlaying nowPlaying) {
checkNotNull(nowPlaying);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = addNowPlayingStation(nowPlaying);
db.insert(TableColumns.NowPlayingStationEntry.TABLE_NAME, null, values);
}
@Override
public Observable<NowPlaying> getNowPlayingStation() {
NowPlaying nowPlaying = null;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + TableColumns.NowPlayingStationEntry.TABLE_NAME;
Cursor c = db.rawQuery(sql, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
nowPlaying = getNowPlayingFromCursor(c);
}
if (c != null) {
c.close();
}
db.close();
if (nowPlaying == null) {
return Observable.empty();
}
return Observable.just(nowPlaying);
}
@Override
public void refreshNowPlaying(@NonNull NowPlaying nowPlaying) {
checkNotNull(nowPlaying);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = addNowPlayingStation(nowPlaying);
db.update(TableColumns.NowPlayingStationEntry.TABLE_NAME, values,
TableColumns.NowPlayingStationEntry.COLUMN_STATION_ID + " =?",
new String[]{String.valueOf(nowPlaying.getStationId())});
}
}
| [
"[email protected]"
]
| |
923aed90dac5932d3970ba2c19af2397670d3e29 | b8d369a54905377d0398557fa496b9e4213149e0 | /UserFront/src/main/java/com/userfront/domain/PrimaryAccount.java | e58f2543ddc25d08c9c0a1119f40de4c4eca1e08 | []
| no_license | zeus28/spring_boot | dcd22c6c10ff5e36d6fb9a57cfb5083ad0292a74 | 384948a3f8c6ba37beb70485587ea45ff6521bb8 | refs/heads/master | 2021-08-14T10:47:41.154283 | 2017-11-15T12:51:41 | 2017-11-15T12:51:41 | 109,136,729 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,583 | java | package com.userfront.domain;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class PrimaryAccount {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int accountNumber;
private BigDecimal accountBalance;
@OneToMany(mappedBy = "primaryAccount", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonIgnore
private List<PrimaryTransaction> primaryTransactionList;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public BigDecimal getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(BigDecimal accountBalance) {
this.accountBalance = accountBalance;
}
public List<PrimaryTransaction> getPrimaryTransactionList() {
return primaryTransactionList;
}
public void setPrimaryTransactionList(List<PrimaryTransaction> primaryTransactionList) {
this.primaryTransactionList = primaryTransactionList;
}
} | [
"[email protected]"
]
| |
25518b4652bf1bc7bee8080d472afa0a3a08edd9 | 1991ab40a50e1a17caf1b1f56b596397e8fb6577 | /src/main/java/eu/abra/dto/dev/wadl/_2009/_02/ObjectFactory.java | 978fa8ba73bf96afdbeb5a2fd95bb604640cd2a3 | []
| no_license | stapa/twido | ff27a9a6179c6a597322b32ff59e9005add895a7 | 8159b846016c80845ea6619d74d012e430c9b34a | refs/heads/master | 2020-08-28T00:33:33.675669 | 2012-04-16T18:11:13 | 2012-04-16T18:11:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,321 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.06 at 02:48:12 odp. CEST
//
package eu.abra.dto.dev.wadl._2009._02;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the eu.abra.dto.dev.wadl._2009._02 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.abra.dto.dev.wadl._2009._02
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Doc }
*
*/
public Doc createDoc() {
return new Doc();
}
/**
* Create an instance of {@link Response }
*
*/
public Response createResponse() {
return new Response();
}
/**
* Create an instance of {@link ResourceType }
*
*/
public ResourceType createResourceType() {
return new ResourceType();
}
/**
* Create an instance of {@link Link }
*
*/
public Link createLink() {
return new Link();
}
/**
* Create an instance of {@link Application }
*
*/
public Application createApplication() {
return new Application();
}
/**
* Create an instance of {@link Resources }
*
*/
public Resources createResources() {
return new Resources();
}
/**
* Create an instance of {@link Include }
*
*/
public Include createInclude() {
return new Include();
}
/**
* Create an instance of {@link Param }
*
*/
public Param createParam() {
return new Param();
}
/**
* Create an instance of {@link Grammars }
*
*/
public Grammars createGrammars() {
return new Grammars();
}
/**
* Create an instance of {@link Option }
*
*/
public Option createOption() {
return new Option();
}
/**
* Create an instance of {@link Representation }
*
*/
public Representation createRepresentation() {
return new Representation();
}
/**
* Create an instance of {@link Resource }
*
*/
public Resource createResource() {
return new Resource();
}
/**
* Create an instance of {@link Method }
*
*/
public Method createMethod() {
return new Method();
}
/**
* Create an instance of {@link Request }
*
*/
public Request createRequest() {
return new Request();
}
}
| [
"st@n.(none)"
]
| st@n.(none) |
c099f62ff2a0cebc960dbcb261c6cf07a5d082aa | 0f792e82ccc1e7cf13310067a3c363092e0a4bec | /src/Folowingsibling.java | 6de626886d8d0ec240e476fcc70c7967d026903b | []
| no_license | arvindhmk/basicsSelenium | 8a88eac08273e506c8ccbc8def5e48e5dc3b6ee9 | b5d916ce70358d25a515f04353f0507151bc0d52 | refs/heads/master | 2022-06-20T09:22:29.551433 | 2020-05-13T09:54:54 | 2020-05-13T09:54:54 | 263,579,227 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,364 | java | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Folowingsibling {
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\Compressed\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String str = "http://www.qaclickacademy.com/interview.php";
driver.get(str);
driver.findElement(By.xpath("//li[@id='tablist1-tab1']")).click();
driver.findElement(By.xpath("//li[@id='tablist1-tab1']/following-sibling::li")).click();
driver.findElement(By.xpath("//li[@id='tablist1-tab1']/following-sibling::li[2]")).click();
driver.findElement(By.xpath("//li[@id='tablist1-tab1']/following-sibling::li[3]")).click();
driver.close();
// //driver.findElement(By.xpath("//div[@class='a4bIc']/input")).sendKeys("Test");
// driver.findElement(By.xpath("//p[@class='top']/input")).sendKeys("DemoCSR");
// driver.findElement(By.xpath("//input[@id='password']")).sendKeys("crmsfa");
// driver.findElement(By.cssSelector("input.decorativeSubmit\r\n")).click();
// driver.findElement(By.xpath("//img[@src='/opentaps_images/integratingweb/crm.png']")).click();
// driver.findElement(By.xpath("//div[@id='left-content-column']/div/div[2]/ul/li[2]")).click();
}
} | [
"[email protected]"
]
| |
5a42838e30b8b133a185cd44be0e921907be54a6 | 119ac25712822c80d8a525ef952c8fbe5bf1aecc | /app/src/main/java/com/wishland/www/controller/fragment/fundsmanagement/pagerview/FundsCathectic.java | b9df47f11d721904983341a33e03795617d76617 | []
| no_license | RightManCode/wishland | 7c1a3b4a1c545441b6a20b1ab4920122cc79bc98 | 3b673e5a0e7ca33b91466e86ee418a8e88918073 | refs/heads/master | 2021-05-09T22:52:11.454551 | 2018-01-24T12:54:39 | 2018-01-24T12:54:39 | 118,765,146 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 10,604 | java | package com.wishland.www.controller.fragment.fundsmanagement.pagerview;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.wishland.www.R;
import com.wishland.www.controller.base.BastView;
import com.wishland.www.controller.fragment.fundsmanagement.FundsManagementPage;
import com.wishland.www.model.Model;
import com.wishland.www.model.sp.UserSP;
import com.wishland.www.utils.AppUtils;
import com.wishland.www.utils.LogUtil;
import com.wishland.www.utils.NetUtils;
import com.wishland.www.utils.ToastUtil;
import com.wishland.www.utils.Utils_time;
import com.wishland.www.view.customgridview.CustomViewPager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import rx.Subscriber;
/**
* 投注记录
*/
public class FundsCathectic extends BastView {
@BindView(R.id.funds_deal_radiobutton_add)
RadioButton fundsDealRadiobuttonAdd;
@BindView(R.id.funds_deal_radiobutton_get)
RadioButton fundsDealRadiobuttonGet;
@BindView(R.id.funds_deal_radiobutton_atm)
RadioButton fundsDealRadiobuttonAtm;
@BindView(R.id.funds_deal_radiobutton_other)
RadioButton fundsDealRadiobuttonOther;
@BindView(R.id.funds_deal_radiogroup)
RadioGroup fundsDealRadiogroup;
@BindView(R.id.funds_deal_start_yearmd)
Button fundsDealStartYearmd;
@BindView(R.id.funds_deal_start_hour)
Button fundsDealStartHour;
@BindView(R.id.funds_deal_start_minute)
Button fundsDealStartMinute;
@BindView(R.id.funds_deal_end_yearmd)
Button fundsDealEndYearmd;
@BindView(R.id.funds_deal_end_hour)
Button fundsDealEndHour;
@BindView(R.id.funds_deal_end_minute)
Button fundsDealEndMinute;
@BindView(R.id.funds_deal_content_linear)
LinearLayout fundsDealContentLinear;
@BindView(R.id.funds_deal_button)
Button fundsDealButton;
@BindView(R.id.funds_deal_content)
Button fundsDealContent;
private int maketype;
private static final int PLAYGAME = 0;
private static final int TIMENOTE = 1;
private static final int NOTEPAGE = 2;
private static final int SEXNOTE = 3;
private FundsManagementPage fundsmanagement;
private Model instance;
private UserSP userSP;
private Map<String, String> map;
public FundsCathectic(Context context, CustomViewPager fundsViewpager, FundsManagementPage fundsManagementPage) {
super(context, fundsViewpager);
this.fundsmanagement = fundsManagementPage;
}
@Override
public View setView() {
View view = View.inflate(bastcontext, R.layout.fundscathecticlayout, null);
ButterKnife.bind(this, view);
bastViewpager.setObjectForPosition(view, 4);
return view;
}
@Override
public void initData() {
super.initData();
init();
setGroupListener();
}
private void init() {
fundsDealContentLinear.setVisibility(View.VISIBLE);
instance = Model.getInstance();
userSP = instance.getUserSP();
map = new HashMap<>();
fundsDealRadiobuttonAdd.setText(R.string.playcolor);
fundsDealRadiobuttonGet.setText(R.string.timecolor);
fundsDealRadiobuttonAtm.setText(R.string.colornote);
fundsDealRadiobuttonOther.setText(R.string.sexcolor);
fundsDealRadiogroup.check(R.id.funds_deal_radiobutton_add);
maketype = PLAYGAME;
}
private void setGroupListener() {
fundsDealRadiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int id = fundsDealRadiogroup.indexOfChild(fundsDealRadiogroup.findViewById(i));
switch (id) {
case PLAYGAME:
fundsDealContentLinear.setVisibility(View.VISIBLE);
maketype = PLAYGAME;
break;
case TIMENOTE:
fundsDealContentLinear.setVisibility(View.VISIBLE);
maketype = TIMENOTE;
break;
case NOTEPAGE:
fundsDealContentLinear.setVisibility(View.VISIBLE);
maketype = NOTEPAGE;
break;
case SEXNOTE:
fundsDealContentLinear.setVisibility(View.GONE);
maketype = SEXNOTE;
break;
}
}
});
}
@OnClick({R.id.funds_deal_content, R.id.funds_deal_start_yearmd, R.id.funds_deal_start_hour, R.id.funds_deal_start_minute, R.id.funds_deal_end_yearmd, R.id.funds_deal_end_hour, R.id.funds_deal_end_minute, R.id.funds_deal_button})
public void onViewClicked(View view) {
String type = null;
switch (view.getId()) {
case R.id.funds_deal_start_yearmd:
fundsmanagement.setDataPopup(fundsmanagement.listyear, fundsDealStartYearmd, 1);
break;
case R.id.funds_deal_end_yearmd:
fundsmanagement.setDataPopup(fundsmanagement.listyear, fundsDealEndYearmd, 1);
break;
case R.id.funds_deal_start_hour:
if (fundsmanagement.list.size() != 0) {
fundsmanagement.list.clear();
}
Collections.addAll(fundsmanagement.list, Utils_time.hourarray);
fundsmanagement.setDataPopup(fundsmanagement.list, fundsDealStartHour, 1);
break;
case R.id.funds_deal_end_hour:
if (fundsmanagement.list.size() != 0) {
fundsmanagement.list.clear();
}
Collections.addAll(fundsmanagement.list, Utils_time.hourarray);
fundsmanagement.setDataPopup(fundsmanagement.list, fundsDealEndHour, 1);
break;
case R.id.funds_deal_start_minute:
if (fundsmanagement.list.size() != 0) {
fundsmanagement.list.clear();
}
Collections.addAll(fundsmanagement.list, Utils_time.minutearray);
fundsmanagement.setDataPopup(fundsmanagement.list, fundsDealStartMinute, 1);
break;
case R.id.funds_deal_end_minute:
if (fundsmanagement.list.size() != 0) {
fundsmanagement.list.clear();
}
Collections.addAll(fundsmanagement.list, Utils_time.minutearray);
fundsmanagement.setDataPopup(fundsmanagement.list, fundsDealEndMinute, 1);
break;
case R.id.funds_deal_content:
break;
case R.id.funds_deal_button:
switch (maketype) {
case PLAYGAME:
type = "ty";
ToastUtil.showShort(bastcontext, "体育信息查询");
requestMessage(type);
break;
case TIMENOTE:
type = "ss";
ToastUtil.showShort(bastcontext, "时时彩信息查询");
requestMessage(type);
break;
case NOTEPAGE:
type = "pt";
ToastUtil.showShort(bastcontext, "彩票信息查询");
requestMessage(type);
break;
case SEXNOTE:
type = "other";
ToastUtil.showShort(bastcontext, "六合彩信息查询");
requestMessage(type);
break;
}
break;
}
}
private void requestMessage(final String type) {
String starttime = fundsDealStartYearmd.getText().toString() + " " + fundsDealStartHour.getText().toString() + ":" + fundsDealStartMinute.getText().toString();
String endtime = fundsDealEndYearmd.getText().toString() + " " + fundsDealEndHour.getText().toString() + ":" + fundsDealEndMinute.getText().toString();
String token = userSP.getToken(UserSP.LOGIN_TOKEN);
int queryCnt = 500;
int queryId = 0;
int Subtype = 0;
if (map.size() != 0) {
map.clear();
}
map.put("start", starttime);
map.put("queryCnt", queryCnt + "");
map.put("queryId", queryId + "");
map.put("end", endtime);
map.put("Subtype", Subtype + "");
map.put("type", type);
instance.apiBet(starttime, queryCnt, queryId + "", endtime, Subtype, type, token, NetUtils.getParamsPro(map).get("signature"), new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
AppUtils.getInstance().onRespons("投注记录查询完成");
LogUtil.e("投注記錄查詢完成");
}
@Override
public void onError(Throwable e) {
AppUtils.getInstance().onRespons("投注记录查询异常:" + e.getMessage());
LogUtil.e("投注記錄查詢異常:" + e.getMessage());
}
@Override
public void onNext(ResponseBody queryBetBean) {
try {
String string = queryBetBean.string();
JSONObject jsonObject = instance.getJsonObject(string);
instance.setToken_SP(jsonObject.optString("token"));
int status = jsonObject.optInt("status");
if (status == 200) {
LogUtil.e("投注記錄查詢成功");
} else {
ToastUtil.showShort(bastcontext, "投注記錄查詢成功");
}
} catch (IOException e) {
AppUtils.getInstance().onRespons("投注记录查询异常:" + e.getMessage());
e.printStackTrace();
} catch (JSONException e) {
AppUtils.getInstance().onRespons("投注记录查询异常:" + e.getMessage());
e.printStackTrace();
}
}
});
}
}
| [
"[email protected]"
]
| |
9fc83ba408b3b1b7d04a37f92dbfa38032b758bd | 24bd964a44a0d9a0dba636b2447aab88e12bb762 | /src/main/java/edu/ssm/mapper/TestMapper.java | 3742a67b054f02d44a651b14e64e185db32d5b35 | []
| no_license | Lixiaobing12/Student-time-project | 1c5f495b377449b1f4d4a3a72a3ef3c4766349c5 | cf72e76d47017a8ec3da3742ca9c49afd106c1b8 | refs/heads/master | 2022-12-22T05:07:50.297652 | 2019-10-13T13:52:22 | 2019-10-13T13:52:22 | 214,822,027 | 2 | 0 | null | 2022-12-16T04:43:44 | 2019-10-13T13:08:59 | Java | UTF-8 | Java | false | false | 180 | java | package edu.ssm.mapper;
import tk.mybatis.mapper.common.BaseMapper;
/**
* @author Blse
* @date 2019/6/25
* @description
*/
public interface TestMapper {
int select();
}
| [
"[email protected]"
]
| |
4ef1beea505adaed52ec0d9cc7d884702f77ac63 | 3e7bc37d2ee9b1aac654d66336650fdbc23eeef8 | /src/view/DeleteTagScene.java | da155b74f88a0ba943dd6c6d5453cf4937a668a0 | []
| no_license | xinrunw/Image-Viewer | 71a3f6142e3586b9949b2aea1d717310f19ffecc | 77069d654803a6f19ccf4295b20de36203cdae0e | refs/heads/master | 2020-09-16T14:50:41.303583 | 2019-11-24T20:39:33 | 2019-11-24T20:39:33 | 223,805,198 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,172 | java | package view;
import controller.DeleteTagSceneController;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import model.Database;
import model.Photo;
import java.util.ArrayList;
public class DeleteTagScene {
/** Stage we will back to */
private static Stage mainWindow;
/** VBox of tags CheckBoxes */
private static VBox tags;
/**
* show a DeleteTagScene which allows user to delete selected tags.
*
* @param window the Stage where the photo is shown.
* @param directory the Database which the photo belongs to.
* @param photo the Photo we are deleting tags from.
*/
public static void show(Stage window, Database directory, Photo photo) {
mainWindow = window;
// initiate the Stage, make ImageScene untouchable
Stage DeleteTag = new Stage();
DeleteTag.setTitle("Delete Tags");
DeleteTag.initModality(Modality.APPLICATION_MODAL);
// connect to Controller
DeleteTagSceneController.setPhoto(photo);
DeleteTagSceneController.setDatabase(directory);
// tansfer all tags to CheckBoxes and add to VBox
tags = new VBox(10);
for (String tag : DeleteTagSceneController.viewTags()) {
CheckBox box = new CheckBox(tag);
tags.getChildren().add(box);
}
tags.setAlignment(Pos.CENTER_LEFT);
tags.setPadding(new Insets(10, 10, 10, 10));
// right part for the Button delete
VBox right = new VBox();
right.setAlignment(Pos.CENTER);
Button delete = new Button("Delete");
delete.setAlignment(Pos.CENTER);
// set event to delete Button
delete.setOnAction(
e -> {
// get all checked CheckBoxes of tag
ArrayList<String> checkTags = new ArrayList<>();
for (Object box : tags.getChildren().toArray()) {
if (((CheckBox) box).isSelected()) {
checkTags.add(((CheckBox) box).getText());
}
}
// pass tags to Controller
Photo image = DeleteTagSceneController.deleteTags(checkTags);
// back to ImageScene
DeleteTag.close();
ImageScene.show(mainWindow, directory, image);
});
right.getChildren().add(delete);
// bottom part for close Button
HBox bottom = new HBox();
bottom.setAlignment(Pos.BOTTOM_RIGHT);
Button close = new Button("Close");
close.setAlignment(Pos.BOTTOM_RIGHT);
close.setOnAction(e -> DeleteTag.close());
bottom.getChildren().add(close);
// initiate the layout
BorderPane layout = new BorderPane();
layout.setMinSize(200, 200);
layout.setPadding(new Insets(10, 10, 10, 10));
layout.setCenter(tags);
layout.setRight(right);
layout.setBottom(bottom);
Scene deleteScene = new Scene(layout);
DeleteTag.setScene(deleteScene);
DeleteTag.showAndWait();
}
}
| [
"[email protected]"
]
| |
e42b5d5007217ad40df344264eeca82b4e72ee0f | 1ecd3e4fddec6143b35dbed78be2fb8dbd7f2ca6 | /springboot/12.SpringBoot-Swagger/src/test/java/com/yangonion/swagger/SwaggerApplicationTests.java | 58b76c836184d263eab90b808ddf4462b34de514 | [
"Apache-2.0"
]
| permissive | Yang-Onion/JavaWorkSpace | 2326ec270f2ec54d31cd1da5eaeef0cc1aa7012a | 23a4fdd964b456c9fdd787017ae5707fd92620bc | refs/heads/master | 2020-03-25T13:26:01.897743 | 2018-11-22T09:58:10 | 2018-11-22T09:58:10 | 143,824,614 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 339 | java | package com.yangonion.swagger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SwaggerApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"[email protected]"
]
| |
37789e98d192aa49948c670fa08dc0b45e983b0d | 005c12bffc0b3ddedb7ce7973e2e088b6418c95d | /src/jd/http/AbstractAuthenticationFactory.java | 4cc8b668c554774e4c156cfa37ae7345494a50ea | []
| no_license | svn2github/jdownloader-browser | b2390ca49e0b02221000484da3e40e42e663b917 | bd85d2fe215bebf0f1cb274439c42149a230ad02 | refs/heads/master | 2020-04-04T05:54:52.490232 | 2018-12-10T14:32:45 | 2018-12-10T14:32:45 | 16,731,366 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,189 | java | package jd.http;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.appwork.net.protocol.http.HTTPConstants;
import org.appwork.utils.Regex;
import org.appwork.utils.StringUtils;
public abstract class AbstractAuthenticationFactory implements AuthenticationFactory {
protected boolean requiresAuthentication(Request request) {
return request.getHttpConnection().getResponseCode() == 401 && this.getWWWAuthenticate(request) != null;
}
protected CopyOnWriteArrayList<Authentication> authentications = new CopyOnWriteArrayList<Authentication>();
public boolean containsAuthentication(Authentication authentication) {
return authentication != null && this.getAuthentications().contains(authentication);
}
public boolean addAuthentication(Authentication authentication) {
return authentication != null && this.getAuthentications().addIfAbsent(authentication);
}
public boolean removeAuthentication(Authentication authentication) {
return authentication != null && this.getAuthentications().remove(authentication);
}
public CopyOnWriteArrayList<Authentication> getAuthentications() {
return this.authentications;
}
protected String[] getUserInfo(Request request) {
final String[] userInfo = new Regex(request.getURL().getUserInfo(), "^(.*?)(:(.*?))?$").getRow(0);
if (userInfo != null && (StringUtils.isNotEmpty(userInfo[0]) || StringUtils.isNotEmpty(userInfo[2]))) {
return userInfo;
} else {
return null;
}
}
protected abstract Authentication buildBasicAuthentication(Browser browser, Request request, final String realm);
protected abstract Authentication buildDigestAuthentication(Browser browser, Request request, final String realm);
@Override
public boolean retry(Authentication authentication, Browser browser, Request request) {
return authentication != null && this.containsAuthentication(authentication) && authentication.retry(browser, request);
}
protected String getRealm(Request request) {
final List<String> wwwAuthenticateMethods = this.getWWWAuthenticate(request);
if (wwwAuthenticateMethods != null) {
for (final String wwwAuthenticateMethod : wwwAuthenticateMethods) {
final String realm = new Regex(wwwAuthenticateMethod, "realm\\s*=\\s*\"(.*?)\"").getMatch(0);
if (realm != null) {
return realm;
}
}
}
return null;
}
protected List<String> getWWWAuthenticate(Request request) {
return request.getResponseHeaders(HTTPConstants.HEADER_RESPONSE_WWW_AUTHENTICATE);
}
@Override
public Authentication buildAuthentication(Browser browser, Request request) {
if (request.getAuthentication() == null && this.requiresAuthentication(request)) {
final List<String> wwwAuthenticateMethods = this.getWWWAuthenticate(request);
if (wwwAuthenticateMethods != null) {
final String realm = this.getRealm(request);
for (final String wwwAuthenticateMethod : wwwAuthenticateMethods) {
if (wwwAuthenticateMethod.matches("(?i)^\\s*Basic.*")) {
final Authentication ret = this.buildBasicAuthentication(browser, request, realm);
this.addAuthentication(ret);
return ret;
} else if (wwwAuthenticateMethod.matches("(?i)^\\s*Digest.*")) {
final Authentication ret = this.buildDigestAuthentication(browser, request, realm);
this.addAuthentication(ret);
return ret;
}
}
}
}
return null;
}
@Override
public Authentication authorize(Browser browser, Request request) {
for (final Authentication authentication : this.getAuthentications()) {
if (authentication.authorize(browser, request)) {
return authentication;
}
}
return null;
}
}
| [
"jiaz@ebf7c1c2-ba36-0410-9fe8-c592906822b4"
]
| jiaz@ebf7c1c2-ba36-0410-9fe8-c592906822b4 |
3e9bf22a11140eeb692efc8171cdcf963a58eea8 | bc22263a57e58259fb44a20d02d2585ac8e3b7e3 | /app/src/main/java/com/fudan/cosmosapp/ui/discover/model/imple/CnCompositionClassifyModelImple.java | a73bc76ac617c542827a7eacad614628735d13f0 | []
| no_license | Catfeeds/costpmApp | 78dab7563bdfe9505be3a91da07b07a620e0c21c | e41f3f7f534e6d1e19d0de4135c0c77c56be908f | refs/heads/master | 2020-04-05T17:29:06.297431 | 2018-05-30T03:46:18 | 2018-05-30T03:46:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,218 | java | package com.fudan.cosmosapp.ui.discover.model.imple;
import com.fudan.cosmosapp.app.CosmosApplication;
import com.fudan.cosmosapp.bean.ChCompositionTitleArray;
import com.fudan.cosmosapp.bean.CnCompositionClassifyBean;
import com.fudan.cosmosapp.httpClient.Api;
import com.fudan.cosmosapp.httpClient.CourseNetwork;
import com.fudan.cosmosapp.ui.discover.model.CnCompositionClassifyModel;
import io.reactivex.Observable;
/**
* Created by Administrator on 2017/8/20 0020.
*/
public class CnCompositionClassifyModelImple implements CnCompositionClassifyModel {
@Override
public Observable<CnCompositionClassifyBean> getCnCompositionClassify() {
Api api = CourseNetwork.getInstance().getApi(CosmosApplication.getContext());
return api.getChCompositionClassify().compose(CourseNetwork.schedulersTransformer);
}
@Override
public Observable<ChCompositionTitleArray> getChCompositionTitleListByClassifyId(String classificationId) {
Api api = CourseNetwork.getInstance().getApi(CosmosApplication.getContext());
return api.getChCompositionTitleListByClassifyId(classificationId).compose(CourseNetwork.schedulersTransformer);
}
}
| [
"[email protected]"
]
| |
113d53d783ce6ae7e929dbea9b6ae99ebfc20986 | 9f7eef233fd337db65f6a3a2a76d2d6995708ccc | /mushmall-member/src/main/java/com/yw/mushmall/member/service/impl/MemberLevelServiceImpl.java | ec04b9275969ed659a3d398bcb9dc8ab0b75d232 | [
"Apache-2.0"
]
| permissive | Rylie-W/Mushroom | e4a147f3f59261e419781d11da965edd71b7e112 | e6205fe223737b410578c2855c4b1324ec3ab63f | refs/heads/main | 2023-08-02T20:54:33.738503 | 2021-09-12T16:01:38 | 2021-09-12T16:01:38 | 401,360,055 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 998 | java | package com.yw.mushmall.member.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yw.common.utils.PageUtils;
import com.yw.common.utils.Query;
import com.yw.mushmall.member.dao.MemberLevelDao;
import com.yw.mushmall.member.entity.MemberLevelEntity;
import com.yw.mushmall.member.service.MemberLevelService;
@Service("memberLevelService")
public class MemberLevelServiceImpl extends ServiceImpl<MemberLevelDao, MemberLevelEntity> implements MemberLevelService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<MemberLevelEntity> page = this.page(
new Query<MemberLevelEntity>().getPage(params),
new QueryWrapper<MemberLevelEntity>()
);
return new PageUtils(page);
}
} | [
"[email protected]"
]
| |
a1fa6029ccefda1ed8d611274efb992fa4153581 | ee98e564b1c68d0736d9cfd271845746283d556c | /src/huawei/biz/SubwayManager.java | b61f7027ffffb6db6dabb3a866cca7b5b035342b | []
| no_license | xzfreewind/SubwaySEC | 71f6e9dc168ab6c29038ac680d044f88b6c609ac | aa61e24e28836d9193197812186550321d0d4bf5 | refs/heads/master | 2020-03-21T17:42:25.352087 | 2018-03-15T01:38:01 | 2018-03-15T01:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 983 | java | package huawei.biz;
import huawei.exam.SubwayException;
import huawei.model.Card;
import huawei.model.Subways;
/**
* <p>Title: 车乘中心</p>
*
* <p>Description: 考生不得修改,亦无须关注此文件内容</p>
*
* <p>Copyright: Copyright (c) 2013</p>
*
* <p>Company: </p>
*
* @author
* @version 1.0
*/
public interface SubwayManager
{
/**
* 线路初始化
*/
void manageSubways();
/**
* Query subways.
*
* @return the list
*/
Subways querySubways();
/**
* 乘车
*
* @param cardId the card id
* @param enterStation the enter station
* @param enterTime the enter time
* @param exitStation the exit station
* @param exitTime the exit time
* @return 卡当前状态
* @throws SubwayException the subway exception
*/
Card takeSubway(String cardId, String enterStation, String enterTime, String exitStation, String exitTime)
throws SubwayException;
} | [
"[email protected]"
]
| |
7370324ac969040d542f19730142db3961021ce3 | a2b3865aee84b82336c15a7573686c1b4538d633 | /app/src/test/java/com/example/heesun/customdialog_example/ExampleUnitTest.java | 4b6f63f5d0d5ef9bfeb3c562b4c11334b2aa126f | []
| no_license | limheesun4898/CustomDialog_Example | 8232e92807976cd005f215bbc77b2765f7e549db | c3aef00c43f7968491c628575d8a44c12dc09874 | refs/heads/master | 2020-04-15T16:14:57.011265 | 2019-01-09T09:04:01 | 2019-01-09T09:04:01 | 164,824,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package com.example.heesun.customdialog_example;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
0fbc1a69a7baf4783797ac3a66960dd3e9d18207 | 6a067d2bf15aa176a4d35e9bb1f842f2baea2d11 | /src/main/java/collectionsPlusEnumsTask/Groups.java | 81d98e72796dcfa51383ebbb6823ec172a8b2a8a | []
| no_license | levgren/TasksEpam | 2fbb583fdf85a6283de18739206b7a671dd27934 | 52f58f518a7fb03b25664384c2c6d276b588d2c7 | refs/heads/master | 2021-07-08T01:25:06.402134 | 2019-08-20T14:07:55 | 2019-08-20T14:07:55 | 201,232,899 | 0 | 0 | null | 2020-10-13T15:29:25 | 2019-08-08T10:13:38 | Java | UTF-8 | Java | false | false | 270 | java | package collectionsPlusEnumsTask;
public enum Groups {
SMARTS("умные"),
BOTANY("зубры"),
MAZHORY("башляют"),
DEBILOIDY("дебилы"),
;
private final String name;
Groups(String name) {
this.name = name;
}
}
| [
"[email protected]"
]
| |
9274b4c1d0440dea7e7111fd5b023bcf9f22a6ed | 250ee29573400d625e0b2ac11f615d1ca3fec911 | /pet-clinic-data/src/test/java/sfgpetclinic/services/springdata/OwnerSDServiceTest.java | 64a8de23ba197aafe929f3bb089af1b6031a0393 | []
| no_license | romantorkit/sfg-pet-clinic | 20194d96abc4a6ea10af1ce3ca0c2f6184c33ef9 | f15b8e151cfe2235485a3c3b7bde2231562cb200 | refs/heads/master | 2020-09-06T22:49:47.948091 | 2020-05-03T23:32:11 | 2020-05-03T23:32:11 | 220,580,456 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,043 | java | package sfgpetclinic.services.springdata;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import sfgpetclinic.model.Owner;
import sfgpetclinic.repositories.OwnerRepository;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class OwnerSDServiceTest {
Owner expectedOwner;
Long expectedOwnerId = 1L;
String expectedFirstName = "Roman";
String expectedLastName = "Torkit";
@Mock
OwnerRepository ownerRepository;
@InjectMocks
OwnerSDService service;
@BeforeEach
void setUp() {
expectedOwner = Owner.builder()
.id(expectedOwnerId)
.firstName(expectedFirstName)
.lastName(expectedLastName)
.build();
}
@Test
void findByLastName() {
when(ownerRepository.findByLastName(anyString())).thenReturn(expectedOwner);
Owner actual = service.findByLastName(expectedLastName);
assertNotNull(actual);
assertEquals(expectedLastName, actual.getLastName());
verify(ownerRepository).findByLastName(any());
}
@Test
void findAll() {
Set<Owner> expectedSet = new HashSet<>();
expectedSet.add(Owner.builder().id(1L).build());
expectedSet.add(Owner.builder().id(2L).build());
when(ownerRepository.findAll()).thenReturn(expectedSet);
Set<Owner> actualSet = service.findAll();
assertNotNull(actualSet);
assertEquals(expectedSet.size(), actualSet.size());
}
@Test
void findById() {
when(ownerRepository.findById(expectedOwnerId)).thenReturn(Optional.of(expectedOwner));
Owner actual = service.findById(expectedOwnerId);
assertNotNull(actual);
assertEquals(expectedOwnerId, actual.getId());
}
@Test
void findById_ThrowsException() {
when(ownerRepository.findById(anyLong())).thenThrow(NoSuchElementException.class);
assertThrows(NoSuchElementException.class, () -> service.findById(expectedOwnerId));
}
@Test
void save() {
when(ownerRepository.save(any())).thenReturn(expectedOwner);
Owner actual = service.save(Owner.builder().firstName(expectedFirstName).lastName(expectedLastName).build());
assertNotNull(actual);
assertEquals(expectedOwnerId, actual.getId());
verify(ownerRepository).save(any());
}
@Test
void delete() {
service.delete(expectedOwner);
verify(ownerRepository).delete(any());
}
@Test
void deleteById() {
service.deleteById(expectedOwnerId);
verify(ownerRepository, times(1)).deleteById(anyLong());
}
} | [
"[email protected]"
]
| |
36c04cdd9695d35fa78a67416ee0c12c3eb5a2b8 | e5a0b508c949633bec1ff6ccc8ba411d0eb524f8 | /src/net/server/Server.java | 70a2519ce8bdb7ae35d48098536d95ed760903db | []
| no_license | qing3gan/Practice | 085d0c292016df2c7361e9f9687c2536fcd18b7a | 832f8e1d36ac7adbf4b8a61bdba41a48c36c73a6 | refs/heads/master | 2020-06-22T16:46:15.409902 | 2020-01-16T11:38:52 | 2020-01-16T11:38:52 | 197,747,993 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 830 | java | package net.server;
import util.Constants;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Agony on 2018/5/18.
*/
public class Server {
public static final List<Socket> clients = Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(Constants.PORT)) {
while (true) {
Socket socket = serverSocket.accept();
System.out.println("socket connected.");
clients.add(socket);
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
]
| |
8f9d83d198a460210ae14d6e4ca9ddffba6e0f4c | a4a2f08face8d49aadc16b713177ba4f793faedc | /flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/SourceFetcher.java | 5a658b6e102dacfef28765c027229bf3dbc56ba0 | [
"BSD-3-Clause",
"MIT",
"OFL-1.1",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | wyfsxs/blink | 046d64afe81a72d4d662872c007251d94eb68161 | aef25890f815d3fce61acb3d1afeef4276ce64bc | refs/heads/master | 2021-05-16T19:05:23.036540 | 2020-03-27T03:42:35 | 2020-03-27T03:42:35 | 250,431,969 | 0 | 1 | Apache-2.0 | 2020-03-27T03:48:25 | 2020-03-27T03:34:26 | Java | UTF-8 | Java | false | false | 3,890 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.runtime.io;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.source.SourceRecord;
import org.apache.flink.streaming.api.operators.StreamSourceV2;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.tasks.InputSelector.InputSelection;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* The type Source fetcher.
*/
class SourceFetcher implements InputFetcher {
private final StreamSourceV2 operator;
private final SourceInputProcessor processor;
private final SourceFunction.SourceContext context;
private final InputSelection inputSelection;
private boolean isIdle = false;
private volatile boolean finishedInput = false;
private InputFetcherAvailableListener listener;
/**
* Instantiates a new Source fetcher.
*
* @param operator the operator
* @param context the context
* @param processor the processor
*/
public SourceFetcher(
InputSelection inputSelection,
StreamSourceV2 operator,
SourceFunction.SourceContext context,
SourceInputProcessor processor) {
this.inputSelection = checkNotNull(inputSelection);
this.operator = checkNotNull(operator);
this.processor = checkNotNull(processor);
this.context = checkNotNull(context);
}
@Override
public void setup() throws Exception {
}
@SuppressWarnings("unchecked")
@Override
public boolean fetchAndProcess() throws Exception {
if (isFinished()) {
finishInput();
return false;
}
final SourceRecord sourceRecord = operator.next();
if (sourceRecord != null) {
final Object out = sourceRecord.getRecord();
if (sourceRecord.getWatermark() != null) {
context.emitWatermark(sourceRecord.getWatermark());
}
if (out != null) {
if (sourceRecord.getTimestamp() > 0) {
context.collectWithTimestamp(out, sourceRecord.getTimestamp());
} else {
context.collect(out);
}
}
isIdle = false;
} else {
context.markAsTemporarilyIdle();
isIdle = true;
}
if (isFinished()) {
finishInput();
return false;
}
// TODO: return !idle status, register a timer
return !isIdle;
}
private void finishInput() throws Exception {
if (!finishedInput) {
context.emitWatermark(Watermark.MAX_WATERMARK);
synchronized (context.getCheckpointLock()) {
processor.endInput();
processor.release();
}
finishedInput = true;
}
}
@Override
public boolean isFinished() {
return operator.isFinished();
}
@Override
public boolean moreAvailable() {
// TODO: register a timer to trigger available
return !isFinished();
}
@Override
public void cleanup() {
}
@Override
public void cancel() {
operator.cancel();
}
@Override
public InputSelection getInputSelection() {
return inputSelection;
}
@Override
public void registerAvailableListener(InputFetcherAvailableListener listener) {
checkState(this.listener == null);
this.listener = listener;
}
}
| [
"[email protected]"
]
| |
2175b02c3a031992a1e79c3b8b7654cc06801497 | c015b18a0e834064d6a5af141c8078acec777ae1 | /src/main/java/museum/controller/OwnerController.java | 9ff8e99e33745c1c2a684907a95f7f91140ffeb3 | []
| no_license | akuma190/Museum-Manager-Plus | 5d64bd1c7ac35b50dbdd87fbe149eaf25c316e2c | 56f40a4ce2133d93345f51a3be7c7e66f1a0bbd4 | refs/heads/main | 2023-01-30T00:52:18.993218 | 2020-12-10T02:17:59 | 2020-12-10T02:17:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,312 | java | package museum.controller;
import museum.model.*;
import museum.repository.*;
import museum.service.EmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Controller
public class OwnerController {
@Autowired
EmployeeServiceImpl empServ;
@Autowired
AuthoritiesRepository authoritiesRepository;
@Autowired
UsersRepository usersRepo;
@Autowired
AshishRepository ashRepo;
@Autowired
ArtistRepository artistRepo;
@Autowired
ArtworkRepository artworkRepository;
@Autowired
CollectorRepository collectorRepository;
@Autowired
ReportRepository reportRepository;
@Autowired
EmployeeRepository employeeRepository;
@Autowired
EventRepository eventRepository;
@Autowired
EventArtWorkRepository eventArtWorkRepository;
@Autowired
CustomerRepository customerRepository;
@Autowired
CharacteristicsRepository characteristicsRepository;
//to generate the links of all the artist pages pages.
@RequestMapping("/ownerIndex")
public String ownerIndex(@SessionAttribute("session") Session session,ModelMap model){
model.put("session",session);
List<report> repo=reportRepository.findBySellDate();
HashMap<report,artwork> hash=new HashMap<report,artwork>();
for(report re:repo){
System.out.println(re);
// System.out.println(artworkRepository.findOne(re.getArtworkid()));
hash.put(re,artworkRepository.findOne(re.getArtworkid()));
}
model.put("hash",hash);
return "owner_index";
}
@RequestMapping("/ownerArtworkList")
public String ownerArtworkList(@SessionAttribute("session") Session session,ModelMap model){
model.put("session",session);
List<artwork> artWo=artworkRepository.findAllForEvent();
model.put("artWo",artWo);
return "owner_artwork_list";
}
@RequestMapping("/ownerPaintingsApprove")
public String ownerPaintingsApprove(ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(artworkRepository.findAllByWait());
List<artwork> repo=artworkRepository.findAllByWait();
model.put("repo",repo);
return "owner_painting_approve";
}
@RequestMapping("/ownerCreateEvent")
public String ownerCreateEvent(ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
List<artist> repo= (List<artist>) artistRepo.findAll();
List<event> eventRepo= (List<event>) eventRepository.findAll();
model.put("repo",repo);
return "owner_create_event";
}
@RequestMapping("/ownerCheckReport")
public String ownerCheckReport(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
List<report> listRepo=reportRepository.findBySellDate();
HashMap<report,artwork> hash=new HashMap<report,artwork>();
ArrayList<String> arr=new ArrayList<String>();
int sum=0;
HashMap<Integer,String> hashName=new HashMap<Integer,String>();
for(report re:listRepo){
hash.put(re,artworkRepository.findOne(re.getArtworkid()));
System.out.println(artworkRepository.findOne(re.getArtworkid()).getArtist_type());
if(artworkRepository.findOne(re.getArtworkid()).getArtist_type().equals("collector")){
for(collector col:collectorRepository.findAll()){
hashName.put(col.getCollector_id(),col.getCollector_name());
}
}else{
for(artist ar:artistRepo.findAll()){
hashName.put(ar.getArtist_id(),ar.getArtist_name());
}
}
sum=sum+re.getSoldamount();
artist arti=artistRepo.findOneById(re.getArtcolid());
}
System.out.println(hash);
map.put("hash",hash);
map.put("sum",sum);
map.put("hashName",hashName);
return "owner_check_report";
}
@RequestMapping("/ownerManagePaintings")
public String ownerManagePaintings(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
System.out.println(artworkRepository.findForManageArt());
List<artwork> artWo=artworkRepository.findForManageArt();
map.put("artWo",artWo);
return "owner_manage_paintings";
}
@RequestMapping("/ownerManageArtwork")
public String ownerManageArtwork(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
List<artwork> artWo=artworkRepository.findAllForEvent();
map.put("artWo",artWo);
return "owner_manage_artwork";
}
@RequestMapping("/ownerManageArtists")
public String ownerManageArtists(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
List<artist> artistList= (List<artist>) artistRepo.findAll();
HashMap<users,artist> hash=new HashMap<users,artist>();
for(artist srt:artistList){
users user=usersRepo.findOne(srt.getArtist_name());
hash.put(user,srt);
}
map.put("hash",hash);
return "owner_manage_artist";
}
@RequestMapping("/ownerManageCollectors")
public String ownerManageCollectors(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
List<collector> artistList= (List<collector>) collectorRepository.findAll();
HashMap<users,collector> hash=new HashMap<users,collector>();
for(collector srt:artistList){
users user=usersRepo.findOne(srt.getCollector_name());
hash.put(user,srt);
}
map.put("hash",hash);
return "owner_manage_collector";
}
@RequestMapping("/ownerManageCustomers")
public String ownerManageCustomers(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
List<customer> artistList= (List<customer>) customerRepository.findAll();
HashMap<users,customer> hash=new HashMap<users,customer>();
for(customer srt:artistList){
users user=usersRepo.findOne(srt.getCustomername());
hash.put(user,srt);
}
map.put("hash",hash);
return "owner_manage_customer";
}
@RequestMapping("/ownerManageEvents")
public String ownerManageEvents(@SessionAttribute("session") Session session,ModelMap map){
map.put("session",session);
// System.out.println(eventRepository.findByEventId());
// System.out.println(eventRepository.findCountById(1));
HashMap<event,Integer> hash=new HashMap<event,Integer>();
for(event re:eventRepository.findByEventId()){
System.out.println(eventRepository.findCountById(re.getEventid()));
// if()
hash.put(re,eventRepository.findCountById(re.getEventid())==null?0:eventRepository.findCountById(re.getEventid()));
System.out.println(hash);
}
map.put("hash",hash);
return "owner_manage_events";
}
@RequestMapping("/deleteEvent/{eventId}")
public String deleteEvent(@PathVariable Integer eventId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(eventId);
int deleteId=eventId;
System.out.println(eventRepository.findOne(deleteId));
//delete from event
eventRepository.delete(eventRepository.findOne(deleteId));
System.out.println(eventArtWorkRepository.findMyEventList(deleteId));
for(eventArtwork eveart:eventArtWorkRepository.findMyEventList(deleteId)){
eventArtWorkRepository.delete(eveart);
}
//delete from artwork list
return "redirect:../ownerManageEvents";
}
@RequestMapping("/ownerEventInter")
public String ownerEventInter(@ModelAttribute("eve")event eve, ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
model.put("eve",eve);
return "owner_event_inter";
}
@RequestMapping("/ownerAddPaintings")
public String ownerAddPaintings(event eve,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
List<event> eventRepo= (List<event>) eventRepository.findAll();
int max=0;
for(event ar:eventRepo){
if(ar.getEventid()>max){
max=ar.getEventid();
}
}
eve.setEventid(max+1);
System.out.println(eve);
System.out.println(eve.getArtistid());
List<artwork> artRepo=new ArrayList<>();
if(eve.getArtistid()==-1){
artRepo=artworkRepository.findAllForEvent();
}else{
artRepo=artworkRepository.findForEvent(eve.getArtistid());
}
System.out.println(eve);
eventRepository.save(eve);
System.out.println(artRepo);
model.put("artRepo",artRepo);
model.put("max",(max+1));
return "owner_add_paintings";
}
@RequestMapping("/ownerPaintingDetails/{artId}")
public String ownerPaintingDetails(@PathVariable Integer artId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
artwork art=artworkRepository.findOne(artId);
characteristics chart=characteristicsRepository.findOne(artId);
return "owner_painting_details";
}
@RequestMapping("/ownerfinalApprove/{artId}")
public String ownerfinalApprove(@PathVariable Integer artId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(artId);
System.out.println(employeeRepository.findAll());
ArrayList<employee> arr= (ArrayList<employee>) employeeRepository.findAllXcpt();
artwork repo=artworkRepository.findOne(artId);
model.put("repo",repo);
model.put("arr",arr);
return "owner_final_approve";
}
@RequestMapping("/deleteArtwork")
public String deleteArtwork(@RequestParam int artId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(artId);
artwork art=artworkRepository.findOne(artId);
artworkRepository.delete(art);
return "redirect:ownerPaintingsApprove";
}
@RequestMapping("/ownerEditEmployee/{username}")
public String ownerEditEmployee(@PathVariable String username,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println("edit"+username);
users user=usersRepo.findOne(username);
model.put("user",user);
return "owner_edit_employee";
}
@RequestMapping("/ownerEditArtwork/{artId}")
public String ownerEditEmployee(@PathVariable Integer artId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println("edit"+artId);
artwork artWo=artworkRepository.findOne(artId);
model.put("artWo",artWo);
characteristics charec=characteristicsRepository.findOne(artId);
System.out.println(charec);
model.put("charec",charec);
return "owner_edit_artwork";
}
@RequestMapping("/ownerFinalEditArtwork")
public String ownerFinalEditArtwork(ModelMap model,@SessionAttribute("session") Session session,artwork artwo,characteristics chare){
model.put("session",session);
System.out.println(artwo);
System.out.println(chare);
// artworkRepository.save(artwo);
// characteristicsRepository.save(chare);
return "redirect:ownerManageArtwork";
}
@RequestMapping("/ownerFinalEditEmployee")
public String ownerFinalEditEmployee(ModelMap model,@SessionAttribute("session") Session session,users user){
model.put("session",session);
System.out.println("edit2"+user);
users userChange=usersRepo.findOne(user.getUsername());
userChange.setFirstname(user.getFirstname());
userChange.setFirstname(user.getLastname());
System.out.println(userChange);
//usersRepo.save(userChange);
if(authoritiesRepository.findOne(user.getUsername()).getAuthority().equals("collector")){
return "redirect:ownerManageCollectors";
}
else if(authoritiesRepository.findOne(user.getUsername()).getAuthority().equals("artist")){
return "redirect:ownerManageArtists";
}
else{
return "redirect:ownerManageCustomers";
}
}
@RequestMapping("/ownerDeleteEmployee/{username}")
public String ownerDeleteEmployee(@PathVariable String username,ModelMap model,@SessionAttribute("session") Session session){
System.out.println("delete"+username);
return "redirect:../ownerManageCustomers";
}
@RequestMapping("/ownerExtendPainting/{artId}")
public String ownerExtendPainting(@PathVariable Integer artId,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(artId);
artwork art=artworkRepository.findOne(artId);
art.setCreationdate(LocalDate.now().toString());
System.out.println(art);
artworkRepository.save(art);
return "redirect:../ownerManagePaintings";
}
@RequestMapping("/actionAddPainting")
public String actionAddPainting(@RequestParam String artId,@RequestParam String salesname,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println(artId);
System.out.println(salesname);
artwork art=artworkRepository.findOne(Integer.parseInt(artId));
art.setStatus("in_museum");
art.setSalesperson(Integer.parseInt(salesname));
artworkRepository.save(art);
return "redirect:ownerPaintingsApprove";
}
@RequestMapping("/addNewEvent")
public String actionAddPainting(@RequestParam int eventId,CheckBox chkb,ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
System.out.println("hello");
System.out.println(eventId);
System.out.println(chkb);
String[] arr=chkb.getCheckBoxes();
int max=0;
for(eventArtwork test :eventArtWorkRepository.findAll()){
if(test.getEventartid()>max){
max=test.getArtworkid();
}
}
System.out.println(max);
for(String ir:arr){
max=max+1;
eventArtwork eventArt=new eventArtwork();
eventArt.setEventid(eventId);
artwork art=artworkRepository.findOne(Integer.parseInt(ir));
System.out.println(art);
eventArt.setArtworkid(Integer.parseInt(ir));
eventArt.setSalesperson(art.getSalesperson());
eventArt.setEventartid(max);
eventArt.setStatus("in_event");
System.out.println(eventArt);
eventArtWorkRepository.save(eventArt);
art.setStatus("in_event");
artworkRepository.save(art);
}
return "owner_create_event";
}
@RequestMapping("/ownerManageAccount")
public String ownerManageAccount(ModelMap model,@SessionAttribute("session") Session session){
model.put("session",session);
users user=usersRepo.findOne(session.getUsername());
model.put("user",user);
return "owner_manage_account";
}
@RequestMapping("/changeAccount")
public String changeAccount(ModelMap model,@SessionAttribute("session") Session session,users user){
model.put("session",session);
System.out.println(user);
usersRepo.save(user);
return "redirect:ownerManageAccount";
}
}
| [
"[email protected]"
]
| |
9e569c1e374fb5995d1cbaac08d1c13dac27bae9 | d3cfa92668ee88c05403932c259e780799e45b7d | /src/main/java/com/rongji/cms/recommend/engine/common/TableMappingToHbase.java | db72800852158e258beded3cc6b0cacbcc43bd1b | []
| no_license | hadbeanliu/RECOMMEND-ENGINE | fb751dc63a1dbe47b2f15a425ca7861b1bb23917 | 2a5561146ecef644c846142d2439986060d7f9a2 | refs/heads/master | 2021-08-22T03:48:25.164477 | 2017-11-29T05:59:09 | 2017-11-29T05:59:09 | 112,433,026 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,671 | java | //package com.rongji.cms.recommend.engine.common;
//
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import org.apache.hadoop.conf.Configuration;
//import org.apache.hadoop.hbase.HColumnDescriptor;
//import org.apache.hadoop.hbase.HTableDescriptor;
//import org.apache.hadoop.hbase.MasterNotRunningException;
//import org.apache.hadoop.hbase.ZooKeeperConnectionException;
//import org.apache.hadoop.hbase.client.HBaseAdmin;
//import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
//import org.apache.hadoop.hbase.regionserver.BloomType;
//import org.apache.hadoop.hbase.util.Bytes;
//import org.jdom.Document;
//import org.jdom.Element;
//import org.jdom.JDOMException;
//import org.jdom.input.SAXBuilder;
//
//
//public class TableMappingToHbase {
//
// private static String MappingFile = "base-hbase-mapping.xml";
//
// private static Map<String, Map<String, HColumnDescriptor>> tableToFamilys = new HashMap<String, Map<String, HColumnDescriptor>>();
//
// private Map<String, HColumnDescriptor> getOrCreateFamilys(String name) {
//
// if (tableToFamilys.containsKey(name))
// return tableToFamilys.get(name);
// else {
// Map<String, HColumnDescriptor> familys = new HashMap<String, HColumnDescriptor>();
// tableToFamilys.put(name, familys);
// return familys;
// }
// }
//
// private HColumnDescriptor getOrCreateCol(String name,Map<String, HColumnDescriptor> hCols) {
// if (hCols.containsKey(name))
// return hCols.get(name);
// else {
//
// HColumnDescriptor hCol = new HColumnDescriptor(name);
// hCols.put(name, hCol);
// return hCol;
// }
// }
//
// public HColumnDescriptor build(String tableName, String familyName, String
// compression, String blockCache, String blockSize, String
// bloomFilter,String maxVersions, String timeToLive, String
// inMemory){
//
// Map<String, HColumnDescriptor> familys=getOrCreateFamilys(tableName);
// HColumnDescriptor columnDescriptor=getOrCreateCol(familyName, familys);
//
// if(compression != null)
// columnDescriptor.setCompressionType(Algorithm.valueOf(compression));
// if(blockCache != null)
// columnDescriptor.setBlockCacheEnabled(Boolean.parseBoolean(blockCache));
// if(blockSize != null)
// columnDescriptor.setBlocksize(Integer.parseInt(blockSize));
// if(bloomFilter != null)
// columnDescriptor.setBloomFilterType(BloomType.valueOf(bloomFilter));
// if(maxVersions != null)
// columnDescriptor.setMaxVersions(Integer.parseInt(maxVersions));
// if(timeToLive != null)
// columnDescriptor.setTimeToLive(Integer.parseInt(timeToLive));
// if(inMemory != null)
// columnDescriptor.setInMemory(Boolean.parseBoolean(inMemory));
// return columnDescriptor;
//
// } /**
// * @param args
// * @throws IOException
// * @throws JDOMException
// */
//
// public Map<String,HTableDescriptor> readMappingFile(String fileName) throws JDOMException, IOException{
// String mappingFile=MappingFile;
// if(fileName!=null)
// mappingFile=fileName;
//
// SAXBuilder build=new SAXBuilder();
//
// Document doc=build.build(TableMappingToHbase.class.getClassLoader().getResourceAsStream(mappingFile));
//
// Element root=doc.getRootElement();
//
// List<Element> tables=root.getChildren("table");
//
// Map<String,HTableDescriptor> descs=new HashMap<String,HTableDescriptor>();
//
// for(int i=0;i<tables.size();i++){
//
// Element table=tables.get(i);
//
// String tableName=table.getAttributeValue("name");
//
// HTableDescriptor desc=new HTableDescriptor(tableName);
//
// String keyClass=table.getAttributeValue("keyClass");
//
// List<Element> fields=table.getChildren("family");
//
// for(int j=0;j<fields.size();j++){
//
// Element family=fields.get(j);
// String familyName = family.getAttributeValue("name");
// String compression = family.getAttributeValue("compression");
// String blockCache = family.getAttributeValue("blockCache");
// String blockSize = family.getAttributeValue("blockSize");
// String bloomFilter = family.getAttributeValue("bloomFilter");
// String maxVersions = family.getAttributeValue("maxVersions");
// String timeToLive = family.getAttributeValue("timeToLive");
// String inMemory = family.getAttributeValue("inMemory");
//
// HColumnDescriptor hcol= build(tableName, familyName, compression, blockCache, blockSize, bloomFilter, maxVersions, timeToLive, inMemory);
//// println(tableName, familyName, compression, blockCache, blockSize, bloomFilter, maxVersions, timeToLive, inMemory)
// desc.addFamily(hcol);
// }
// descs.put(tableName, desc);
//
// }
//
// return descs;
//
// }
//
// public void createTable(HTableDescriptor desc,Configuration conf){
//
// String name=conf.get("preferred.table.name",Bytes.toString(desc.getName()));
//
// HBaseAdmin admin = null;
// try {
// admin = new HBaseAdmin(conf);
// if(!(admin.tableExists(name)||admin.isTableDisabled(name))){
// desc.setName(name.getBytes());
// admin.createTable(desc);
// admin.flush(name);
// }
// } catch (MasterNotRunningException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (ZooKeeperConnectionException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }finally{
// try {
// admin.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void main(String[] args) {
// // TODO Auto-generated method stub
//
// }
//
//}
| [
"[email protected]"
]
| |
fb10a2d482124b2bae88073417f29442040e1502 | 09d0ddd512472a10bab82c912b66cbb13113fcbf | /TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/JADX/src/main/java/com/google/android/exoplayer2/trackselection/AdaptiveTrackSelection.java | 1cc088c69d01ec486286c98c506aff60b7577285 | []
| no_license | sgros/activity_flow_plugin | bde2de3745d95e8097c053795c9e990c829a88f4 | 9e59f8b3adacf078946990db9c58f4965a5ccb48 | refs/heads/master | 2020-06-19T02:39:13.865609 | 2019-07-08T20:17:28 | 2019-07-08T20:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,229 | java | package com.google.android.exoplayer2.trackselection;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.MediaChunk;
import com.google.android.exoplayer2.source.chunk.MediaChunkIterator;
import com.google.android.exoplayer2.trackselection.TrackSelection.Definition;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Util;
import java.util.List;
public class AdaptiveTrackSelection extends BaseTrackSelection {
private final BandwidthProvider bandwidthProvider;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final Clock clock;
private final int[] formatBitrates;
private final Format[] formats;
private long lastBufferEvaluationMs;
private final long maxDurationForQualityDecreaseUs;
private final long minDurationForQualityIncreaseUs;
private final long minDurationToRetainAfterDiscardUs;
private final long minTimeBetweenBufferReevaluationMs;
private float playbackSpeed;
private int reason;
private int selectedIndex;
private TrackBitrateEstimator trackBitrateEstimator;
private final int[] trackBitrates;
private interface BandwidthProvider {
long getAllocatedBandwidth();
}
private static final class DefaultBandwidthProvider implements BandwidthProvider {
private final float bandwidthFraction;
private final BandwidthMeter bandwidthMeter;
private long nonAllocatableBandwidth;
DefaultBandwidthProvider(BandwidthMeter bandwidthMeter, float f) {
this.bandwidthMeter = bandwidthMeter;
this.bandwidthFraction = f;
}
public long getAllocatedBandwidth() {
return Math.max(0, ((long) (((float) this.bandwidthMeter.getBitrateEstimate()) * this.bandwidthFraction)) - this.nonAllocatableBandwidth);
}
/* Access modifiers changed, original: 0000 */
public void experimental_setNonAllocatableBandwidth(long j) {
this.nonAllocatableBandwidth = j;
}
}
public static final class Factory implements com.google.android.exoplayer2.trackselection.TrackSelection.Factory {
private final float bandwidthFraction;
private final BandwidthMeter bandwidthMeter;
private boolean blockFixedTrackSelectionBandwidth;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final Clock clock;
private final int maxDurationForQualityDecreaseMs;
private final int minDurationForQualityIncreaseMs;
private final int minDurationToRetainAfterDiscardMs;
private final long minTimeBetweenBufferReevaluationMs;
private TrackBitrateEstimator trackBitrateEstimator;
@Deprecated
public Factory(BandwidthMeter bandwidthMeter) {
this(bandwidthMeter, 10000, 25000, 25000, 0.75f, 0.75f, 2000, Clock.DEFAULT);
}
@Deprecated
public Factory(BandwidthMeter bandwidthMeter, int i, int i2, int i3, float f, float f2, long j, Clock clock) {
this.bandwidthMeter = bandwidthMeter;
this.minDurationForQualityIncreaseMs = i;
this.maxDurationForQualityDecreaseMs = i2;
this.minDurationToRetainAfterDiscardMs = i3;
this.bandwidthFraction = f;
this.bufferedFractionToLiveEdgeForQualityIncrease = f2;
this.minTimeBetweenBufferReevaluationMs = j;
this.clock = clock;
this.trackBitrateEstimator = TrackBitrateEstimator.DEFAULT;
}
public TrackSelection[] createTrackSelections(Definition[] definitionArr, BandwidthMeter bandwidthMeter) {
TrackSelection[] trackSelectionArr = new TrackSelection[definitionArr.length];
AdaptiveTrackSelection adaptiveTrackSelection = null;
int i = 0;
for (int i2 = 0; i2 < definitionArr.length; i2++) {
Definition definition = definitionArr[i2];
if (definition != null) {
int[] iArr = definition.tracks;
if (iArr.length > 1) {
adaptiveTrackSelection = createAdaptiveTrackSelection(definition.group, bandwidthMeter, iArr);
trackSelectionArr[i2] = adaptiveTrackSelection;
} else {
trackSelectionArr[i2] = new FixedTrackSelection(definition.group, iArr[0]);
int i3 = definition.group.getFormat(definition.tracks[0]).bitrate;
if (i3 != -1) {
i += i3;
}
}
}
}
if (this.blockFixedTrackSelectionBandwidth && adaptiveTrackSelection != null) {
adaptiveTrackSelection.experimental_setNonAllocatableBandwidth((long) i);
}
return trackSelectionArr;
}
private AdaptiveTrackSelection createAdaptiveTrackSelection(TrackGroup trackGroup, BandwidthMeter bandwidthMeter, int[] iArr) {
BandwidthMeter bandwidthMeter2 = this.bandwidthMeter;
if (bandwidthMeter2 == null) {
bandwidthMeter2 = bandwidthMeter;
}
AdaptiveTrackSelection adaptiveTrackSelection = r2;
AdaptiveTrackSelection adaptiveTrackSelection2 = new AdaptiveTrackSelection(trackGroup, iArr, new DefaultBandwidthProvider(bandwidthMeter2, this.bandwidthFraction), (long) this.minDurationForQualityIncreaseMs, (long) this.maxDurationForQualityDecreaseMs, (long) this.minDurationToRetainAfterDiscardMs, this.bufferedFractionToLiveEdgeForQualityIncrease, this.minTimeBetweenBufferReevaluationMs, this.clock);
adaptiveTrackSelection2 = adaptiveTrackSelection;
adaptiveTrackSelection2.experimental_setTrackBitrateEstimator(this.trackBitrateEstimator);
return adaptiveTrackSelection2;
}
}
public Object getSelectionData() {
return null;
}
private AdaptiveTrackSelection(TrackGroup trackGroup, int[] iArr, BandwidthProvider bandwidthProvider, long j, long j2, long j3, float f, long j4, Clock clock) {
super(trackGroup, iArr);
this.bandwidthProvider = bandwidthProvider;
this.minDurationForQualityIncreaseUs = j * 1000;
this.maxDurationForQualityDecreaseUs = j2 * 1000;
this.minDurationToRetainAfterDiscardUs = j3 * 1000;
this.bufferedFractionToLiveEdgeForQualityIncrease = f;
this.minTimeBetweenBufferReevaluationMs = j4;
this.clock = clock;
this.playbackSpeed = 1.0f;
int i = 0;
this.reason = 0;
this.lastBufferEvaluationMs = -9223372036854775807L;
this.trackBitrateEstimator = TrackBitrateEstimator.DEFAULT;
int i2 = this.length;
this.formats = new Format[i2];
this.formatBitrates = new int[i2];
this.trackBitrates = new int[i2];
while (i < this.length) {
Format format = getFormat(i);
Format[] formatArr = this.formats;
formatArr[i] = format;
this.formatBitrates[i] = formatArr[i].bitrate;
i++;
}
}
public void experimental_setTrackBitrateEstimator(TrackBitrateEstimator trackBitrateEstimator) {
this.trackBitrateEstimator = trackBitrateEstimator;
}
public void experimental_setNonAllocatableBandwidth(long j) {
((DefaultBandwidthProvider) this.bandwidthProvider).experimental_setNonAllocatableBandwidth(j);
}
public void enable() {
this.lastBufferEvaluationMs = -9223372036854775807L;
}
public void onPlaybackSpeed(float f) {
this.playbackSpeed = f;
}
public void updateSelectedTrack(long j, long j2, long j3, List<? extends MediaChunk> list, MediaChunkIterator[] mediaChunkIteratorArr) {
j = this.clock.elapsedRealtime();
this.trackBitrateEstimator.getBitrates(this.formats, list, mediaChunkIteratorArr, this.trackBitrates);
if (this.reason == 0) {
this.reason = 1;
this.selectedIndex = determineIdealSelectedIndex(j, this.trackBitrates);
return;
}
int i = this.selectedIndex;
this.selectedIndex = determineIdealSelectedIndex(j, this.trackBitrates);
if (this.selectedIndex != i) {
if (!isBlacklisted(i, j)) {
Format format = getFormat(i);
Format format2 = getFormat(this.selectedIndex);
if (format2.bitrate > format.bitrate && j2 < minDurationForQualityIncreaseUs(j3)) {
this.selectedIndex = i;
} else if (format2.bitrate < format.bitrate && j2 >= this.maxDurationForQualityDecreaseUs) {
this.selectedIndex = i;
}
}
if (this.selectedIndex != i) {
this.reason = 3;
}
}
}
public int getSelectedIndex() {
return this.selectedIndex;
}
public int getSelectionReason() {
return this.reason;
}
public int evaluateQueueSize(long j, List<? extends MediaChunk> list) {
long elapsedRealtime = this.clock.elapsedRealtime();
if (!shouldEvaluateQueueSize(elapsedRealtime)) {
return list.size();
}
this.lastBufferEvaluationMs = elapsedRealtime;
int i = 0;
if (list.isEmpty()) {
return 0;
}
int size = list.size();
long playoutDurationForMediaDuration = Util.getPlayoutDurationForMediaDuration(((MediaChunk) list.get(size - 1)).startTimeUs - j, this.playbackSpeed);
long minDurationToRetainAfterDiscardUs = getMinDurationToRetainAfterDiscardUs();
if (playoutDurationForMediaDuration < minDurationToRetainAfterDiscardUs) {
return size;
}
Format format = getFormat(determineIdealSelectedIndex(elapsedRealtime, this.formatBitrates));
while (i < size) {
MediaChunk mediaChunk = (MediaChunk) list.get(i);
Format format2 = mediaChunk.trackFormat;
if (Util.getPlayoutDurationForMediaDuration(mediaChunk.startTimeUs - j, this.playbackSpeed) >= minDurationToRetainAfterDiscardUs && format2.bitrate < format.bitrate) {
int i2 = format2.height;
if (i2 != -1 && i2 < 720) {
int i3 = format2.width;
if (i3 != -1 && i3 < 1280 && i2 < format.height) {
return i;
}
}
}
i++;
}
return size;
}
/* Access modifiers changed, original: protected */
public boolean canSelectFormat(Format format, int i, float f, long j) {
return ((long) Math.round(((float) i) * f)) <= j;
}
/* Access modifiers changed, original: protected */
public boolean shouldEvaluateQueueSize(long j) {
long j2 = this.lastBufferEvaluationMs;
return j2 == -9223372036854775807L || j - j2 >= this.minTimeBetweenBufferReevaluationMs;
}
/* Access modifiers changed, original: protected */
public long getMinDurationToRetainAfterDiscardUs() {
return this.minDurationToRetainAfterDiscardUs;
}
private int determineIdealSelectedIndex(long j, int[] iArr) {
long allocatedBandwidth = this.bandwidthProvider.getAllocatedBandwidth();
int i = 0;
int i2 = 0;
while (i < this.length) {
if (j == Long.MIN_VALUE || !isBlacklisted(i, j)) {
if (canSelectFormat(getFormat(i), iArr[i], this.playbackSpeed, allocatedBandwidth)) {
return i;
}
i2 = i;
}
i++;
}
return i2;
}
private long minDurationForQualityIncreaseUs(long j) {
Object obj = (j == -9223372036854775807L || j > this.minDurationForQualityIncreaseUs) ? null : 1;
return obj != null ? (long) (((float) j) * this.bufferedFractionToLiveEdgeForQualityIncrease) : this.minDurationForQualityIncreaseUs;
}
}
| [
"[email protected]"
]
| |
686c4c4df6cd553ffb703a6dec51c46d780596b2 | 8d4361caaf7fd62771dc2ae274a3e43ecc4df74d | /src/com/aj/sotf/graphics/Sprite.java | 8dbbf80729f04ee52d95e0e7ec933c8defba234e | []
| no_license | andrewj6574/SotF | 6d1f4901d4c8882c961ae0a84401a066498f0644 | 258cae046299dd5f7fda4e0770a19566111d0986 | refs/heads/master | 2021-05-30T17:19:25.014701 | 2015-12-11T21:06:32 | 2015-12-11T21:06:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,920 | java | package com.aj.sotf.graphics;
public class Sprite {
private int x;
private int y;
public int size;
private SpriteSheet sheet;
public int[] pixels;
public static Sprite s1 = new Sprite(0, 0, 16, SpriteSheet.tiles);
public static Sprite s2 = new Sprite(1, 0, 16, SpriteSheet.tiles);
public static Sprite grass = new Sprite(2, 0, 16, SpriteSheet.tiles);
public static Sprite water = new Sprite(0, 1, 16, SpriteSheet.tiles);
public static Sprite water2 = new Sprite(1, 1, 16, SpriteSheet.tiles);
public static Sprite dirt = new Sprite(1, 0, 16, SpriteSheet.tiles);
public static Sprite player_up = new Sprite(0, 0, 16, SpriteSheet.player);
public static Sprite player_up2 = new Sprite(1, 0, 16, SpriteSheet.player);
public static Sprite player_up3 = new Sprite(2, 0 , 16, SpriteSheet.player);
public static Sprite player_right = new Sprite(0, 1, 16, SpriteSheet.player);
public static Sprite player_right2 = new Sprite(1, 1, 16, SpriteSheet.player);
public static Sprite player_right3 = new Sprite(2, 1, 16, SpriteSheet.player);
public static Sprite player_down = new Sprite(0, 2, 16, SpriteSheet.player);
public static Sprite player_down2 = new Sprite(1, 2, 16, SpriteSheet.player);
public static Sprite player_down3 = new Sprite(2, 2, 16, SpriteSheet.player);
public static Sprite player_left = new Sprite(0, 3, 16, SpriteSheet.player);
public static Sprite player_left2 = new Sprite(1, 3, 16, SpriteSheet.player);
public static Sprite player_left3 = new Sprite(2, 3, 16, SpriteSheet.player);
public Sprite(int x, int y, int size, SpriteSheet sheet) {
this.size = size;
this.x = x * size;
this.y = y * size;
this.sheet = sheet;
pixels = new int[size*size];
load();
}
public void load() {
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
pixels[x + y * size] = sheet.pixels[(x + this.x) + (y + this.y) * sheet.size];
}
}
}
public void render(int xx, int yy, float intensity, Screen screen) {
// for (int y = yy; y < yy + Sprite.s1.size; y++) {
// int ya = this.y + y;
// for (int x = xx; x < xx + Sprite.s1.size; x++) {
// int xa = this.x + x;
// screen.pixels[xa + ya * screen.width] = Sprite.s1.pixels[(x - xx) + (y - yy) * Sprite.s1.size];
// }
// }
int tx = xx * size;
int ty = yy * size;
for (int y = 0; y < size; y++) {
int ya = ty + y;
for (int x = 0; x < size; x++) {
int xa = tx + x;
if (xa < 0 || xa >= screen.width || ya < 0 || ya >= screen.height) break;
// System.out.println("xa : " + xa + ", ya : " + ya);
int colour = pixels[x + y * size];
if (colour == 0xFFFF00FF) continue;
int r = (colour >> 16) & 0xff;
int g = (colour >> 8) & 0xff;
int b = (colour) & 0xff;
r *= intensity;
g *= intensity;
b *= intensity;
colour = (r << 16) | (g << 8) | b;
screen.pixels[xa + ya * screen.width] = colour;
}
}
}
}
| [
"[email protected]"
]
| |
c7cfc5741a8a63c7fc5dcd79bd28a86265b52446 | 95e944448000c08dd3d6915abb468767c9f29d3c | /sources/com/google/android/gms/ads/mediation/C14883b.java | 4365dc2bfc3e5e7c943f1e8f62b4742f3fcd28fd | []
| no_license | xrealm/tiktok-src | 261b1faaf7b39d64bb7cb4106dc1a35963bd6868 | 90f305b5f981d39cfb313d75ab231326c9fca597 | refs/heads/master | 2022-11-12T06:43:07.401661 | 2020-07-04T20:21:12 | 2020-07-04T20:21:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 745 | java | package com.google.android.gms.ads.mediation;
import android.os.Bundle;
/* renamed from: com.google.android.gms.ads.mediation.b */
public interface C14883b {
/* renamed from: com.google.android.gms.ads.mediation.b$a */
public static class C14884a {
/* renamed from: a */
private int f38519a;
/* renamed from: a */
public final C14884a mo37907a(int i) {
this.f38519a = 1;
return this;
}
/* renamed from: a */
public final Bundle mo37906a() {
Bundle bundle = new Bundle();
bundle.putInt("capabilities", this.f38519a);
return bundle;
}
}
void onDestroy();
void onPause();
void onResume();
}
| [
"[email protected]"
]
| |
9d3e3ad825d1fc4b076d6852876b23d32847ef11 | a31467252e383a5cf8b527627686be70211edf39 | /src/main/java/object/HelloDate.java | 31aa1e8349a41bafe4489dcb15ce5caced3c3c12 | []
| no_license | xiaozhiliaoo/thinkinginjava-practice | 214604f6e843ffc989b2c8bc2f62e11fc17622f5 | c47a8c578dfef275cfe956252a2462554f245020 | refs/heads/master | 2022-08-09T18:08:39.063874 | 2022-07-30T09:57:35 | 2022-07-30T09:57:35 | 248,148,101 | 0 | 0 | null | 2020-10-13T20:26:58 | 2020-03-18T05:41:16 | Java | UTF-8 | Java | false | false | 598 | java | //: object/HelloDate.java
package object;
import java.util.*;
/** The first Thinking in Java example program.
* Displays a string and today's date. i am lili
* @author Bruce Eckel
* @author www.MindView.net
* @version 4.0
*/
//P30
public class HelloDate {
/** Entry point to class & application.
* @param args array of string arguments
* @throws exceptions No exceptions thrown
*/
public static void main(String[] args) {
System.out.println("Hello, it's: ");
System.out.println(new Date());
}
} /* Output: (55% match)
Hello, it's:
Wed Oct 05 14:39:36 MDT 2005
*///:~
| [
"[email protected]"
]
| |
caddebe49ef4c05f56621968481577912ef53c18 | 22bff10f70ddbe1e8e6a2ef2d3d4272c15b010ed | /src/decorate/CornDecorator.java | f9479234e427592fd4d65e6ac841d9f6974c0bb7 | []
| no_license | yydsyzc/design | 95a1621c65d065a39d211c86269ff9707aa87007 | e1e47a020a2866f3a924817162ac8bd2cca484c1 | refs/heads/master | 2021-09-21T09:53:09.820276 | 2018-08-24T03:49:52 | 2018-08-24T03:49:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 815 | java | package decorate;
/**
* Created with IntelliJ IDEA.
* Description:制作带有颜色的馒头
* CornDecorator继承了AbstractBread类,可以有选择的覆盖(重写)AbstractBread的制作普通馒头的方法,
* 并添加原有方法的原来的信息,最主要的是可以添加自己需要的方法
* 装饰者模式中这里最关键,
* 对应上述的第1个注意点:装饰者类要实现真实类同样的接口
*
* @Author: yangzhicheng
* @Date: 2018/7/31 17:03
*/
public class CornDecorator extends AbstractBread {
public CornDecorator(IBread iBread) {
super(iBread);
}
public void paint(){
System.out.println("添加染色剂.....");
}
public void kneadFlour(){
paint();//添加染色剂
super.kneadFlour();//和面
}
}
| [
"[email protected]"
]
| |
bbbcc705a66ecaa6d13fdd820eec7e3e10e7c91f | 0f745e96a4de5aba24a6fdf590cb94033970e657 | /app/src/main/java/com/loremjit/centraldechamados/activities/LoginActivity.java | 44f620aef231a2826ce2c1a72c47c535cff99751 | []
| no_license | risesmj/HelpDeskpLoremJIT | 7d5c2ace4b3d2d367b629eae751f5926ff1c3312 | 9c0d57e545e4c4e208f9158895d038196196a970 | refs/heads/main | 2023-06-15T13:06:08.779846 | 2021-07-09T15:04:06 | 2021-07-09T15:04:06 | 384,472,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,315 | java | package com.loremjit.centraldechamados.activities;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.loremjit.centraldechamados.R;
import com.loremjit.centraldechamados.model.Login.Autenticacao;
public class LoginActivity extends AppCompatActivity {
private EditText etUsuario;
private EditText etSenha;
private Switch swManterConectado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
etUsuario = findViewById(R.id.etUsuario);
etSenha = findViewById(R.id.etSenha);
swManterConectado = findViewById(R.id.swManterConectado);
}
public void botaoEntrar(View v){
Autenticacao autenticacao = new Autenticacao(etUsuario.getText().toString(),
etSenha.getText().toString(),
swManterConectado.isChecked());
if(autenticacao.connect()) {
setResult(RESULT_OK);
finish();
}else{
Toast.makeText(this,getString(R.string.login_invalido),Toast.LENGTH_LONG).show();
}
}
}
| [
"[email protected]"
]
| |
77e5c821d89b72e37e602fe37e66dea1a4648ab4 | 2a86ca01267216d0e0479d651c900816fa96cf3f | /AutomationCoolTesterMayo/src/test/java/com/java/BucleStatement.java | 077b0163017c9b224dc9e94d9160c563524a7399 | []
| no_license | marcelamontgel/web-selenium-course-may | 9913f727996b50278be63c597073ec52d1817ff4 | feb1d9fda0930148da85e49c13584f9d608abd76 | refs/heads/master | 2023-05-27T22:27:07.440467 | 2021-06-19T03:18:06 | 2021-06-19T03:18:06 | 374,129,873 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 261 | java | package com.java;
public class BucleStatement {
public static void main(String[] args) {
// TODO Auto-generated method stub
// While
int numero = 1;
while (numero <= 10) {
System.out.println("El número es: " + numero);
++numero;
}
}
}
| [
"[email protected]"
]
| |
053f5eb939a31b5aae1504db4872ef493b9ec454 | c34e8b5a777cab51125b9aef80d0acfbffd659c7 | /src/main/java/com/example/katemovies/service/ActorServiceImpl.java | d90b01492bdd0ace6ff43b9963dd8742988507c7 | []
| no_license | kmouzakiti/katemovies | 29e787fedfa30cef08d3099954ba67c23c949a4f | 5117849c77e785b9da210bf6f1f00551a5887963 | refs/heads/master | 2023-04-28T15:28:00.167465 | 2021-05-20T17:34:44 | 2021-05-20T17:34:44 | 368,823,796 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 885 | java | package com.example.katemovies.service;
import com.example.katemovies.domain.Actor;
import com.example.katemovies.domain.Movie;
import com.example.katemovies.repository.ActorRepository;
import com.example.katemovies.transfer.KeyValue;
import lombok.RequiredArgsConstructor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ActorServiceImpl extends com.example.katemovies.service.AbstractServiceImpl<Actor> implements ActorService {
private final ActorRepository actorRepository;
@Override
public JpaRepository<Actor, Long> getRepository() {
return actorRepository;
}
@Override
public Actor findActorbyAge(String title) {
return actorRepository.findActorbyAge(title);
}
}
| [
"[email protected]"
]
| |
f54eb82d745edff4828dc9cc5a683d7d7d97a1cf | 92b5f277f6e02a09b54626dbcce545a181499986 | /JDBC-Assignment1/com/metacube/jdbc/test/testQueries.java | 56b29926f392e591365ccec2954b6fef44a68fc4 | []
| no_license | meta-prateek-jain/GET2017 | d780821885ce7e8a35d07b16359ab5a896d3cc56 | f5cbbab7c594e07083dcb9ade47c2b303bfe80fb | refs/heads/master | 2021-01-01T04:41:51.510949 | 2017-10-30T08:49:01 | 2017-10-30T08:49:01 | 97,224,828 | 0 | 1 | null | 2019-11-13T03:27:09 | 2017-07-14T10:59:13 | Java | UTF-8 | Java | false | false | 2,416 | java | /**
*
*/
package com.metacube.jdbc.test;
import static org.junit.Assert.*;
import java.sql.SQLException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.metacube.jdbc.model.Title;
import com.metacube.jdbc.util.Constants;
import com.metacube.jdbc.util.Helper;
import com.metacube.jdbc.util.MySQlConnection;
/**
* Test class to check queries are correct or not
*
* @author Prateek Jain
*
*/
public class TestQueries {
private Helper helper;
/**
* Method is used to set up the class object before start testing
*/
@Before
public void setUp() {
helper = Helper.getInstance();
}
/**
* Test method to check connection password is right
*/
@Test
public void testConnectionWhenEstablish() {
assertNotNull(MySQlConnection.establish());
}
/**
* Test method to check books fetch method for valid author name
*
* @throws SQLException
*/
@Test
public void testFetchMethodWhenValid() throws SQLException {
List<Title> titlesList = helper.fetchBooksWrittenByAuthor("henry");
String actualResult = "";
// loop continue till end of list
for (Title title : titlesList) {
actualResult += title.getName();
}
assertEquals("Physics", actualResult);
}
/**
* Test method to check books fetch method for wrong author name
*
* @throws SQLException
*/
@Test
public void testFetchBooksMethodWhenInvalid() throws SQLException {
List<Title> titlesList = helper.fetchBooksWrittenByAuthor("example");
String actualResult = "";
// loop continue till end of list
for (Title title : titlesList) {
actualResult += title.getName();
}
assertNotEquals("Physics", actualResult);
}
/**
* Test method to check book issued when book name is valid
*
* @throws SQLException
*/
@Test
public void testIsBookIssuedWhenValid() throws SQLException {
assertEquals(0, helper.isBookIssued("Cooking With Computers"));
}
/**
* Test method to check book issued when book name is Invalid
*
* @throws SQLException
*/
@Test
public void testIsBookIssuedWhenInvalid() throws SQLException {
assertEquals(-1, helper.isBookIssued("example"));
}
/**
* Test method to check book deleted or not which are not issued since last year
*
* @throws SQLException
*/
@Test
public void testDeleteBooksNotIssuedSinceLastYear() throws SQLException {
assertEquals(0, helper.deleteBooksNotIssuedSinceLastYear());
}
}
| [
"[email protected]"
]
| |
b2c67e3d815a0124fe9647133e7ed3afaaab0b8a | 130d4e7c5c36e5e33cd99893a65e9b2dd540dee0 | /app/src/main/java/com/example/showhour/view/ShowDetailActivity.java | a47c29f29e18ae6766d2aacc027484f35dedba89 | []
| no_license | aarshic/ShowHour | 48ba0ae00bd09a041608c48da3528f68b6b9edbd | 2fba8f7ea4fe83e3f440ffa2e9fec07ec0fb19cd | refs/heads/main | 2023-05-31T15:12:34.849531 | 2021-06-23T18:47:13 | 2021-06-23T18:47:13 | 377,481,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,016 | java | package com.example.showhour.view;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.showhour.R;
import com.example.showhour.adapters.EpisodesAdapter;
import com.example.showhour.adapters.ImageSliderAdapter;
import com.example.showhour.databinding.ActivityShowDetailBinding;
import com.example.showhour.databinding.EpisodesLayoutBinding;
import com.example.showhour.viewModel.ShowDetailViewModel;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import java.util.Locale;
public class ShowDetailActivity extends AppCompatActivity {
private ActivityShowDetailBinding activityShowDetailBinding;
private ShowDetailViewModel showDetailViewModel;
private BottomSheetDialog episodesBottomSheetDialog;
private EpisodesLayoutBinding episodesLayoutBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
activityShowDetailBinding = DataBindingUtil.setContentView(this, R.layout.activity_show_detail);
showDetailViewModel = new ViewModelProvider(this).get(ShowDetailViewModel.class);
showDetailViewModel.init();
activityShowDetailBinding.setShowDetailViewModel(showDetailViewModel);
activityShowDetailBinding.backIcon.setOnClickListener(v -> onBackPressed());
activityShowDetailBinding.showDetailScrollview.setVisibility(View.GONE);
getShowDetail();
}
private void getShowDetail() {
int id = getIntent().getIntExtra("id", - 1);
activityShowDetailBinding.setIsLoading(true);
showDetailViewModel.getShowDetail().observe(this, showDetailResponse -> {
activityShowDetailBinding.setIsLoading(false);
if (showDetailViewModel.getShowDetailModel() == null) {
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.no_detail_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button okBtn = dialog.findViewById(R.id.ok_btn);
okBtn.setOnClickListener(v -> finish());
dialog.show();
} else {
activityShowDetailBinding.showDetailScrollview.setVisibility(View.VISIBLE);
activityShowDetailBinding.showDetailWebsiteBtn.setVisibility(View.VISIBLE);
activityShowDetailBinding.showDetailEpisodesBtn.setVisibility(View.VISIBLE);
activityShowDetailBinding.showDetailName.setTextIsSelectable(true);
if (showDetailViewModel.getPictures() != null) {
loadImageSlider(showDetailViewModel.getPictures());
}
activityShowDetailBinding.showDetailDescription.setText(String.valueOf(HtmlCompat.fromHtml(showDetailViewModel.getDescription(), HtmlCompat.FROM_HTML_MODE_LEGACY)));
activityShowDetailBinding.showDetailRatingText.setText(String.format(Locale.getDefault(), "%.2f", Double.parseDouble(showDetailViewModel.getRating())) + "/10");
if (showDetailViewModel.getGenres() == null) {
activityShowDetailBinding.showDetailGenre.setText("N/A");
}
activityShowDetailBinding.showDetailReadMore.setOnClickListener(v -> {
if (activityShowDetailBinding.showDetailReadMore.getText().toString().equals("Read More")) {
activityShowDetailBinding.showDetailDescription.setMaxLines(Integer.MAX_VALUE);
activityShowDetailBinding.showDetailDescription.setEllipsize(null);
activityShowDetailBinding.showDetailReadMore.setText(R.string.read_less);
} else {
activityShowDetailBinding.showDetailDescription.setMaxLines(4);
activityShowDetailBinding.showDetailDescription.setEllipsize(TextUtils.TruncateAt.END);
activityShowDetailBinding.showDetailReadMore.setText(R.string.read_more);
}
});
activityShowDetailBinding.showDetailWebsiteBtn.setOnClickListener(v1 -> {
Intent websiteIntent = new Intent(Intent.ACTION_VIEW);
websiteIntent.setData(Uri.parse(showDetailViewModel.getUrl()));
startActivity(websiteIntent);
});
activityShowDetailBinding.showDetailEpisodesBtn.setOnClickListener(v13 -> {
if (episodesBottomSheetDialog == null) {
episodesBottomSheetDialog = new BottomSheetDialog(ShowDetailActivity.this);
episodesLayoutBinding = DataBindingUtil.inflate(
LayoutInflater.from(ShowDetailActivity.this), R.layout.episodes_layout,
ShowDetailActivity.this.findViewById(R.id.episodes_container), false
);
episodesBottomSheetDialog.setContentView(episodesLayoutBinding.getRoot());
episodesLayoutBinding.episodesRecyclerview.setAdapter(new EpisodesAdapter(showDetailViewModel, showDetailViewModel.getEpisodes()));
episodesLayoutBinding.episodesTitle.setText(String.format("Episodes | %s", showDetailViewModel.getName()));
episodesLayoutBinding.closeIcon.setOnClickListener(v12 -> episodesBottomSheetDialog.dismiss());
}
FrameLayout frameLayout = episodesBottomSheetDialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
if (frameLayout != null) {
BottomSheetBehavior<View> bottomSheetBehavior = BottomSheetBehavior.from(frameLayout);
bottomSheetBehavior.setPeekHeight(Resources.getSystem().getDisplayMetrics().heightPixels);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
episodesBottomSheetDialog.show();
});
}
activityShowDetailBinding.invalidateAll();
});
showDetailViewModel.fetchShowDetails(id);
}
private void loadImageSlider(String[] sliderImages) {
activityShowDetailBinding.sliderViewPager.setOffscreenPageLimit(1);
activityShowDetailBinding.sliderViewPager.setAdapter(new ImageSliderAdapter(sliderImages));
activityShowDetailBinding.sliderViewPager.setVisibility(View.VISIBLE);
activityShowDetailBinding.viewFadingEdge.setVisibility(View.VISIBLE);
setUpSliderIndicator(sliderImages.length);
activityShowDetailBinding.sliderViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setCurrentSliderIndicator(position);
}
});
}
private void setUpSliderIndicator(int count) {
ImageView[] indicators = new ImageView[count];
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(8, 0, 8, 0);
for (int i = 0; i < indicators.length; i++) {
indicators[i] = new ImageView(this);
indicators[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.background_slider_indicator_inactive));
indicators[i].setLayoutParams(layoutParams);
activityShowDetailBinding.layoutSliderIndicator.addView(indicators[i]);
}
activityShowDetailBinding.layoutSliderIndicator.setVisibility(View.VISIBLE);
setCurrentSliderIndicator(0);
}
private void setCurrentSliderIndicator(int position) {
int childCount = activityShowDetailBinding.layoutSliderIndicator.getChildCount();
for (int i = 0; i < childCount; i++) {
ImageView imageView = (ImageView) activityShowDetailBinding.layoutSliderIndicator.getChildAt(i);
if (i == position) {
imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.background_slider_indicator_active));
} else {
imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.background_slider_indicator_inactive));
}
}
}
}
| [
"[email protected]"
]
| |
6ea9f0c9acd89a63dd13cbc1a7580dabfac0ce1d | 0a63b0b211e803d41f52a63f936eb41017dd0324 | /app/src/main/java/com/zyj010/huaba/model/User.java | 27b5b3c7cc6d3db1703310327acda531154abe6b | []
| no_license | molian001/myHuaBa | 50b76dffdb1aa3a386c12267d2ae67c1bb1da98b | 840079edaa770b455e47620852f726b23591f732 | refs/heads/master | 2021-01-16T23:16:33.088276 | 2016-06-15T15:45:44 | 2016-06-15T15:50:22 | 60,150,418 | 2 | 1 | null | 2016-06-05T05:31:08 | 2016-06-01T06:14:37 | Java | UTF-8 | Java | false | false | 305 | java | package com.zyj010.huaba.model;
/**
* Created by zyj010 on 2016/4/19 0019.
*/
public class User extends BaseModel {
private String userId;
private String password;
public String getUserId() {
return userId;
}
public String getPassword() {
return password;
}
}
| [
"[email protected]"
]
| |
ebd5f716f31618b7f29627eb821b1a51d87d8d2a | 2af1f6753e8634c1f2caffcede34f9ffa667ddda | /PartI/programAssign1/MCSimulation.java | 1445beedef3c663ff58f9fd3482975c02471b584 | []
| no_license | shyang292/Algorithms-4th-Edition | 09c017e0e7a0f04816638b383eeca4f949699e95 | dc10369b500f2fbb7811d20591e359fdc533945b | refs/heads/master | 2021-07-15T04:44:42.776313 | 2016-10-11T22:42:52 | 2016-10-11T22:42:52 | 57,076,336 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,000 | java | package programAssign1;
import java.text.DecimalFormat;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class MCSimulation {
//private boolean[][] blockArr;
private int size;
Percolation pc;
private int count=0;
public MCSimulation(int N){
pc = new Percolation(N);
size = N;
}
public float simulation(){
float p=0;
int i;
int j;
while(!pc.percolates()){
//random i, j [1,N]
i = StdRandom.uniform(1, size+1);
j = StdRandom.uniform(1, size+1);
while(pc.isOpen(i, j)){
i = StdRandom.uniform(1, size+1);
j = StdRandom.uniform(1, size+1);
}
//System.out.println("i= "+i+" j= "+j);
//i,j not open
//open (i,j)
pc.open(i, j);
count++;
//percolates
}
p = (float)count/(size*size);
return p;
}
public static void main(String[] args){
MCSimulation mcs = new MCSimulation(4);
float p = mcs.simulation();
System.out.println(" "+p);
}
}
| [
"[email protected]"
]
| |
c5541a594f8abd569f52a633f334e08c4e841a08 | 39638a7f377598dfe456b3e9f5884e2614d20e43 | /src/main/java/com/test/bot/domain/AbstractAuditingEntity.java | a732855bb6b4fc5f07d129a035ffde0d2d9ce529 | []
| no_license | CarlTheBot/testBot | 16a77eee87af7d5fd1b3c943559743198ba33d96 | b5d754f1a0302594503034c8424a18f21a07fda4 | refs/heads/master | 2021-01-11T04:06:17.382703 | 2016-10-18T12:56:30 | 2016-10-18T12:56:30 | 71,246,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,906 | java | package com.test.bot.domain;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Field;
import java.time.ZonedDateTime;
/**
* Base abstract class for entities which will hold definitions for created, last modified by and created,
* last modified by date.
*/
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Field("created_by")
@JsonIgnore
private String createdBy;
@CreatedDate
@Field("created_date")
@JsonIgnore
private ZonedDateTime createdDate = ZonedDateTime.now();
@LastModifiedBy
@Field("last_modified_by")
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Field("last_modified_date")
@JsonIgnore
private ZonedDateTime lastModifiedDate = ZonedDateTime.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public ZonedDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(ZonedDateTime createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public ZonedDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(ZonedDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
| [
"[email protected]"
]
| |
eaf2b523919227b38eff4a4e2cd27c262cccdaa9 | 993cae9edae998529d4ef06fc67e319d34ee83ef | /src/cn/edu/sau/javashop/core/service/IMemberAddressManager.java | b2ae245258fdf7351fd31735fba394e7c10bc1e7 | []
| no_license | zhangyuanqiao93/MySAUShop | 77dfe4d46d8ac2a9de675a9df9ae29ca3cae1ef7 | cc72727b2bc1148939666b0f1830ba522042b779 | refs/heads/master | 2021-01-25T05:02:20.602636 | 2017-08-03T01:06:43 | 2017-08-03T01:06:43 | 93,504,556 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package cn.edu.sau.javashop.core.service;
import java.util.List;
import cn.edu.sau.app.base.core.model.MemberAddress;
/**
* 会员中心-接收地址
* @author zyq<br/>
* 2010-3-17 下午02:49:23<br/>
* version 1.0<br/>
*/
public interface IMemberAddressManager {
/**
* 列表接收地址
* @return
*/
public List listAddress();
/**
* 取得地址详细信息
* @param addr_id
* @return
*/
public MemberAddress getAddress(int addr_id);
public void addAddress(MemberAddress address);
public void updateAddress(MemberAddress address);
public void deleteAddress(int addr_id);
}
| [
"[email protected]"
]
| |
5172ce10d22924c1997549c4c15a9e527933b1b3 | db82ce601999fe883587e8e28c27cf2ac5e4fe15 | /Sockets-UPnP/src/UpnpUtils.java | 12505ea818149447ec0bd0f10bb1d87b2769ed92 | []
| no_license | guilherme-deschamps/Java-Sockets-With-UPnP | f3617e00d3e5795a15f037a21cc49a4c2a53957f | 735a6abefcdf56903073ebe199ef83bcf2c69ec7 | refs/heads/master | 2023-01-23T15:26:13.549765 | 2020-11-23T23:32:24 | 2020-11-23T23:32:24 | 313,745,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,146 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import com.dosse.upnp.UPnP;
/**
*
* @author guilh
*/
public class UpnpUtils {
private static UpnpUtils instance;
private int port = 80;
private UpnpUtils() {
}
public synchronized static UpnpUtils getInstance() {
if (instance == null)
instance = new UpnpUtils();
return instance;
}
public boolean openUPnPPort() {
boolean portOpened = false;
System.out.println("Attempting UPnP port forwarding");
if (UPnP.isUPnPAvailable()) {
if (UPnP.openPortTCP(port)) {
System.out.println("UPnP port forwarding enabled.");
portOpened = true;
} else {
System.out.println("UPnP port forwarding failed.");
}
} else {
System.out.println("UPnP is not available.");
}
return portOpened;
}
public int getPort(){
return port;
}
}
| [
"[email protected]"
]
| |
308b32f83efd648999b3731ac74b7dc19d204201 | b9b8c16c74af939562737e182c80764813649928 | /Employee-test/src/main/java/com/yuntu/pojo/Employee.java | 4d6752bf960cff858689c9116e0bef321d8a60cd | []
| no_license | YuJiaxing925/MyIDEAProject | 915d1f2d16ad8810076c012509022de69160dec3 | 1a9fef37e59d7b99b312b1d4d29b20fee14cc0ea | refs/heads/master | 2023-01-13T15:58:42.701813 | 2020-11-18T02:29:52 | 2020-11-18T02:29:52 | 313,800,666 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,161 | java | package com.yuntu.pojo;
import java.util.Date;
public class Employee {
private int e_id;
private String e_name;
private String e_edu;
private int e_r_id ;
private Date e_hiredate;
private int e_money;
private Role role;
@Override
public String toString() {
return "Employee{" +
"e_id=" + e_id +
", e_name='" + e_name + '\'' +
", e_edu='" + e_edu + '\'' +
", e_r_id=" + e_r_id +
", e_hiredate=" + e_hiredate +
", e_money=" + e_money +
" }";
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public int getE_id() {
return e_id;
}
public void setE_id(int e_id) {
this.e_id = e_id;
}
public String getE_name() {
return e_name;
}
public void setE_name(String e_name) {
this.e_name = e_name;
}
public String getE_edu() {
return e_edu;
}
public void setE_edu(String e_edu) {
this.e_edu = e_edu;
}
public int getE_r_id() {
return e_r_id;
}
public void setE_r_id(int e_r_id) {
this.e_r_id = e_r_id;
}
public Date getE_hiredate() {
return e_hiredate;
}
public void setE_hiredate(Date e_hiredate) {
this.e_hiredate = e_hiredate;
}
public int getE_money() {
return e_money;
}
public void setE_money(int e_money) {
this.e_money = e_money;
}
public Employee() {
}
public Employee(String e_name, String e_edu, int e_r_id, Date e_hiredate, int e_money) {
this.e_name = e_name;
this.e_edu = e_edu;
this.e_r_id = e_r_id;
this.e_hiredate = e_hiredate;
this.e_money = e_money;
}
public Employee(int e_id, String e_name, String e_edu, int e_r_id, Date e_hiredate, int e_money) {
this.e_id = e_id;
this.e_name = e_name;
this.e_edu = e_edu;
this.e_r_id = e_r_id;
this.e_hiredate = e_hiredate;
this.e_money = e_money;
}
}
| [
"[email protected]"
]
| |
a5f1a22ae7ac74db16a310043be1d5482db3976f | dff5c0519dd5b8219f8a2b5578f77e5e2740dd91 | /netsnmpj-preliminary/jsrc/org/netsnmp/junittests/getNextTest.java | ef119f34992591701a209b4da753902719587510 | []
| no_license | tnarnold/netsnmpj | 3cc2a77cfcc3920a8907dd9e2ae48f5d30945871 | 3153c3e9297dd7de7db9d1a65c97f77937ae147b | refs/heads/master | 2016-09-02T05:51:09.475316 | 2014-06-04T13:35:13 | 2014-06-04T13:35:13 | 20,484,286 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,750 | java | /*
Copyright(c) 2003 by Andrew E. Page
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appears in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name Andrew E. Page not be used
in advertising or publicity pertaining to distribution of the software
without specific, written prior permission.
ANDREW E. PAGE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL ANDREW E. PAGE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
package org.netsnmp.junittests;
import junit.framework.* ;
import java.util.* ;
import org.netsnmp.* ;
import org.netsnmp.util.snmpgetRunner ;
/**
* @author Andrew E. Page <a href=mailto:[email protected]>[email protected]</a>
* test for the GETNEXT operation
*/public class getNextTest extends TestCase {
static final String testHost = TestProperties.agent;
static final String testCommunity = TestProperties.community;
ArrayList getNextResults = new ArrayList();
boolean testDone;
boolean timeoutFlag ;
public void testGETNEXT() throws Exception, NetSNMPSession.readInterrupt {
final NetSNMPSession s = new NetSNMPSession(testHost, testCommunity);
PDU start_pdu = new PDU(NetSNMP.MSG_GETNEXT);
final OID start_oid = new DefaultOID("1.3.6.1.2.1.system");
NetSNMPAction e;
Iterator it;
PDU.entry ent;
testDone = false;
getNextResults.clear();
e = new NetSNMPAction() {
public synchronized boolean actionPerformed(
int result,
NetSNMPSession session,
PDU pdu,
Object o)
throws NetSNMPException {
int i;
PDU next = new PDU(NetSNMP.MSG_GETNEXT);
if (result == NetSNMP.STAT_TIMEOUT) {
timeoutFlag = true ;
notify() ;
}
for (i = 0; i < pdu.entries.length; i++) {
if (start_oid.compareTo(pdu.entries[i].oid, start_oid.length()) != 0) {
//System.out.println("getnext done");
// we're done, don't submit another request
notify() ;
return true;
}
// System.out.println("oid = " + pdu.entries[i].oid.toString() + " " + pdu.entries[i].value.toJavaObject().toString());
next.addNullEntry(pdu.entries[i].oid);
// collect the results, then play them back against the snmpgetrunner
getNextResults.add(pdu.entries[i]);
}
//System.out.println("pdu = " + pdu.toString());
session.send(next, o);
return true;
}
};
s.addListener(e);
start_pdu.addNullEntry(start_oid);
timeoutFlag = false ;
synchronized( e ) {
s.send(start_pdu, null);
e.wait() ;
} // synchronized
if( timeoutFlag )
fail() ;
it = getNextResults.iterator();
snmpgetRunner runner = new snmpgetRunner(testHost, testCommunity);
while (it.hasNext()) {
ent = (PDU.entry) it.next();
if (ent.value.type() == ASN_TYPE.ASN_OBJECT_ID) {
//System.out.println("oid ent = " + ent);
if (new DefaultOID(ent.value.toOBJECTID())
.compareTo(runner.getOID(ent.oid))
!= 0) {
fail();
return;
}
continue;
}
if (ent.value.type() == ASN_TYPE.ASN_OCTET_STR) {
// System.out.println("str ent = " + ent) ;
if (new String(ent.value.toOctetString())
.compareTo(runner.getString(ent.oid))
!= 0) {
fail();
return;
}
continue;
}
if (ent.value.type() == ASN_TYPE.ASN_TIMETICKS) {
// time ticks are used for 'time counters' which
// change between the reads
long fetchedValue = ent.value.toInt64(),
testValue = runner.getInt(ent.oid);
if (fetchedValue - testValue > 250) {
fail();
return;
}
continue;
}
//System.out.println("ent = " + ent);
}
}
public static Test suite() {
return new TestSuite(getNextTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite()) ;
}
}
/*
* $Log: getNextTest.java,v $
* Revision 1.4 2003/04/18 01:48:47 aepage
* improvement in tests
*
* Revision 1.3 2003/03/29 00:06:53 aepage
* adaptations for new thread architecture
*
* Revision 1.2 2003/02/09 23:36:09 aepage
* failure for a timeout on an snmpgetnext operation
*
* Revision 1.1.1.1 2003/02/07 23:56:51 aepage
* Migration Import
*
* Revision 1.2 2003/02/07 22:23:03 aepage
* pre sourceforge.net migration checkins
*
*/
| [
"[email protected]"
]
| |
f4e7c3a8c9428ad8ca5e4f295d5ea2628cd0720c | 02e5d040ead1455a2789c41bc7ae174e2e42d5a3 | /core/src/main/java/com/rkeenan/components/model/ChildListModel.java | 605b4a14b41a3aef39b4c33c6e75b84487b9365a | []
| no_license | id-keenan/sling-app | cee4a42fc513bed7b7ff19e4318d4f12d80b15f8 | c0524fb6bd9c829efa395bb8ecf73894a83837f0 | refs/heads/master | 2022-11-27T17:08:05.856492 | 2019-06-09T20:04:03 | 2019-06-09T20:04:03 | 190,652,204 | 0 | 0 | null | 2022-11-16T12:20:54 | 2019-06-06T21:29:12 | Java | UTF-8 | Java | false | false | 2,017 | java | package com.rkeenan.components.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.rkeenan.util.AppointmentUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Optional;
@Model(adaptables = SlingHttpServletRequest.class)
public class ChildListModel {
private List<Resource> children;
private Pattern resTypePattern;
@Inject
private Resource resource;
@Inject
@Optional
private String resType;
@Inject
@Optional
private boolean recursive;
@PostConstruct
protected void init() {
resTypePattern = Pattern.compile(resType);
Resource currentPage = AppointmentUtil.getPage(resource);
children = generateChildList(currentPage);
}
private List<Resource> generateChildList(Resource parent) {
List<Resource> output = new ArrayList<>();
Iterator<Resource> childResources = parent.listChildren();
while (childResources.hasNext()) {
Resource child = childResources.next();
if (StringUtils.isNotBlank(resType) && matchesResourceType(child)) {
output.add(child);
if (recursive) {
output.addAll(generateChildList(child));
}
} else if (StringUtils.isBlank(resType)){
output.add(child);
if (recursive) {
output.addAll(generateChildList(child));
}
}
}
return output;
}
private boolean matchesResourceType(Resource input) {
return resTypePattern.matcher(input.getResourceType()).matches();
}
public List<Resource> getChildren() {
return children;
}
}
| [
"[email protected]"
]
| |
263ee808cb26d7f42aa9d4071ad6d965498739ca | 3fc1dfbd0a9f3c4ce016a797c61371cb6ce90e74 | /Try/app/src/main/java/com/example/acer/atry/Fragments/FragmentDua.java | 5b4a90a862597ec691a6da473c9dc2ec0488da1e | []
| no_license | OliviaNarulita/IdeSkripsi | b7832a9e4cd485c252314e78627196b187c23b44 | 44ff7e40470043241add55d5818fa100e3b9612d | refs/heads/master | 2020-04-03T14:54:31.492810 | 2018-10-30T07:42:39 | 2018-10-30T07:42:39 | 155,341,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 600 | java | package com.example.acer.atry.Fragments;
import android.os.Bundle;
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.example.acer.atry.R;
/**
* Created by Acer on 18/09/2018.
*/
public class FragmentDua extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dua,container , false);
}
}
| [
"[email protected]"
]
| |
a064a1a96ab8019449b3f1109b3da0fc9b2f2ad4 | ff1490abfb906c84bb40257393d4099ddac3cf71 | /lesson8.1/src/kg/geektech/les8/players/Tank.java | a6e470a593e9c1adc6247f58386e71f3b562cb29 | []
| no_license | omar-collab/lesson8.1 | 49e28577ee6eb78363112ae88690df1485314f91 | a518022c4b2337cc7e230c0c1d9636ac03ec8559 | refs/heads/master | 2022-12-25T19:53:46.059742 | 2020-10-02T17:59:23 | 2020-10-02T17:59:23 | 300,696,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 802 | java | package kg.geektech.les8.players;
import java.util.Random;
public class Tank extends Hero {
public Tank(int health, int damage, SuperAbility superAbility) {
super(health, damage, superAbility);
}
@Override
public void applySuperAbility(Boss boss, Hero[] heroes) {
for (int i = 0; i < heroes.length; i++) {
Random r = new Random();
int randomShield = r.nextInt(50);
System.out.println("Shield hero " + heroes[i].getHealth() + " damage");
System.out.println("____________________");
if (heroes[i].getHealth() > 0) {
boss.setDamage(boss.getDamage() - randomShield);
} else if (getHealth() <= 0) {
System.out.println("Golem died");
}
}
}
}
| [
"[email protected]"
]
| |
188ce26c7090429b24ba2059f628699843d15465 | 3a2f04ae5a5d39ca6e3fba0e5bd101bf4edd1cfa | /vas/v10-soap/src/test/java/io/motown/vas/v10/soap/VasConversionServiceTest.java | 85bb810bc4e7d4089d4edebdfc1ee1eeb238c7be | [
"Apache-2.0"
]
| permissive | motown-io/motown | c0a0d934e1c962ce98ec01e70b553e95d455d6d3 | 783ccda7c28b273a529ddd47defe8673b1ea365b | refs/heads/master | 2020-04-05T05:51:06.645765 | 2019-02-01T10:32:58 | 2019-02-01T10:32:58 | 14,305,692 | 31 | 18 | null | null | null | null | UTF-8 | Java | false | false | 1,970 | java | /**
* Copyright (C) 2013 Motown.IO ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.motown.vas.v10.soap;
import io.motown.vas.v10.soap.schema.ChargePoint;
import io.motown.vas.viewmodel.persistence.entities.ChargingStation;
import org.junit.Before;
import org.junit.Test;
import static io.motown.domain.api.chargingstation.test.ChargingStationTestUtils.CHARGING_STATION_ID;
public class VasConversionServiceTest {
private VasConversionService service;
@Before
public void setup() {
service = new VasConversionService();
}
@Test
public void getVasRepresentationNewChargingStationNoExceptions() {
service.getVasRepresentation(new ChargingStation(CHARGING_STATION_ID.getId()));
}
@Test
public void getVasRepresentationNewChargingStationValidateReturnValue() {
ChargingStation cs = new ChargingStation(CHARGING_STATION_ID.getId());
ChargePoint vasRepresentation = service.getVasRepresentation(cs);
VasSoapTestUtils.compareChargingStationToVasRepresentation(cs, vasRepresentation);
}
@Test
public void getVasRepresentationFilledChargingStationValidateReturnValue() {
ChargingStation cs = VasSoapTestUtils.getConfiguredAndFilledChargingStation();
ChargePoint vasRepresentation = service.getVasRepresentation(cs);
VasSoapTestUtils.compareChargingStationToVasRepresentation(cs, vasRepresentation);
}
}
| [
"[email protected]"
]
| |
d555ff6e0166494ca55e08c7f738e2d8b011c8c1 | 9df9e93726589f3302b3ff4c69285cfbd1591315 | /src/main/java/gov/nih/nlm/bioscores/agreement/SemanticCoercionAgreement.java | f23078289adcb90d1a91f27c2d096a7064d3eae6 | [
"LicenseRef-scancode-public-domain"
]
| permissive | CorefrenceAlliance/CoreferenceNN | e8f6882a0442f78845e372ef55db0a311a6a94c5 | 94a2a3452e580c3601444f86187133d749ad559b | refs/heads/master | 2021-01-21T16:15:18.185382 | 2016-06-06T21:04:29 | 2016-06-06T21:04:29 | 58,513,179 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,492 | java | package gov.nih.nlm.bioscores.agreement;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import gov.nih.nlm.bioscores.core.CoreferenceProperties;
import gov.nih.nlm.bioscores.core.CoreferenceType;
import gov.nih.nlm.bioscores.core.ExpressionType;
import gov.nih.nlm.ling.core.SurfaceElement;
import gov.nih.nlm.ling.sem.Conjunction;
import gov.nih.nlm.ling.sem.ConjunctionDetection;
import gov.nih.nlm.ling.sem.SemanticItem;
/**
* Agreement constraint that is based on the notion of semantic coercion,
* described in Castano and Pustejovsky (2002). It is currently applicable to possessive
* pronouns. <p>
*
* Agreement is predicted if the possesive pronoun (coreferential mention) modifies a head
* that indicates event trigger or a meronym of a given semantic type AND the candidate referent is
* associated with semantics of that semantic type. For example, <i>its</i> in the mention
* <i>its expression</i> can corefer with a gene name, assuming <i>expression</i> is defined
* as a event trigger for gene terms.
*
* @author Halil Kilicoglu
*
*/
// TODO It can be extended to personal pronouns and generalized.
public class SemanticCoercionAgreement implements Agreement {
@Override
public boolean agree(CoreferenceType corefType, ExpressionType expType, SurfaceElement exp, SurfaceElement referent) {
if (expType != ExpressionType.PossessivePronoun) return false;
LinkedHashSet<SemanticItem> sems = null;
if (ConjunctionDetection.filterByConjunctions(referent).size() > 0) {
Conjunction conjPred = (Conjunction)ConjunctionDetection.filterByConjunctions(referent).iterator().next();
sems = new LinkedHashSet<>(conjPred.getArgItems());
}
else sems = referent.getSemantics();
if (sems == null) return false;
return (canBeCoerced(CoreferenceProperties.EVENT_TRIGGERS,exp,sems) ||
canBeCoerced(CoreferenceProperties.MERONYMS,exp,sems));
}
private static boolean canBeCoerced(Map<String,List<String>> wordList, SurfaceElement exp, LinkedHashSet<SemanticItem> sems) {
for (String h: wordList.keySet()) {
List<String> words = wordList.get(h);
List<String> semtypes = CoreferenceProperties.SEMTYPES.get(h);
for (String w: words) {
if (exp.containsLemma(w)) {
for (SemanticItem sem: sems) {
if (CollectionUtils.containsAny(semtypes,sem.getAllSemtypes()))
return true;
}
}
}
}
return false;
}
}
| [
"micha@DESKTOP-1U93V40"
]
| micha@DESKTOP-1U93V40 |
f7ed4301f158ce713eb2131e26242892dbcee0c6 | 4a29a4a885235c327d7c73574c06c21065c6136b | /app/src/test/java/com/example/ubuntu/sqliteexample/ExampleUnitTest.java | 5f2c4b8caff8643d13adce9429df1e4546983396 | []
| no_license | makhare854/SQLiteExample2 | 97d5a3a82e9e9fb4409fdc80bda980b2ac5271ed | 0e7059220806dc8628636e62fe86542506bfe745 | refs/heads/master | 2021-09-01T13:31:04.263747 | 2017-12-27T07:49:15 | 2017-12-27T07:49:15 | 115,496,307 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 410 | java | package com.example.ubuntu.sqliteexample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
552a677115090cb5ed518bcf1a16e301b0c1e7de | b9c7a137a78af364bef859f2352a2a36ef38ad20 | /src/main/java/br/ufrn/dimap/dim0863/webserver/exceptions/ChaveNaoDisponivelException.java | 4ddf9b7508e550e939df0e926d7bb8f3aac2ae57 | []
| no_license | luksrn/DIM0863-ws | 0b072f4d712ff77f045711be0019592049715335 | 42a1caf24f76b139515a0ff54f9c7d00d7358449 | refs/heads/master | 2020-03-15T02:32:24.430574 | 2018-05-13T19:05:04 | 2018-05-13T19:05:04 | 131,920,401 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package br.ufrn.dimap.dim0863.webserver.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.NOT_MODIFIED)
public class ChaveNaoDisponivelException extends RuntimeException {
public ChaveNaoDisponivelException() {
super("Chave não disponível");
}
}
| [
"[email protected]"
]
| |
8fbc0808aad6a6e2fd5be361b5328a693a272785 | 380d6439b6e8ca2f2088562b8688fdfa34680eba | /spring-boot-09-mybatis/src/main/java/com/kyle/springboot/SpringBoot09MybatisApplication.java | 64ac6be43771582d58247489da3aa00de7b5c90b | []
| no_license | Kyle0432/SpringBoot_Test | b7dac8a61550392421d5997203487afc2e29b3a9 | 620d4915247ff9fdc7ebc825969712b1cfdda583 | refs/heads/master | 2022-06-24T05:02:36.198215 | 2019-10-28T13:48:41 | 2019-10-28T13:48:41 | 213,132,542 | 0 | 0 | null | 2022-06-21T01:59:44 | 2019-10-06T08:23:12 | Java | UTF-8 | Java | false | false | 350 | java | package com.kyle.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBoot09MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot09MybatisApplication.class, args);
}
}
| [
"[email protected]"
]
| |
fdee7fab5ea5c04e6fe6c91c3fa78618f05022b7 | 4901cda2ff40bea3a4dbe9c9a32ea7b43e5d5393 | /java02/src/step06/Exam055_3.java | 23a51ea0f8099246b4f76da06997090439772ae8 | []
| no_license | Liamkimjihwan/java01 | 287adc817ba7c7c4e711c392cb78e965d967742c | 3e0c75e63b81acbb94c9e91a63251a252c18af77 | refs/heads/master | 2021-06-07T16:22:28.061338 | 2016-11-04T11:38:44 | 2016-11-04T11:38:44 | 72,842,529 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java |
package step06;
public class Exam055_3 {
static void swap(int[] values) {
int temp = values[0];
values[0] = values[1];
values[1] = temp;
}
public static void main(String[] args) {
int[] values = {10, 20};
System.out.printf("main():%d, %d\n", values[0], values[1]);
swap(values);
System.out.printf("main():%d, %d\n", values[0], values[1]);
}
}
/*
call by value
-메서드를 호출할 때 넘겨주는 것이 일반 값일 경우
*/
| [
"[email protected]"
]
| |
8b438c15f8b5f8cb41b4928aee75f0d2f5e8f7d5 | e020ee939e2d19bea64fbe96a9a0904a4eae8610 | /src/main/java/guru/springframework/controller/IndexController.java | 8d9fd5441f15b1dcfba1443ec5348669e1353b3a | []
| no_license | mangelo123/spring5-recipe-app | 419266396611b3674daebffa797fca3b97adfafc | b0cb039ed9f0758233b5be056eb6a6093dc1cab8 | refs/heads/master | 2021-01-09T10:42:50.946249 | 2020-03-01T00:38:14 | 2020-03-01T00:38:14 | 242,270,242 | 0 | 0 | null | 2020-02-22T03:01:37 | 2020-02-22T03:01:36 | null | UTF-8 | Java | false | false | 677 | java | package guru.springframework.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import guru.springframework.service.RecipeService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class IndexController {
private RecipeService recipeService;
public IndexController(RecipeService recipeService) {
super();
this.recipeService = recipeService;
}
@RequestMapping({"", "/", "/index"})
public String index(Model model) {
log.debug("At the index page");
model.addAttribute("recipes", recipeService.getRecipes());
return "index";
}
}
| [
"[email protected]"
]
| |
e5461a0434d450a7d2080226719c30482ac96367 | da20bf115536c96944e094e4d4c1b99775afa25f | /DungeonDivers v0.1/app/src/main/java/com/example/rommo_000/dungeondivers/PostBattleScreen.java | baf872c7637aa0fa8039fa7780f5027b23b5336a | []
| no_license | sethwi219/DungeonDivers-1 | 6816ce7d4e54b1e4d13d4c8d14c9161c6bb4f508 | 6820715785623afd0f65e36701dc3dcf21c14530 | refs/heads/master | 2021-01-18T21:39:39.320369 | 2017-04-02T19:16:48 | 2017-04-02T19:16:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,485 | java | package com.example.rommo_000.dungeondivers;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class PostBattleScreen extends AppCompatActivity {
ArrayList<String> playerInfo;
public Player player;
ImageView charSpriteImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_battle_screen);
Intent i = getIntent();
playerInfo = (ArrayList<String>) getIntent().getSerializableExtra("playerInfo");
player = new Player(playerInfo);
//update player sprite on screen
charSpriteImage = (ImageView) findViewById(R.id.charSprite);
String playerIcon = player.getRaceClassGender();
charSpriteImage.setBackgroundResource(getResources().getIdentifier(playerIcon, "drawable", getApplicationContext().getPackageName()));
AnimationDrawable frameAnimation = (AnimationDrawable) charSpriteImage.getBackground();
frameAnimation.start();
}
public void continueButton(View view)
{
Intent intent = new Intent(getApplicationContext(), adventureActivity2.class);
intent.putExtra("playerInfo", playerInfo);
startActivity(intent);
}
}
| [
"[email protected]"
]
| |
02ac3a9986d93b30ec57aed710241e3163910400 | 2ad28dbefabb973aaff800efef9229963a9f57e6 | /roteiro3/contas-jpa/src/br/edu/ifpb/jpa/entidades/Movimentacao.java | f2f77a4712f61e0dae3061fd795c61749efed338 | []
| no_license | Gabriel-Aragao/ifpb-dac | 5106ef1521bec7311f87a1c06ac229979c2ed24d | 3e43d797aa0018fb78fcd2e441df28a613fad304 | refs/heads/main | 2023-01-05T09:03:19.629383 | 2020-10-13T15:45:04 | 2020-10-13T15:45:04 | 301,836,955 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,329 | java | package br.edu.ifpb.jpa.entidades;
import java.sql.Date;
import java.sql.Time;
import java.util.List;
import javax.persistence.*;
import br.edu.ifpb.jpa.entidades.enums.TipoMovimentacao;
@Entity
public class Movimentacao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private double valor;
private Date data;
private Time hora;
@OneToOne
private Conta conta;
@Enumerated(EnumType.STRING)
private TipoMovimentacao tipo;
@ElementCollection(targetClass=String.class)
private List<String> categorias;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public Time getHora() {
return hora;
}
public void setHora(Time hora) {
this.hora = hora;
}
public Conta getConta() {
return conta;
}
public void setConta(Conta conta) {
this.conta = conta;
}
public TipoMovimentacao getTipo() {
return tipo;
}
public void setTipo(TipoMovimentacao tipo) {
this.tipo = tipo;
}
public List<String> getCategorias() {
return categorias;
}
public void setCategorias(List<String> categorias) {
this.categorias = categorias;
}
}
| [
"[email protected]"
]
| |
d19f46abc59bf9ebe0c1a9d93033bfdf0720202b | 4d6c00789d5eb8118e6df6fc5bcd0f671bbcdd2d | /src/main/java/com/alipay/api/domain/AlipayFundAuthOrderUnfreezeModel.java | 6e8479a8cde5c380f2f1f37b67061913df29314d | [
"Apache-2.0"
]
| permissive | weizai118/payment-alipay | 042898e172ce7f1162a69c1dc445e69e53a1899c | e3c1ad17d96524e5f1c4ba6d0af5b9e8fce97ac1 | refs/heads/master | 2020-04-05T06:29:57.113650 | 2018-11-06T11:03:05 | 2018-11-06T11:03:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,761 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 预授权资金解冻接口
*
* @author auto create
* @since 1.0, 2018-07-23 11:31:38
*/
public class AlipayFundAuthOrderUnfreezeModel extends AlipayObject {
private static final long serialVersionUID = 2122243151539979538L;
/**
* 本次操作解冻的金额,单位为:元(人民币),精确到小数点后两位,取值范围:[0.01,100000000.00]
*/
@ApiField("amount")
private String amount;
/**
* 支付宝资金授权订单号
*/
@ApiField("auth_no")
private String authNo;
/**
* 解冻扩展信息,json格式;unfreezeBizInfo 目前为芝麻消费字段,支持Key值如下:
"bizComplete":"true" -- 选填:标识本次解冻用户是否履约,如果true信用单会完结为COMPLETE
*/
@ApiField("extra_param")
private String extraParam;
/**
* 商户本次资金操作的请求流水号,同一商户每次不同的资金操作请求,商户请求流水号不能重复
*/
@ApiField("out_request_no")
private String outRequestNo;
/**
* 商户对本次解冻操作的附言描述,长度不超过100个字母或50个汉字
*/
@ApiField("remark")
private String remark;
/**
* Gets amount.
*
* @return the amount
*/
public String getAmount() {
return this.amount;
}
/**
* Sets amount.
*
* @param amount the amount
*/
public void setAmount(String amount) {
this.amount = amount;
}
/**
* Gets auth no.
*
* @return the auth no
*/
public String getAuthNo() {
return this.authNo;
}
/**
* Sets auth no.
*
* @param authNo the auth no
*/
public void setAuthNo(String authNo) {
this.authNo = authNo;
}
/**
* Gets extra param.
*
* @return the extra param
*/
public String getExtraParam() {
return this.extraParam;
}
/**
* Sets extra param.
*
* @param extraParam the extra param
*/
public void setExtraParam(String extraParam) {
this.extraParam = extraParam;
}
/**
* Gets out request no.
*
* @return the out request no
*/
public String getOutRequestNo() {
return this.outRequestNo;
}
/**
* Sets out request no.
*
* @param outRequestNo the out request no
*/
public void setOutRequestNo(String outRequestNo) {
this.outRequestNo = outRequestNo;
}
/**
* Gets remark.
*
* @return the remark
*/
public String getRemark() {
return this.remark;
}
/**
* Sets remark.
*
* @param remark the remark
*/
public void setRemark(String remark) {
this.remark = remark;
}
}
| [
"[email protected]"
]
| |
484e5a8a046398b34674733a0ba491135ff43134 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /IntroClassJava/dataset/smallest/346b1d3c1cdc3032d07222a8a5e0027a2abf95bb1697b9d367d7cca7db1af769d8298e232c56471a122f05e87e79f4bd965855c9c0f8b173ebc0ef5d0abebc7b/010/mutations/220/smallest_346b1d3c_010.java | 826733d29d8dec62bc8a12291b83364c54c98bb7 | []
| no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,705 | java | package introclassJava;
class IntObj {
public int value;
public IntObj () {
} public IntObj (int i) {
value = i;
}
}
class FloatObj {
public float value;
public FloatObj () {
} public FloatObj (float i) {
value = i;
}
}
class LongObj {
public long value;
public LongObj () {
} public LongObj (long i) {
value = i;
}
}
class DoubleObj {
public double value;
public DoubleObj () {
} public DoubleObj (double i) {
value = i;
}
}
class CharObj {
public char value;
public CharObj () {
} public CharObj (char i) {
value = i;
}
}
public class smallest_346b1d3c_010 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
smallest_346b1d3c_010 mainClass = new smallest_346b1d3c_010 ();
String output;
if (args.length > 0) {
mainClass.scanner = new java.util.Scanner (args[0]);
} else {
mainClass.scanner = new java.util.Scanner (System.in);
}
mainClass.exec ();
System.out.println (mainClass.output);
}
public void exec () throws Exception {
IntObj a = new IntObj (), b = new IntObj (), c = new IntObj (), d =
new IntObj (), num_1 = new IntObj (), num_2 = new IntObj (), num_3 =
new IntObj (), num_4 = new IntObj ();
output +=
(String.format ("Please enter 4 numbers separated by spaces > "));
num_1.value = scanner.nextInt ();
num_2.value = scanner.nextInt ();
num_3.value = scanner.nextInt ();
num_4.value = scanner.nextInt ();
a.value = (num_1.value);
b.value = (num_2.value);
c.value = (num_3.value);
d.value = (num_4.value);
if (a.value <= b.value && a.value <= c.value && (a.value) <= (b.value)) {
output += (String.format ("%d is the smallest\n", a.value));
if (true)
return;;
} else if (b.value <= a.value && b.value <= c.value && b.value <= d.value) {
output += (String.format ("%d is the smalles\n", b.value));
if (true)
return;;
} else if (c.value <= a.value && c.value <= b.value && c.value <= d.value) {
output += (String.format ("%d is the smallest\n", c.value));
if (true)
return;;
} else if (d.value <= a.value && d.value <= b.value && d.value <= c.value) {
output += (String.format ("%d is the smallest\n", d.value));
if (true)
return;;
}
if (true)
return;;
}
}
| [
"[email protected]"
]
| |
3928a09cb8008c9de228f0d4d65a9ec27cd011b0 | e36a34287cc1049f64c01cd4ff9aa7aa149d0f88 | /app/src/main/java/com/mperfit/perfit/base/BaseFragment.java | 38456b8805d3be18a1490477fbae57e0b6647392 | []
| no_license | AceInAndroid/Perfit | b2f28d4d6cb4dfc4531b31e9f4e04400dcbad8ab | a77d43a577ca24ae41b375b4fd3fcfb4d364d787 | refs/heads/master | 2020-07-24T22:36:42.375988 | 2017-10-26T02:15:05 | 2017-10-26T02:15:05 | 73,785,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,974 | java | package com.mperfit.perfit.base;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mperfit.perfit.R;
import com.mperfit.perfit.app.App;
import com.mperfit.perfit.component.ActivityLifeCycleEvent;
import com.mperfit.perfit.di.component.DaggerFragmentComponent;
import com.mperfit.perfit.di.component.FragmentComponent;
import com.mperfit.perfit.di.module.FragmentModule;
import com.mperfit.perfit.utils.SystemUtil;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Subscription;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;
/**
* Created by zhangbing on 2016/10/13.
* MVP Fragment基类
*/
public abstract class BaseFragment<T extends BasePresenter> extends SupportFragment implements BaseView {
public final PublishSubject<ActivityLifeCycleEvent> lifecycleSubject = PublishSubject.create();
@Inject
protected T mPresenter;
protected View mView;
protected Activity mActivity;
protected Context mContext;
private Unbinder mUnBinder;
private boolean isFirst = true;
//Fragment的View加载完毕的标记
private boolean isViewCreated;
//Fragment对用户可见的标记
private boolean isUIVisible;
//setUserVisibleHint(boolean isVisibleToUser)方法会多次回调,而且可能会在onCreateView()方法执行完毕之前回调
// 如果isVisibleToUser==true,然后进行数据加载和控件数据填充,但是onCreateView()方法并未执行完毕,
// 此时就会出现NullPointerException空指针异常. 所以给onCreateView 添加标记位
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
this.isUIVisible = isVisibleToUser;
super.setUserVisibleHint(isVisibleToUser);
}
@Override
public void onAttach(Context context) {
mActivity = (Activity) context;
mContext = context;
super.onAttach(context);
}
//注入相应的fragment实例
protected FragmentComponent getFragmentComponent() {
return DaggerFragmentComponent.builder()
.appComponent(App.getAppComponent())
.fragmentModule(getFragmentModule())
.build();
}
protected FragmentModule getFragmentModule() {
return new FragmentModule(this);
}
private LoadingLayout loadingLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(getLayoutId(), null);
initInject();
isViewCreated =true;
return mView;
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
initEventAndData();
isFirst = false;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//presenter 和view 绑定
mPresenter.attachView(this);
mUnBinder = ButterKnife.bind(this, view);
// lazyLoad();
}
private void lazyLoad() {
//这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
if (isViewCreated && isUIVisible) {
// initEventAndData();
//数据加载完毕,恢复标记,防止重复加载
isViewCreated = false;
isUIVisible = false;
}
}
// public abstract void loadData();
// @Override
// public void onSupportVisible() {
// super.onSupportVisible();
// Logger.e("onSupportVisible调用了");
//
// if (!isHidden()) {
// initEventAndData();
// Logger.e("!isHidden调用了");
//
// }
// }
//
// @Override
// public void onHiddenChanged(boolean hidden) {
// super.onHiddenChanged(hidden);
// if (!hidden) {
// initEventAndData();
// }
// }
@Override
public void onResume() {
super.onResume();
MobclickAgent.onPageStart("Fragment");
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd("Fragment");
}
@Override
public void onDestroyView() {
super.onDestroyView();
mUnBinder.unbind();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) mPresenter.detachView();
}
// /** Fragment当前状态是否可见 */
// protected boolean isVisible =false;
//
//
// @Override
// public void setUserVisibleHint(boolean isVisibleToUser) {
// super.setUserVisibleHint(isVisibleToUser);
//
// if(getUserVisibleHint()) {
// isVisible = true;
// initEventAndData();
// } else {
// isVisible = false;
// }
// }
protected CompositeSubscription mCompositeSubscription;
protected void unSubscribe() {
if (mCompositeSubscription != null) {
mCompositeSubscription.unsubscribe();
}
}
protected void addSubscrebe(Subscription subscription) {
if (mCompositeSubscription == null) {
mCompositeSubscription = new CompositeSubscription();
}
mCompositeSubscription.add(subscription);
}
protected abstract void initInject();
protected abstract int getLayoutId();
protected abstract void initEventAndData();
} | [
"[email protected]"
]
| |
8313989c0a42d79354ffd424256ba52478b789ec | a15fa7e813c91a8d53fa6ee987ec49e7da77c6c9 | /SecondTaskOrderMethod.java | 4f0dfeac9dfba66c00fabab63eda307560ea9bdf | []
| no_license | kaiqiangh/WordCount-using-Hadoop | 9dad63b2226f23a0072d0a690f09091a8841756d | 2fc12f9b82d4d7be22767440a0f2f9797ea2ad05 | refs/heads/master | 2021-07-25T17:21:44.239709 | 2017-11-06T12:36:36 | 2017-11-06T12:36:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 880 | java | /*
* Author: Kaiqiang Huang
* Student Number: D14122793
* programming code: DT228/A
* Stream: Data Analytics
* */
package MapReduce;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
/* The sorting method is for second mapper*/
public class SecondTaskOrderMethod extends WritableComparator {
protected SecondTaskOrderMethod() {
super(IntWritable.class, true);
}
@Override
/*Override the method of compare*/
public int compare(WritableComparable value1, WritableComparable value2) {
IntWritable key1 = (IntWritable) value1;
IntWritable key2 = (IntWritable) value2;
/*Compare all keys and time -1 to make a descending sorting */
int sort = (-1)*key1.compareTo(key2);
/*Return the descending sorting*/
return sort;
}
}
| [
"[email protected]"
]
| |
a54649bce26ccb5bab57418ea72e71c304b6e474 | c4560a9ba1d06d0f00cf0320bc364b9cd644dd0d | /src/main/java/org/opensha/oaf/oetas/env/OEtasResults.java | 5c1874597b000084dffcbc46d7e554370f813eed | [
"CC0-1.0"
]
| permissive | opensha/opensha-oaf | d9486c34a715a2e94d31b1e509a0718b10173f66 | e05205db5f52ceb36b3c30c07996a4837754a1a4 | refs/heads/master | 2023-08-02T07:13:36.968882 | 2023-07-30T00:08:58 | 2023-07-30T00:08:58 | 145,740,135 | 1 | 2 | Apache-2.0 | 2021-11-13T13:04:51 | 2018-08-22T17:16:58 | Java | UTF-8 | Java | false | false | 17,684 | java | package org.opensha.oaf.oetas.env;
import org.opensha.oaf.util.MarshalReader;
import org.opensha.oaf.util.MarshalWriter;
import org.opensha.oaf.util.MarshalException;
import org.opensha.oaf.util.Marshalable;
import org.opensha.oaf.util.MarshalUtils;
import org.opensha.oaf.util.SimpleUtils;
import org.opensha.oaf.util.TestArgs;
import org.opensha.oaf.oetas.fit.OEDisc2History;
import org.opensha.oaf.oetas.fit.OEDisc2InitFitInfo;
import org.opensha.oaf.oetas.fit.OEDisc2InitVoxSet;
import org.opensha.oaf.oetas.fit.OEGridPoint;
import org.opensha.oaf.oetas.OECatalogRange;
import org.opensha.oaf.oetas.OESimulator;
// Class to hold results for operational ETAS.
// Author: Michael Barall 05/04/2022.
//
// This class contains results that are saved in the database and the download file.
public class OEtasResults implements Marshalable {
//----- Inputs -----
public OEtasCatalogInfo cat_info;
//----- History -----
// Catalog magnitude of completeness.
public double magCat;
// Number of ruptures.
public int rupture_count;
// Number of intervals.
public int interval_count;
// Number of ruptures that were accepted.
// Note: This is primarily an output to support testing.
public int accept_count;
// Number of ruptures that were rejected.
// Note: This is primarily an output to support testing.
public int reject_count;
//----- Fitting -----
// Number of groups. (Zero if grouping was not enabled.)
public int group_count;
// Mainshock magnitude, the largest magnitude among ruptures considered mainshocks, or NO_MAG_NEG if none.
public double mag_main;
// Time interval for interpreting branch ratios, in days.
public double tint_br;
//----- Grid -----
// The MLE grid point.
public OEGridPoint mle_grid_point;
// The MLE grid points for generic, sequence-specific, and Bayesian models.
public OEGridPoint gen_mle_grid_point;
public OEGridPoint seq_mle_grid_point;
public OEGridPoint bay_mle_grid_point;
// Bayesian prior weight (1 = Bayesian, 0 = Sequence-specific, see OEConstants.BAY_WT_XXX).
public double bay_weight;
//----- Simulation -----
// The range of time and magnitude used for simulation.
public OECatalogRange sim_range;
// Number of simulations.
public int sim_count;
//----- Forecast -----
// ETAS results JSON.
public String etas_json = "";
//----- Construction -----
// Clear contents.
public final void clear () {
cat_info = null;
magCat = 0.0;
rupture_count = 0;
interval_count = 0;
accept_count = 0;
reject_count = 0;
group_count = 0;
mag_main = 0.0;
tint_br = 0.0;
mle_grid_point = null;
gen_mle_grid_point = null;
seq_mle_grid_point = null;
bay_mle_grid_point = null;
bay_weight = 0.0;
sim_range = null;
sim_count = 0;
etas_json = "";
return;
}
// Default constructor.
public OEtasResults () {
clear();
}
// Copy the values.
public final OEtasResults copy_from (OEtasResults other) {
this.cat_info = (new OEtasCatalogInfo()).copy_from (other.cat_info);
this.magCat = other.magCat;
this.rupture_count = other.rupture_count;
this.interval_count = other.interval_count;
this.accept_count = other.accept_count;
this.reject_count = other.reject_count;
this.group_count = other.group_count;
this.mag_main = other.mag_main;
this.tint_br = other.tint_br;
this.mle_grid_point = (new OEGridPoint()).copy_from (other.mle_grid_point);
this.gen_mle_grid_point = (new OEGridPoint()).copy_from (other.gen_mle_grid_point);
this.seq_mle_grid_point = (new OEGridPoint()).copy_from (other.seq_mle_grid_point);
this.bay_mle_grid_point = (new OEGridPoint()).copy_from (other.bay_mle_grid_point);
this.bay_weight = other.bay_weight;
this.sim_range = (new OECatalogRange()).copy_from (other.sim_range);
this.sim_count = other.sim_count;
this.etas_json = other.etas_json;
return this;
}
// Display our contents.
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append ("OEtasResults:" + "\n");
result.append ("cat_info = {" + cat_info.toString() + "}\n");
result.append ("magCat = " + magCat + "\n");
result.append ("rupture_count = " + rupture_count + "\n");
result.append ("interval_count = " + interval_count + "\n");
result.append ("accept_count = " + accept_count + "\n");
result.append ("reject_count = " + reject_count + "\n");
result.append ("group_count = " + group_count + "\n");
result.append ("mag_main = " + mag_main + "\n");
result.append ("tint_br = " + tint_br + "\n");
result.append ("mle_grid_point = {" + mle_grid_point.toString() + "}\n");
result.append ("gen_mle_grid_point = {" + gen_mle_grid_point.toString() + "}\n");
result.append ("seq_mle_grid_point = {" + seq_mle_grid_point.toString() + "}\n");
result.append ("bay_mle_grid_point = {" + bay_mle_grid_point.toString() + "}\n");
result.append ("bay_weight = " + bay_weight + "\n");
result.append ("sim_range = {" + sim_range.toString() + "}\n");
result.append ("sim_count = " + sim_count + "\n");
result.append ("etas_json = " + etas_json + "\n");
return result.toString();
}
// Display our contents, with the JSON string in display format.
public String to_display_string () {
StringBuilder result = new StringBuilder();
result.append ("OEtasResults:" + "\n");
result.append ("cat_info = {" + cat_info.toString() + "}\n");
result.append ("magCat = " + magCat + "\n");
result.append ("rupture_count = " + rupture_count + "\n");
result.append ("interval_count = " + interval_count + "\n");
result.append ("accept_count = " + accept_count + "\n");
result.append ("reject_count = " + reject_count + "\n");
result.append ("group_count = " + group_count + "\n");
result.append ("mag_main = " + mag_main + "\n");
result.append ("tint_br = " + tint_br + "\n");
result.append ("mle_grid_point = {" + mle_grid_point.toString() + "}\n");
result.append ("gen_mle_grid_point = {" + gen_mle_grid_point.toString() + "}\n");
result.append ("seq_mle_grid_point = {" + seq_mle_grid_point.toString() + "}\n");
result.append ("bay_mle_grid_point = {" + bay_mle_grid_point.toString() + "}\n");
result.append ("bay_weight = " + bay_weight + "\n");
result.append ("sim_range = {" + sim_range.toString() + "}\n");
result.append ("sim_count = " + sim_count + "\n");
result.append ("etas_json = " + "\n");
if (etas_json.length() > 0) {
result.append (MarshalUtils.display_json_string (etas_json));
}
return result.toString();
}
// Set input data.
// Parameters:
// the_cat_info = Catalog information. This object is not retained.
public void set_inputs (OEtasCatalogInfo the_cat_info) {
cat_info = (new OEtasCatalogInfo()).copy_from (the_cat_info);
return;
}
// Set history data.
// Parameters:
// history = The history.
public void set_history (OEDisc2History history) {
magCat = history.magCat;
rupture_count = history.rupture_count;
interval_count = history.interval_count;
accept_count = history.accept_count;
reject_count = history.reject_count;
return;
}
// Set fitting data.
// Parameters:
// fit_info = Fitting information.
public void set_fitting (OEDisc2InitFitInfo fit_info) {
group_count = fit_info.group_count;
mag_main = fit_info.mag_main;
tint_br = fit_info.tint_br;
return;
}
// Set grid data.
// Parameters:
// voxel_set = Voxel set containing the grid.
public void set_grid (OEDisc2InitVoxSet voxel_set) {
mle_grid_point = voxel_set.get_mle_grid_point();
gen_mle_grid_point = voxel_set.get_gen_mle_grid_point();
seq_mle_grid_point = voxel_set.get_seq_mle_grid_point();
bay_mle_grid_point = voxel_set.get_bay_mle_grid_point();
bay_weight = voxel_set.get_bay_weight();
return;
}
// Set simulation data.
// Parameters:
// simulator = The simulator.
public void set_simulation (OESimulator simulator) {
sim_range = (new OECatalogRange()).copy_from (simulator.sim_catalog_range);
sim_count = simulator.sim_count;
return;
}
// Set forecast data.
// Parameters:
// json_string = String containing forecast JSON.
public void set_forecast (String json_string) {
etas_json = json_string;
return;
}
//----- Marshaling -----
// Marshal version number.
private static final int MARSHAL_VER_1 = 126001;
private static final String M_VERSION_NAME = "OEtasResults";
// Marshal object, internal.
private void do_marshal (MarshalWriter writer) {
// Version
int ver = MARSHAL_VER_1;
writer.marshalInt (M_VERSION_NAME, ver);
// Contents
switch (ver) {
case MARSHAL_VER_1: {
OEtasCatalogInfo.static_marshal (writer, "cat_info", cat_info);
writer.marshalDouble ("magCat", magCat);
writer.marshalInt ("rupture_count", rupture_count);
writer.marshalInt ("interval_count", interval_count);
writer.marshalInt ("accept_count", accept_count);
writer.marshalInt ("reject_count", reject_count);
writer.marshalInt ("group_count", group_count);
writer.marshalDouble ("mag_main", mag_main);
writer.marshalDouble ("tint_br", tint_br);
OEGridPoint.static_marshal (writer, "mle_grid_point", mle_grid_point);
OEGridPoint.static_marshal (writer, "gen_mle_grid_point", gen_mle_grid_point);
OEGridPoint.static_marshal (writer, "seq_mle_grid_point", seq_mle_grid_point);
OEGridPoint.static_marshal (writer, "bay_mle_grid_point", bay_mle_grid_point);
writer.marshalDouble ("bay_weight", bay_weight);
OECatalogRange.static_marshal (writer, "sim_range", sim_range);
writer.marshalInt ("sim_count", sim_count);
writer.marshalJsonString ("etas_json", etas_json);
}
break;
}
return;
}
// Unmarshal object, internal.
private void do_umarshal (MarshalReader reader) {
// Version
int ver = reader.unmarshalInt (M_VERSION_NAME, MARSHAL_VER_1, MARSHAL_VER_1);
// Contents
switch (ver) {
case MARSHAL_VER_1: {
cat_info = OEtasCatalogInfo.static_unmarshal (reader, "cat_info");
magCat = reader.unmarshalDouble ("magCat");
rupture_count = reader.unmarshalInt ("rupture_count");
interval_count = reader.unmarshalInt ("interval_count");
accept_count = reader.unmarshalInt ("accept_count");
reject_count = reader.unmarshalInt ("reject_count");
group_count = reader.unmarshalInt ("group_count");
mag_main = reader.unmarshalDouble ("mag_main");
tint_br = reader.unmarshalDouble ("tint_br");
mle_grid_point = OEGridPoint.static_unmarshal (reader, "mle_grid_point");
gen_mle_grid_point = OEGridPoint.static_unmarshal (reader, "gen_mle_grid_point");
seq_mle_grid_point = OEGridPoint.static_unmarshal (reader, "seq_mle_grid_point");
bay_mle_grid_point = OEGridPoint.static_unmarshal (reader, "bay_mle_grid_point");
bay_weight = reader.unmarshalDouble ("bay_weight");
sim_range = OECatalogRange.static_unmarshal (reader, "sim_range");
sim_count = reader.unmarshalInt ("sim_count");
etas_json = reader.unmarshalJsonString ("etas_json");
}
break;
}
return;
}
// Marshal object.
@Override
public void marshal (MarshalWriter writer, String name) {
writer.marshalMapBegin (name);
do_marshal (writer);
writer.marshalMapEnd ();
return;
}
// Unmarshal object.
@Override
public OEtasResults unmarshal (MarshalReader reader, String name) {
reader.unmarshalMapBegin (name);
do_umarshal (reader);
reader.unmarshalMapEnd ();
return this;
}
// Marshal object.
public static void static_marshal (MarshalWriter writer, String name, OEtasResults etas_results) {
etas_results.marshal (writer, name);
return;
}
// Unmarshal object.
public static OEtasResults static_unmarshal (MarshalReader reader, String name) {
return (new OEtasResults()).unmarshal (reader, name);
}
//----- Testing -----
// Make a value to use for testing purposes.
private static OEtasResults make_test_value () {
OEtasResults etas_results = new OEtasResults();
etas_results.cat_info = OEtasCatalogInfo.make_test_value();
etas_results.magCat = 3.01;
etas_results.rupture_count = 3000;
etas_results.interval_count = 250;
etas_results.accept_count = 3500;
etas_results.reject_count = 2500;
etas_results.group_count = 150;
etas_results.mag_main = 7.8;
etas_results.tint_br = 365.0;
etas_results.mle_grid_point = (new OEGridPoint()).set (1.00, 1.10, 0.200, 1.20, 0.800, 2.60, 3.40);
etas_results.gen_mle_grid_point = (new OEGridPoint()).set (1.01, 1.11, 0.201, 1.21, 0.801, 2.61, 3.41);
etas_results.seq_mle_grid_point = (new OEGridPoint()).set (1.02, 1.12, 0.202, 1.22, 0.802, 2.62, 3.42);
etas_results.bay_mle_grid_point = (new OEGridPoint()).set (1.03, 1.13, 0.203, 1.23, 0.803, 2.63, 3.43);
etas_results.bay_weight = 1.0;
etas_results.sim_range = (new OECatalogRange()).set_range_seed_est (0.0, 365.0, 3.0, 8.0, -4.0, 8.5, -3.0, 9.5, 100, 0.0, 20, 0.90, 0.02, 800);
etas_results.sim_count = 500000;
etas_results.etas_json = "{\"msg\" : \"This is a test\", \"code\" : 1234}";
return etas_results;
}
public static void main(String[] args) {
try {
TestArgs testargs = new TestArgs (args, "OEtasResults");
// Subcommand : Test #1
// Command format:
// test1
// Construct test values, and display it.
// Marshal to JSON and display JSON text, then unmarshal and display the results.
if (testargs.is_test ("test1")) {
// Read arguments
System.out.println ("Constructing, displaying, marshaling, and copying results");
testargs.end_test();
// Create the values
OEtasResults etas_results = make_test_value();
// Display the contents
System.out.println ();
System.out.println ("********** Result Display **********");
System.out.println ();
System.out.println (etas_results.toString());
// Display the contents, in display format
System.out.println ();
System.out.println ("********** Result Display, in Display Format **********");
System.out.println ();
System.out.println (etas_results.to_display_string());
// Marshal to JSON
System.out.println ();
System.out.println ("********** Marshal to JSON **********");
System.out.println ();
String json_string = MarshalUtils.to_json_string (etas_results);
System.out.println (MarshalUtils.display_json_string (json_string));
// Unmarshal from JSON
System.out.println ();
System.out.println ("********** Unmarshal from JSON **********");
System.out.println ();
OEtasResults etas_results2 = new OEtasResults();
MarshalUtils.from_json_string (etas_results2, json_string);
// Display the contents
System.out.println (etas_results2.toString());
// Copy values
System.out.println ();
System.out.println ("********** Copy info **********");
System.out.println ();
OEtasResults etas_results3 = new OEtasResults();
etas_results3.copy_from (etas_results2);
// Display the contents
System.out.println (etas_results3.toString());
// Done
System.out.println ();
System.out.println ("Done");
return;
}
// Subcommand : Test #2
// Command format:
// test2 filename
// Construct test values, and write them to a file.
if (testargs.is_test ("test2")) {
// Read arguments
System.out.println ("Writing test values to a file");
String filename = testargs.get_string ("filename");
testargs.end_test();
// Create the values
OEtasResults etas_results = make_test_value();
// Marshal to JSON
String formatted_string = MarshalUtils.to_formatted_json_string (etas_results);
// Write the file
SimpleUtils.write_string_as_file (filename, formatted_string);
// Done
System.out.println ();
System.out.println ("Done");
return;
}
// Subcommand : Test #3
// Command format:
// test3 filename
// Construct test values, and write them to a file.
// This test writes the raw JSON.
// Then it reads back the file and displays it.
if (testargs.is_test ("test3")) {
// Read arguments
System.out.println ("Writing test values to a file, raw JSON");
String filename = testargs.get_string ("filename");
testargs.end_test();
// Create the values
OEtasResults etas_results = make_test_value();
// Write to file
MarshalUtils.to_json_file (etas_results, filename);
// Read back the file and display it
OEtasResults etas_results2 = new OEtasResults();
MarshalUtils.from_json_file (etas_results2, filename);
System.out.println ();
System.out.println (etas_results2.toString());
// Done
System.out.println ();
System.out.println ("Done");
return;
}
// Subcommand : Test #4
// Command format:
// test4 filename
// Construct typical parameters, and write them to a file.
// This test writes the formatted JSON.
// Then it reads back the file and displays it.
if (testargs.is_test ("test4")) {
// Read arguments
System.out.println ("Writing test values to a file, formatted JSON");
String filename = testargs.get_string ("filename");
testargs.end_test();
// Create the values
OEtasResults etas_results = make_test_value();
// Write to file
MarshalUtils.to_formatted_json_file (etas_results, filename);
// Read back the file and display it
OEtasResults etas_results2 = new OEtasResults();
MarshalUtils.from_json_file (etas_results2, filename);
System.out.println ();
System.out.println (etas_results2.toString());
// Done
System.out.println ();
System.out.println ("Done");
return;
}
// Unrecognized subcommand, or exception
testargs.unrecognized_test();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
}
| [
"[email protected]"
]
| |
f7dd521927d02fce9e3ec1fd57bae6c72f597a68 | 86d2c6e478457ca97b72ee4fe142021cd203ad20 | /hapi-fhir-storage-batch2-jobs/src/main/java/ca/uhn/fhir/batch2/jobs/imprt/NdJsonFileJson.java | 481dca3d78faf70cba4e43858080084d5beb39f7 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | nmdp-bioinformatics/hapi-fhir | c43874d5a4862a13a7c6fb434acabbec77e9dc6a | 9ae71aba95d4af7650642f912c5b034ce537e835 | refs/heads/master | 2023-05-13T06:08:11.470244 | 2023-05-07T12:25:29 | 2023-05-07T12:25:29 | 71,417,241 | 1 | 1 | Apache-2.0 | 2022-12-23T16:21:54 | 2016-10-20T02:17:53 | Java | UTF-8 | Java | false | false | 1,296 | java | /*-
* #%L
* hapi-fhir-storage-batch2-jobs
* %%
* Copyright (C) 2014 - 2023 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package ca.uhn.fhir.batch2.jobs.imprt;
import ca.uhn.fhir.model.api.IModelJson;
import com.fasterxml.jackson.annotation.JsonProperty;
public class NdJsonFileJson implements IModelJson {
@JsonProperty("ndJsonText")
private String myNdJsonText;
@JsonProperty("sourceName")
private String mySourceName;
public String getNdJsonText() {
return myNdJsonText;
}
public NdJsonFileJson setNdJsonText(String theNdJsonText) {
myNdJsonText = theNdJsonText;
return this;
}
public String getSourceName() {
return mySourceName;
}
public void setSourceName(String theSourceName) {
mySourceName = theSourceName;
}
}
| [
"[email protected]"
]
| |
91dee49e1c90b85adc0d18b3b4050464c4e2542d | 81bd4f077d167440fcbbb150c6f9c5062c34079e | /nsdb-core/src/main/java/org/apache/lucene/facet/range/LongRangeFacetDoubleSum.java | 90282429d9ff527fbcc747ef9b36511f58001429 | [
"Apache-2.0"
]
| permissive | cybermarinella/NSDb | b47ee71e6fcbd4ce3f98378c8ad78bc3c274d441 | 98e60ffd2f829b4ab75ff4b76aad876dcef63579 | refs/heads/master | 2021-01-16T05:42:58.415392 | 2020-02-25T11:17:42 | 2020-02-25T11:17:42 | 242,996,262 | 1 | 0 | Apache-2.0 | 2020-02-25T12:38:13 | 2020-02-25T12:38:12 | null | UTF-8 | Java | false | false | 4,577 | java | /*
* Copyright 2018-2020 Radicalbit S.r.l.
*
* 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.apache.lucene.facet.range;
import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.facet.Facets;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsCollector.MatchingDocs;
import org.apache.lucene.facet.LabelAndValue;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.search.*;
import java.io.IOException;
import java.util.List;
/** {@link Facets} implementation that computes sum for
* dynamic double ranges from a provided {@link DoubleValuesSource}. Use
* this for dimensions that change in real-time (e.g. a
* relative time based dimension like "Past day", "Past 2
* days", etc.) or that change for each request (e.g.
* distance from the user's location, "< 1 km", "< 2 km",
* etc.).
*/
public class LongRangeFacetDoubleSum extends RangeFacetCounts {
private final double[] summations;
/** Create {@code LongRangeFacetCounts}, using {@link
* LongValuesSource} from the specified rangeField. */
public LongRangeFacetDoubleSum(String rangeField, String valueField, FacetsCollector hits, LongRange... ranges) throws IOException {
super(rangeField, ranges, null);
summations = new double[ranges.length];
sum(LongValuesSource.fromLongField(rangeField), DoubleValuesSource.fromDoubleField(valueField), hits.getMatchingDocs());
}
private void sum(LongValuesSource rangeSource, DoubleValuesSource valueSource, List<MatchingDocs> matchingDocs) throws IOException {
LongRange[] ranges = (LongRange[]) this.ranges;
LongRangeDoubleSummation counter = new LongRangeDoubleSummation(ranges);
int missingCount = 0;
for (MatchingDocs hits : matchingDocs) {
LongValues fv = rangeSource.getValues(hits.context, null);
DoubleValues values = valueSource.getValues(hits.context, null);
totCount += hits.totalHits;
final DocIdSetIterator fastMatchDocs;
if (fastMatchQuery != null) {
final IndexReaderContext topLevelContext = ReaderUtil.getTopLevelContext(hits.context);
final IndexSearcher searcher = new IndexSearcher(topLevelContext);
searcher.setQueryCache(null);
final Weight fastMatchWeight = searcher.createWeight(searcher.rewrite(fastMatchQuery), ScoreMode.COMPLETE_NO_SCORES, 1);
Scorer s = fastMatchWeight.scorer(hits.context);
if (s == null) {
continue;
}
fastMatchDocs = s.iterator();
} else {
fastMatchDocs = null;
}
DocIdSetIterator docs = hits.bits.iterator();
for (int doc = docs.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; ) {
if (fastMatchDocs != null) {
int fastMatchDoc = fastMatchDocs.docID();
if (fastMatchDoc < doc) {
fastMatchDoc = fastMatchDocs.advance(doc);
}
if (doc != fastMatchDoc) {
doc = docs.advance(fastMatchDoc);
continue;
}
}
// Skip missing docs:
if (fv.advanceExact(doc) && values.advanceExact(doc)) {
counter.add(fv.longValue(),values.doubleValue());
} else {
missingCount++;
}
doc = docs.nextDoc();
}
}
int x = counter.fillSummations(summations);
missingCount += x;
totCount -= missingCount;
}
@Override
public FacetResult getTopChildren(int topN, String dim, String... path) {
if (!dim.equals(field)) {
throw new IllegalArgumentException("invalid dim \"" + dim + "\"; should be \"" + field + "\"");
}
if (path.length != 0) {
throw new IllegalArgumentException("path.length should be 0");
}
LabelAndValue[] labelValues = new LabelAndValue[counts.length];
for(int i=0;i<counts.length;i++) {
labelValues[i] = new LabelAndValue(ranges[i].label, summations[i]);
}
return new FacetResult(dim, path, totCount, labelValues, labelValues.length);
}
}
| [
"[email protected]"
]
| |
e64c6738ee17fd6e75790ad14f4b560240f5f7ba | 139960e2d7d55e71c15e6a63acb6609e142a2ace | /mobile_app1/module1158/src/main/java/module1158packageJava0/Foo74.java | 041328f249ef8ccb11aa0a9ff2c9210310a355d2 | [
"Apache-2.0"
]
| permissive | uber-common/android-build-eval | 448bfe141b6911ad8a99268378c75217d431766f | 7723bfd0b9b1056892cef1fef02314b435b086f2 | refs/heads/master | 2023-02-18T22:25:15.121902 | 2023-02-06T19:35:34 | 2023-02-06T19:35:34 | 294,831,672 | 83 | 7 | Apache-2.0 | 2021-09-24T08:55:30 | 2020-09-11T23:27:37 | Java | UTF-8 | Java | false | false | 431 | java | package module1158packageJava0;
import java.lang.Integer;
public class Foo74 {
Integer int0;
Integer int1;
public void foo0() {
new module1158packageJava0.Foo73().foo6();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
public void foo6() {
foo5();
}
}
| [
"[email protected]"
]
| |
71046667f56a83b7e11fa755d29026aa50a8b1e1 | 270ad9c70235799c8578e829f80bf2678de9518d | /src/main/java/com/services/QueryService.java | f01967cb6e6423ffe09c3c7a77b3606c7041f37f | []
| no_license | smitbhojani5555/E-Farming | 639264c52dbf69318feb14a5560233cc9253e4b2 | e09ff79e5c6ef8ddb5d1439ea6f7cab03ec08828 | refs/heads/master | 2022-12-24T07:49:32.130521 | 2020-03-16T18:26:35 | 2020-03-16T18:26:35 | 177,145,821 | 0 | 0 | null | 2022-12-16T03:46:52 | 2019-03-22T13:33:26 | JavaScript | UTF-8 | Java | false | false | 536 | java | package com.services;
import java.util.List;
public interface QueryService {
List<Object[]> listqueries();
List<Object[]> describeproblem(int problemid);
String addUser(String subject, String discription,long farmerId,int status,String createddate);
String addComment(String parameter,long agronomistid, int problemid,String createddate1);
List<Object[]> searchquery( String searchtext);
String removequery(int problemid);
String deletequery(int status, int problemid);
List<Object[]> listadminqueries();
}
| [
"[email protected]"
]
| |
c6f87e240331168fa95df3b6c5b08019bd566078 | 53745e874b0d99a951575676b5786037ec0f7a00 | /android/build/generated/source/r/debug/com/rtmap/gm/myvuforia/R.java | 499f5685fb728739694b4355008e2edba1d119d3 | []
| no_license | gm-jack/MyVuforia2 | cc02b87080bce253890ebac97ffe6f515951c8c9 | 62db211596ddaf3fceca97da91145ad1347eadba | refs/heads/master | 2021-01-06T20:35:04.433057 | 2017-08-25T08:49:32 | 2017-08-25T08:49:32 | 99,524,502 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 242 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package com.rtmap.gm.myvuforia;
public final class R {
}
| [
"[email protected]"
]
| |
50597ad0b33cd05d75871e2a14087bdb2f865336 | 8dff1554d9fa994b92650a2caed4d925e9ae086e | /XadrezOnline/src/modelo/Modalidade.java | ce77c1cf1e1339fb6d5a6274cee1e15facc4bca8 | []
| no_license | vigusmao/Comp2_2020_2 | 390cb1db094eadce1ad857e8c30723bc6329cc44 | 7d6a60bfee1bfd5d6dfb326576adcc27f2d3c170 | refs/heads/main | 2023-06-06T22:51:41.400673 | 2021-07-11T21:53:51 | 2021-07-11T21:53:51 | 350,093,244 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 649 | java | package modelo;
public enum Modalidade {
BULLET(1, 0),
BLITZ(5, 3),
RAPID(15, 10),
CLASSICAL(30, 20);
private int tempoTotalEmMinutos;
private int incrementoDeTempoPorLanceEmSegundos;
Modalidade(int tempoTotalEmMinutos, int incrementoDeTempoPorLanceEmSegundos) {
this.tempoTotalEmMinutos = tempoTotalEmMinutos;
this.incrementoDeTempoPorLanceEmSegundos = incrementoDeTempoPorLanceEmSegundos;
}
public int getTempoTotalEmMinutos() {
return tempoTotalEmMinutos;
}
public int getIncrementoDeTempoPorLanceEmSegundos() {
return incrementoDeTempoPorLanceEmSegundos;
}
}
| [
"[email protected]"
]
| |
59efd2ba529e3b894578728aad8aeb7171addfc4 | 3eba848172de9729468b2657c993abea6204fbc1 | /src/com/service/impl/UsersServiceImpl.java | 45f2385f00a99db972aed06c906384fc3b87e070 | []
| no_license | hnluke/Shopping | 227f1e7dae6212e2d2f6f7fc8182ccf2af0923c5 | 1d67f4955758fec5873a3981c9f6a6e83c8e595d | refs/heads/master | 2021-05-16T18:58:05.748976 | 2020-05-18T10:03:25 | 2020-05-18T10:03:25 | 250,429,418 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 940 | java | package com.service.impl;
import com.dao.IUsersDao;
import com.dao.impl.UsersDaoImpl;
import com.db.DBConnection;
import com.pojo.Users;
import com.service.IUsersService;
import java.sql.*;
public class UsersServiceImpl implements IUsersService {
UsersDaoImpl usersDaoImpl = null;
Connection conn = null;
public UsersServiceImpl() {
conn = DBConnection.getConnect("c3p0");
this.usersDaoImpl = new UsersDaoImpl(conn);
}
@Override
public boolean verify(String id, String pwd) {
boolean flag = false;
Users users = usersDaoImpl.findById(id);
if(users != null) {
if(users.getU_pwd().equals(pwd)) {
flag = true;
}
}
return flag;
}
@Override
public Double queryAccountById(String id) {
if("".equals(id) || id == null)
return 0.0;
return usersDaoImpl.queryAccountById(id);
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.