hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
f7f6db7db0436aabe2bf39c81131b60a7bb9f00d | 7,647 | /*
* 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 games.rockola.musa.controlador;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextArea;
import games.rockola.musa.servicios.Dialogo;
import games.rockola.musa.servicios.Imagen;
import games.rockola.musa.MainApp;
import games.rockola.musa.ws.HttpUtils;
import games.rockola.musa.ws.pojos.Artista;
import games.rockola.musa.ws.pojos.FotoArtista;
import games.rockola.musa.ws.pojos.Mensaje;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.StageStyle;
/**
* FXML Controller class
*
* @author José Andrés Domínguez González
*/
public class ArtistaController implements Initializable {
@FXML
private Label labelArtista;
@FXML
private JFXTextArea areaBio;
@FXML
private JFXListView<Image> listaImagenes;
@FXML
private JFXListView<Image> listaAlbumes;
@FXML
private JFXButton agregarImagen;
Artista artista;
/**
* Initializes the controller class.
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
artista = LoginController.artistaLogueado;
areaBio.setText(artista.getBiografia());
labelArtista.setText(artista.getNombre());
listaImagenes.setCellFactory(lv -> {
ImageView vista = new ImageView();
ListCell<Image> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
MenuItem eliminar = new MenuItem("Eliminar");
eliminar.setOnAction((event) -> {
listaImagenes.getItems().remove(cell.getItem());
if(listaImagenes.getItems().size() < 5){
agregarImagen.setDisable(false);
}
});
contextMenu.getItems().addAll(eliminar);
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
cell.itemProperty().addListener((obs, oldItem, newItem) -> {
vista.setFitHeight(80);
vista.setFitWidth(80);
if (newItem != null) {
try {
vista.setImage(newItem);
} catch (Exception ex) {}
}
});
cell.emptyProperty().addListener((obs, wasEmpty, isEmpty) -> {
if (isEmpty) {
cell.setGraphic(null);
} else {
cell.setGraphic(vista);
}
});
cell.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
return cell ;
});
listaAlbumes.setCellFactory(lv -> {
ImageView vista = new ImageView();
ListCell<Image> cell = new ListCell<>();
cell.itemProperty().addListener((obs, oldItem, newItem) -> {
vista.setFitHeight(100);
vista.setFitWidth(100);
if (newItem != null) {
try {
vista.setImage(newItem);
} catch (Exception ex) {}
}
});
cell.emptyProperty().addListener((obs, wasEmpty, isEmpty) -> {
if (isEmpty) {
cell.setGraphic(null);
} else {
cell.setGraphic(vista);
}
});
cell.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
return cell ;
});
Mensaje mensaje = HttpUtils.recuperarFotosArtista(artista.getIdArtista());
Type listaFotos = new TypeToken<ArrayList<FotoArtista>>(){}.getType();
List<FotoArtista> fotosRecuperadas = new Gson().fromJson(mensaje.getMensaje(), listaFotos);
fotosRecuperadas.forEach((foto) -> {
try {
listaImagenes.getItems().add(Imagen.decodificarImagen(foto.getFoto()));
} catch (Exception ex) {
}
});
}
@FXML
public void anadirImagen(){
FileChooser seleccionarFoto = new FileChooser();
seleccionarFoto.setInitialDirectory(new File(System.getProperty("user.home")));
seleccionarFoto.getExtensionFilters().add(new FileChooser.ExtensionFilter(
"Imágenes", "*.jpg"));
File archivo = seleccionarFoto.showOpenDialog(MainApp.getVentana());
if(archivo != null) {
try {
listaImagenes.getItems().add(Imagen.archivoAImagen(archivo));
} catch (Exception ex) {
}
if(listaImagenes.getItems().size() > 4) {
agregarImagen.setDisable(true);
}
}
}
@FXML
public void guardarCambios(){
List<FotoArtista> fotos = new ArrayList<>();
listaImagenes.getItems().forEach((imagen) -> {
try {
fotos.add(new FotoArtista(Imagen.imagenAString(imagen), artista.getIdArtista()));
} catch (Exception ex) {
}
});
Mensaje mensaje = HttpUtils.actualizarArtista(artista.getIdArtista(), areaBio.getText());
Mensaje mensajeEliminar = HttpUtils.eliminarFotosArtista(artista.getIdArtista());
Mensaje mensajeFotos = HttpUtils.subirFotos(fotos);
System.out.println(mensaje.getMensaje() + " " + mensajeEliminar.getMensaje() + " " + mensajeFotos.getMensaje());
if("16".equals(mensaje.getMensaje()) && "16".equals(mensajeFotos.getMensaje()) &&
"16".equals(mensajeEliminar.getMensaje())){
new Dialogo(mensaje.getMensaje(), ButtonType.OK).show();
} else {
new Dialogo("17", ButtonType.OK).show();
}
}
@FXML
public void nuevoAlbum() {
AnchorPane anchor = null;
try {
anchor = FXMLLoader.load(getClass().getResource("/fxml/AgregarAlbum.fxml"));
} catch (IOException ex) {ex.printStackTrace();}
Dialog dialog = new Dialog<>();
dialog.setTitle("Nuevo album");
dialog.initStyle(StageStyle.UNDECORATED);
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.setContent(anchor);
dialogPane.setPrefSize(500, 300);
dialog.show();
}
@FXML
public void regresarLogin(){
MainApp main = new MainApp();
try {
main.cambiarEscena(1);
} catch (IOException ex) {}
}
}
| 34.138393 | 120 | 0.587812 |
d59e7fed26978a444c23048b6ec06d59ebe5d971 | 373 | package james.gustavo.helloworldrestrepositories;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloworldrestrepositoriesApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldrestrepositoriesApplication.class, args);
}
}
| 26.642857 | 75 | 0.849866 |
d7e3edb2c0d79044ab2b0c3e0c680841e87d0fc7 | 1,806 | package com.bber.company.android.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.bber.company.android.constants.Constants;
import com.bber.company.android.tools.SharedPreferencesUtils;
import com.bber.company.android.tools.Tools;
import com.bber.company.android.util.CLog;
/**
*/
public class MsfService extends Service {
private static MsfService mInstance = null;
private final IBinder binder = new MyBinder();
public String mUserName, mPassword;
private boolean isLogin = true;//false:表示注册, true:表示登录
public static MsfService getInstance() {
return mInstance;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
String userid = SharedPreferencesUtils.get(this, Constants.USERID, "-1") + "";
this.mUserName = userid + "buyer";
this.mPassword = Tools.md5("c" + mUserName);
mInstance = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
CLog.i( "onStartCommand");
if (intent != null) {
this.isLogin = intent.getBooleanExtra("isLogin", true);
String userid = SharedPreferencesUtils.get(this, Constants.USERID, "-1") + "";
this.mUserName = userid + "buyer";
this.mPassword = Tools.md5("c" + mUserName);
}
return START_STICKY;
}
@Override
public void onDestroy() {
CLog.i( "---- service onDestroy");
super.onDestroy();
}
public class MyBinder extends Binder {
public MsfService getService() {
return MsfService.this;
}
}
}
| 26.558824 | 90 | 0.645072 |
1054f58f4dbfe0d8e352edcf65fc165cdcfc2be0 | 20,948 | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.security.openid;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.authentication.SessionAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.UrlEncoded;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Constraint;
/**
* <p>Implements authentication using OpenId Connect on top of OAuth 2.0.
*
* <p>The OpenIdAuthenticator redirects unauthenticated requests to the OpenID Connect Provider. The End-User is
* eventually redirected back with an Authorization Code to the /j_security_check URI within the context.
* The Authorization Code is then used to authenticate the user through the {@link OpenIdCredentials} and {@link OpenIdLoginService}.
* </p>
* <p>
* Once a user is authenticated the OpenID Claims can be retrieved through an attribute on the session with the key {@link #CLAIMS}.
* The full response containing the OAuth 2.0 Access Token can be obtained with the session attribute {@link #RESPONSE}.
* </p>
* <p>{@link SessionAuthentication} is then used to wrap Authentication results so that they are associated with the session.</p>
*/
public class OpenIdAuthenticator extends LoginAuthenticator
{
private static final Logger LOG = Log.getLogger(OpenIdAuthenticator.class);
public static final String CLAIMS = "org.eclipse.jetty.security.openid.claims";
public static final String RESPONSE = "org.eclipse.jetty.security.openid.response";
public static final String ERROR_PAGE = "org.eclipse.jetty.security.openid.error_page";
public static final String J_URI = "org.eclipse.jetty.security.openid.URI";
public static final String J_POST = "org.eclipse.jetty.security.openid.POST";
public static final String J_METHOD = "org.eclipse.jetty.security.openid.METHOD";
public static final String CSRF_TOKEN = "org.eclipse.jetty.security.openid.csrf_token";
public static final String J_SECURITY_CHECK = "/j_security_check";
private OpenIdConfiguration _configuration;
private String _errorPage;
private String _errorPath;
private boolean _alwaysSaveUri;
public OpenIdAuthenticator()
{
}
public OpenIdAuthenticator(OpenIdConfiguration configuration, String errorPage)
{
this._configuration = configuration;
if (errorPage != null)
setErrorPage(errorPage);
}
@Override
public void setConfiguration(AuthConfiguration configuration)
{
super.setConfiguration(configuration);
String error = configuration.getInitParameter(ERROR_PAGE);
if (error != null)
setErrorPage(error);
if (_configuration != null)
return;
LoginService loginService = configuration.getLoginService();
if (!(loginService instanceof OpenIdLoginService))
throw new IllegalArgumentException("invalid LoginService");
this._configuration = ((OpenIdLoginService)loginService).getConfiguration();
}
@Override
public String getAuthMethod()
{
return Constraint.__OPENID_AUTH;
}
/**
* If true, uris that cause a redirect to a login page will always
* be remembered. If false, only the first uri that leads to a login
* page redirect is remembered.
*
* @param alwaysSave true to always save the uri
*/
public void setAlwaysSaveUri(boolean alwaysSave)
{
_alwaysSaveUri = alwaysSave;
}
public boolean isAlwaysSaveUri()
{
return _alwaysSaveUri;
}
private void setErrorPage(String path)
{
if (path == null || path.trim().length() == 0)
{
_errorPath = null;
_errorPage = null;
}
else
{
if (!path.startsWith("/"))
{
LOG.warn("error-page must start with /");
path = "/" + path;
}
_errorPage = path;
_errorPath = path;
if (_errorPath.indexOf('?') > 0)
_errorPath = _errorPath.substring(0, _errorPath.indexOf('?'));
}
}
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request)
{
if (LOG.isDebugEnabled())
LOG.debug("login {} {} {}", username, credentials, request);
UserIdentity user = super.login(username, credentials, request);
if (user != null)
{
HttpSession session = ((HttpServletRequest)request).getSession();
Authentication cached = new SessionAuthentication(getAuthMethod(), user, credentials);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
session.setAttribute(CLAIMS, ((OpenIdCredentials)credentials).getClaims());
session.setAttribute(RESPONSE, ((OpenIdCredentials)credentials).getResponse());
}
return user;
}
@Override
public void logout(ServletRequest request)
{
super.logout(request);
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(false);
if (session == null)
return;
//clean up session
session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
session.removeAttribute(CLAIMS);
session.removeAttribute(RESPONSE);
}
@Override
public void prepareRequest(ServletRequest request)
{
//if this is a request resulting from a redirect after auth is complete
//(ie its from a redirect to the original request uri) then due to
//browser handling of 302 redirects, the method may not be the same as
//that of the original request. Replace the method and original post
//params (if it was a post).
//
//See Servlet Spec 3.1 sec 13.6.3
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(false);
if (session == null || session.getAttribute(SessionAuthentication.__J_AUTHENTICATED) == null)
return; //not authenticated yet
String juri = (String)session.getAttribute(J_URI);
if (juri == null || juri.length() == 0)
return; //no original uri saved
String method = (String)session.getAttribute(J_METHOD);
if (method == null || method.length() == 0)
return; //didn't save original request method
StringBuffer buf = httpRequest.getRequestURL();
if (httpRequest.getQueryString() != null)
buf.append("?").append(httpRequest.getQueryString());
if (!juri.equals(buf.toString()))
return; //this request is not for the same url as the original
//restore the original request's method on this request
if (LOG.isDebugEnabled())
LOG.debug("Restoring original method {} for {} with method {}", method, juri, httpRequest.getMethod());
Request baseRequest = Request.getBaseRequest(request);
baseRequest.setMethod(method);
}
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
final HttpServletRequest request = (HttpServletRequest)req;
final HttpServletResponse response = (HttpServletResponse)res;
final Request baseRequest = Request.getBaseRequest(request);
final Response baseResponse = baseRequest.getResponse();
String uri = request.getRequestURI();
if (uri == null)
uri = URIUtil.SLASH;
mandatory |= isJSecurityCheck(uri);
if (!mandatory)
return new DeferredAuthentication(this);
if (isErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
return new DeferredAuthentication(this);
try
{
if (request.isRequestedSessionIdFromURL())
{
if (LOG.isDebugEnabled())
LOG.debug("Session ID should be cookie for OpenID authentication to work");
baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), URIUtil.addPaths(request.getContextPath(), _errorPage));
return Authentication.SEND_FAILURE;
}
// Handle a request for authentication.
if (isJSecurityCheck(uri))
{
String authCode = request.getParameter("code");
if (authCode != null)
{
// Verify anti-forgery state token
String state = request.getParameter("state");
String antiForgeryToken = (String)request.getSession().getAttribute(CSRF_TOKEN);
if (antiForgeryToken == null || !antiForgeryToken.equals(state))
{
LOG.warn("auth failed 403: invalid state parameter");
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return Authentication.SEND_FAILURE;
}
// Attempt to login with the provided authCode
OpenIdCredentials credentials = new OpenIdCredentials(authCode, getRedirectUri(request), _configuration);
UserIdentity user = login(null, credentials, request);
HttpSession session = request.getSession(false);
if (user != null)
{
// Redirect to original request
String nuri;
synchronized (session)
{
nuri = (String)session.getAttribute(J_URI);
if (nuri == null || nuri.length() == 0)
{
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
}
OpenIdAuthentication openIdAuth = new OpenIdAuthentication(getAuthMethod(), user);
if (LOG.isDebugEnabled())
LOG.debug("authenticated {}->{}", openIdAuth, nuri);
response.setContentLength(0);
baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), nuri);
return openIdAuth;
}
}
// not authenticated
if (LOG.isDebugEnabled())
LOG.debug("OpenId authentication FAILED");
if (_errorPage == null)
{
if (LOG.isDebugEnabled())
LOG.debug("auth failed 403");
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else
{
if (LOG.isDebugEnabled())
LOG.debug("auth failed {}", _errorPage);
baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), URIUtil.addPaths(request.getContextPath(), _errorPage));
}
return Authentication.SEND_FAILURE;
}
// Look for cached authentication
HttpSession session = request.getSession(false);
Authentication authentication = session == null ? null : (Authentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (authentication != null)
{
// Has authentication been revoked?
if (authentication instanceof Authentication.User && _loginService != null &&
!_loginService.validate(((Authentication.User)authentication).getUserIdentity()))
{
if (LOG.isDebugEnabled())
LOG.debug("auth revoked {}", authentication);
session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
}
else
{
synchronized (session)
{
String jUri = (String)session.getAttribute(J_URI);
if (jUri != null)
{
//check if the request is for the same url as the original and restore
//params if it was a post
if (LOG.isDebugEnabled())
LOG.debug("auth retry {}->{}", authentication, jUri);
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
if (jUri.equals(buf.toString()))
{
@SuppressWarnings("unchecked")
MultiMap<String> jPost = (MultiMap<String>)session.getAttribute(J_POST);
if (jPost != null)
{
if (LOG.isDebugEnabled())
LOG.debug("auth rePOST {}->{}", authentication, jUri);
baseRequest.setContentParameters(jPost);
}
session.removeAttribute(J_URI);
session.removeAttribute(J_METHOD);
session.removeAttribute(J_POST);
}
}
}
if (LOG.isDebugEnabled())
LOG.debug("auth {}", authentication);
return authentication;
}
}
// if we can't send challenge
if (DeferredAuthentication.isDeferred(response))
{
if (LOG.isDebugEnabled())
LOG.debug("auth deferred {}", session == null ? null : session.getId());
return Authentication.UNAUTHENTICATED;
}
// remember the current URI
session = (session != null ? session : request.getSession(true));
synchronized (session)
{
// But only if it is not set already, or we save every uri that leads to a login redirect
if (session.getAttribute(J_URI) == null || isAlwaysSaveUri())
{
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(J_URI, buf.toString());
session.setAttribute(J_METHOD, request.getMethod());
if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod()))
{
MultiMap<String> formParameters = new MultiMap<>();
baseRequest.extractFormParameters(formParameters);
session.setAttribute(J_POST, formParameters);
}
}
}
// send the the challenge
String challengeUri = getChallengeUri(request);
if (LOG.isDebugEnabled())
LOG.debug("challenge {}->{}", session.getId(), challengeUri);
baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), challengeUri);
return Authentication.SEND_CONTINUE;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
public boolean isJSecurityCheck(String uri)
{
int jsc = uri.indexOf(J_SECURITY_CHECK);
if (jsc < 0)
return false;
int e = jsc + J_SECURITY_CHECK.length();
if (e == uri.length())
return true;
char c = uri.charAt(e);
return c == ';' || c == '#' || c == '/' || c == '?';
}
public boolean isErrorPage(String pathInContext)
{
return pathInContext != null && (pathInContext.equals(_errorPath));
}
private static int getRedirectCode(HttpVersion httpVersion)
{
return (httpVersion.getVersion() < HttpVersion.HTTP_1_1.getVersion()
? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
}
private String getRedirectUri(HttpServletRequest request)
{
final StringBuffer redirectUri = new StringBuffer(128);
URIUtil.appendSchemeHostPort(redirectUri, request.getScheme(),
request.getServerName(), request.getServerPort());
redirectUri.append(request.getContextPath());
redirectUri.append(J_SECURITY_CHECK);
return redirectUri.toString();
}
protected String getChallengeUri(HttpServletRequest request)
{
HttpSession session = request.getSession();
String antiForgeryToken;
synchronized (session)
{
antiForgeryToken = (session.getAttribute(CSRF_TOKEN) == null)
? new BigInteger(130, new SecureRandom()).toString(32)
: (String)session.getAttribute(CSRF_TOKEN);
session.setAttribute(CSRF_TOKEN, antiForgeryToken);
}
// any custom scopes requested from configuration
StringBuilder scopes = new StringBuilder();
for (String s : _configuration.getScopes())
{
scopes.append(" ").append(s);
}
return _configuration.getAuthEndpoint() +
"?client_id=" + UrlEncoded.encodeString(_configuration.getClientId(), StandardCharsets.UTF_8) +
"&redirect_uri=" + UrlEncoded.encodeString(getRedirectUri(request), StandardCharsets.UTF_8) +
"&scope=openid" + UrlEncoded.encodeString(scopes.toString(), StandardCharsets.UTF_8) +
"&state=" + antiForgeryToken +
"&response_type=code";
}
@Override
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser)
{
return true;
}
/**
* This Authentication represents a just completed OpenId Connect authentication.
* Subsequent requests from the same user are authenticated by the presents
* of a {@link SessionAuthentication} instance in their session.
*/
public static class OpenIdAuthentication extends UserAuthentication implements Authentication.ResponseSent
{
public OpenIdAuthentication(String method, UserIdentity userIdentity)
{
super(method, userIdentity);
}
@Override
public String toString()
{
return "OpenId" + super.toString();
}
}
}
| 41.563492 | 149 | 0.595379 |
e314c09e6f5f078331d2f40b064b6158b55bd39c | 421 | /**
* Server-side support for testing Spring MVC applications with {@code MockMvc}
* and the Selenium {@code HtmlUnitDriver}.
* @see org.springframework.test.web.servlet.MockMvc
* @see org.openqa.selenium.htmlunit.HtmlUnitDriver
*/
@NonNullApi
@NonNullFields
package org.springframework.test.web.servlet.htmlunit.webdriver;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
| 32.384615 | 79 | 0.800475 |
5c16bd169e16cea3e8f9f18ef44fa49917c1dc2c | 728 | package com.supinfo.supsms.client.dto;
public class Contact {
private Long _ID;
private String DNAME;
private String EMAIL;
private String PNUM;
public Long get_ID() {
return _ID;
}
public void set_ID(Long _ID) {
this._ID = _ID;
}
public String getDNAME() {
return DNAME;
}
public void setDNAME(String DNAME) {
this.DNAME = DNAME;
}
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL;
}
public String getPNUM() {
return PNUM;
}
public void setPNUM(String PNUM) {
this.PNUM = PNUM;
}
}
| 17.333333 | 41 | 0.537088 |
87487052cbd59296b10c5de50625c6bf33223612 | 720 | package com.wxm.pt.dao;
import com.wxm.pt.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author Alex Wang
* @date 2019/05/11
*/
@Repository
public interface StudentDao extends JpaRepository<Student,Long> {
public List<Student> findStudentsByNameLike(String name);
@Query("select distinct sp.student from StudyProgram sp where 0<(select count(c) from sp.primaryCourses c where c.id=:courseId)")
public List<Student> findStudentsBySelectCourseId(@Param("courseId") long courseId);
}
| 34.285714 | 133 | 0.7875 |
86c521b9eefdbf87c319b7a20940c0f4f363aebc | 1,071 | package dbAccess;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import resources.LoanAccount;
public class LoanAccountDao {
public static int saveAccount(LoanAccount newAccount) {
int status = 0;
try {
Connection con = DB.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO loan_accounts (accountId, customerId, ammountOriginal, amountToBePaid, currentAmount, duration, monthlyRate,"
+ " interestRate) VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, newAccount.getAccountId());
ps.setString(2, newAccount.getCustomerId());
ps.setDouble(3, newAccount.getAmountOriginal());
ps.setDouble(4, newAccount.getAmountToBePaid());
ps.setDouble(5, newAccount.getCurrentAmount());
ps.setInt(6, newAccount.getDuration());
ps.setDouble(7, newAccount.getMonthlyRate());
ps.setDouble(8, newAccount.getInterestRate());
status = ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
System.out.println(e);
}
return status;
}
}
| 29.75 | 169 | 0.711485 |
55663c65ee848ea86d05c340a5c7473300474f8f | 135 | package co.uk.rushorm.android.testobjects;
/**
* Created by Stuart on 21/01/15.
*/
public class MyClass {
public String name;
}
| 15 | 42 | 0.688889 |
6033683cc6e0d7c0d1ff1bc2946400d5d997ea78 | 498 | package com.example.springsourcedemo.bean.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @ClassName BeanTest
* @Description TODO
* @Author chenzl
* @Date 2020/9/25 15:31
*/
public class BeanTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
TestService bean = ac.getBean(TestService.class);
System.out.println(bean.getClass().getName());
}
} | 27.666667 | 98 | 0.7751 |
e9cd259f9be26dd1c7a395147c5911871f42feb2 | 2,702 | public class Cell {
// Square objects drawn on screen, can contain occupants, and are the basis of
// interaction
int gridX, gridY;
Grid pGrid;
int bgc;
// determines bgc of square
Occupant occupant;
int terrainType;
Cell(Grid gridP, int gx, int gy) {
gridX = gx;
gridY = gy;
this.pGrid = gridP;
occupant = new Occupant();
// graveyarded occupant for the moment
terrainType = Integer.parseInt(String.valueOf(GC.mapData[gy].charAt(gx)));
bgc = GC.terrainColours[terrainType];
}
public boolean cameraContainsMouse() {
return (pGrid.p.mouseX - GC.cameraX > x() && pGrid.p.mouseX - GC.cameraX < x() + GC.scale
&& pGrid.p.mouseY - GC.cameraY > y() && pGrid.p.mouseY - GC.cameraY < y() + GC.scale);
}
public void drawBG() {
// draGC.scale in terrain square
pGrid.p.stroke(GC.terrainBorders[terrainType]);
pGrid.p.strokeWeight(1);
pGrid.p.fill(this.cameraContainsMouse() || this.occupant.isSelected() ? bgc + pGrid.p.color(40) : bgc);
// rnd colours make it interesting
pGrid.p.rect(x() + GC.cameraX, y() + GC.cameraY, GC.scale, GC.scale);
if (!GC.players[GC.activePlayer].FOW[gridX][gridY]) {
pGrid.p.fill(pGrid.p.color(30, 100));
pGrid.p.stroke(40, 100);
pGrid.p.rect(x() + GC.cameraX, y() + GC.cameraY, GC.scale, GC.scale);
}
}
public void drawUnit() {
// unit and triangle indicator
if (GC.gameState == 2 && occupant.isSelected()) {
occupant.moveAnim();
} else if (GC.gameState == 3 && occupant.isSelected()) {
occupant.atkAnim();
}
if (occupant.id != -1) {
if (occupant.id == -2) {
pGrid.p.image(pGrid.p.loadImage("Unitimages/Rubble.png"), x() + occupant.moveX + GC.cameraX, y() + occupant.moveY + GC.cameraY,
GC.scale, GC.scale);
}
else {
pGrid.p.image(GC.unitImg[occupant.id], x() + occupant.moveX + GC.cameraX, y() + occupant.moveY + GC.cameraY,
GC.scale, GC.scale);
pGrid.p.fill((this.cameraContainsMouse() || this.occupant.isSelected()
? GC.ownerColours[occupant.owner] + pGrid.p.color(30)
: GC.ownerColours[occupant.owner]));
pGrid.p.triangle(x() + GC.cameraX, y() + GC.cameraY, x() + GC.cameraX + (GC.scale / 2),
y() + GC.cameraY + GC.scale / 5, x() + GC.scale + GC.cameraX, y() + GC.cameraY);
pGrid.p.fill(255, 100, 100);
pGrid.p.rect(x() + GC.cameraX, y() + GC.cameraY + GC.scale * 7 / 8,
GC.scale * occupant.stats.vals[Occupant.hp] / occupant.stats.maxHP, GC.scale / 8);
}
}
}
public void drawUI() {
if (occupant.isSelected() && occupant.id != -1) {
occupant.drawComponents();
}
}
public int x() {
return pGrid.x + GC.scale * gridX;
}
public int y() {
return pGrid.y + GC.scale * gridY;
}
} | 27.02 | 131 | 0.630644 |
ae4713b77d4c39bf8c248e760ff49155881e690c | 1,966 | package models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
public class WorkOrderItemsDetail
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int workOrderItemsId;
private String itemName;
private int quantity;
private int workOrderId;
private BigDecimal discount;
private BigDecimal retailPrice;
private BigDecimal retailTotal;
private BigDecimal saleTotal;
private int itemTotal;
private int workOrderIdCount;
//TODO NEED TO ADD ALL COLUMNS TO ENABLE CREATE WORK ORDER PAGE
public WorkOrderItemsDetail(int workOrderItemsId, String itemName, int quantity, int workOrderId, BigDecimal discount, BigDecimal retailPrice, BigDecimal saleTotal)
{
this.workOrderItemsId = workOrderItemsId;
this.itemName = itemName;
this.quantity = quantity;
this.workOrderId = workOrderId;
this.discount = discount;
this.retailPrice = retailPrice;
this.saleTotal = saleTotal;
}
public int getWorkOrderItemsId()
{
return workOrderItemsId;
}
public String getItemName()
{
return itemName;
}
public int getQuantity()
{
return quantity;
}
public int getWorkOrderId()
{
return workOrderId;
}
public BigDecimal getDiscount()
{
return discount;
}
public BigDecimal getRetailPrice()
{
return retailPrice;
}
public BigDecimal getSaleTotal()
{
return saleTotal;
}
public BigDecimal getRetailTotal()
{
retailTotal = retailPrice.multiply(new BigDecimal(quantity));
return retailTotal;
}
public int getItemTotal()
{
itemTotal = quantity * workOrderItemsId;
return itemTotal;
}
}
| 21.844444 | 168 | 0.676501 |
6c420d80f0d9527fc468b098cb8578a45b50cc68 | 382 | package com.biprom.bram.amcalapp.mongoRepositories;
import com.biprom.bram.amcalapp.data.entity.mongodbEntities.Korting;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface KortingRepository extends MongoRepository <Korting, String> {
Korting findByKorting(String kortingsCode);
}
| 34.727273 | 78 | 0.84555 |
e1866b0745cca08ee9bacd8ea96b16bd6516b5ee | 2,236 | /* Copyright (c) 2001-2019, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.cmdline.sqltool;
import java.util.ArrayList;
/* @(#)$Id: TokenList.java 5969 2019-04-27 14:59:54Z fredt $ */
/**
* A list of SqlFile Tokens
*/
public class TokenList extends ArrayList<Token> implements TokenSource {
static final long serialVersionUID = 5441418591320947274L;
public TokenList() {
super();
}
public TokenList(TokenList inList) {
super(inList);
}
public Token yylex() {
if (size() < 1) return null;
//return remove(0);
// Java5
return remove(0);
}
public TokenList dup() {
return new TokenList(this);
}
}
| 36.655738 | 80 | 0.729428 |
f8e8cb498141c1124252addcd2728fdc289f1006 | 1,251 | package repast.simphony.visualization.decorator;
import org.jogamp.java3d.Group;
import repast.simphony.space.projection.Projection;
import repast.simphony.visualization.visualization3D.Display3D;
/**
* Interface for classes that will decorate projection visualizations. Decorating
* a projection refers to such things as adding grid lines for a grid projection,
* bounding boxes, etc.
*
* @author Nick Collier
* @version $Revision$ $Date$
*/
public interface ProjectionDecorator3D<T extends Projection> {
/**
* Initializes the decorator. Implementors should add
* the decorating shapes to the parent branch group.
*
* @param display
* @param parent the parent to which the decoration should be added
*/
void init(Display3D display, Group parent);
/**
* Updates the decorator. The intention is that this would only do something if
* the decoration has changed from that created in init.
*/
void update();
/**
* Sets the that this decorator decorates.
*
* @param projection
*/
void setProjection(T projection);
/**
* Gets the projection that this decorator decorates.
*
* @return the projection that this decorator decorates.
*/
T getProjection();
}
| 26.617021 | 82 | 0.711431 |
ba02df23481449109264b1dde8e558e1b5a0f08c | 103 | package com.maprosoft.maproweb.jira;
public interface MaprosoftJiraComponent {
String getName();
} | 20.6 | 41 | 0.786408 |
c0a37b2207ddaab8bbe136b276487defb01340d3 | 425 | package com.revolsys.record.io.format.openstreetmap.model;
import org.jeometry.common.data.identifier.SingleIdentifier;
public class OsmWayIdentifier extends SingleIdentifier {
public OsmWayIdentifier(final long id) {
super(id);
}
@Override
public boolean equals(final Object other) {
if (other instanceof OsmWayIdentifier) {
return super.equals(other);
} else {
return false;
}
}
}
| 21.25 | 60 | 0.72 |
8578a4c1db93d4e9b485a8a7e409dcd819ba6493 | 1,278 | package kr.co.popone.fitts.di.module;
import dagger.internal.Factory;
import dagger.internal.Preconditions;
import okhttp3.HttpUrl;
public final class GlobeConfigModule_ProvideBaseUrl$app_productionFittsReleaseFactory implements Factory<HttpUrl> {
private final GlobeConfigModule module;
public GlobeConfigModule_ProvideBaseUrl$app_productionFittsReleaseFactory(GlobeConfigModule globeConfigModule) {
this.module = globeConfigModule;
}
public HttpUrl get() {
return provideInstance(this.module);
}
public static HttpUrl provideInstance(GlobeConfigModule globeConfigModule) {
return proxyProvideBaseUrl$app_productionFittsRelease(globeConfigModule);
}
public static GlobeConfigModule_ProvideBaseUrl$app_productionFittsReleaseFactory create(GlobeConfigModule globeConfigModule) {
return new GlobeConfigModule_ProvideBaseUrl$app_productionFittsReleaseFactory(globeConfigModule);
}
public static HttpUrl proxyProvideBaseUrl$app_productionFittsRelease(GlobeConfigModule globeConfigModule) {
return (HttpUrl) Preconditions.checkNotNull(globeConfigModule.provideBaseUrl$app_productionFittsRelease(), "Cannot return null from a non-@Nullable @Provides method");
}
}
| 42.6 | 176 | 0.791862 |
1a92b4b2a081e87b3a9fe44c96ee4a739181b536 | 784 | /*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.api.mapper.functions;
import com.emc.storageos.api.mapper.BlockMapper;
import com.emc.storageos.db.client.model.UnManagedDiscoveredObjects.UnManagedVolume;
import com.emc.storageos.model.block.UnManagedVolumeRestRep;
import com.google.common.base.Function;
public class MapUnmanagedVolume implements Function<UnManagedVolume, UnManagedVolumeRestRep> {
public static final MapUnmanagedVolume instance = new MapUnmanagedVolume();
public static MapUnmanagedVolume getInstance() {
return instance;
}
private MapUnmanagedVolume() {
}
@Override
public UnManagedVolumeRestRep apply(UnManagedVolume volume) {
return BlockMapper.map(volume);
}
}
| 29.037037 | 94 | 0.769133 |
fe9dc688278ebaf68eb3864cac0a0c72ca88594c | 393 | package com.marceltbr.okready.repositories.okrs;
import com.marceltbr.okready.entities.okrs.YearSemester;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface YearSemesterRepository extends JpaRepository<YearSemester, Long> {
YearSemester findById(long id);
}
| 35.727273 | 83 | 0.849873 |
47935c03dfbe4148504bb3ead8d0510579384f23 | 6,264 | package cn.hylstudio.android.testdatabase.fragment;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cn.hylstudio.android.testdatabase.R;
import cn.hylstudio.android.testdatabase.adapter.WordListAdapter;
import cn.hylstudio.android.testdatabase.dao.WordDao;
import cn.hylstudio.android.testdatabase.daoimpl.WordDaoImpl;
import cn.hylstudio.android.testdatabase.daoimpl.WordsDBHelper;
import cn.hylstudio.android.testdatabase.model.Word;
import cn.hylstudio.android.testdatabase.util.Util;
/**
* Created by HYL on 2016/9/4.
*/
public class WordListFragment extends ListFragment {
public static final String TAG = "fragment_word";
private itemListener itemListener;
private List<Word> words;
private WordDao db;
private EditText text_word;
private EditText text_meaning;
private EditText text_sample;
private Word w;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: begin");
db = new WordDaoImpl(getActivity());
words = db.getAllWords();
// for (int i = 0; i < 20; i++) {
// words.add(new Word(i, "apple" + i, "苹果" + i, "this is an apple" + i));
// }
Log.d(TAG, "onCreate: end");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: begin");
View view = inflater.inflate(R.layout.word_list, container, false);
if (view instanceof ListView) {
setListAdapter(new WordListAdapter(getActivity(), words));
ListView list_words = (ListView) view;
registerForContextMenu(list_words);
}
Log.d(TAG, "onCreateView: end");
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d(TAG, "onAttach: begin");
if (context instanceof itemListener) {
itemListener = (itemListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement itemListener");
}
Log.d(TAG, "onAttach: end");
}
@Override
public void onDetach() {
super.onDetach();
itemListener = null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.word_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View clickedItem = info.targetView;
TextView tv_word = (TextView) clickedItem.findViewById(R.id.tv_item_word);
switch (item.getItemId()) {
case R.id.menu_item_update_word:
updateWord(tv_word.getText() + "");
Log.d(TAG, "onContextItemSelected:updateWord: " + tv_word.getText());
break;
case R.id.menu_item_delete_word:
db.delWord(tv_word.getText() + "");
refreshList();
Log.d(TAG, "onContextItemSelected:delWord: " + tv_word.getText());
break;
}
return true;
}
private void updateWord(final String word) {
w = db.getWordByContent(word);
View updateWordDialog = getActivity().getLayoutInflater().inflate(R.layout.word_dialog, null);
text_word = (EditText) updateWordDialog.findViewById(R.id.text_dialog_word);
text_meaning = (EditText) updateWordDialog.findViewById(R.id.text_dialog_meaning);
text_sample = (EditText) updateWordDialog.findViewById(R.id.text_dialog_sample);
text_word.setText(w.getWord());
text_meaning.setText(w.getMeaning());
text_sample.setText(w.getSample());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("修改单词");//标题
builder.setView(updateWordDialog);//设置视图
//确定按钮及其动作
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Word newWord = db.getWordByContent(w.getWord());
newWord.setWord(text_word.getText() + "");
newWord.setMeaning(text_meaning.getText() + "");
newWord.setSample(text_sample.getText() + "");
db.updateWord(newWord);
//单词已经插入到数据库,更新显示列表
refreshList(w.getWord());
Log.d(TAG, "onClick: update word" + text_word.getText());
}
});
//取消按钮及其动作
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: update word cancel");
}
});
builder.create();//创建对话框
builder.show();//显示对话框
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
itemListener.onItemClick(((TextView) v).getText() + "");
}
public void refreshList() {
words = db.getAllWords();
setListAdapter(new WordListAdapter(getActivity(), words));
}
public void refreshList(String wordContent) {
refreshList();
if (Util.isLand(getActivity())) {
itemListener.onItemClick(wordContent);
}
}
public interface itemListener {
void onItemClick(String wordContent);
}
}
| 35.794286 | 106 | 0.647031 |
2d8c7197fc97ba8e3f1b2f3f0ab6f77367616825 | 270 | package com.staxrt.tutorial.service;
import com.staxrt.tutorial.model.IsvedimoDuomenys;
import java.io.IOException;
import java.util.List;
public interface AtbulinisIsvedimasService {
IsvedimoDuomenys AtliktiAtbuliniIsvedima(String goal1, List<String> facts1);
}
| 24.545455 | 80 | 0.822222 |
11a04de01550cb7486263d4082808a6345be0c08 | 666 | import java.util.ArrayList;
/**
* Created by Marci Blum on 2017.07.16..
*/
public class Queen implements PieceType{
ArrayList<Coords> directions;
public Queen(){
directions = new ArrayList<>();
directions.add(Directions.UP);
directions.add(Directions.UP_LEFT);
directions.add(Directions.UP_RIGHT);
directions.add(Directions.DOWN);
directions.add(Directions.DOWN_LEFT);
directions.add(Directions.DOWN_RIGHT);
directions.add(Directions.LEFT);
directions.add(Directions.RIGHT);
}
@Override
public ArrayList<Coords> getMoveDirections() {
return directions;
}
}
| 25.615385 | 50 | 0.659159 |
4d3ffdb07e4fe5bd7b6643543cfac0af442e0836 | 5,943 | /*-
* #%L
* OfficeFrame
* %%
* Copyright (C) 2005 - 2020 Daniel Sagenschneider
* %%
* 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 net.officefloor.frame.impl.execute.office;
import java.util.Map;
import java.util.function.Consumer;
import net.officefloor.frame.api.manage.ObjectUser;
import net.officefloor.frame.api.manage.StateManager;
import net.officefloor.frame.api.manage.UnknownObjectException;
import net.officefloor.frame.api.managedobject.ManagedObject;
import net.officefloor.frame.impl.execute.linkedlistset.AbstractLinkedListSetEntry;
import net.officefloor.frame.impl.execute.office.LoadManagedObjectFunctionFactory.LoadManagedObjectParameter;
import net.officefloor.frame.internal.structure.Flow;
import net.officefloor.frame.internal.structure.FlowCompletion;
import net.officefloor.frame.internal.structure.FunctionState;
import net.officefloor.frame.internal.structure.ManagedFunctionContainer;
import net.officefloor.frame.internal.structure.ManagedFunctionMetaData;
import net.officefloor.frame.internal.structure.MonitorClock;
import net.officefloor.frame.internal.structure.ThreadState;
/**
* {@link StateManager} implementation.
*
* @author Daniel Sagenschneider
*/
public class StateManagerImpl implements StateManager {
/**
* Load object {@link ManagedFunctionMetaData} instances by the loading object
* bound name.
*/
private final Map<String, ManagedFunctionMetaData<?, ?>> loadObjectMetaDatas;
/**
* {@link ThreadState} for context of the {@link ManagedObject} instances.
*/
private final ThreadState threadState;
/**
* {@link MonitorClock}.
*/
private final MonitorClock monitorClock;
/**
* Executes the {@link FunctionState} instances.
*/
private final Consumer<FunctionState> functionExecutor;
/**
* Cleans up state on closing {@link StateManager}.
*/
private final Runnable cleanUpState;
/**
* Instantiate.
*
* @param loadObjectMetaDatas Load object {@link ManagedFunctionMetaData}
* instances by the loading object bound name.
* @param threadState {@link ThreadState} for context of the
* {@link ManagedObject} instances.
* @param monitorClock {@link MonitorClock}.
* @param functionExecutor Executes the {@link FunctionState} instances.
* @param cleanUpState Cleans up state on closing {@link StateManager}.
*/
public StateManagerImpl(Map<String, ManagedFunctionMetaData<?, ?>> loadObjectMetaDatas, ThreadState threadState,
MonitorClock monitorClock, Consumer<FunctionState> functionExecutor, Runnable cleanUpState) {
this.loadObjectMetaDatas = loadObjectMetaDatas;
this.threadState = threadState;
this.monitorClock = monitorClock;
this.functionExecutor = functionExecutor;
this.cleanUpState = cleanUpState;
}
/*
* ===================== StateManager =========================
*/
@Override
public <O> void load(String boundObjectName, ObjectUser<O> user) throws UnknownObjectException {
// Obtain the function meta-data to load the bound object
ManagedFunctionMetaData<?, ?> loadMetaData = this.loadObjectMetaDatas.get(boundObjectName);
if (loadMetaData == null) {
throw new UnknownObjectException(boundObjectName);
}
// Create the load completion to capture object (or possible failure)
LoadObjectCompletion<?> loadCompletion = new LoadObjectCompletion<>(user);
// Create flow to load object
Flow flow = this.threadState.createFlow(loadCompletion, null);
// Create the managed object to load the object
FunctionState loader = flow.createManagedFunction(loadCompletion, loadMetaData, true, null);
// Undertake function to load the object
this.functionExecutor.accept(loader);
}
@Override
public <O> O getObject(String boundObjectName, long timeoutInMilliseconds) throws Throwable {
// Obtain the object
ObjectUserImpl<O> user = new ObjectUserImpl<O>(boundObjectName, this.monitorClock);
this.load(boundObjectName, user);
// Return the loaded object (or fail)
return user.getObject(timeoutInMilliseconds);
}
@Override
public void close() throws Exception {
this.cleanUpState.run();
}
/**
* Captures the result of loading an object.
*/
private static class LoadObjectCompletion<O>
extends AbstractLinkedListSetEntry<FlowCompletion, ManagedFunctionContainer>
implements LoadManagedObjectParameter, FlowCompletion {
/**
* {@link ObjectUser}.
*/
private final ObjectUser<O> objectUser;
/**
* Instantiate.
*
* @param objectUser {@link ObjectUser}.
*/
private LoadObjectCompletion(ObjectUser<O> objectUser) {
this.objectUser = objectUser;
}
/*
* =================== LoadManagedObjectParameter ======================
*/
@Override
@SuppressWarnings("unchecked")
public void load(Object object) {
this.objectUser.use((O) object, null);
}
/*
* ==================== FlowCompletion =================================
*/
@Override
public ManagedFunctionContainer getLinkedListSetOwner() {
throw new IllegalStateException("Should not require " + ManagedFunctionContainer.class.getSimpleName()
+ " for " + StateManager.class.getSimpleName());
}
@Override
public FunctionState flowComplete(Throwable escalation) {
// Handle the escalation
if (escalation != null) {
this.objectUser.use(null, escalation);
}
// Nothing further
return null;
}
}
}
| 31.278947 | 113 | 0.72455 |
50a49fbef186b2ca82bf10e1b6ef871d9c0cbf05 | 1,473 | package stacksandcompilers;
import java.io.Reader;
import java.util.Stack;
public class Balance {
private int errors;
private Tokenizer tok;
public Balance(Reader inStream) {
errors = 0;
tok = new Tokenizer(inStream);
}
private int checkBalance() {
char ch;
Symbol match = null;
Stack pendingTokens = new Stack();
while ((ch = tok.getNextOpenClose()) != '\0') {
Symbol lastSymbol = new Symbol(ch, tok.getLineNumber());
switch (ch) {
case '(':
case '[':
case '{':
pendingTokens.push(lastSymbol);
break;
case ')':
case ']':
case '}':
if (pendingTokens.isEmpty()) {
errors++;
} else {
match = (Symbol) pendingTokens.pop();
checkMatch(match, lastSymbol);
}
break;
default:
break;
}
}
while (!pendingTokens.isEmpty()) {
match = (Symbol) pendingTokens.pop();
System.out.println(String.format("Unmatched %c at line %d", match.token, match.theLine));
errors++;
}
return errors + tok.getErrorCount();
}
private static class Symbol {
public char token;
public int theLine;
public Symbol(char token, int line) {
this.token = token;
this.theLine = line;
}
}
private void checkMatch(Symbol opSym, Symbol clSym) {
if(opSym.token == '(' && clSym.token != ')' ||
opSym.token == '[' && clSym.token != ']' ||
opSym.token == '{' && clSym.token != '}' ) {
errors++;
}
}
}
| 21.347826 | 93 | 0.578411 |
1e7b9cec7be07d810b4146d9c3834ad381cc5486 | 21,947 | package com.tal.wangxiao.conan.agent.service.impl;
import com.google.common.collect.Lists;
import com.tal.wangxiao.conan.agent.service.RecordService;
import com.tal.wangxiao.conan.common.api.ResponseCode;
import com.tal.wangxiao.conan.common.constant.enums.HttpMethodConstants;
import com.tal.wangxiao.conan.common.constant.enums.TaskStatus;
import com.tal.wangxiao.conan.common.entity.db.*;
import com.tal.wangxiao.conan.common.exception.BaseException;
import com.tal.wangxiao.conan.common.model.Result;
import com.tal.wangxiao.conan.common.model.bo.RecordDetailInfo;
import com.tal.wangxiao.conan.common.model.bo.RecordInfo;
import com.tal.wangxiao.conan.common.model.query.RequestQuery;
import com.tal.wangxiao.conan.common.redis.RedisTemplateTool;
import com.tal.wangxiao.conan.common.repository.db.*;
import com.tal.wangxiao.conan.common.utils.task.TaskStatusUtil;
import com.tal.wangxiao.conan.common.utils.DynamicEsUtils;
import com.tal.wangxiao.conan.sys.common.exception.CustomException;
import com.tal.wangxiao.conan.utils.enumutils.EnumUtil;
import com.tal.wangxiao.conan.utils.regex.RegexUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
/**
* @author liujinsong
* @date 2020/1/8
*/
@Service
@Slf4j
public class RecordServiceImpl implements RecordService {
@Resource
private RecordRepository recordRepository;
@Resource
private RecordDetailRepository recordDetailRepository;
@Resource
private TaskRepository taskRepository;
@Resource
private TaskExecutionRepository taskExecutionRepository;
@Resource
private DepartmentRepository departmentRepository;
@Resource
private UserRepository userRepository;
@Resource
private DomainRepository domainRepository;
@Resource
private ApiRepository apiRepository;
@Resource
private TaskApiRelationRepository taskApiRelationRepository;
@Resource
private RecordResultRepository recordResultRepository;
@Resource
private TaskStatusUtil taskStatusUtil;
@Resource
private EsConditionSettingRepository esConditionSettingRepository;
@Resource
private EsSourceRepository esSourceRepository;
@Resource
private RedisTemplateTool redisTemplateTool;
//根据任务执行ID获取任务执行信息
@Override
public Result findByTaskExecutionId(Integer taskExecutionId) throws Exception {
RecordInfo recordInfo = new RecordInfo();
List<RecordDetailInfo> recordDetailInfoList = Lists.newArrayList();
recordInfo.setRecordDetailInfoList(recordDetailInfoList);
recordInfo.setTaskExecutionId(taskExecutionId);
Optional<Record> recordOptional = recordRepository.findFirstByTaskExecutionId(taskExecutionId);
if (!recordOptional.isPresent()) {
return new Result(ResponseCode.INVALID_RECORD_ID, ResponseCode.INVALID_RECORD_ID.getDesc());
}
Record record = recordOptional.get();
recordInfo.setRecordId(record.getId());
recordInfo.setApiCount(record.getApiCount());
recordInfo.setStartAt(record.getStartTime());
recordInfo.setEndAt(record.getEndTime());
recordInfo.setSuccessRate(record.getSuccessRate());
Optional<User> userOptional = userRepository.findById(record.getOperateBy());
if (!userOptional.isPresent()) {
return new Result(ResponseCode.INVALID_USER_ID, "没有找到有效的录制人信息");
}
recordInfo.setOperateBy(userOptional.get().getNickName());
Optional<TaskExecution> taskExecutionOptional = taskExecutionRepository.findById(taskExecutionId);
if (!taskExecutionOptional.isPresent()) {
return new Result(ResponseCode.INVALID_TASK_EXECUTION_ID, "该任务执行ID无效,找不到有关task_execution_id=" + taskExecutionId + "的执行信息");
}
Optional<Task> taskOptional = taskRepository.findById(taskExecutionOptional.get().getTaskId());
if (!taskOptional.isPresent()) {
return new Result(ResponseCode.INVALID_TASK_ID, "未找到任务实体,task_execution_id = " + taskExecutionId + ", task_id = " + taskExecutionOptional.get().getTaskId());
}
recordInfo.setTaskId(taskOptional.get().getId());
recordInfo.setTaskName(taskOptional.get().getName());
Optional<Department> departmentOptional = departmentRepository.findById(taskOptional.get().getDepartmentId());
if (!departmentOptional.isPresent()) {
return new Result(ResponseCode.INVALID_DEPARTMENT_ID, "未找到部门实体:task_id = " + taskOptional.get().getId() + ", department_id = " + taskOptional.get().getDepartmentId());
}
recordInfo.setDepartmentId(departmentOptional.get().getId());
recordInfo.setDepartment(departmentOptional.get().getDeptName());
List<RecordDetail> recordDetailList = recordDetailRepository.findByRecordId(record.getId());
if (recordDetailList.isEmpty()) {
return new Result(ResponseCode.INVALID_RECORD_ID, "未找到录制详情实体:record_id = " + record.getId());
}
for (RecordDetail recordDetail : recordDetailList) {
RecordDetailInfo recordDetailInfo = new RecordDetailInfo();
Optional<Api> apiOptional = apiRepository.findById(recordDetail.getApiId());
if (!apiOptional.isPresent()) {
return new Result(ResponseCode.INVALID_API_ID, "未找到接口实体:api_id = " + recordDetail.getApiId() + ", record_id = " + recordDetail.getRecordId());
}
recordDetailInfo.setApiId(apiOptional.get().getId());
recordDetailInfo.setApiName(apiOptional.get().getName());
recordDetailInfo.setDomainId(apiOptional.get().getDomainId());
recordDetailInfo.setApiMethod(EnumUtil.getByField(HttpMethodConstants.class, "getValue", String.valueOf(apiOptional.get().getMethod())).getLabel());
recordDetailInfo.setRecordableCount(apiOptional.get().getRecordableCount());
int expectCount = recordDetail.getExpectCount();
if (expectCount == 0) {
expectCount = 1;
}
recordDetailInfo.setExpectCount(expectCount);
recordDetailInfo.setActualCount(expectCount);
Integer successRate = (recordDetail.getActualCount() * 100) / expectCount;
recordDetailInfo.setSuccessRate(String.valueOf(successRate) + "%");
Optional<Domain> domainOptional = domainRepository.findById(apiOptional.get().getDomainId());
if (!domainOptional.isPresent()) {
return new Result(ResponseCode.INVALID_API_ID, "未找到域名实体:domain_id = " + apiOptional.get().getDomainId() + ", api_id = " + apiOptional.get().getId());
}
recordDetailInfo.setDomainName(domainOptional.get().getName());
recordDetailInfoList.add(recordDetailInfo);
}
return new Result(ResponseCode.SUCCESS, recordInfo);
}
//admin下发录制任务 agent初始化录制任务
@Override
public void startRecord(Integer taskExecutionId, Integer recordId) throws Exception {
redisTemplateTool.setRecordProgress(recordId, "1");
redisTemplateTool.setLogByRecordId_START(recordId, "Agent收到任务消息,即将开始录制录制:record_id=" + recordId);
try {
taskStatusUtil.updateTaskStatus(taskExecutionId, TaskStatus.RECORD);
} catch (CustomException e) {
//注册等处理流程发生错误
log.error("更新状态失败" + e);
taskStatusUtil.updateTaskStatus(taskExecutionId, TaskStatus.RECORD_FAIL);
}
//获取执行人 后面修改
//LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Integer taskId = taskExecutionRepository.findById(taskExecutionId).get().getTaskId();
Optional<TaskExecution> taskExecutionOptional = taskExecutionRepository.findById(taskExecutionId);
if (!taskExecutionOptional.isPresent()) {
throw new BaseException("录制失败,找不到执行记录:taskExecutionId=" + taskExecutionId);
}
//创建录制对象成功,创建录制详情
Optional<List<TaskApiRelation>> taskApiRelationList = taskApiRelationRepository.findAllByTaskId(taskId);
if (!taskApiRelationList.isPresent()) {
throw new BaseException("录制失败,该任务找不到接口关联关系:taskId=" + taskId);
}
List<Integer> apiList = Lists.newArrayList();
for (TaskApiRelation taskApiRelation : taskApiRelationList.get()) {
Integer apiId = taskApiRelation.getApiId();
apiList.add(apiId);
}
for (TaskApiRelation taskApiRelation : taskApiRelationList.get()) {
Integer apiId = taskApiRelation.getApiId();
log.info("apiId=" + apiId);
Integer recordCount = taskApiRelation.getRecordCount();
createRecordDetail(recordId, apiId, recordCount);
}
//开始执行录制逻辑
record(recordId);
}
//生成任务录制详情信息信息
private void createRecordDetail(Integer recordId, Integer apiId, Integer recordCount) {
RecordDetail recordDetail = new RecordDetail();
recordDetail.setRecordId(recordId);
recordDetail.setApiId(apiId);
recordDetail.setExpectCount(recordCount);
recordDetailRepository.save(recordDetail);
}
//流量采集业务逻辑
public void record(Integer recordId) throws Exception {
redisTemplateTool.setRecordProgress(recordId, "5");
log.info("正在开始录制,录制ID:record_id=" + recordId);
redisTemplateTool.setLogByRecordId_INFO(recordId, "正在开始录制,录制ID:record_id=" + recordId);
Optional<Record> recordOptional = recordRepository.findById(recordId);
if (!recordOptional.isPresent()) {
log.error("无效的录制ID:record_id = " + recordId);
throw new BaseException("无效的录制ID:record_id = ");
}
List<RecordDetail> recordDetailList = recordDetailRepository.findByRecordId(recordId);
if (Objects.isNull(recordDetailList) || recordDetailList.isEmpty()) {
log.error("无找到录制详情实体:record_id = " + recordId);
throw new BaseException("无找到录制详情实体:record_id = " + recordId);
}
Integer totalExpectCount = 0;
Integer totalActualCount = 0;
for (RecordDetail recordDetail : recordDetailList) {
Optional<Api> apiOptional = apiRepository.findById(recordDetail.getApiId());
if (!apiOptional.isPresent()) {
//把对应的回放ID的日志写入Redis, key='logByrecordId='+recordId
log.error("未找到该接口api_id = " + recordDetail.getApiId());
throw new BaseException("未找到该接口api_id = " + recordDetail.getApiId());
}
Api api = apiOptional.get();
Optional<Domain> domainOptional = domainRepository.findById(api.getDomainId());
if (!domainOptional.isPresent()) {
log.error("未找到该域名domain_id = " + api.getDomainId());
throw new BaseException("未找到该域名domain_id = " + api.getDomainId());
}
String domain = domainOptional.get().getName();
RequestQuery requestQuery = RequestQuery.builder()
.domain(domain)
.api(api.getName())
.method(api.getMethod())
.count(recordDetail.getExpectCount()).build();
totalExpectCount += recordDetail.getExpectCount();
log.info("开始录制流量 " + domainOptional.get().getName() + api.getName());
redisTemplateTool.setLogByRecordId_INFO(recordId, "开始录制流量 " + domainOptional.get().getName() + api.getName());
//查询并存储流量
List<String> flowByEsClient = getFlowByEsClientAndSaveFLow(requestQuery, recordId, api.getDomainId());
log.info(api.getName() + "录制完成: 期望录制总数=" + recordDetail.getExpectCount() + "," + "实际录制总数=" + flowByEsClient.size());
redisTemplateTool.setLogByRecordId_INFO(recordId, api.getName() + "录制完成: 期望录制总数=" + recordDetail.getExpectCount() + "," + "实际录制总数=" + flowByEsClient.size());
totalActualCount += flowByEsClient.size();
recordDetail.setActualCount(flowByEsClient.size());
recordDetailRepository.save(recordDetail);
}
redisTemplateTool.setRecordProgress(recordId, "99");
double successRate = 0;//录制成功率
if (totalExpectCount <= 0) {
successRate = 0;
} else {
successRate = (totalActualCount * 100.0) / totalExpectCount;
}
recordOptional.get().setSuccessRate(successRate);
recordOptional.get().setEndTime(LocalDateTime.now());
recordRepository.save(recordOptional.get());
log.info("录制任务完成 任务ID={} 成功率={}", recordId, successRate);
redisTemplateTool.setLogByRecordId_END(recordId, "录制任务执行完成,录制完成率:" + successRate + "%");
taskStatusUtil.updateTaskStatus(recordOptional.get().getTaskExecutionId(), TaskStatus.RECORD_SUCCESS);
}
/**
* 获取ES流量
*
* @param requestQuery
* @return ES 数据源配置,域名需要绑定ES数据源
*/
public List<String> getFlowByEsClientAndSaveFLow(RequestQuery requestQuery, Integer recordId, Integer domainId) {
String domainKeyword = "";
String url = "";
String method = EnumUtil.getByField(HttpMethodConstants.class, "getValue", String.valueOf(requestQuery.getMethod())).getLabel();
SearchResponse searchResponse = null;
List<String> requestIdLists = new ArrayList<String>();
long totalElements = 0;
int scanElements = requestQuery.getCount();
//根据域名获取es mapping设置
Optional<EsConditionSetting> esConditionSetting = esConditionSettingRepository.findByDomainId(domainId);
if (esConditionSetting.isPresent()) {
domainKeyword = esConditionSetting.get().getDomain();
url = esConditionSetting.get().getApi();
} else {
log.info("域名" + requestQuery.getDomain() + "无es mapping信息配置");
return null;
}
QueryBuilder shouldQuery = QueryBuilders.boolQuery()
.should(QueryBuilders.termQuery(domainKeyword + ".keyword", requestQuery.getDomain()));
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.wildcardQuery(url + ".keyword", method + " " + requestQuery.getApi() + "*"))
.must(shouldQuery);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
log.info(queryBuilder.toString());
sourceBuilder.query(queryBuilder);
sourceBuilder.sort("@timestamp", SortOrder.ASC);
sourceBuilder.size(500);
Scroll scroll = new Scroll(TimeValue.timeValueMinutes(10L));
SearchRequest searchRequest = new SearchRequest();
searchRequest.source(sourceBuilder).scroll(scroll).indices();
//根据域名获取对应es配置信息
RestHighLevelClient restHighLevelClient = getRestHighLevelClient(domainId);
try {
searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
redisTemplateTool.setLogByRecordId_WARN(recordId, "日志ES查询失败");
log.error("日志查询失败" + e);
}
String scrollId = searchResponse.getScrollId();
log.info("scroll_id=" + scrollId);
totalElements = searchResponse.getHits().totalHits;
int total = (int) totalElements;
log.info("查询到总流量" + totalElements + "条");
int length = searchResponse.getHits().getHits().length;
log.info("查询到总流量 length" + length + "");
int page = total / 10000;//计算总页数,每次搜索数量为分片数*设置的size大小
page = page + 1;
//控制单个接口录制条数
for (int i = 0; i < page; i++) {
if (i != 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(searchResponse.getScrollId());
scroll = new Scroll(TimeValue.timeValueMinutes(10L));
scrollRequest.scroll(scroll);
try {
searchResponse = restHighLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
log.error("日志查询失败");
}
}
//控制录制总流量数
scanElements += length;
if (scanElements >= 800000) {
redisTemplateTool.setLogByRecordId_WARN(recordId, "扫描的流量数已达到100W条,将结束录制");
break;
}
}
// 业务逻辑
for (SearchHit at : searchResponse.getHits().getHits()) {
String requestId = at.getId();
log.info(requestId);
if (!"".equals(requestId)) {
requestIdLists.add(requestId);
//遍历流量并且存储
saveFlowInDb(recordId, at, esConditionSetting.get());
if (requestIdLists.size() == requestQuery.getCount()) {
break;
}
}
}
//清除scroll
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(scrollId);//也可以选择setScrollIds()将多个scrollId一起使用
ClearScrollResponse clearScrollResponse = null;
try {
clearScrollResponse = restHighLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
boolean succeeded = clearScrollResponse.isSucceeded();
log.info("ES succeeded = " + succeeded);
return requestIdLists;
}
/**
* 根据domain获取restHighLevelClient
*
* @param domainId
* @return restHighLevelClient
*/
private RestHighLevelClient getRestHighLevelClient(Integer domainId) {
Optional<Domain> domainOptional = domainRepository.findById(domainId);
if (domainOptional.isPresent()) {
Optional<EsConditionSetting> esConditionSetting = esConditionSettingRepository.findByDomainId(domainOptional.get().getId());
if (esConditionSetting.isPresent()) {
Optional<EsSource> esSource = esSourceRepository.findById(domainOptional.get().getEsSourceId());
if (esSource.isPresent()) {
String esIp = esSource.get().getEsIp();
Integer esPort = esSource.get().getEsPort();
String beanName = esSource.get().getEsBeanName();
return DynamicEsUtils.getRestHighLevelClient(beanName, esIp, esPort);
}
}
}
return null;
}
/**
* 根据ES内流量数据存储至DB
*
* @param recordId,hit,esConditionSetting
*/
private void saveFlowInDb(int recordId, SearchHit hit, EsConditionSetting esConditionSetting) {
RecordResult recordResult = new RecordResult();
Map esFlowMap = hit.getSourceAsMap();
String apiKey = esConditionSetting.getApi();
//当URL中GET 请求参数是单独的字段存储的时候,采用接口key?参数key
if (apiKey.contains("?")) {
String[] urlPathKeys = apiKey.split("\\?");
apiKey = urlPathKeys[0];
}
String domianKey = esConditionSetting.getDomain();
String methodKey = esConditionSetting.getMethod();
String requestBodyKey = esConditionSetting.getRequestBody();
String headerKey = esConditionSetting.getHeader();
// 在获取不到key时避免抛出 NullPointerException 空指针异常
String apiName = RegexUtils.getMsgByRegex(esFlowMap.get(apiKey) + "", esConditionSetting.getApiRegex());
String method = RegexUtils.getMsgByRegex(esFlowMap.get(methodKey) + "", esConditionSetting.getMethodRegex());
Api api = getApiInfo(recordId,method,apiName);
if (api !=null) {
int apiId = api.getId();
List<Api> apiList = apiRepository.findByNameAndMethod(apiName, HttpMethodConstants.valueOf(method).getValue());
if (apiList.size() != 0) {
apiId = apiList.get(0).getId();
String body = RegexUtils.getMsgByRegex(esFlowMap.get(requestBodyKey) + "", esConditionSetting.getRequestBodyRegex());
String header = RegexUtils.getMsgByRegex(esFlowMap.get(headerKey) + "", esConditionSetting.getHeaderRegex());
String requestId = hit.getId();
recordResult.setApiId(apiId);
recordResult.setBody(body);
recordResult.setHeader(header);
recordResult.setRequestId(requestId);
recordResult.setRecordId(recordId);
recordResultRepository.save(recordResult);
} else {
log.error("未查询到api数据 API={}", apiName);
}
}
}
private Api getApiInfo(Integer recordId, String method,String apiName) {
List<Api> apiList = apiRepository.findByNameAndMethod(apiName, HttpMethodConstants.valueOf(method).getValue());
if(apiList == null) {
return null;
}
if(apiList.size()<1) {
return null;
}
List<RecordDetail> recordDetailList = recordDetailRepository.findByRecordId(recordId);
for (Api api : apiList) {
if (recordDetailList.isEmpty()) {
continue;
}
for (RecordDetail recordDetail : recordDetailList) {
if (recordDetail.getApiId().intValue() == api.getId().intValue()) {
return api;
}
}
}
return apiList.get(0);
}
}
| 45.914226 | 179 | 0.661275 |
ca224d77d5e1fe26594975dd192d21cca9651021 | 33,382 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 dev.nokee.ide.xcode.internal.tasks;
import com.dd.plist.*;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import dev.nokee.ide.xcode.*;
import dev.nokee.ide.xcode.internal.DefaultXcodeIdeBuildSettings;
import dev.nokee.ide.xcode.internal.XcodeIdePropertyAdapter;
import dev.nokee.ide.xcode.internal.services.XcodeIdeGidGeneratorService;
import dev.nokee.ide.xcode.internal.xcodeproj.*;
import lombok.Value;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.api.internal.tasks.TaskDependencyContainer;
import org.gradle.api.internal.tasks.TaskDependencyResolveContext;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public abstract class GenerateXcodeIdeProjectTask extends DefaultTask {
public static final XcodeIdeProductType INDEXER_PRODUCT_TYPE = XcodeIdeProductType.of("dev.nokee.product-type.indexer");
private static final String PRODUCTS_GROUP_NAME = "Products";
private Map<String, PBXFileReference> pathToFileReferenceMapping = new HashMap<>();
private final XcodeIdeProject xcodeProject;
@Internal
public abstract Property<FileSystemLocation> getProjectLocation();
@Internal
public abstract Property<XcodeIdeGidGeneratorService> getGidGenerator();
@Internal
public abstract Property<String> getGradleCommand();
@Internal
public abstract Property<String> getBridgeTaskPath();
@Internal
public abstract ListProperty<String> getAdditionalGradleArguments();
@Inject
public GenerateXcodeIdeProjectTask(XcodeIdeProject xcodeProject) {
this.xcodeProject = xcodeProject;
// Workaround for https://github.com/gradle/gradle/issues/13405, this really sucks...
this.dependsOn(new TaskDependencyContainer() {
@Override
public void visitDependencies(TaskDependencyResolveContext context) {
xcodeProject.getTargets().stream().flatMap(it -> it.getBuildConfigurations().stream()).flatMap(it -> ((DefaultXcodeIdeBuildSettings)it.getBuildSettings()).getProviders().stream()).forEach(it -> {
if (it instanceof TaskDependencyContainer) {
((TaskDependencyContainer) it).visitDependencies(context);
}
});
}
});
}
@Inject
protected abstract ObjectFactory getObjects();
// TODO: Ensure that half generated projects are deleted (avoid leaking files)
@TaskAction
private void generate() throws IOException {
File projectDirectory = getProjectLocation().get().getAsFile();
FileUtils.deleteDirectory(projectDirectory);
projectDirectory.mkdirs();
PBXProject project = new PBXProject(getProject().getPath());
// Convert all Gradle Xcode IDE targets to PBXTarget
project.getTargets().addAll(xcodeProject.getTargets().stream().map(this::toTarget).collect(Collectors.toList()));
// Configure sources
xcodeProject.getSources().forEach(file -> {
project.getMainGroup().getChildren().add(toAbsoluteFileReference(file));
});
xcodeProject.getGroups().forEach(group -> {
List<PBXReference> fileReferences = project.getMainGroup().getOrCreateChildGroupByName(group.getName()).getChildren();
group.getSources().forEach(file -> fileReferences.add(toAbsoluteFileReference(file)));
});
// Add all target product reference to Products source group
project.getMainGroup().getOrCreateChildGroupByName(PRODUCTS_GROUP_NAME).getChildren().addAll(project.getTargets().stream().map(PBXTarget::getProductReference).collect(Collectors.toList()));
// Create all build configuration at the project level, Xcode expect that.
xcodeProject.getTargets().stream().flatMap(it -> it.getBuildConfigurations().stream()).map(XcodeIdeBuildConfiguration::getName).forEach(name -> {
project.getBuildConfigurationList().getBuildConfigurationsByName().getUnchecked(name);
});
// Do the schemes...
File schemesDirectory = new File(projectDirectory, "xcshareddata/xcschemes");
schemesDirectory.mkdirs();
XmlMapper xmlMapper = new XmlMapper();
SimpleModule simpleModule = new SimpleModule("BooleanAsYesNoString", new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(Boolean.class,new XcodeIdeBooleanSerializer());
simpleModule.addSerializer(boolean.class,new XcodeIdeBooleanSerializer());
xmlMapper.registerModule(simpleModule);
xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
for (PBXTarget xcodeTarget : project.getTargets().stream().filter(it -> !isTestingTarget(it)).collect(Collectors.toList())) {
ImmutableList.Builder<Scheme.BuildAction.BuildActionEntry> buildActionBuilder = ImmutableList.builder();
buildActionBuilder.add(new Scheme.BuildAction.BuildActionEntry(false, true, false, false, false, newBuildableReference(xcodeTarget)));
ImmutableList.Builder<Scheme.TestAction.TestableReference> testActionBuilder = ImmutableList.builder();
project.getTargets().stream().filter(this::isTestingTarget).forEach(it -> {
buildActionBuilder.add(new Scheme.BuildAction.BuildActionEntry(true, false, false, false, false, newBuildableReference(it)));
testActionBuilder.add(new Scheme.TestAction.TestableReference(newBuildableReference(it)));
});
xmlMapper.writeValue(new File(schemesDirectory, xcodeTarget.getName() + ".xcscheme"), new Scheme(
new Scheme.BuildAction(buildActionBuilder.build()),
new Scheme.TestAction(testActionBuilder.build()),
new Scheme.LaunchAction(xcodeTarget.getProductType().equals(XcodeIdeProductTypes.DYNAMIC_LIBRARY) ? null : new Scheme.LaunchAction.BuildableProductRunnable(newBuildableReference(xcodeTarget)))
));
}
// Lastly, create the indexing target
project.getTargets().addAll(xcodeProject.getTargets().stream().filter(this::isIndexableTarget).map(this::toIndexTarget).collect(Collectors.toList()));
XcodeprojSerializer serializer = new XcodeprojSerializer(getGidGenerator().get(), project);
NSDictionary rootObject = serializer.toPlist();
PropertyListParser.saveAsASCII(rootObject, new File(projectDirectory, "project.pbxproj"));
// Write the WorkspaceSettings file
File workspaceSettingsFile = new File(projectDirectory, "project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings");
workspaceSettingsFile.getParentFile().mkdirs();
FileUtils.writeStringToFile(workspaceSettingsFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
"<plist version=\"1.0\">\n" +
"<dict>\n" +
"\t<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>\n" +
"\t<false/>\n" +
"</dict>\n" +
"</plist>", Charset.defaultCharset());
}
private boolean isTestingTarget(PBXTarget xcodeTarget) {
return isTestingProductType(xcodeTarget.getProductType());
}
private boolean isTestingProductType(XcodeIdeProductType productType) {
return productType.equals(XcodeIdeProductTypes.UNIT_TEST) || productType.equals(XcodeIdeProductTypes.UI_TEST);
}
private Scheme.BuildableReference newBuildableReference(PBXTarget xcodeTarget) {
return new Scheme.BuildableReference(xcodeTarget.getGlobalID(), xcodeTarget.getProductName(), xcodeTarget.getName(), "container:" + getProjectLocation().get().getAsFile().getName());
}
private boolean isIndexableTarget(XcodeIdeTarget xcodeTarget) {
// TODO: Use a white list of target instead of all known values
return !xcodeTarget.getProductType().get().equals(XcodeIdeProductTypes.UNIT_TEST) && !xcodeTarget.getProductType().get().equals(XcodeIdeProductTypes.UI_TEST) && Arrays.stream(XcodeIdeProductTypes.getKnownValues()).anyMatch(xcodeTarget.getProductType().get()::equals);
}
private PBXTarget toTarget(XcodeIdeTarget xcodeTarget) {
if (isTestingProductType(xcodeTarget.getProductType().get())) {
return toGradleXCTestTarget(xcodeTarget);
}
return toGradleTarget(xcodeTarget);
}
/**
* = Generating XCTest Target (Unit and UI testing)
* It is required to use native targets to integrate XCTest components with Xcode to allow a _vanilla_ test experience.
* The _vanilla_ test experience is defined by the auto-discovering tests.
* The tests can then be interacted with via the Test navigator tab and inline with the code via the side dot.
*
* == Xcode love triangle
* The native targets pose certain limitation which creates a love triangle with the following edges:
* 1- The _vanilla_ test experience
* 2- The code indexing
* 3- The delegation to Gradle
*
* === 1- The _vanilla_ test experience
* Xcode provide a nice testing experience only in the presence of a native target with the test product types (e.g. ui-testing/unit-test).
* Using a com.sun.tools.javac.resources.legacy target to allow org.gradle.api.invocation.Gradle delegation won't work here.
* The test target also needs to be part of a scheme.
* Typically, the tests are part of the same scheme as the tested component.
* For example, if we are testing an iOS application, the tests would be part of the iOS application scheme.
*
* === 2- The code indexing
* Xcode uses SourceKit to index the code on the fly as well as `-index-store-path` flag for indexing during compilation.
* On the fly indexing only works for native targets and requires a compile source build phase to be configured.
* SourceKit will build the compile flags based on the target's build configuration.
* When delegating to Gradle via legacy targets, we can add a matching native target for indexing.
* This works as Xcode will ignore the legacy target and will use the native target for indexing.
* As we reference the legacy target for building and launching, the indexing target is only ever used by SourceKit.
* It never invoke the compile source build phased configured on the native target for indexing.
* For testing target, the same strategy won't work as Xcode will use the target providing _vanilla_ test experience.
* It will ignore the matching indexing target is present.
* It is not a problem in itself, but it's becomes an issue when delegating to Gradle.
* We have to use the native target for building in the scheme.
* Xcode will end up invoking the compile source build phase.
*
* === 3- The delegation to Gradle
* There are two different ways to delegate to Gradle.
* The first one is via legacy targets.
* The second one is to use a script build phase on a native target.
* Both works more or less the same.
* A "script" is written that just delegate to Gradle via a bridge task.
*
* == Additional problems
* === Keeping SourceKit active
* Some integration would use two different build configurations: the original one and a prefixed one, i.e. __NokeeTestRunner_.
* The original one would be used for indexing and never referenced while the other one would disable the compile source phase by setting
* `OTHER_LDFLAGS`, `OTHER_CFLAGS`, and `OTHER_SWIFT_FLAGS` build settings with `--version` (less output) or `-help` (more output).
* When using the target inside the tested target scheme, the UI test were failing due to a permission issue.
* (NOTE: I looked at everything and couldn't figure out why it was happening)
* It seems the other integration are using separate schemes for the test target which may work around the issue.
* Regardless, it's also troublesome during Gradle delegation as the BUILT_PRODUCT_DIR value needs to be adjusted.
* The received value points at the original build configuration and the product needs to be copied to the prefixed build configuration.
* It is also worth nothing the prefixed build configuration *AND* the build settings configuration are needed.
* Only using the build settings configuration trick will disable SourceKit as it seems to interpret the `--version` or `-help` flags.
* SourceKit won't produce anything useful and jumping to definition for #import/#include won't work.
*
* === Xcode build process
* Xcode implies additional steps during compile source build phase which can clash with Gradle.
* For example, it will process the Info.plist files and copy it to the final location where Gradle copies the product that it built.
* Care must be taken to ensure the file is processed by Xcode before Gradle copies it's product.
* Xcode will also sign, copy Swift stdlib, generate debug symbols, copy frameworks into the bundle, etc.
* Some of those steps can be disabled via more build settings.
*
* == Solution
* What's the problem then?
* We need:
* - a native target (for _vanilla_ test experience),
* - configured with both a compile source (for indexing) and script (for Gradle delegation) build phase
* - where the compile source build phase is somehow ignored to avoid 1) duplicated work and 2) clashing with Gradle's work
* - while allowing tests to execute properly.
*
* The decision for the Nokee plugins is to:
* - use a native target (for _vanilla_ test experience),
* - configure a script build phase (for Gradle delegation),
* - configure a compile source build phase (for indexing)
* - configure undocumented compiler/linker build settings to disable the indexing build phase while keeping SourceKit active.
* - add test target to the tested target scheme
* - disable as much as possible the *normal* Xcode build process
* The undocumented build settings are `CC`, `LD`, `CPLUSPLUS`, and `LDPLUSPLUS`.
* See http://lists.llvm.org/pipermail/cfe-dev/2014-March/035816.html
* The build settings for the Swift compiler is an open question.
* (NOTE: I suggest going after DevToolsCore.framework and dump the strings to identify all possible build settings.)
*/
private PBXTarget toGradleXCTestTarget(XcodeIdeTarget xcodeTarget) {
PBXNativeTarget target = new PBXNativeTarget(xcodeTarget.getName(), xcodeTarget.getProductType().get());
// Configure build phases
target.getBuildPhases().add(newGradleBuildPhase());
// Tulsi integration uses a script phase here to generate the dependency files, we use a Gradle task action instead.
// See XcodeIdeObjectiveCIosApplicationPlugin
target.getBuildPhases().add(newSourcesBuildPhase(xcodeTarget.getSources()));
target.setProductName(xcodeTarget.getProductName().get());
target.setGlobalID(getGidGenerator().get().generateGid("PBXNativeTarget", xcodeTarget.getName().hashCode()));
// Configures the product reference.
// We only configure the .xctest, the -Runner.app and co. are an implementation detail.
PBXFileReference productReference = new PBXFileReference(xcodeTarget.getProductReference().get(), xcodeTarget.getProductReference().get(), PBXReference.SourceTree.BUILT_PRODUCTS_DIR);
target.setProductReference(productReference);
xcodeTarget.getBuildConfigurations().forEach(buildConfiguration -> {
// TODO: Set default PRODUCT_NAME if not set
NSDictionary settings = target.getBuildConfigurationList().getBuildConfigurationsByName().getUnchecked(buildConfiguration.getName()).getBuildSettings();
settings.put("__DO_NOT_CHANGE_ANY_VALUE_HERE__", "Instead, use the build.gradle[.kts] files.");
for (Map.Entry<String, Object> entry : buildConfiguration.getBuildSettings().getElements().get().entrySet()) {
settings.put(entry.getKey(), toValue(entry.getValue()));
}
// Prevent Xcode from attempting to create a fat binary with lipo from artifacts that were
// never generated by the linker nop's.
settings.put("ONLY_ACTIVE_ARCH", "YES");
// Fixes an Xcode "Upgrade to recommended settings" warning. Technically the warning only
// requires this to be added to the Debug build configuration but as code is never compiled
// anyway it doesn't hurt anything to set it on all configs.
settings.put("ENABLE_TESTABILITY", "YES");
// Assume sources are ARC by default and uses per-file flags to override the default.
settings.put("CLANG_ENABLE_OBJC_ARC", "YES");
// FIXME: We rely on Xcode signing capability.
// When Nokee plugin can replace signing from Xcode, we should prevent Xcode from signing.
// We should also move the delegate build phase after the source compile build phase.
// // Disable Xcode's signing as the applications are already signed by Nokee.
// settings.put("CODE_SIGNING_REQUIRED", "NO");
// settings.put("CODE_SIGN_IDENTITY", "");
// TODO: This is most likely not required
// Explicitly setting the FRAMEWORK_SEARCH_PATHS will allow Xcode to resolve references to the
// XCTest framework when performing Live issues analysis.
// settings.put("FRAMEWORK_SEARCH_PATHS", "$(PLATFORM_DIR)/Developer/Library/Frameworks");
// Prevent Xcode from replacing the Swift StdLib dylibs already packaged by Nokee.
settings.put("DONT_RUN_SWIFT_STDLIB_TOOL", "YES");
// Disable Xcode's attempts at generating dSYM bundles as it conflicts with the operation of the
// special test runner build configurations (which have associated sources but don't actually
// compile anything).
settings.put("DEBUG_INFORMATION_FORMAT", "dwarf");
// Disable compilers/linkers by using a command that will accept all flags and return a successful exit code.
settings.put("CC", "true");
settings.put("LD", "true");
settings.put("CPLUSPLUS", "true");
settings.put("LDPLUSPLUS", "true");
});
return target;
}
private PBXTarget toIndexTarget(XcodeIdeTarget xcodeTarget) {
PBXFileReference productReference = new PBXFileReference(xcodeTarget.getProductReference().get(), xcodeTarget.getProductReference().get(), PBXReference.SourceTree.BUILT_PRODUCTS_DIR);
PBXNativeTarget target = new PBXNativeTarget("__indexer_" + xcodeTarget.getName(), INDEXER_PRODUCT_TYPE);
target.setProductName(xcodeTarget.getProductName().get());
target.getBuildPhases().add(newSourcesBuildPhase(xcodeTarget.getSources()));
target.setGlobalID(getGidGenerator().get().generateGid("PBXNativeTarget", xcodeTarget.getName().hashCode()));
target.setProductReference(productReference);
xcodeTarget.getBuildConfigurations().forEach(buildConfiguration -> {
NSDictionary settings = target.getBuildConfigurationList().getBuildConfigurationsByName().getUnchecked(buildConfiguration.getName()).getBuildSettings();
settings.put("__DO_NOT_CHANGE_ANY_VALUE_HERE__", "Instead, use the build.gradle[.kts] files.");
for (Map.Entry<String, Object> entry : buildConfiguration.getBuildSettings().getElements().get().entrySet()) {
settings.put(entry.getKey(), toValue(entry.getValue()));
}
// TODO: Set default PRODUCT_NAME if not set
});
return target;
}
/**
* Create a new sources build phase.
* Sources build phase should only include compilation units.
* When including other type of files, there will be issues with the indexing.
*
* For indexer target, the behaviour seems to be inconsistent indexing of the files.
* For example, some files will allows following #import/#include while others won't.
* There is not consistency between each compilation units.
* (NOTE: I noted the first file after clearing the derived data would properly follow the #import/#include while the other files wouldn't.)
* ( Sometime, two of the three files would behave properly.)
*
* For XCTest targets, including the Info.plist file would cause the build to fail because of duplicated entries:
* one entry in the sources build phase and one entry implied by the `INFOPLIST_FILE` build setting.
*
* @param sourceFiles All source files for the target.
* @return a new sources build phase, never null.
*/
private PBXSourcesBuildPhase newSourcesBuildPhase(FileCollection sourceFiles) {
PBXSourcesBuildPhase result = new PBXSourcesBuildPhase();
for (File file : sourceFiles.filter(GenerateXcodeIdeProjectTask::keepingOnlyCompilationUnits)) {
result.getFiles().add(new PBXBuildFile(toAbsoluteFileReference(file)));
}
return result;
}
private static Set<String> COMPILATION_UNITS_EXTENSIONS = ImmutableSet.<String>builder()
.add("m")
.add("cp", "cpp", "c++", "cc", "cxx")
.add("c")
.add("mm")
.add("swift")
.build();
private static boolean keepingOnlyCompilationUnits(File sourceFile) {
return COMPILATION_UNITS_EXTENSIONS.contains(FilenameUtils.getExtension(sourceFile.getName()));
}
private PBXTarget toGradleTarget(XcodeIdeTarget xcodeTarget) {
PBXFileReference productReference = toBuildProductFileReference(xcodeTarget.getProductReference().get());
PBXLegacyTarget target = new PBXLegacyTarget(xcodeTarget.getName(), xcodeTarget.getProductType().get());
target.setProductName(xcodeTarget.getProductName().get());
target.setBuildToolPath(getGradleCommand().get());
target.setBuildArgumentsString(getGradleBuildArgumentsString());
target.setGlobalID(getGidGenerator().get().generateGid("PBXLegacyTarget", xcodeTarget.getName().hashCode()));
target.setProductReference(productReference);
// For now, we want unidirectional configuration of the build logic, that is Gradle -> Xcode IDE.
// It's not impossible to allow changes to build settings inside Xcode IDE to tickle down into Gradle for a directional configuration.
// However, there are a lot of things to consider and it's not a priority at the moment.
// If you are a user of the Nokee plugins reading this, feel free to open an feature request with your use cases.
target.setPassBuildSettingsInEnvironment(false);
xcodeTarget.getBuildConfigurations().forEach(buildConfiguration -> {
NSDictionary settings = target.getBuildConfigurationList().getBuildConfigurationsByName().getUnchecked(buildConfiguration.getName()).getBuildSettings();
settings.put("__DO_NOT_CHANGE_ANY_VALUE_HERE__", "Instead, use the build.gradle[.kts] files.");
for (Map.Entry<String, Object> entry : buildConfiguration.getBuildSettings().getElements().get().entrySet()) {
settings.put(entry.getKey(), toValue(entry.getValue()));
}
// We use the product reference here because Xcode uses the product type on PBXNativeTarget to infer an extension.
// It is bolted onto the product name to form the path to the file under Products group.
// With PBXLegacyTarget Xcode ignores the product reference on the target for the path.
// Instead, it uses the PRODUCT_NAME settings to infer the path inside the BUILT_PRODUCT_DIR.
settings.put("PRODUCT_NAME", xcodeTarget.getProductReference().get());
});
return target;
}
private PBXShellScriptBuildPhase newGradleBuildPhase() {
PBXShellScriptBuildPhase result = new PBXShellScriptBuildPhase();
// Gradle startup script is sh compatible.
result.setShellPath("/bin/sh");
// We nullify the stdin as Xcode console is non-interactive.
result.setShellScript("exec \"" + getGradleCommand().get() + "\" " + getGradleBuildArgumentsString() + " < /dev/null");
// When using a native target, Xcode process the Info.plist files to the same destination than Nokee.
// To ensure we always use Nokee's artifact, we use the Info.plist as an input which force Xcode process the Info.plist before us.
result.getInputPaths().add("$(TARGET_BUILD_DIR)/$(INFOPLIST_PATH)");
return result;
}
private String getGradleBuildArgumentsString() {
return String.join(" ", Iterables.concat(XcodeIdePropertyAdapter.getAdapterCommandLine(), getAdditionalGradleArguments().get())) + " " + XcodeIdePropertyAdapter.adapt("GRADLE_IDE_PROJECT_NAME", xcodeProject.getName()) + " " + getBridgeTaskPath().get();
}
private static class XcodeIdeBooleanSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
if (value) {
jgen.writeString("YES");
} else {
jgen.writeString("NO");
}
}
}
private static NSObject toValue(Object o) {
if (o instanceof Integer) {
return new NSNumber((Integer) o);
} else if (o instanceof Long) {
return new NSNumber((Long) o);
} else if (o instanceof Double) {
return new NSNumber((Double) o);
} else if (o instanceof Collection) {
NSArray result = new NSArray(((Collection<?>) o).size());
int key = 0;
for (Object obj : (Collection<?>)o) {
result.setValue(key, toValue(obj));
key++;
}
return result;
}
return new NSString(o.toString());
}
private PBXFileReference toAbsoluteFileReference(File file) {
return computeFileReferenceIfAbsent(file.getAbsolutePath(),
path -> new PBXFileReference(file.getName(), file.getAbsolutePath(), PBXReference.SourceTree.ABSOLUTE));
}
private PBXFileReference toBuildProductFileReference(String name) {
return computeFileReferenceIfAbsent(name,
key -> new PBXFileReference(name, name, PBXReference.SourceTree.BUILT_PRODUCTS_DIR));
}
// FIXME: Multiple group using the same code is only included in one place...
private PBXFileReference computeFileReferenceIfAbsent(String key, Function<String, PBXFileReference> provider) {
return pathToFileReferenceMapping.computeIfAbsent(key, provider);
}
/**
* <Scheme
* LastUpgradeVersion = "0830"
* version = "1.3">
* ...
* </Scheme>
*/
@Value
private static class Scheme {
@JacksonXmlProperty(localName = "BuildAction")
BuildAction buildAction;
@JacksonXmlProperty(localName = "TestAction")
TestAction testAction;
@JacksonXmlProperty(localName = "LaunchAction")
LaunchAction launchAction;
@JacksonXmlProperty(localName = "ProfileAction")
ProfileAction profileAction = new ProfileAction();
@JacksonXmlProperty(localName = "AnalyzeAction")
AnalyzeAction analyzeAction = new AnalyzeAction();
@JacksonXmlProperty(localName = "ArchiveAction")
ArchiveAction archiveAction = new ArchiveAction();
@JacksonXmlProperty( localName = "LastUpgradeVersion", isAttribute = true)
public String getLastUpgradeVersion() {
return "0830";
}
@JacksonXmlProperty(isAttribute = true)
public String getVersion() {
return "1.3";
}
/**
* <BuildAction
* parallelizeBuildables = "YES"
* buildImplicitDependencies = "YES">
* <BuildActionEntries>
* </BuildActionEntries>
* </BuildAction>
*/
@Value
public static class BuildAction {
@JacksonXmlElementWrapper(localName = "BuildActionEntries")
@JacksonXmlProperty(localName = "BuildActionEntry")
List<BuildActionEntry> buildActionEntries;
@JacksonXmlProperty(isAttribute = true)
public boolean getParallelizeBuildables() {
// Gradle takes care of executing the build in parallel.
return false;
}
@JacksonXmlProperty(isAttribute = true)
public boolean getBuildImplicitDependencies() {
// Gradle takes care of the project dependencies.
return false;
}
@Value
public static class BuildActionEntry {
@JacksonXmlProperty(isAttribute = true)
boolean buildForTesting;
@JacksonXmlProperty(isAttribute = true)
boolean buildForRunning;
@JacksonXmlProperty(isAttribute = true)
boolean buildForProfiling;
@JacksonXmlProperty(isAttribute = true)
boolean buildForArchiving;
@JacksonXmlProperty(isAttribute = true)
boolean buildForAnalyzing;
@JacksonXmlProperty(localName = "BuildableReference")
BuildableReference buildableReference;
}
}
@Value
public static class TestAction {
@JacksonXmlElementWrapper(localName = "Testables")
@JacksonXmlProperty(localName = "TestableReference")
List<TestableReference> testables;
@JacksonXmlProperty(isAttribute = true)
public String getBuildConfiguration() {
return "Default";
}
@JacksonXmlProperty(isAttribute = true)
public String getSelectedDebuggerIdentifier() {
return "Xcode.DebuggerFoundation.Debugger.LLDB";
}
@JacksonXmlProperty(isAttribute = true)
public String getSelectedLauncherIdentifier() {
return "Xcode.DebuggerFoundation.Launcher.LLDB";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getShouldUseLaunchSchemeArgsEnv() {
return true;
}
// TODO: AdditionalOptions
/**
* Note: The attributes are lowerCamelCase.
*/
@Value
public static class TestableReference {
@JacksonXmlProperty(localName = "BuildableReference")
BuildableReference buildableReference;
@JacksonXmlProperty(isAttribute = true)
public boolean getSkipped() {
return false;
}
}
}
@Value
public static class LaunchAction {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JacksonXmlProperty(localName = "BuildableProductRunnable")
BuildableProductRunnable buildableProductRunnable;
@JacksonXmlProperty(isAttribute = true)
public String getBuildConfiguration() {
return "Default";
}
@JacksonXmlProperty(isAttribute = true)
public String getSelectedDebuggerIdentifier() {
return "Xcode.DebuggerFoundation.Debugger.LLDB";
}
@JacksonXmlProperty(isAttribute = true)
public String getSelectedLauncherIdentifier() {
return "Xcode.DebuggerFoundation.Launcher.LLDB";
}
@JacksonXmlProperty(isAttribute = true)
public String getLaunchStyle() {
return "0";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getUseCustomWorkingDirectory() {
return false;
}
@JacksonXmlProperty(isAttribute = true)
public boolean getIgnoresPersistentStateOnLaunch() {
return false;
}
@JacksonXmlProperty(isAttribute = true)
public boolean getDebugDocumentVersioning() {
return true;
}
@JacksonXmlProperty(isAttribute = true)
public String getDebugServiceExtension() {
return "internal";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getAllowLocationSimulation() {
return true;
}
// TODO: AdditionalOptions
@Value
public static class BuildableProductRunnable {
@JacksonXmlProperty(localName = "BuildableReference")
BuildableReference buildableReference;
@JacksonXmlProperty(isAttribute = true)
public String getRunnableDebuggingMode() {
return "0";
}
}
}
@Value
public static class ProfileAction {
@JacksonXmlProperty(isAttribute = true)
public String getBuildConfiguration() {
return "Default";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getShouldUseLaunchSchemeArgsEnv() {
return true;
}
@JacksonXmlProperty(isAttribute = true)
public String getSavedToolIdentifier() {
return "";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getUseCustomWorkingDirectory() {
return false;
}
@JacksonXmlProperty(isAttribute = true)
public boolean getDebugDocumentVersioning() {
return true;
}
}
@Value
public static class AnalyzeAction {
@JacksonXmlProperty(isAttribute = true)
public String getBuildConfiguration() {
return "Default";
}
}
@Value
public static class ArchiveAction {
@JacksonXmlProperty(isAttribute = true)
public String getBuildConfiguration() {
return "Default";
}
@JacksonXmlProperty(isAttribute = true)
public boolean getRevealArchiveInOrganizer() {
return true;
}
}
@Value
@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public static class BuildableReference {
@JacksonXmlProperty(isAttribute = true)
String blueprintIdentifier;
@JacksonXmlProperty(isAttribute = true)
String buildableName;
@JacksonXmlProperty(isAttribute = true)
String blueprintName;
@JacksonXmlProperty(isAttribute = true)
String referencedContainer;
@JacksonXmlProperty(isAttribute = true)
public String getBuildableIdentifier() {
return "primary";
}
}
}
}
| 43.865966 | 269 | 0.75996 |
13fa09862da2908f5b2c9b8d10d1c29239cea2c3 | 1,425 | /*
* This file is part of jTransfo, a library for converting to and from transfer objects.
* Copyright (c) PROGS bvba, Belgium
*
* The program is available in open source according to the Apache License, Version 2.0.
* For full licensing details, see LICENSE.txt in the project root.
*/
package org.jtransfo;
import org.jtransfo.internal.SyntheticField;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Assertions.assertThat;
public class NoConversionTypeConverterTest {
private TypeConverter<Object, Object> typeConverter;
@Mock
private SyntheticField field;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
typeConverter = new NoConversionTypeConverter();
}
@Test
public void testCanConvert() throws Exception {
assertThat(typeConverter.canConvert(Boolean.class, Boolean.class)).isTrue();
assertThat(typeConverter.canConvert(Boolean.class, Integer.class)).isFalse();
}
@Test
public void testConvert() throws Exception {
Object obj = new Object();
assertThat(typeConverter.convert(obj, field, null)).isEqualTo(obj);
}
@Test
public void testReverse() throws Exception {
Object obj = new Object();
assertThat(typeConverter.reverse(obj, field, null)).isEqualTo(obj);
}
}
| 27.941176 | 88 | 0.712982 |
1d35ef97ee7da8df4ecd837f0b21990116dddad2 | 849 | package com.intenthq.challenge;
import java.util.Collections;
import java.util.List;
public class JConnectedGraph {
// Find if two nodes in a directed graph are connected.
// Based on http://www.codewars.com/kata/53897d3187c26d42ac00040d
// For example:
// a -+-> b -> c -> e
// |
// +-> d
// run(a, a) == true
// run(a, b) == true
// run(a, c) == true
// run(b, d) == false
public static boolean run(JNode source, JNode target) {
throw new RuntimeException("Not implemented");
}
public static class JNode {
public final int value;
public final List<JNode> edges;
public JNode(final int value, final List<JNode> edges) {
this.value = value;
this.edges = edges;
}
public JNode(final int value) {
this.value = value;
this.edges = Collections.emptyList();
}
}
}
| 24.257143 | 67 | 0.623086 |
cdeeb38ab5a0435651d7ecb5119e06bf291b170d | 5,529 | /*
* Copyright 2017 Rakuten, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rakuten.tech.mobile.datastore.crypto;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Crypto operations implementing encrypt-then-mac with AES/CBC/PKCS7Padding and HmacSHA256.
*
* @since 0.1 {@inheritDoc}
*/
@SuppressFBWarnings("CIPHER_INTEGRITY")
public class SimpleCryptoOperations implements CryptoOperations {
private static final int SIGNATURE_LENGTH = 32;
private static final int IV_LENGTH = 16;
private final Random random;
private final Key encryptionKey;
private final Key signingKey;
/**
* Create a new instance using a default {@link Random}.
*
* @param encryptionKey Key to use for encryption/decryption.
* @param signingKey Key to use for signing/verifying.
* @since 0.1
*/
public SimpleCryptoOperations(
final @NotNull Key encryptionKey,
final @NotNull Key signingKey) {
this(encryptionKey, signingKey, new SecureRandom());
}
/**
* Create a new instance.
*
* @param encryptionKey Key to use for encryption/decryption.
* @param signingKey Key to use for signing/verifying.
* @param random If {@code null}, {@link #encrypt(ByteBuffer)} will not specify an {@link
* IvParameterSpec} when calling {@link Cipher#init(int, Key)}. This is useful if the provider
* automatically manages IVs, such as e.g. the {@code AndroidKeyStore} provider.
* @since 0.1
*/
public SimpleCryptoOperations(
final @NotNull Key encryptionKey,
final @NotNull Key signingKey,
final @Nullable Random random) {
this.encryptionKey = encryptionKey;
this.signingKey = signingKey;
this.random = random;
}
@NotNull
protected Mac createNewMacInstance() throws GeneralSecurityException {
final Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
return mac;
}
@NotNull
@SuppressFBWarnings("STATIC_IV")
protected Cipher createNewCipherInstance(final int mode, final @Nullable ByteBuffer presetIv)
throws GeneralSecurityException {
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
if (presetIv == null) {
cipher.init(mode, encryptionKey);
} else {
cipher.init(mode, encryptionKey, new IvParameterSpec(
presetIv.array(), presetIv.arrayOffset() + presetIv.position(), presetIv.remaining()));
}
return cipher;
}
@NotNull
@Override
public ByteBuffer encrypt(final @NotNull ByteBuffer message) throws GeneralSecurityException {
ByteBuffer iv = null;
if (random != null) {
iv = ByteBuffer.allocate(IV_LENGTH);
random.nextBytes(iv.array());
}
final Cipher cipher = createNewCipherInstance(Cipher.ENCRYPT_MODE, iv);
ByteBuffer buffer = ByteBuffer.allocate(
SIGNATURE_LENGTH + IV_LENGTH + cipher.getOutputSize(message.remaining()));
// Copy IV
buffer.position(SIGNATURE_LENGTH);
buffer.put(cipher.getIV());
// Encrypt
int size = SIGNATURE_LENGTH + IV_LENGTH + cipher.doFinal(message.slice(), buffer);
buffer.rewind();
buffer.limit(size);
// Sign IV and message, and prepend signature
final Mac mac = createNewMacInstance();
buffer.position(SIGNATURE_LENGTH);
mac.update(buffer);
mac.doFinal(buffer.array(), 0);
buffer.rewind();
return buffer.slice();
}
@NotNull
@Override
public ByteBuffer decrypt(final @NotNull ByteBuffer message) throws GeneralSecurityException {
// Grab a slice for the signature
ByteBuffer signature = message.slice();
signature.limit(SIGNATURE_LENGTH);
signature = signature.slice();
// …and a slice for the IV
ByteBuffer iv = message.slice();
iv.position(SIGNATURE_LENGTH);
iv.limit(iv.position() + IV_LENGTH);
iv = iv.slice();
// …and one for the encrypted content
ByteBuffer encrypted = message.slice();
encrypted.position(SIGNATURE_LENGTH + IV_LENGTH);
encrypted = encrypted.slice();
// Verify signature
final Mac mac = createNewMacInstance();
mac.update(iv);
mac.update(encrypted);
final ByteBuffer expected = ByteBuffer.wrap(mac.doFinal());
if (signature.compareTo(expected) != 0) {
throw new SignatureException("Signature mismatch");
}
// Decrypt
iv.rewind();
encrypted.rewind();
final Cipher cipher = createNewCipherInstance(Cipher.DECRYPT_MODE, iv);
ByteBuffer buffer = ByteBuffer.allocate(cipher.getOutputSize(encrypted.remaining()));
int size = cipher.doFinal(encrypted, buffer);
buffer.rewind();
buffer.limit(size);
return buffer.slice();
}
}
| 31.594286 | 97 | 0.71333 |
c95c4c0572c496ac722179e19013a2e7e83a0a2d | 1,537 | package org.opendatakit.data;
import org.opendatakit.database.data.Row;
import org.opendatakit.database.data.UserTable;
import java.util.Map;
import java.util.TreeMap;
/**
* Created by clarice on 3/22/16.
*/
public class ColorGuideGroup {
private Map<String, ColorGuide> mRowIdToColors = new TreeMap<String, ColorGuide>();
private ColorRuleGroup mCRG;
private UserTable mUT;
public ColorGuideGroup(ColorRuleGroup crg, UserTable ut) {
if (crg == null) {
return;
}
mCRG = crg;
if (ut == null) {
return;
}
mUT = ut;
for (int i = 0; i < mUT.getNumberOfRows(); i++) {
ColorGuide tcg = mCRG.getColorGuide(mUT.getColumnDefinitions(), mUT.getRowAtIndex(i));
mRowIdToColors.put(mUT.getRowId(i), tcg);
}
}
public Map<String, ColorGuide> getAllColorGuides() {
return mRowIdToColors;
}
public ColorGuide getColorGuideForRowIndex(int i) {
ColorGuide cg = null;
Row colorRow = null;
try {
colorRow = mUT.getRowAtIndex(i);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
if (colorRow != null && mRowIdToColors != null) {
if (mRowIdToColors.containsKey(mUT.getRowId(i))) {
cg = mRowIdToColors.get(mUT.getRowId(i));
}
}
return cg;
}
public ColorGuide getColorGuideForRowId(String rowId) {
ColorGuide cg = null;
if (mRowIdToColors != null) {
if (mRowIdToColors.containsKey(rowId)) {
cg = mRowIdToColors.get(rowId);
}
}
return cg;
}
}
| 20.77027 | 92 | 0.644763 |
5e67aed68dc21c8b7c0711033fd1bbe22186d0fe | 13,285 | package logbook.gui;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import logbook.config.AppConfig;
import logbook.constants.AppConstants;
import logbook.gui.logic.LayoutLogic;
import logbook.util.AwtUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
/**
* キャプチャダイアログ
*
*/
public final class CaptureDialog extends Dialog {
private Shell shell;
private Composite composite;
private Text text;
private Button capture;
private Button interval;
private Spinner intervalms;
private Rectangle rectangle;
private Timer timer;
private boolean isAlive;
private Font font;
/**
* Create the dialog.
* @param parent
*/
public CaptureDialog(Shell parent) {
super(parent, SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.RESIZE);
this.setText("キャプチャ");
}
/**
* Open the dialog.
* @return the result
*/
public void open() {
try {
this.createContents();
this.shell.open();
this.shell.layout();
Display display = this.getParent().getDisplay();
while (!this.shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} finally {
// タイマーを停止させる
if (this.timer != null) {
this.timer.cancel();
}
// フォントを開放
if (this.font != null) {
this.font.dispose();
}
}
}
/**
* Create contents of the dialog.
*/
private void createContents() {
// シェル
this.shell = new Shell(this.getParent(), this.getStyle());
this.shell.setText(this.getText());
// レイアウト
GridLayout glShell = new GridLayout(1, false);
glShell.horizontalSpacing = 1;
glShell.marginHeight = 1;
glShell.marginWidth = 1;
glShell.verticalSpacing = 1;
this.shell.setLayout(glShell);
// 太字にするためのフォントデータを作成する
FontData defaultfd = this.shell.getFont().getFontData()[0];
FontData fd = new FontData(defaultfd.getName(), defaultfd.getHeight(), SWT.BOLD);
this.font = new Font(Display.getDefault(), fd);
// コンポジット
Composite rangeComposite = new Composite(this.shell, SWT.NONE);
rangeComposite.setLayout(new GridLayout(2, false));
// 範囲設定
this.text = new Text(rangeComposite, SWT.BORDER | SWT.READ_ONLY);
GridData gdText = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gdText.widthHint = 120;
this.text.setLayoutData(gdText);
this.text.setText("範囲が未設定です");
Button button = new Button(rangeComposite, SWT.NONE);
button.setText("範囲を選択");
button.addSelectionListener(new SelectRectangleAdapter());
// コンポジット
this.composite = new Composite(this.shell, SWT.NONE);
GridLayout loglayout = new GridLayout(3, false);
this.composite.setLayout(loglayout);
this.composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
// 周期設定
this.interval = new Button(this.composite, SWT.CHECK);
this.interval.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CaptureDialog.this.capture.setText(getCaptureButtonText(false,
CaptureDialog.this.interval.getSelection()));
}
});
this.interval.setText("周期");
this.intervalms = new Spinner(this.composite, SWT.BORDER);
this.intervalms.setMaximum(60000);
this.intervalms.setMinimum(100);
this.intervalms.setSelection(1000);
this.intervalms.setIncrement(100);
Label label = new Label(this.composite, SWT.NONE);
label.setText("ミリ秒");
this.capture = new Button(this.shell, SWT.NONE);
this.capture.setFont(this.font);
GridData gdCapture = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
gdCapture.horizontalSpan = 3;
gdCapture.heightHint = 64;
this.capture.setLayoutData(gdCapture);
this.capture.setEnabled(false);
this.capture.setText(getCaptureButtonText(false, this.interval.getSelection()));
this.capture.addSelectionListener(new CaptureStartAdapter());
this.shell.pack();
}
/**
* キャプチャボタンの文字を取得します
*
* @param isrunning
* @param interval
* @return
*/
private static String getCaptureButtonText(boolean isrunning, boolean interval) {
if (isrunning && interval) {
return "停 止";
} else if (interval) {
return "開 始";
} else {
return "キャプチャ";
}
}
/**
* 範囲の選択を押した時
*
*/
public final class SelectRectangleAdapter extends SelectionAdapter {
/** ダイアログが完全に消えるまで待つ時間 */
private static final int WAIT = 250;
@Override
public void widgetSelected(SelectionEvent paramSelectionEvent) {
try {
Display display = Display.getDefault();
// ダイアログを非表示にする
CaptureDialog.this.shell.setVisible(false);
// 消えるまで待つ
Thread.sleep(WAIT);
// ディスプレイに対してGraphics Contextを取得する(フルスクリーンキャプチャ)
GC gc = new GC(display);
Image image = new Image(display, display.getBounds());
gc.copyArea(image, 0, 0);
gc.dispose();
try {
// 範囲を取得する
Rectangle rectangle = new FullScreenDialog(CaptureDialog.this.shell, image,
CaptureDialog.this.shell.getMonitor())
.open();
if ((rectangle != null) && (rectangle.width > 1) && (rectangle.height > 1)) {
CaptureDialog.this.rectangle = rectangle;
CaptureDialog.this.text.setText("(" + rectangle.x + "," + rectangle.y + ")-("
+ (rectangle.x + rectangle.width) + "," + (rectangle.y + rectangle.height) + ")");
CaptureDialog.this.capture.setEnabled(true);
}
} finally {
image.dispose();
}
CaptureDialog.this.shell.setVisible(true);
CaptureDialog.this.shell.setActive();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* キャプチャボタンを押した時
*
*/
public final class CaptureStartAdapter extends SelectionAdapter {
@Override
public void widgetSelected(SelectionEvent e) {
Timer timer = CaptureDialog.this.timer;
Rectangle rectangle = CaptureDialog.this.rectangle;
boolean interval = CaptureDialog.this.interval.getSelection();
int intervalms = CaptureDialog.this.intervalms.getSelection();
if (timer != null) {
// タイマーを停止させる
timer.cancel();
timer = null;
}
if (CaptureDialog.this.isAlive) {
CaptureDialog.this.capture.setText(getCaptureButtonText(false, interval));
LayoutLogic.enable(CaptureDialog.this.composite, true);
CaptureDialog.this.isAlive = false;
} else {
timer = new Timer(true);
if (interval) {
// 固定レートで周期キャプチャ
timer.scheduleAtFixedRate(new CaptureTask(rectangle), 0, intervalms);
CaptureDialog.this.isAlive = true;
} else {
// 一回だけキャプチャ
timer.schedule(new CaptureTask(rectangle), 0);
}
CaptureDialog.this.capture.setText(getCaptureButtonText(true, interval));
if (interval) {
LayoutLogic.enable(CaptureDialog.this.composite, false);
}
}
CaptureDialog.this.timer = timer;
}
}
/**
* 画面キャプチャスレッド
*
*/
public static final class CaptureTask extends TimerTask {
/** ロガー */
private static final Logger LOG = LogManager.getLogger(CaptureTask.class);
/** Jpeg品質 */
private static final float QUALITY = 0.9f;
/** 日付フォーマット(ファイル名) */
private final SimpleDateFormat fileNameFormat = new SimpleDateFormat(AppConstants.DATE_LONG_FORMAT);
/** 日付フォーマット(ディレクトリ名) */
private final SimpleDateFormat dirNameFormat = new SimpleDateFormat(AppConstants.DATE_DAYS_FORMAT);
/** キャプチャ範囲 */
private final Rectangle rectangle;
/** トリム範囲 */
private java.awt.Rectangle trimRect;
public CaptureTask(Rectangle rectangle) {
this.rectangle = rectangle;
}
@Override
public void run() {
try {
// 時刻からファイル名を作成
Date now = Calendar.getInstance().getTime();
String dir = null;
if (AppConfig.get().isCreateDateFolder()) {
dir = FilenameUtils.concat(AppConfig.get().getCapturePath(), this.dirNameFormat.format(now));
} else {
dir = AppConfig.get().getCapturePath();
}
String fname = FilenameUtils.concat(dir, this.fileNameFormat.format(now) + "."
+ AppConfig.get().getImageFormat());
File file = new File(fname);
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (!(file.canWrite()))
throw new IOException("File '" + file + "' cannot be written to");
} else {
File parent = file.getParentFile();
if ((parent != null) &&
(!(parent.mkdirs())) && (!(parent.isDirectory()))) {
throw new IOException("Directory '" + parent + "' could not be created");
}
}
// 範囲をキャプチャする
BufferedImage image = AwtUtils.getCapture(this.rectangle);
if (image != null) {
ImageOutputStream ios = ImageIO.createImageOutputStream(file);
try {
ImageWriter writer = ImageIO.getImageWritersByFormatName(AppConfig.get().getImageFormat())
.next();
try {
ImageWriteParam iwp = writer.getDefaultWriteParam();
if (iwp.canWriteCompressed()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(QUALITY);
}
writer.setOutput(ios);
if (this.trimRect == null) {
this.trimRect = AwtUtils.getTrimSize(image);
}
writer.write(null, new IIOImage(AwtUtils.trim(image, this.trimRect), null, null), iwp);
} finally {
writer.dispose();
}
} finally {
ios.close();
}
}
} catch (Exception e) {
LOG.warn("キャプチャ中に例外が発生しました", e);
}
}
}
}
| 35.905405 | 116 | 0.541362 |
6e2f1dab630315ced2926be94371371aed14c9de | 5,538 | package com.momohelp.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.momohelp.model.Message;
import com.momohelp.model.User;
import com.momohelp.service.MessageService;
import com.momohelp.service.UserService;
/**
*
* @author Administrator
*
*/
@Controller
public class MessageController {
@Autowired
private MessageService messageService;
@Autowired
private UserService userService;
/**
* 在线工单
*
* @param session
* @param page
* @param rows
* @param message
* @return
*/
@RequestMapping(value = { "/message/" }, method = RequestMethod.GET)
public ModelAndView _i_indexUI(HttpSession session,
@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false, defaultValue = "100") int rows,
Message message) {
ModelAndView result = new ModelAndView("i/message/1.0.2/index");
message.setUser_id(session.getAttribute("session.user.id").toString());
List<Message> list = messageService.findByMessage(message, page,
Integer.MAX_VALUE);
result.addObject("data_list", list);
result.addObject("data_user", session.getAttribute("session.user"));
result.addObject("nav_choose", ",07,0702,");
return result;
}
@RequestMapping(value = { "/message/add" }, method = RequestMethod.GET)
public String _i_profile22UI(HttpSession session, Map<String, Object> map) {
User user = userService.selectByKey(session.getAttribute(
"session.user.id").toString());
map.put("data_user", user);
map.put("nav_choose", ",07,0702,");
return "i/message/1.0.2/add";
}
@ResponseBody
@RequestMapping(value = { "/message/add" }, method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> _i_profile11(HttpSession session, Message message) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("success", false);
message.setUser_id(session.getAttribute("session.user.id").toString());
messageService.save(message);
result.put("success", true);
return result;
}
// /**
// * 发起留言
// *
// * @param session
// * @param message
// * @return
// */
// @ResponseBody
// @RequestMapping(value = { "/message/add" }, method = RequestMethod.POST,
// produces = "application/json")
// public Map<String, Object> _i_add(HttpSession session, Message message) {
//
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("success", false);
// return result;
// }
/**** 后台 ****/
/**
* 在线工单
*
* @param session
* @return
*/
@RequestMapping(value = { "/manage/message/" }, method = RequestMethod.GET)
public ModelAndView _manage_indexUI(HttpSession session,
@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false, defaultValue = "100") int rows,
Message message) {
ModelAndView result = new ModelAndView("m/message/index");
List<Message> list = messageService.findByMessage(message, page,
Integer.MAX_VALUE);
result.addObject("data_list", list);
result.addObject("data_user", session.getAttribute("session.user"));
result.addObject("nav_choose", ",09,0902,");
return result;
}
@RequestMapping(value = { "/manage/message/edit" }, method = RequestMethod.GET)
public String _i_profile2233UI(HttpSession session,
Map<String, Object> map, Message message) {
User user = userService.selectByKey(session.getAttribute(
"session.user.id").toString());
map.put("data_user", user);
Message _message = messageService.selectByKey(message.getId());
map.put("data_message", _message);
map.put("nav_choose", ",09,0902,");
return "m/message/edit";
}
@ResponseBody
@RequestMapping(value = { "/manage/message/edit" }, method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> _i_profile1144(HttpSession session,
Message message) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("success", false);
message.setReply_time(new Date());
message.setReply_user_id(session.getAttribute("session.user.id")
.toString());
messageService.updateNotNull(message);
result.put("success", true);
return result;
}
// /**
// * 回复留言
// *
// * @param message
// * @param session
// * @return
// */
// @ResponseBody
// @RequestMapping(value = { "/manage/message/edit" }, method =
// RequestMethod.POST, produces = "application/json")
// public Map<String, Object> _manage_edit(Message message, HttpSession
// session) {
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("success", false);
// // TODO
// return result;
// }
//
// /**
// * 删除留言
// *
// * @param id
// * @return
// */
// @ResponseBody
// @RequestMapping(value = { "/manage/message/remove" }, method =
// RequestMethod.POST, produces = "application/json")
// public Map<String, Object> _manage_remove(
// @RequestParam(required = true) String id) {
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("success", false);
// // TODO
// return result;
// }
} | 27.829146 | 112 | 0.699892 |
8a50dfef7455e5269314dff56e66e3e90e4ad924 | 2,756 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.ui.toolkit.impl.swing.view.widget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import net.sf.mmm.ui.toolkit.api.event.UiEventType;
import net.sf.mmm.ui.toolkit.api.feature.UiFileAccess;
import net.sf.mmm.ui.toolkit.api.view.widget.UiFileUpload;
import net.sf.mmm.ui.toolkit.base.feature.UiFileAccessSimple;
import net.sf.mmm.ui.toolkit.impl.swing.UiFactorySwing;
/**
* This class is the implementation of the
* {@link net.sf.mmm.ui.toolkit.api.view.widget.UiFileUpload} interface using
* Swing as the UI toolkit.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
public class UiFileUploadImpl extends AbstractUiWidgetSwing<JButton> implements UiFileUpload {
/** the access to the uploaded data */
private UiFileAccess access;
/** the file-chooser used to select where to save the download to */
private final JFileChooser fileChooser;
/**
* The constructor.
*
* @param uiFactory is the {@link #getFactory() factory} instance.
*/
public UiFileUploadImpl(UiFactorySwing uiFactory) {
// TODO: i18n
super(uiFactory, new JButton("Upload"));
this.access = null;
this.fileChooser = new JFileChooser();
this.fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
// this.button.setToolTipText("Upload " + this.access.getFilename());
getAdapter().getDelegate().addActionListener(new Listener());
}
/**
* {@inheritDoc}
*/
public UiFileAccess getSelection() {
return this.access;
}
/**
* {@inheritDoc}
*/
public String getType() {
return TYPE;
}
/**
* {@inheritDoc}
*/
public String getValue() {
return getAdapter().getDelegate().getText();
}
/**
* {@inheritDoc}
*/
public void setValue(String text) {
getAdapter().getDelegate().setText(text);
}
/**
* This inner class implements the listener that handles the button selection.
*/
private class Listener implements ActionListener {
/**
* {@inheritDoc}
*/
public void actionPerformed(ActionEvent e) {
UiFileUploadImpl.this.fileChooser.setDialogTitle(getValue());
int selection = UiFileUploadImpl.this.fileChooser.showOpenDialog(getAdapter().getDelegate());
if (selection == JFileChooser.APPROVE_OPTION) {
File uploadFile = UiFileUploadImpl.this.fileChooser.getSelectedFile();
UiFileUploadImpl.this.access = new UiFileAccessSimple(uploadFile.getAbsolutePath());
sendEvent(UiEventType.CLICK);
}
}
}
}
| 26.5 | 99 | 0.701379 |
6698c980bc4566ca41b40f77e2777f1d8b560385 | 896 | package com.example.antoan.planit.ui;
import android.content.Context;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import java.util.List;
import dagger.Module;
import dagger.Provides;
/**
* Created by Antoan on 2/19/2017.
*/
@Module
public class UiModule {
@Provides
LoadingDialog provideLoadingDialog(Context context){
return new LoadingDialog(context,"Plaese Wait");
}
@Provides
AcountHeaderBuilder provideAccountheaderBuilder(){
return new AcountHeaderBuilder();
}
@Provides
DrawerBuilder provideDrawerBuilder(List<PrimaryDrawerItem> drawerItems){
return new DrawerBuilder(drawerItems);
}
@Provides
DrawerListener provideDrawerListener(){
return new DrawerListener();
}
@Provides
MaterialTimePicker provideMatirialTimePicker(){
return new MaterialTimePicker();
}
}
| 20.837209 | 76 | 0.716518 |
94bc639ccb841733aafbf9ff4637cace26189909 | 1,134 | package ru.intertrust.cm.core.config.form.widget;
import ru.intertrust.cm.core.config.LogicalErrors;
import ru.intertrust.cm.core.config.WidgetConfigurationToValidate;
import static ru.intertrust.cm.core.config.form.widget.WidgetLogicalValidatorHelper.fieldTypeIsBoolean;
import static ru.intertrust.cm.core.config.form.widget.WidgetLogicalValidatorHelper.fieldTypeIsThruReference;
/**
* @author Yaroslav Bondarchuk
* Date: 16.08.2015
* Time: 17:42
*/
public class CheckBoxWidgetLogicalValidator extends AbstractWidgetLogicalValidator {
@Override
public void validate(WidgetConfigurationToValidate widget, LogicalErrors logicalErrors) {
String fieldType = widget.getFieldConfigToValidate().getFieldType().name();
if (fieldTypeIsBoolean(fieldType) || fieldType.equals("REFERENCE")) {
return;
}
String error = String.format("Field '%s' in domain object '%s' isn't a boolean type",
widget.getFieldConfigToValidate().getName(), widget.getDomainObjectTypeToValidate());
logger.error(error);
logicalErrors.addError(error);
}
}
| 40.5 | 109 | 0.737213 |
0549f310f2fe89b887fec9f5895f0cb80b58b675 | 2,225 | package com.example.dhp.chat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
private RecyclerView mMessageRecycler;
private MessageListAdapter mMessageAdapter;
TextView messagehistoy;
EditText messageToSend;
Button sendButton;
Server server;
static List<Message> messageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
messageList = new ArrayList<>();
mMessageRecycler = findViewById(R.id.reyclerview_message_list);
mMessageAdapter = new MessageListAdapter(this, messageList);
mMessageRecycler.setLayoutManager(new LinearLayoutManager(this));
mMessageRecycler.setAdapter(mMessageAdapter);
messagehistoy = findViewById(R.id.messageHistory);
messageToSend = findViewById(R.id.messageToSend);
sendButton = findViewById(R.id.sendButton);
server = new Server(this);
Toast.makeText(getApplicationContext(),
"myServerIP:" + MainActivity.myServerIP +
"\notherServer:" + MainActivity.otherServerIP +
"\nmyServerPort:" + MainActivity.myServerPort +
"\notherServerPort" + MainActivity.otherServerPort,
Toast.LENGTH_LONG).show();
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String message = messageToSend.getText().toString();
messageToSend.setText("");
new Client(message);
messagehistoy.append("\nYou:" + message);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
}
| 34.230769 | 75 | 0.671461 |
20396d5eac7cca01b6b336a376e1caf807d3e0a3 | 476 | // This is a generated file. Not intended for manual editing.
package com.smcplugin.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface SmcStartState extends SmcStateFullName {
@NotNull
List<SmcComment> getCommentList();
@NotNull
SmcStartMapNameElement getStartMapNameElement();
@NotNull
SmcStartStateNameElement getStartStateNameElement();
String getMapName();
String getStateName();
}
| 19.833333 | 61 | 0.781513 |
1e102d855403a0dc0ae835d577564c71e34129c0 | 4,382 | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.cpachecker.cpa.automaton;
import com.google.common.base.Preconditions;
import java.util.HashMap;
import java.util.Map;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
import org.sosy_lab.cpachecker.core.interfaces.Targetable.TargetInformation;
import org.sosy_lab.cpachecker.cpa.automaton.AutomatonExpression.ResultValue;
import org.sosy_lab.cpachecker.exceptions.CPAException;
import org.sosy_lab.cpachecker.exceptions.CPATransferException;
public class AutomatonStateARGCombiningHelper {
private final Map<String, AutomatonInternalState> qualifiedAutomatonStateNameToInternalState;
private final Map<String, Automaton> nameToAutomaton;
public AutomatonStateARGCombiningHelper() {
qualifiedAutomatonStateNameToInternalState = new HashMap<>();
nameToAutomaton = new HashMap<>();
}
public boolean registerAutomaton(final AutomatonState pStateOfAutomata) {
Automaton automaton = pStateOfAutomata.getOwningAutomaton();
final String prefix = automaton.getName() + "::";
String qualifiedName;
if (nameToAutomaton.put(automaton.getName(), automaton) != null) {
return false;
}
for (AutomatonInternalState internal : automaton.getStates()) {
qualifiedName = prefix + internal.getName();
if (qualifiedAutomatonStateNameToInternalState.put(qualifiedName, internal) != null) {
return false;
}
}
return true;
}
public AutomatonState replaceStateByStateInAutomatonOfSameInstance(final AutomatonState toReplace)
throws CPAException {
String qualifiedName =
toReplace.getOwningAutomatonName() + "::" + toReplace.getInternalStateName();
if (qualifiedAutomatonStateNameToInternalState.containsKey(qualifiedName)) {
AutomatonTargetInformation targetInformation = null;
if (toReplace.isTarget() && !toReplace.getTargetInformation().isEmpty()) {
TargetInformation info = toReplace.getTargetInformation().iterator().next();
assert info instanceof AutomatonTargetInformation;
targetInformation = (AutomatonTargetInformation) info;
}
return AutomatonState.automatonStateFactory(
toReplace.getVars(),
qualifiedAutomatonStateNameToInternalState.get(qualifiedName),
nameToAutomaton.get(toReplace.getOwningAutomatonName()),
toReplace.getAssumptions(),
toReplace.getCandidateInvariants(),
toReplace.getMatches(),
toReplace.getFailedMatches(),
targetInformation,
toReplace.isTreatingErrorsAsTarget());
}
throw new CPAException("Changing state failed, unknown state.");
}
public boolean considersAutomaton(final String pAutomatonName) {
return nameToAutomaton.containsKey(pAutomatonName);
}
public static boolean endsInAssumptionTrueState(
final AutomatonState pPredecessor, final CFAEdge pEdge, final LogManager pLogger) {
Preconditions.checkNotNull(pPredecessor);
Preconditions.checkArgument(!pPredecessor.getInternalState().isNonDetState());
AutomatonExpressionArguments exprArgs =
new AutomatonExpressionArguments(
pPredecessor, pPredecessor.getVars(), null, pEdge, pLogger);
try {
for (AutomatonTransition transition : pPredecessor.getInternalState().getTransitions()) {
exprArgs.clearTransitionVariables();
ResultValue<Boolean> match;
match = transition.getTrigger().eval(exprArgs);
if (match.canNotEvaluate()) {
return false;
}
if (match.getValue()) {
if (transition.getFollowState().getName().equals("__TRUE")) {
ResultValue<Boolean> assertionsHold = transition.assertionsHold(exprArgs);
if (!assertionsHold.canNotEvaluate()
&& assertionsHold.getValue()
&& transition.canExecuteActionsOn(exprArgs)) {
return true;
}
}
return false;
}
}
} catch (CPATransferException e) {
return false;
}
return pPredecessor.getInternalState().getName().equals("__TRUE");
}
}
| 36.516667 | 100 | 0.717481 |
a861972f8e6d8f33dd0599a4f65d00c9be7b2d39 | 82 | package me.camdenorrb.sweetsqlj.impl.value.impl.bundle;
public class SqlEnum {
}
| 16.4 | 55 | 0.792683 |
7779742181de1898de3fd24124b9ec165c8642c7 | 1,801 | package com.njfsoft_utils.artpad.filters;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
public class ReliefFilter {
// 浮雕效果函数
public static Bitmap changeToRelief(Bitmap mBitmap) {
Paint mPaint;
int mBitmapWidth = 0;
int mBitmapHeight = 0;
int mArrayColor[] = null;
int mArrayColorLengh = 0;
long startTime = 0;
int mBackVolume = 0;
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
Bitmap bmpReturn = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.RGB_565);
mArrayColorLengh = mBitmapWidth * mBitmapHeight;
int count = 0;
int preColor = 0;
int prepreColor = 0;
int color = 0;
preColor = mBitmap.getPixel(0,0);
for (int i = 0; i < mBitmapWidth; i++) {
for (int j = 0; j < mBitmapHeight; j++) {
int curr_color = mBitmap.getPixel(i,j);
int r = Color.red(curr_color) - Color.red(prepreColor) +128;
int g = Color.green(curr_color) - Color.red(prepreColor) +128;
int b = Color.green(curr_color) - Color.blue(prepreColor) +128;
int a = Color.alpha(curr_color);
int modif_color = Color.argb(a, r, g, b);
bmpReturn.setPixel(i, j, modif_color);
prepreColor = preColor;
preColor = curr_color;
}
}
Canvas c = new Canvas(bmpReturn);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpReturn, 0, 0, paint);
return bmpReturn;
}
}
| 30.525424 | 95 | 0.65186 |
6ce83de79f5e3d611a664788c85b2c46b3b5714f | 6,820 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.rekognition.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CompareFacesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Source image either as bytes or an S3 object
* </p>
*/
private Image sourceImage;
/**
* <p>
* Target image either as bytes or an S3 object
* </p>
*/
private Image targetImage;
/**
* <p>
* The minimum level of confidence in the match you want included in the result.
* </p>
*/
private Float similarityThreshold;
/**
* <p>
* Source image either as bytes or an S3 object
* </p>
*
* @param sourceImage
* Source image either as bytes or an S3 object
*/
public void setSourceImage(Image sourceImage) {
this.sourceImage = sourceImage;
}
/**
* <p>
* Source image either as bytes or an S3 object
* </p>
*
* @return Source image either as bytes or an S3 object
*/
public Image getSourceImage() {
return this.sourceImage;
}
/**
* <p>
* Source image either as bytes or an S3 object
* </p>
*
* @param sourceImage
* Source image either as bytes or an S3 object
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompareFacesRequest withSourceImage(Image sourceImage) {
setSourceImage(sourceImage);
return this;
}
/**
* <p>
* Target image either as bytes or an S3 object
* </p>
*
* @param targetImage
* Target image either as bytes or an S3 object
*/
public void setTargetImage(Image targetImage) {
this.targetImage = targetImage;
}
/**
* <p>
* Target image either as bytes or an S3 object
* </p>
*
* @return Target image either as bytes or an S3 object
*/
public Image getTargetImage() {
return this.targetImage;
}
/**
* <p>
* Target image either as bytes or an S3 object
* </p>
*
* @param targetImage
* Target image either as bytes or an S3 object
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompareFacesRequest withTargetImage(Image targetImage) {
setTargetImage(targetImage);
return this;
}
/**
* <p>
* The minimum level of confidence in the match you want included in the result.
* </p>
*
* @param similarityThreshold
* The minimum level of confidence in the match you want included in the result.
*/
public void setSimilarityThreshold(Float similarityThreshold) {
this.similarityThreshold = similarityThreshold;
}
/**
* <p>
* The minimum level of confidence in the match you want included in the result.
* </p>
*
* @return The minimum level of confidence in the match you want included in the result.
*/
public Float getSimilarityThreshold() {
return this.similarityThreshold;
}
/**
* <p>
* The minimum level of confidence in the match you want included in the result.
* </p>
*
* @param similarityThreshold
* The minimum level of confidence in the match you want included in the result.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompareFacesRequest withSimilarityThreshold(Float similarityThreshold) {
setSimilarityThreshold(similarityThreshold);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSourceImage() != null)
sb.append("SourceImage: ").append(getSourceImage()).append(",");
if (getTargetImage() != null)
sb.append("TargetImage: ").append(getTargetImage()).append(",");
if (getSimilarityThreshold() != null)
sb.append("SimilarityThreshold: ").append(getSimilarityThreshold());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CompareFacesRequest == false)
return false;
CompareFacesRequest other = (CompareFacesRequest) obj;
if (other.getSourceImage() == null ^ this.getSourceImage() == null)
return false;
if (other.getSourceImage() != null && other.getSourceImage().equals(this.getSourceImage()) == false)
return false;
if (other.getTargetImage() == null ^ this.getTargetImage() == null)
return false;
if (other.getTargetImage() != null && other.getTargetImage().equals(this.getTargetImage()) == false)
return false;
if (other.getSimilarityThreshold() == null ^ this.getSimilarityThreshold() == null)
return false;
if (other.getSimilarityThreshold() != null && other.getSimilarityThreshold().equals(this.getSimilarityThreshold()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSourceImage() == null) ? 0 : getSourceImage().hashCode());
hashCode = prime * hashCode + ((getTargetImage() == null) ? 0 : getTargetImage().hashCode());
hashCode = prime * hashCode + ((getSimilarityThreshold() == null) ? 0 : getSimilarityThreshold().hashCode());
return hashCode;
}
@Override
public CompareFacesRequest clone() {
return (CompareFacesRequest) super.clone();
}
}
| 30.311111 | 132 | 0.618622 |
fa644963227d99b4ba239c6e263fd69e4b74c312 | 204 | import javax.swing.SwingUtilities;
public class Main {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Login();
}
});
}
}
| 13.6 | 45 | 0.647059 |
c46fb83396da14f67e4c45194331c75ee1f5ba1a | 159 | package io.smallrye.graphql.test.apps.jsonp.api;
import jakarta.json.JsonObject;
public class Token {
public String name;
public JsonObject value;
}
| 17.666667 | 48 | 0.754717 |
81d8ab3a65442ce48a94478d550b6be325bbcaac | 19,148 | package bg.bas.iinf.sinus.wicket.owl.filter.searchresults;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import bg.bas.iinf.sinus.hibernate.dao.Home;
import bg.bas.iinf.sinus.hibernate.dao.SavedSearchesHome;
import bg.bas.iinf.sinus.hibernate.dao.SelectedResultsHome;
import bg.bas.iinf.sinus.hibernate.entity.SavedSearches;
import bg.bas.iinf.sinus.hibernate.entity.SearchDisplayValues;
import bg.bas.iinf.sinus.hibernate.entity.SearchResults;
import bg.bas.iinf.sinus.hibernate.entity.SelectedResults;
import bg.bas.iinf.sinus.hibernate.filter.SelectedResultsFilter;
import bg.bas.iinf.sinus.hibernate.filter.StringFilter;
import bg.bas.iinf.sinus.hibernate.filter.StringFilter.STRING_MATCH;
import bg.bas.iinf.sinus.hibernate.lifecycle.ScopedEntityManagerFactory;
import bg.bas.iinf.sinus.wicket.auth.UserSession;
import bg.bas.iinf.sinus.wicket.common.IModalWindowContainer;
import bg.bas.iinf.sinus.wicket.common.NotificationEventPayload;
import bg.bas.iinf.sinus.wicket.common.NotificationType;
import bg.bas.iinf.sinus.wicket.model.SavedSearchLDM;
import bg.bas.iinf.sinus.wicket.model.owl.AllOntologiesLDM;
import bg.bas.iinf.sinus.wicket.model.owl.OWLNamedObjectNameLDM;
import bg.bas.iinf.sinus.wicket.model.owl.OWLOntologiesLDM;
import bg.bas.iinf.sinus.wicket.owl.filter.FilterPage;
import bg.bas.iinf.sinus.wicket.owl.filter.searchresults.SearchResultsDataView.OWLNamedObjectResult;
import bg.bas.iinf.sinus.wicket.owl.filter.searchresults.SelectedResultsPanel.SelectedResultsSubmittedEP;
import bg.bas.iinf.sinus.wicket.page.BasePage;
import css.CSS;
/**
* Stranica s rezultati ot tyrsene (moje da se izpolzva za tekushto i za stari tyrseniq)
* @author hok
*
*/
public class SearchResultsPage extends BasePage {
private static final long serialVersionUID = -2890494303607721815L;
public static final String ID = "id";
private SearchDataProvider dataProvider;
private Label nrl;
private IModel<Set<OWLOntology>> ontologies;
private Set<String> selectedObjects;
public SearchResultsPage(PageParameters parameters) {
super(parameters);
setDefaultModel(new SavedSearchLDM(parameters.get(ID).toOptionalInteger()));
}
public SearchResultsPage(IModel<SavedSearches> model) {
super(model);
}
@Override
protected void onDetach() {
super.onDetach();
ontologies.detach();
}
@SuppressWarnings("unchecked")
@Override
protected void onInitialize() {
super.onInitialize();
selectedObjects = new HashSet<String>();
ontologies = new OWLOntologiesLDM(new HashSet<OWLOntology>(new AllOntologiesLDM(true).getObject()));
// rezultati
// forma za checkgroup-ata
final Form<Void> checkForm = new Form<Void>("check_form") {
private static final long serialVersionUID = -2020722279552107114L;
@Override
protected void onConfigure() {
super.onConfigure();
nrl.configure();
setVisible(!nrl.isVisible());
}
@Override
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof ResultSelectedEP) {
ResultSelectedEP payload = (ResultSelectedEP) event.getPayload();
payload.getTarget().add(this);
}
}
};
checkForm.setOutputMarkupId(true);
checkForm.setOutputMarkupPlaceholderTag(true);
add(checkForm);
SavedSearches search = (SavedSearches) getDefaultModelObject();
if (search.getSavedSearches() != null) {
checkForm.add(new SearchWithContextFragment("search_data", "search_with_context_fragment", this, (IModel<SavedSearches>) getDefaultModel()));
} else {
checkForm.add(new MultiLineLabel("search_data", new PropertyModel<String>(getDefaultModel(), "humanReadable")).setEscapeModelStrings(false));
}
// izbirat se vsichki
checkForm.add(new AjaxCheckBox("groupselector", new Model<Boolean>(false)) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
if (getConvertedInput()) {
selectedObjects.addAll(dataProvider.getIndividualIRIs());
} else {
selectedObjects.clear();
}
SavedSearches search = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
search.setAllSelected(getConvertedInput());
send(getPage(), Broadcast.BREADTH, new GroupSelectedEP(target));
}
@Override
protected void onConfigure() {
super.onConfigure();
SavedSearches ss = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
setVisible(ss.getSavedSearchesId() == null && UserSession.get().getUserId() != null);
}
});
dataProvider = new SearchDataProvider((IModel<SavedSearches>) getDefaultModel(), ontologies);
// generirat se zaglaviqta na otdelnite koloni (na baza izbrani property-ta za pokazvane)
RepeatingView rv = new RepeatingView("titles");
checkForm.add(rv);
for (SearchDisplayValues sdv : search.getSearchDisplayValueses()) {
String[] s = sdv.getUriPath().split(",");
String title = null;
if (s.length == 1) {
title = OWLNamedObjectNameLDM.load(OWLOntologiesLDM.getOWLNamedObject(IRI.create(s[s.length - 1]).toURI().toString(), ontologies.getObject()), ontologies);
} else {
title = OWLNamedObjectNameLDM.load(OWLOntologiesLDM.getOWLNamedObject(IRI.create(s[s.length - 2]).toURI().toString(), ontologies.getObject()), ontologies) + " -> " + OWLNamedObjectNameLDM.load(OWLOntologiesLDM.getOWLNamedObject(IRI.create(s[s.length - 1]).toURI().toString(), ontologies.getObject()), ontologies);
}
rv.add(new Label(rv.newChildId(), title));
}
// spisyk s rezultati
DataView<OWLNamedObjectResult<String>> dataView = new SearchResultsDataView<String>("results", search.getObjectUri(), dataProvider, 10) {
private static final long serialVersionUID = -4744872461512107366L;
@Override
protected void populateItem(final Item<OWLNamedObjectResult<String>> bindingItem) {
super.populateItem(bindingItem);
IModel<Boolean> model = new LoadableDetachableModel<Boolean>() {
private static final long serialVersionUID = -5365429009659575302L;
@Override
protected Boolean load() {
return selectedObjects.contains(bindingItem.getModelObject().getIri());
}
};
bindingItem.add(new AjaxCheckBox("check", model) {
private static final long serialVersionUID = 1803734419181574578L;
@Override
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof GroupSelectedEP) {
GroupSelectedEP payload = (GroupSelectedEP) event.getPayload();
payload.getTarget().add(this);
}
}
@Override
protected void onUpdate(AjaxRequestTarget target) {
if (getConvertedInput()) {
selectedObjects.add(bindingItem.getModelObject().getIri());
} else {
selectedObjects.remove(bindingItem.getModelObject().getIri());
}
send(getPage(), Broadcast.BREADTH, new GroupSelectedEP(target));
}
@Override
protected void onConfigure() {
super.onConfigure();
SavedSearches ss = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
setVisible(ss.getSavedSearchesId() == null && UserSession.get().getUserId() != null);
}
});
}
};
checkForm.add(dataView);
checkForm.add(new AjaxPagingNavigator("paging", dataView));
nrl = new Label("no_results", new ResourceModel("no_results")) {
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure() {
super.onConfigure();
dataProvider.detach();
setVisible(dataProvider.size() == 0);
}
};
nrl.setOutputMarkupId(true);
nrl.setOutputMarkupPlaceholderTag(true);
add(nrl);
checkForm.add(new IndicatingAjaxButton("new_search") {
private static final long serialVersionUID = -1504424634823375744L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
SavedSearches search = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
if (search.getSavedSearchesId() == null && selectedObjects.size() > 0) {
for (String s : selectedObjects) {
search.getSearchResultses().add(new SearchResults(search, s));
}
saveSearch();
}
target.appendJavaScript("window.parent.location.hash = 'search_" + search.getSavedSearchesId() + "'");
target.appendJavaScript("window.location = '" + urlFor(FilterPage.class, null) + "'");
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(UserSession.get().getUserId() != null);
}
});
// dobavqne kym izbranite v koshnicata
checkForm.add(new AjaxButton("add_to_selected") {
private static final long serialVersionUID = -1504424634823375744L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
if (selectedObjects.size() == 0) {
send(getPage(), Broadcast.BREADTH, new NotificationEventPayload(target, new StringResourceModel("choose_results", this, null), NotificationType.ERROR));
return;
}
SavedSearches search = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
search.setIsSelected(true);
if (search.getSavedSearchesId() == null) {
for (String s : selectedObjects) {
search.getSearchResultses().add(new SearchResults(search, s));
}
saveSearch();
search = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
}
SelectedResultsFilter filter = new SelectedResultsFilter();
filter.setUserId(UserSession.get().getUserId());
filter.setClassIRI(search.getObjectUri());
if (!StringUtils.isEmpty(UserSession.get().getSearchSessionId())) {
filter.setTag(new StringFilter(STRING_MATCH.IS_EXACTLY, UserSession.get().getSearchSessionId()));
}
List<SelectedResults> results = SelectedResultsHome.getSelectedResults(ScopedEntityManagerFactory.getEntityManager(), filter, null);
Set<String> objectsToAdd = new HashSet<String>();
skip:
for (String s : selectedObjects) {
for (SelectedResults result : results) {
if (s.equals(result.getObjectIri())) {
continue skip;
}
}
objectsToAdd.add(s);
}
if (objectsToAdd.size() > 0) {
List<SelectedResults> newResults = new ArrayList<SelectedResults>();
for (String s : objectsToAdd) {
newResults.add(new SelectedResults(search, UserSession.get().getUser(), search.getObjectUri(), s));
}
Home.persistInOneTransaction(ScopedEntityManagerFactory.getEntityManager(), newResults);
}
PageParameters pp = new PageParameters();
pp.set(ID, search.getSavedSearchesId());
send(getPage(), Broadcast.BREADTH, new NotificationEventPayload(target, new ResourceModel("save_success"), NotificationType.INFO));
send(getPage(), Broadcast.BREADTH, new ResultSelectedEP(target));
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
}
@Override
protected void onConfigure() {
super.onConfigure();
SavedSearches ss = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
setVisible(UserSession.get().getUserId() != null && ss.getSavedSearchesId() == null && UserSession.get().getUserId() != null);
}
});
// pokazvane na izbranite
checkForm.add(new IndicatingAjaxLink<Void>("selected_results") {
private static final long serialVersionUID = 7122622004349298642L;
private transient Integer size;
@Override
protected void onDetach() {
super.onDetach();
size = null;
}
@Override
protected void onInitialize() {
super.onInitialize();
setOutputMarkupId(true).setOutputMarkupPlaceholderTag(true);
}
@Override
public void onClick(AjaxRequestTarget target) {
ModalWindow modal = findParent(IModalWindowContainer.class).getModalWindow();
modal.setTitle(new StringResourceModel("selected_results", this, null));
SavedSearches s = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
SelectedResultsPanel content = new SelectedResultsPanel(modal.getContentId(), s.getObjectUri(), ontologies);
content.add(new AttributeModifier("style", new LoadableDetachableModel<String>() {
private static final long serialVersionUID = 3965123518668161711L;
@Override
protected String load() {
return "width:1000px; height:500px;";
}
}));
modal.setContent(content);
modal.show(target);
}
@Override
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof ResultSelectedEP) {
((ResultSelectedEP) event.getPayload()).getTarget().add(this);
} else if (event.getPayload() instanceof SelectedResultsSubmittedEP) {
SelectedResultsSubmittedEP payload = (SelectedResultsSubmittedEP) event.getPayload();
payload.getTarget().add(this);
findParent(IModalWindowContainer.class).getModalWindow().close(payload.getTarget());
payload.getTarget().appendJavaScript("window.parent.location.hash = 'selected_results_" + UserSession.get().getSearchSessionId() + "'");
}
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(getSize() > 0);
if (isVisible()) {
setBody(new StringResourceModel("selected_results_count", this, null, getSize()));
}
}
private Integer getSize() {
if (size == null) {
if (UserSession.get().getUserId() == null) {
size = 0;
} else {
SelectedResultsFilter filter = new SelectedResultsFilter();
filter.setUserId(UserSession.get().getUserId());
if (!StringUtils.isEmpty(UserSession.get().getSearchSessionId())) {
filter.setTag(new StringFilter(STRING_MATCH.IS_EXACTLY, UserSession.get().getSearchSessionId()));
}
SavedSearches s = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
filter.setClassIRI(s.getObjectUri());
size = SelectedResultsHome.getSelectedResultsCount(ScopedEntityManagerFactory.getEntityManager(), filter).intValue();
}
}
return size;
}
});
}
@Override
public IModel<String> getPageTitle() {
return new StringResourceModel("search_results", this, null);
}
/**
* zapomnqne na tova tyrsene
*/
private void saveSearch() {
SavedSearches search = (SavedSearches) SearchResultsPage.this.getDefaultModelObject();
if (StringUtils.isEmpty(search.getTag())) {
search.setTag(UserSession.get().getSearchSessionId());
}
SavedSearchesHome.persistOrMergeInOneTransaction(ScopedEntityManagerFactory.getEntityManager(), search);
SearchResultsPage.this.setDefaultModel(new SavedSearchLDM(search));
}
@Override
public IModel<String> getDescription() {
return new StringResourceModel("search_results", this, null);
}
@Override
public void renderHead(final IHeaderResponse response) {
super.renderHead(response);
response.renderCSSReference(new PackageResourceReference(CSS.class, "list.css"));
response.renderCSSReference(new PackageResourceReference(CSS.class, "navigation.css"));
}
private static class GroupSelectedEP {
private AjaxRequestTarget target;
public GroupSelectedEP(AjaxRequestTarget target) {
super();
this.target = target;
}
public AjaxRequestTarget getTarget() {
return target;
}
}
/**
* zapomneno tyrsene + contexta mu
* @author hok
*
*/
private static class SearchWithContextFragment extends Fragment {
private static final long serialVersionUID = -3487870384026006950L;
public SearchWithContextFragment(String id, String markupId, MarkupContainer markupProvider, IModel<SavedSearches> model) {
super(id, markupId, markupProvider, model);
model.getObject().setSavedSearches(Home.findById(ScopedEntityManagerFactory.getEntityManager(), model.getObject().getSavedSearches().getSavedSearchesId(), SavedSearches.class));
}
@Override
protected void onInitialize() {
super.onInitialize();
add(new MultiLineLabel("humanReadable", new PropertyModel<String>(getDefaultModel(), "humanReadable")).setEscapeModelStrings(false));
add(new Label("context_uris", new LoadableDetachableModel<String>() {
private static final long serialVersionUID = 6024596146225012475L;
@Override
protected String load() {
SavedSearches s = (SavedSearches) getDefaultModelObject();
List<String> uris = new ArrayList<String>();
for (SearchResults r : s.getSavedSearches().getSearchResultses()) {
uris.add(r.getResult());
}
return StringUtils.join(uris, ", ");
}
}));
add(new MultiLineLabel("contextHumanReadable", new PropertyModel<String>(getDefaultModel(), "savedSearches.humanReadable")).setEscapeModelStrings(false));
}
}
private static class ResultSelectedEP {
private AjaxRequestTarget target;
public ResultSelectedEP(AjaxRequestTarget target) {
super();
this.target = target;
}
public AjaxRequestTarget getTarget() {
return target;
}
}
} | 36.196597 | 317 | 0.712816 |
871bec474f48e76c03429fd2f2b04814623720f8 | 3,070 | /*-
* #%L
* anchor-image-io
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
package org.anchoranalysis.image.io.stack.input;
import java.nio.file.Path;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.anchoranalysis.core.time.OperationContext;
import org.anchoranalysis.image.core.mask.Mask;
import org.anchoranalysis.image.core.stack.Stack;
import org.anchoranalysis.image.io.ImageIOException;
import org.anchoranalysis.image.io.bean.stack.reader.StackReader;
import org.anchoranalysis.image.voxel.binary.values.BinaryValuesInt;
/**
* Utility functions for reading a {@link Mask} from the file-system.
*
* @author Owen Feehan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MaskReader {
/**
* Utility functions for opening a single-channeled stack as a {@link Mask}.
*
* @param stackReader the raster-reader for reading the stack.
* @param path the path the raster is located at.
* @param binaryValues what constitutes <i>on</i> and <i>off</i> voxels in the raster.
* @param context context for reading a stack from the file-system.
* @return a newly created {@link Mask} as read from the file-system.
* @throws ImageIOException if the underlying image cannot be successfully read from the
* file-system.
*/
public static Mask openMask(
StackReader stackReader,
Path path,
BinaryValuesInt binaryValues,
OperationContext context)
throws ImageIOException {
Stack stack = stackReader.readStack(path, context);
if (stack.getNumberChannels() != 1) {
throw new ImageIOException(
String.format(
"There must be exactly one channel, but there are %d",
stack.getNumberChannels()));
}
return new Mask(stack.getChannel(0), binaryValues);
}
}
| 39.87013 | 93 | 0.705537 |
8385dcc40c4fd8b8749798693a7a4be8c04223bb | 1,191 | package com.iotoast.todo.mapper;
import com.iotoast.todo.pojo.IoTodo;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface TodoDao {
/**
* 通过ID查询todo信息
* @return todo信息
*/
@Select("SELECT * FROM io_todo WHERE id = #{id}")
IoTodo findTodoById(@Param("id") String id);
/**
* 查询所有的todo
* @return 返回所有todo
*/
@Select("SELECT * FROM io_todo ")
List<IoTodo> findAllTodo();
/**
* 新增一条todo
*/
@Insert("INSERT INTO io_todo(id,tag_id,group_id,start_time,end_time,done_time,remind_time,title,content,status,is_loop,priority,creator,create_time,update_time) " +
"VALUES(#{id},#{tagId},#{groupId},#{startTime},#{endTime},#{doneTime},#{remindTime},#{title},#{content},#{status},#{isLoop},#{priority},#{creator},#{createTime},#{updateTime})")
void insertTodo(IoTodo todo);
/**
* 更新一条todo
*/
@Update("UPDATE user SET name = #{name},age = #{age},money= #{money} WHERE id = #{id}")
void updateUser();
/**
* 根据ID删除一条todo
* @param id
*/
@Delete("DELETE FROM todo WHERE id = #{id}")
void deleteTodo(@Param("id") int id);
}
| 26.466667 | 197 | 0.607053 |
5d3a46cc056f21d407510ab2ef22a812c942e90d | 122 | package p019d.p273h.p276c.p282f;
/* renamed from: d.h.c.f.e */
/* compiled from: BaseApi */
public interface C12868e {
}
| 17.428571 | 32 | 0.688525 |
d5a639d9971a5349c5213ec108993eb5c64c14ff | 1,149 | package com.study.jpkc.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.jpkc.entity.SectionComment;
import org.apache.ibatis.annotations.Param;
/**
* <p>
* Mapper 接口
* </p>
*
* @author [email protected]
* @since 2021-03-22
*/
public interface SectionCommentMapper extends BaseMapper<SectionComment> {
/**
* 获取根评论按时间顺序排序
* @param sectionId 章节id
* @param page 分页信息
* @return 评论信息
*/
Page<SectionComment> selectBySectionIdWithTime(@Param("sectionId") String sectionId, IPage<SectionComment> page);
/**
* 获取根评论按时间倒叙
* @param sectionId 章节id
* @param page 分页信息
* @return 评论信息
*/
Page<SectionComment> selectBySectionIdWithNew(@Param("sectionId") String sectionId, IPage<SectionComment> page);
/**
* 获取根评论按点赞排序
* @param sectionId 章节id
* @param page 分页信息
* @return 评论信息
*/
Page<SectionComment> selectBySectionIdWithStar(@Param("sectionId") String sectionId, IPage<SectionComment> page);
}
| 26.113636 | 117 | 0.698869 |
e0b13ed884176abc93e6339cdea22a06ab35bb8d | 2,330 | /**
* Copyright 2008-2017 Qualogy Solutions B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qualogy.qafe.presentation;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class BusinessActionItemDataObject extends EventItemDataObject implements Serializable {
private static final long serialVersionUID = 349178336673442712L;
private String businessActionId;
private Map<String, Object> inputValues = new HashMap<String, Object>();
private Map<String, String> outputVariables = new HashMap<String, String>();
private Map<String, Object> internalVariables = new HashMap<String, Object>();
public BusinessActionItemDataObject(final String sessionId, final String appId, final String windowId, final String businessActionId,
final Map<String, Object> inputValues, Map<String, String> outputVariables, Map<String, Object> internalVariables) {
super(sessionId, appId, windowId);
this.businessActionId = businessActionId;
this.inputValues = inputValues;
this.outputVariables = outputVariables;
this.internalVariables = internalVariables;
}
public final String getBusinessActionId() {
return businessActionId;
}
public Map<String, Object> getInputValues() {
return inputValues;
}
public void setInputValues(Map<String, Object> inputValues) {
this.inputValues = inputValues;
}
public Map<String, String> getOutputVariables() {
return outputVariables;
}
public void setOutputVariables(Map<String, String> outputVariables) {
this.outputVariables = outputVariables;
}
/**
* @return the internalVariables
*/
public Map<String, Object> getInternalVariables() {
return internalVariables;
}
}
| 32.816901 | 137 | 0.72618 |
417d2e2a5babc679a27d39d2bf2b2f4b604eb30e | 434 | package topic0.Exercise2;
public class ConnectionFactory extends AbstractFactory{
@Override
public Connection getConnection(String connection) {
if (connection.equalsIgnoreCase("POSTGRE")) {
return new PostgreConnection();
}
if (connection.equalsIgnoreCase("MYSQL")) {
return new MysqlConnection();
}
if (connection.equalsIgnoreCase("ORACLE")) {
return new OracleConnection();
}
return null;
}
}
| 18.869565 | 55 | 0.718894 |
9dda65e4b86148ceabc25615384d6ba8d6d5baa6 | 583 | import java.util.Scanner;
public class Exercicio11 {
public static void main(String[] args)
{
int numero = 0;
Scanner entrada = new Scanner(System.in);
System.out.println("Informe um numero: ");
System.out.println("Antecessor de " + numero + " : " + (numero - 1));
System.out.println("Sucessor de " + numero + " : " + (numero + 1));
System.out.println("Dobro de " + numero + " : " + (Math.pow(numero, 2)));
System.out.println("Metade de " + numero + " : " + (numero / 2));
entrada.close();
}
}
| 29.15 | 81 | 0.545455 |
8124da83e4369c3f426cf9b2ba464fd1eba6481a | 4,118 | /*
* Copyright 2014 Alexey Plotnik
*
* 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.stem.db;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stem.domain.BlobDescriptor;
import org.stem.domain.ExtendedBlobDescriptor;
import org.stem.transport.ops.DeleteBlobMessage;
import org.stem.transport.ops.ReadBlobMessage;
import org.stem.transport.ops.WriteBlobMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class StorageService {
private static final Logger logger = LoggerFactory.getLogger(StorageService.class);
public static final StorageService instance = new StorageService();
private final Map<UUID, WriteController> wControllers;
private final Map<UUID, ReadController> rControllers;
public StorageService() {
wControllers = new HashMap<>(Layout.getInstance().getMountPoints().size());
rControllers = new HashMap<>(Layout.getInstance().getMountPoints().size());
}
@VisibleForTesting
public int getWriteCandidates(UUID disk) {
return wControllers.get(disk).getWriteCandidates();
}
public ExtendedBlobDescriptor write(WriteBlobMessage message) {
ExtendedBlobDescriptor descriptor = writeOnDisk(message);
updateRemoteIndex(descriptor);
return descriptor;
}
public byte[] read(ReadBlobMessage message) {
ReadController controller = rControllers.get(message.disk); // TODO: if not found?
return controller.read(message.fatFileIndex, message.offset, message.length);
}
public void delete(DeleteBlobMessage message) {
ReadController controller = rControllers.get(message.disk); // TODO: find by message directly
ExtendedBlobDescriptor desc = controller.delete(message.fatFileIndex, message.offset);
StorageNodeDescriptor.getMetaStoreClient().deleteReplica(desc.getKey(), message.disk);
}
private void updateRemoteIndex(ExtendedBlobDescriptor descriptor) {
try {
StorageNodeDescriptor.getMetaStoreClient().updateMeta(descriptor);
} catch (Exception e) {
throw new RuntimeException("Error writing index to meta store");
}
}
private ExtendedBlobDescriptor writeOnDisk(WriteBlobMessage message) {
try {
WriteController wc = wControllers.get(message.disk);
if (null == wc)
throw new RuntimeException(String.format("Mount point %s can not be found", message.disk));
BlobDescriptor descriptor = wc.write(message);
ExtendedBlobDescriptor extDescriptor = new ExtendedBlobDescriptor(message.key, message.getBlobSize(), message.disk, descriptor);
return extDescriptor;
} catch (Exception e) {
logger.error("Error writing blob on disk", e);
throw new RuntimeException(e);
}
}
public void submitFF(FatFile ff, MountPoint mp) {
assert ff.isBlank(); // TODO: normal check with Exception throw
WriteController controller = wControllers.get(mp.uuid);
if (null == controller)
throw new RuntimeException("shit happens"); // TODO: shit is bad
controller.submitBlankFF(ff);
}
public void init() {
for (MountPoint mp : Layout.getInstance().getMountPoints().values()) {
WriteController wc = new WriteController(mp);
ReadController rc = new ReadController(mp);
wControllers.put(mp.uuid, wc);
rControllers.put(mp.uuid, rc);
}
}
}
| 37.099099 | 140 | 0.698883 |
225a95aa91a4dc62dca4873711e2725c69593d62 | 744 | package de.nb.federkiel.feature;
import com.google.common.collect.ImmutableSet;
import de.nb.federkiel.interfaces.IFeatureType;
import de.nb.federkiel.interfaces.IFeatureValue;
/**
* A feature type for string feature values.
*
* @author nbudzyn
*/
public class StringFeatureType implements IFeatureType {
@Override
public ImmutableSet<IFeatureValue> getAllPossibleValues() {
return null;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
}
| 19.578947 | 62 | 0.63172 |
aeb7bde6132552a286bc6c6bda51a370d0da168d | 4,964 | /*
* Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product may include a number of subcomponents with separate copyright notices
* and license terms. Your use of these subcomponents is subject to the terms and
* conditions of the subcomponent's license, as noted in the LICENSE file.
*/
package com.vmware.mangle.inventory.helpers;
import static com.vmware.mangle.utils.VCenterAPIEndpoints.REST_VC_HOST;
import static com.vmware.mangle.utils.constants.Constants.URL_PARAM_SEPARATOR;
import static com.vmware.mangle.utils.constants.Constants.URL_QUERY_SEPARATOR;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.vmware.mangle.adapter.VCenterClient;
import com.vmware.mangle.model.Host;
import com.vmware.mangle.model.ResourceList;
import com.vmware.mangle.model.enums.FolderType;
import com.vmware.mangle.model.enums.VCenterResources;
import com.vmware.mangle.utils.VCenterAPIEndpoints;
import com.vmware.mangle.utils.constants.Constants;
import com.vmware.mangle.utils.constants.ErrorConstants;
import com.vmware.mangle.utils.exceptions.MangleException;
/**
* @author chetanc
*/
@Component
public class HostInventoryHelper {
private ClusterInventoryHelper clusterInventoryHelper;
private DCInventoryHelper dcInventoryHelper;
@Autowired
public HostInventoryHelper(ClusterInventoryHelper clusterInventoryHelper, DCInventoryHelper dcInventoryHelper) {
this.clusterInventoryHelper = clusterInventoryHelper;
this.dcInventoryHelper = dcInventoryHelper;
}
public List<Host> getAllHost(VCenterClient client, String clusterName, String dcName, String folderName)
throws MangleException {
String url = REST_VC_HOST;
boolean isQueryAdded = false;
String queryParam = "";
if (StringUtils.hasText(dcName)) {
String dcId = dcInventoryHelper.getDataCenterId(client, dcName);
queryParam = VCenterAPIEndpoints.addDCFilter(dcId);
isQueryAdded = true;
}
if (StringUtils.hasText(clusterName)) {
String clusterId = clusterInventoryHelper.getClusterId(client, clusterName, null);
if (isQueryAdded) {
queryParam += URL_PARAM_SEPARATOR + VCenterAPIEndpoints.addClusterFilter(clusterId);
} else {
queryParam = VCenterAPIEndpoints.addClusterFilter(clusterId);
}
isQueryAdded = true;
}
if (StringUtils.hasText(folderName)) {
String folderId = FolderInventoryHelper.getFolderId(client, folderName, FolderType.HOST.name());
if (isQueryAdded) {
queryParam += URL_PARAM_SEPARATOR + VCenterAPIEndpoints.addFolderFilter(folderId);
} else {
queryParam = VCenterAPIEndpoints.addClusterFilter(folderId);
}
isQueryAdded = true;
}
if (isQueryAdded) {
url += URL_QUERY_SEPARATOR + queryParam;
}
ResponseEntity<?> responseEntity = client.get(url, Constants.HOST_RESOURCE_LIST);
if (responseEntity == null) {
throw new MangleException(
String.format(ErrorConstants.VCENTER_OBJECT_COULD_NOT_FETCH, VCenterResources.HOST));
}
ResourceList<Host> resourceList = (ResourceList<Host>) responseEntity.getBody();
return resourceList == null ? new ArrayList<>() : resourceList.getValue();
}
public Host getHostByName(VCenterClient client, String host, String clusterName, String dcName,
String folderName) throws MangleException {
List<Host> hosts = getAllHost(client, clusterName, dcName, folderName).stream()
.filter(hostObject -> hostObject.getName().equals(host)).collect(Collectors.toList());
if (CollectionUtils.isEmpty(hosts)) {
throw new MangleException(String.format(ErrorConstants.RESOURCE_NOT_FOUND, VCenterResources.HOST, host));
}
if (!CollectionUtils.isEmpty(hosts) && hosts.size() > 1) {
throw new MangleException(
String.format(ErrorConstants.MULTIPLE_RESOURCES_FOUND, VCenterResources.HOST, host));
}
return hosts.get(0);
}
public String getHostId(VCenterClient client, String hostName, String clusterName, String dcName,
String folderName) throws MangleException {
Host host = getHostByName(client, hostName, clusterName, dcName, folderName);
return host.getHost();
}
}
| 41.366667 | 117 | 0.710113 |
2a408c68c30a704bc58cf85c58d5ab14fa050bfb | 791 | package au.edu.ardc.registry.oai.exception;
import au.edu.ardc.registry.exception.APIException;
public abstract class OAIException extends APIException {
public static final String badArgumentCode = "badArgument";
public static final String cannotDisseminateFormatCode = "cannotDisseminateFormat";
public static final String badResumptionTokenCode = "badResumptionToken";
public static final String badVerbCode = "badVerb";
public static final String idDoesNotExistCode = "idDoesNotExist";
public static final String noRecordsMatchCode = "noRecordsMatch";
public static final String noMetadataFormatsCode = "noMetadataFormats";
public static final String noSetHierarchyCode = "noSetHierarchy";
public OAIException() {
super();
}
public abstract String getCode();
}
| 26.366667 | 84 | 0.798989 |
9419a307fe44654c7feb7479a3209012dce1a2c1 | 492 | package com.blueskykong.lottor.core.netty;
import com.blueskykong.lottor.common.config.TxConfig;
/**
*
*/
public interface NettyClientService {
/**
* 启动netty客户端
*
* @param txConfig 配置信息
*/
void start(TxConfig txConfig);
/**
* 停止服务
*/
void stop();
/**
* 连接netty服务
*/
void doConnect();
/**
* 重启
*/
void restart();
/**
* 检查状态
*
* @return TRUE 正常
*/
boolean checkState();
}
| 11.714286 | 53 | 0.502033 |
853116e142adc27b2a13f7dd29462a505d16c100 | 402 | package com.damon.appwheel.model.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 各种转换方法的工具类
* Created by yao on 2016/10/2.
*/
public class ModelConvertUtils {
public static <T> ArrayList<T> array2List(T[] array) {
List<T> list = Arrays.asList(array);
ArrayList<T> arrayList = new ArrayList<>(list);
return arrayList;
}
}
| 18.272727 | 58 | 0.664179 |
2ad0fdcf63ea83eb7ee904efe387203f1942a7b0 | 790 | package com.sf.minesweeper.timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.sf.minesweeper.panel.MineState;
import com.sf.minesweeper.tools.Tools;
public class Timers implements ActionListener{
private int times;
MineState mineState;
public Timers(MineState mineState){
this.mineState = mineState;
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Tools.time++;
if(Tools.time>999){
Tools.time=999;
}else{
int g = Tools.time%10;
int s = Tools.time/10%10;
int b = Tools.time/100;
mineState.getUsedtimeG().setIcon(Tools.timeCount[g]);
mineState.getUsedtimeS().setIcon(Tools.timeCount[s]);
mineState.getUsedtimeB().setIcon(Tools.timeCount[b]);
}
}
}
| 21.351351 | 56 | 0.726582 |
d0c7202d5f4fe59457e0479ddf8332e1890cef60 | 1,765 | package com.example.liangwenchao.appdemo.ui.view.fragment;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import com.example.liangwenchao.appdemo.R;
import com.example.liangwenchao.appdemo.ui.base.fragment.BaseFragment;
/**
* Created by admin on 2016/5/10.
*/
public class CalculatorFragment extends BaseFragment {
private GridLayout gridLayout;
private String[] chars = new String[]{
"7", "8", "9", "/",
"4", "5", "6", "*",
"3", "2", "1", "-",
".", "0", "=", "+"
};
public final static String CALCULATOR_FRAGMENT_TAG = "CalculatorFragment";
@Override
public View inflateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_calculator, null);
}
@Override
public void initView(View view) {
gridLayout = (GridLayout) view.findViewById(R.id.root);
for (int i = 0; i < chars.length; i++) {
Button button = new Button(getActivity());
button.setText(chars[i]);
button.setTextSize(40);
button.setPadding(5, 35, 5, 35);
GridLayout.Spec rowSpec = GridLayout.spec(i / 4 + 2);
GridLayout.Spec columnSpec = GridLayout.spec(i % 4);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
if(chars[i].equals("8")){
}
params.setGravity(Gravity.FILL_HORIZONTAL);
gridLayout.addView(button,params);
}
}
@Override
public void initData() {
}
}
| 28.934426 | 102 | 0.630595 |
6c3b39a7836a324a8b8ec08ddde66687dc287c22 | 603 | package com.techelevator.model;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class BeerTypeTest {
private BeerType testBeerType;
@Before
public void setUp() {
testBeerType = new BeerType();
}
@Test
public void sameTypesAreSame() {
BeerType actual = new BeerType();
assertEquals(testBeerType.getId(), actual.getId());
assertEquals(testBeerType.getName(), actual.getName());
}
@Test
public void diffTypesAreDiff() {
BeerType actual = new BeerType();
actual.setName("wrong beer");
assertNotEquals(testBeerType, actual);
}
}
| 18.272727 | 57 | 0.719735 |
4804804641004f4c91a131d1d3cc4f08ec67e587 | 883 | /**
*
*/
package org.hamster.weixinmp.dao.entity.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hamster.weixinmp.config.WxConfig;
import org.hamster.weixinmp.dao.entity.base.WxBaseEntity;
import com.google.gson.annotations.SerializedName;
/**
* @author [email protected]
* @version Dec 30, 2013
*
*/
@Entity
@Table(name = WxConfig.TABLE_PREFIX + "user_group")
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class WxGroupEntity extends WxBaseEntity {
@SerializedName("id")
@Column(name="wx_id", nullable=false)
private Long wxId;
@Column(name="name", length=WxConfig.COL_LEN_TITLE, nullable=false)
private String name;
@Column(name="count", nullable=false)
private String count;
}
| 23.236842 | 68 | 0.771234 |
95e50cbb4ef6d7ae8a4d33f3bfe774c45f8b6978 | 332 | package com.imran.SpringBoot.service;
import java.util.List;
import com.imran.SpringBoot.dto.Products;
public interface ProductService
{
List<Products> findAllProducts();
List<Products> deleteProduct(int id);
List<Products> updateProduct(int id, Products product);
List<Products> addProduct(Products product);
}
| 23.714286 | 57 | 0.762048 |
a64385cfe8d5b22464cd3a13d39a0f95f900c7a7 | 10,216 | package com.rfin.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import org.junit.Test;
import org.mockito.Mockito;
import com.rfin.constants.TransferStatus;
import com.rfin.domain.*;
import com.rfin.dto.*;
import com.rfin.error.InvalidTransferException;
import com.rfin.repository.ITransactionManager;
import com.rfin.repository.ITransferRepository;
import com.rfin.validator.ValidationResult;
public class TransferServiceTest {
@Test
public void should_commit_and_return_successful_transaction() {
TransferRequest transferRequest = new TransferRequest(1, 2, "INR", new BigDecimal(15000), "Rent");
var accounts = new ArrayList<Account>();
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
var validationResult = new ArrayList<ValidationResult>();
TransferResponse transferReponse = null;
try {
accounts.add(new Account(1, "ONE", "INR", 4000, true));
accounts.add(new Account(2, "TWO", "INR", 50, true));
Mockito.when(mockRepository.getAccountDetails(1, 2))
.thenReturn(accounts);
Mockito.when(mockValidationService.getResult(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
.thenReturn(validationResult);
Mockito.when(mockRepository.transfer(org.mockito.ArgumentMatchers.any()))
.thenReturn(new Transaction("abadaf", true, null));
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferReponse = transferService.transfer(transferRequest);
Mockito.verify(mockTransactionManager, Mockito.times(1)).commit();
} catch (Exception e) {
fail("Trasfer succesful test failed");
}
assertNotNull(transferReponse.id());
assertEquals(null, transferReponse.message());
assertEquals(TransferStatus.SUCCESS, transferReponse.status());
}
@Test
public void should_return_tansfer_failure_when_validation_fails() {
TransferRequest transferRequest = new TransferRequest(1, 2, "INR", new BigDecimal(15000), "Rent");
var accounts = new ArrayList<Account>();
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
var validationResult = new ArrayList<ValidationResult>();
validationResult.add(new ValidationResult(false, "Something is fishy"));
TransferResponse transferReponse = null;
try {
accounts.add(new Account(1, "ONE", "INR", 4000, true));
accounts.add(new Account(2, "TWO", "INR", 50, true));
Mockito.when(mockRepository.getAccountDetails(1, 2))
.thenReturn(accounts);
Mockito.when(mockValidationService.getResult(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
.thenReturn(validationResult);
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferReponse = transferService.transfer(transferRequest);
Mockito.verify(mockTransactionManager, Mockito.times(0)).commit();
} catch (Exception e) {
fail("Transfer valdiation error test failed");
}
assertNull(transferReponse.id());
assertNotNull(transferReponse.message());
assertEquals(TransferStatus.FAILURE, transferReponse.status());
}
@Test
public void should_rollback_tansaction_when_repository_throws_exception() {
TransferRequest transferRequest = new TransferRequest(1, 2, "INR", new BigDecimal(15000), "Rent");
var accounts = new ArrayList<Account>();
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
var validationResult = new ArrayList<ValidationResult>();
try {
accounts.add(new Account(1, "ONE", "INR", 4000, true));
accounts.add(new Account(2, "TWO", "INR", 50, true));
Mockito.when(mockRepository.getAccountDetails(1, 2))
.thenReturn(accounts);
Mockito.when(mockRepository.transfer(org.mockito.ArgumentMatchers.any())).thenThrow(new SQLException("failed"));
Mockito.when(mockValidationService.getResult(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
.thenReturn(validationResult);
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (SQLException e) {} catch (InvalidTransferException e) {
fail("Transfer test for failure.");
}
try {
Mockito.verify(mockTransactionManager, Mockito.times(0)).commit();
Mockito.verify(mockTransactionManager, Mockito.times(1)).rollback();
} catch (Exception e) {
fail("Tranfer failed verification failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_source_account_is_invalid() {
TransferRequest transferRequest = new TransferRequest(-100, 2, "INR", new BigDecimal(15000), "Rent");
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("Source account for transfer is invalid",e.getMessage());
} catch (Exception e) {
fail("Invalid source account test failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_destination_account_is_invalid() {
TransferRequest transferRequest = new TransferRequest(2, -100, "INR", new BigDecimal(15000), "Rent");
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("Destination account for transfer is invalid",e.getMessage());
} catch (Exception e) {
fail("Invalid destination account test failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_amount_is_invalid() {
TransferRequest transferRequest = new TransferRequest(2, 1, "INR", new BigDecimal(-10), "Rent");
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("The amount cannot be transferred.",e.getMessage());
} catch (Exception e) {
fail("Invalid amount test failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_currency_is_invalid() {
TransferRequest transferRequest = new TransferRequest(1, 2, "adfdf", new BigDecimal(10), "Rent");
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("The currency adfdf is not supported",e.getMessage());
} catch (Exception e) {
fail("Invalid currency code test failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_one_of_the_account_does_not_exist() {
TransferRequest transferRequest = new TransferRequest(1, 2, "INR", new BigDecimal(10), "Rent");
var accounts = new ArrayList<Account>();
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
accounts.add(new Account(1, "One", "INR", 50, true));
Mockito.when(mockRepository.getAccountDetails(1, 2))
.thenReturn(accounts);
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("Accounts for transfer are invalid",e.getMessage());
} catch (Exception e) {
fail("Invalid account for transfer failed");
}
}
@Test
public void should_throw_invalid_tranfer_exception_when_one_account_doesn_not_support_the_currency() {
TransferRequest transferRequest = new TransferRequest(1, 2, "INR", new BigDecimal(10), "Rent");
var accounts = new ArrayList<Account>();
var mockTransactionManager = Mockito.mock(ITransactionManager.class);
var mockValidationService = Mockito.mock(IValidationService.class);
var mockRepository = Mockito.mock(ITransferRepository.class);
try {
accounts.add(new Account(1, "One", "INR", 50, true));
accounts.add(new Account(1, "One", "USD", 50, true));
Mockito.when(mockRepository.getAccountDetails(1, 2))
.thenReturn(accounts);
var transferService = new TransferService(mockTransactionManager, mockValidationService, mockRepository);
transferService.transfer(transferRequest);
} catch (InvalidTransferException e) {
assertEquals("Transfer currency is not supported in both the accounts",e.getMessage());
} catch (Exception e) {
fail("Unsupported currency for transfer failed");
}
}
}
| 39.750973 | 120 | 0.763508 |
64dbeae61c46675480f4d4eca65b5dce123c7bf9 | 2,975 | package com.zebrunner.reporting.web.documented;
import com.zebrunner.reporting.domain.dto.errors.ErrorResponse;
import com.zebrunner.reporting.domain.entity.integration.IntegrationInfo;
import com.zebrunner.reporting.domain.entity.integration.IntegrationPublicInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.List;
import java.util.Map;
@Api("Integrations info API")
public interface IntegrationInfoDocumentedController {
@ApiOperation(
value = "Retrieves all integration connections info grouped by integration types",
notes = "Returns all core integration attributes and groups them by integration type names",
nickname = "getIntegrationsInfo",
httpMethod = "GET",
response = Map.class
)
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", paramType = "header", required = true, value = "The auth token (Bearer)")
})
@ApiResponses({
@ApiResponse(code = 200, message = "Returns found integrations", response = Map.class)
})
Map<String, Map<String, List<IntegrationInfo>>> getIntegrationsInfo();
@ApiOperation(
value = "Retrieves public integrations information",
notes = "Information contains name, icon and url of integration",
nickname = "getPublicInfos",
httpMethod = "GET",
response = List.class
)
@ApiResponses({
@ApiResponse(code = 200, message = "Returns found integrations", response = List.class)
})
List<IntegrationPublicInfo> getPublicInfos();
@ApiOperation(
value = "Retrieves integration connections info by id",
notes = "Returns the core attributes of the integration by its id and the group it belongs to",
nickname = "getIntegrationsInfoById",
httpMethod = "GET",
response = IntegrationInfo.class
)
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", paramType = "header", required = true, value = "The auth token (Bearer)"),
@ApiImplicitParam(name = "id", paramType = "path", dataTypeClass = Long.class, required = true, value = "The integration id"),
@ApiImplicitParam(name = "groupName", paramType = "query", dataType = "string", required = true, value = "The integration group name")
})
@ApiResponses({
@ApiResponse(code = 200, message = "Returns the found integration", response = IntegrationInfo.class),
@ApiResponse(code = 404, message = "Indicates that the integration cannot be found, and its information cannot be obtained", response = ErrorResponse.class)
})
IntegrationInfo getIntegrationsInfoById(Long id, String groupName);
}
| 45.769231 | 168 | 0.688403 |
699e37f6689c22b788ea1e9549470cb33aebdf75 | 16,217 | package com.android.vending.billing.InAppBillingService.LACK.widgets;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.android.vending.billing.InAppBillingService.LACK.BindItem;
import com.android.vending.billing.InAppBillingService.LACK.BinderActivity;
import com.android.vending.billing.InAppBillingService.LACK.listAppsFragment;
import com.chelpus.Utils;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
public class BinderWidget
extends AppWidgetProvider
{
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidgetBinder";
public static String ACTION_WIDGET_RECEIVER_Updater = "ActionReceiverWidgetBinderUpdate";
public static BinderWidget widget = null;
public static void pushWidgetUpdate(Context paramContext, RemoteViews paramRemoteViews)
{
ComponentName localComponentName = new ComponentName(paramContext, BinderWidget.class);
AppWidgetManager.getInstance(paramContext).updateAppWidget(localComponentName, paramRemoteViews);
}
static void updateAppWidget(Context paramContext, AppWidgetManager paramAppWidgetManager, final int paramInt)
{
listAppsFragment.init();
paramContext = new Thread(new Runnable()
{
public void run()
{
RemoteViews localRemoteViews = new RemoteViews(this.val$context.getPackageName(), 2130968589);
Object localObject1 = new Intent(this.val$context, BinderWidget.class);
((Intent)localObject1).setAction(BinderWidget.ACTION_WIDGET_RECEIVER);
((Intent)localObject1).putExtra("appWidgetId", paramInt);
localRemoteViews.setOnClickPendingIntent(2131558449, PendingIntent.getBroadcast(this.val$context, paramInt, (Intent)localObject1, 0));
localRemoteViews.setInt(2131558448, "setBackgroundResource", 2130837585);
localRemoteViews.setTextColor(2131558447, Color.parseColor("#AAAAAA"));
localRemoteViews.setTextViewText(2131558447, "wait");
try
{
AppWidgetManager.getInstance(this.val$context).updateAppWidget(paramInt, localRemoteViews);
if (listAppsFragment.su)
{
localObject1 = BinderWidgetConfigureActivity.loadTitlePref(this.val$context, paramInt);
System.out.println((String)localObject1);
localObject1 = new BindItem(((String)localObject1).replaceAll("~chelpus_disabled~", ""));
if ((((BindItem)localObject1).TargetDir != null) && (!((BindItem)localObject1).TargetDir.equals("")) && (((BindItem)localObject1).SourceDir != null) && (!((BindItem)localObject1).SourceDir.equals("")))
{
Object localObject2 = ((BindItem)localObject1).TargetDir.split("/");
localRemoteViews.setTextViewText(2131558447, localObject2[(localObject2.length - 1)]);
if (Utils.checkBind((BindItem)localObject1))
{
localRemoteViews.setTextColor(2131558447, Color.parseColor("#00FF00"));
localRemoteViews.setInt(2131558448, "setBackgroundResource", 2130837586);
localObject2 = BinderActivity.getBindes(this.val$context);
i = 0;
localObject2 = ((ArrayList)localObject2).iterator();
while (((Iterator)localObject2).hasNext())
{
BindItem localBindItem = (BindItem)((Iterator)localObject2).next();
if ((localBindItem.SourceDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", ""))) && (localBindItem.TargetDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", ""))))
{
localBindItem.TargetDir = localBindItem.TargetDir.replaceAll("~chelpus_disabled~", "");
localBindItem.SourceDir = localBindItem.SourceDir.replaceAll("~chelpus_disabled~", "");
i = 1;
}
}
}
}
}
}
catch (Exception localException3)
{
int i;
for (;;)
{
localException3.printStackTrace();
continue;
localRemoteViews.setTextColor(2131558447, Color.parseColor("#FF0000"));
localRemoteViews.setInt(2131558448, "setBackgroundResource", 2130837585);
}
if (i == 0)
{
if (!listAppsFragment.su) {
break label558;
}
Utils.run_all("umount -f '" + localException3.TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
Utils.run_all("umount -l '" + localException3.TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
}
for (;;)
{
localRemoteViews.setInt(2131558448, "setBackgroundResource", 2130837585);
localRemoteViews.setTextColor(2131558447, Color.parseColor("#AAAAAA"));
localRemoteViews.setTextViewText(2131558447, "unknown bind");
try
{
AppWidgetManager.getInstance(this.val$context).updateAppWidget(paramInt, localRemoteViews);
try
{
AppWidgetManager.getInstance(this.val$context).updateAppWidget(paramInt, localRemoteViews);
return;
}
catch (Exception localException1)
{
label558:
localException1.printStackTrace();
return;
}
Utils.cmd(new String[] { "umount '" + localException3.TargetDir.replaceAll("~chelpus_disabled~", "") + "'" });
}
catch (Exception localException4)
{
for (;;)
{
localException4.printStackTrace();
}
}
}
localException1.setInt(2131558448, "setBackgroundResource", 2130837585);
localException1.setTextColor(2131558447, Color.parseColor("#AAAAAA"));
localException1.setTextViewText(2131558447, "you need root access");
try
{
AppWidgetManager.getInstance(this.val$context).updateAppWidget(paramInt, localException1);
return;
}
catch (Exception localException2)
{
localException2.printStackTrace();
}
}
}
});
paramContext.setPriority(10);
paramContext.start();
}
public void onDeleted(Context paramContext, int[] paramArrayOfInt)
{
int j = paramArrayOfInt.length;
int i = 0;
while (i < j)
{
BinderWidgetConfigureActivity.deleteTitlePref(paramContext, paramArrayOfInt[i]);
i += 1;
}
}
public void onDisabled(Context paramContext) {}
public void onEnabled(Context paramContext) {}
public void onReceive(final Context paramContext, final Intent paramIntent)
{
super.onReceive(paramContext, paramIntent);
String str = paramIntent.getAction();
final Handler localHandler;
if (ACTION_WIDGET_RECEIVER.equals(str))
{
listAppsFragment.init();
if (!BinderWidgetConfigureActivity.loadTitlePref(paramContext, paramIntent.getIntExtra("appWidgetId", -1)).equals("NOT_SAVED_BIND")) {
widget = this;
}
localHandler = new Handler();
}
try
{
paramIntent = new Thread(new Runnable()
{
public void run()
{
listAppsFragment.binder_process = true;
Utils.exitRoot();
int j = paramIntent.getIntExtra("appWidgetId", -1);
final Object localObject1;
Object localObject2;
ArrayList localArrayList;
int i;
Iterator localIterator;
BindItem localBindItem;
if ((j != -1) && (!BinderWidgetConfigureActivity.loadTitlePref(paramContext, j).equals("NOT_SAVED_BIND")))
{
localObject1 = new BindItem(BinderWidgetConfigureActivity.loadTitlePref(paramContext, j));
localObject2 = new RemoteViews(paramContext.getPackageName(), 2130968589);
((BindItem)localObject1).TargetDir = ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "");
((BindItem)localObject1).SourceDir = ((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", "");
if (Utils.checkBind((BindItem)localObject1)) {
break label623;
}
localArrayList = BinderActivity.getBindes(paramContext);
i = 0;
localIterator = localArrayList.iterator();
while (localIterator.hasNext())
{
localBindItem = (BindItem)localIterator.next();
if ((localBindItem.SourceDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", ""))) && (localBindItem.TargetDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", ""))))
{
localBindItem.TargetDir = localBindItem.TargetDir.replaceAll("~chelpus_disabled~", "");
localBindItem.SourceDir = localBindItem.SourceDir.replaceAll("~chelpus_disabled~", "");
BinderWidgetConfigureActivity.saveTitlePref(paramContext, j, localBindItem.toString());
i = 1;
}
}
if (i == 0)
{
if (!listAppsFragment.su) {
break label575;
}
Utils.run_all("umount -f '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
Utils.run_all("umount -l '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
((RemoteViews)localObject2).setInt(2131558448, "setBackgroundResource", 2130837585);
((RemoteViews)localObject2).setTextColor(2131558447, Color.parseColor("#AAAAAA"));
}
BinderActivity.savetoFile(localArrayList, paramContext);
Utils.verify_bind_and_run("mount", "-o bind '" + ((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", "") + "' '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'", ((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", ""), ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", ""));
label456:
if (!Utils.checkBind((BindItem)localObject1)) {
break label1099;
}
((RemoteViews)localObject2).setTextColor(2131558447, Color.parseColor("#00FF00"));
((RemoteViews)localObject2).setInt(2131558448, "setBackgroundResource", 2130837586);
localHandler.post(new Runnable()
{
public void run()
{
Toast.makeText(BinderWidget.2.this.val$context, "ON " + localObject1.TargetDir.replaceAll("~chelpus_disabled~", ""), 0).show();
}
});
}
for (;;)
{
new ComponentName(paramContext, BinderWidget.class);
AppWidgetManager.getInstance(paramContext).updateAppWidget(j, (RemoteViews)localObject2);
localObject1 = AppWidgetManager.getInstance(paramContext);
localObject2 = ((AppWidgetManager)localObject1).getAppWidgetIds(new ComponentName(paramContext, BinderWidget.class));
BinderWidget.widget.onUpdate(paramContext, (AppWidgetManager)localObject1, (int[])localObject2);
listAppsFragment.binder_process = false;
return;
label575:
Utils.cmd(new String[] { "umount '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'" });
break;
label623:
((BindItem)localObject1).TargetDir = ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "");
((BindItem)localObject1).SourceDir = ((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", "");
localArrayList = BinderActivity.getBindes(paramContext);
i = 0;
localIterator = localArrayList.iterator();
while (localIterator.hasNext())
{
localBindItem = (BindItem)localIterator.next();
if ((localBindItem.SourceDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).SourceDir.replaceAll("~chelpus_disabled~", ""))) && (localBindItem.TargetDir.replaceAll("~chelpus_disabled~", "").equals(((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", ""))))
{
localBindItem.TargetDir = ("~chelpus_disabled~" + localBindItem.TargetDir.replaceAll("~chelpus_disabled~", ""));
localBindItem.SourceDir = localBindItem.SourceDir;
i = 1;
}
}
if (i == 0)
{
if (listAppsFragment.su)
{
Utils.run_all("umount -f '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
Utils.run_all("umount -l '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
}
for (;;)
{
((RemoteViews)localObject2).setInt(2131558448, "setBackgroundResource", 2130837585);
((RemoteViews)localObject2).setTextColor(2131558447, Color.parseColor("#AAAAAA"));
break;
Utils.cmd(new String[] { "umount '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'" });
}
}
BinderActivity.savetoFile(localArrayList, paramContext);
if (listAppsFragment.su)
{
Utils.run_all("umount -f '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
Utils.run_all("umount -l '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'");
break label456;
}
Utils.cmd(new String[] { "umount '" + ((BindItem)localObject1).TargetDir.replaceAll("~chelpus_disabled~", "") + "'" });
break label456;
label1099:
((RemoteViews)localObject2).setTextColor(2131558447, Color.parseColor("#FF0000"));
((RemoteViews)localObject2).setInt(2131558448, "setBackgroundResource", 2130837585);
localHandler.post(new Runnable()
{
public void run()
{
Toast.makeText(BinderWidget.2.this.val$context, "OFF " + localObject1.TargetDir.replaceAll("~chelpus_disabled~", ""), 0).show();
}
});
}
}
});
paramIntent.setPriority(10);
if (!listAppsFragment.binder_process) {
paramIntent.start();
}
if (ACTION_WIDGET_RECEIVER_Updater.equals(str))
{
listAppsFragment.binderWidget = true;
paramIntent = AppWidgetManager.getInstance(paramContext);
onUpdate(paramContext, paramIntent, paramIntent.getAppWidgetIds(new ComponentName(paramContext, BinderWidget.class)));
}
return;
}
catch (NullPointerException paramIntent)
{
for (;;)
{
paramIntent.printStackTrace();
}
}
}
public void onUpdate(Context paramContext, AppWidgetManager paramAppWidgetManager, int[] paramArrayOfInt)
{
int j = paramArrayOfInt.length;
int i = 0;
while (i < j)
{
updateAppWidget(paramContext, paramAppWidgetManager, paramArrayOfInt[i]);
i += 1;
}
}
}
/* Location: /Users/sundayliu/Desktop/gamecheat/com.android.vending.billing.InAppBillingService.LACK-1/classes-dex2jar.jar!/com/android/vending/billing/InAppBillingService/LACK/widgets/BinderWidget.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 47.418129 | 368 | 0.621632 |
2308e01d4e219593729f12448d4d86b1ebb5cded | 10,551 | /*
* 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.jclouds.cloudstack.features;
import static org.jclouds.reflect.Reflection2.method;
import java.io.IOException;
import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;
import org.jclouds.Fallbacks.NullOnNotFoundOr404;
import org.jclouds.cloudstack.internal.BaseCloudStackApiTest;
import org.jclouds.cloudstack.options.CreateIPForwardingRuleOptions;
import org.jclouds.cloudstack.options.ListIPForwardingRulesOptions;
import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseFirstJsonValueNamed;
import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.Invokable;
/**
* Tests behavior of {@code NATApi}
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire
@Test(groups = "unit", testName = "NATApiTest")
public class NATApiTest extends BaseCloudStackApiTest<NATApi> {
public void testListIPForwardingRules() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "listIPForwardingRules", ListIPForwardingRulesOptions[].class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
}
public void testListIPForwardingRulesOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "listIPForwardingRules", ListIPForwardingRulesOptions[].class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
ListIPForwardingRulesOptions.Builder.virtualMachineId("3")));
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true&virtualmachineid=3 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
}
public void testGetIPForwardingRule() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "getIPForwardingRule", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true&id=5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(httpRequest);
}
HttpRequest createIpForwardingRule = HttpRequest.builder().method("GET")
.endpoint("http://localhost:8080/client/api")
.addQueryParam("response", "json")
.addQueryParam("command", "createIpForwardingRule")
.addQueryParam("ipaddressid", "7")
.addQueryParam("protocol", "tcp")
.addQueryParam("startport", "22").build();
public void testCreateIPForwardingRuleForVirtualMachine() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(NATApi.class, "createIPForwardingRule", String.class, String.class, int.class,
CreateIPForwardingRuleOptions[].class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(7, "tcp", 22));
assertRequestLineEquals(httpRequest, createIpForwardingRule.getRequestLine());
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest);
}
HttpRequest createIpForwardingRuleOptions = HttpRequest.builder().method("GET")
.endpoint("http://localhost:8080/client/api")
.addQueryParam("response", "json")
.addQueryParam("command", "createIpForwardingRule")
.addQueryParam("ipaddressid", "7")
.addQueryParam("protocol", "tcp")
.addQueryParam("startport", "22")
.addQueryParam("endport", "22").build();
public void testCreateIPForwardingRuleForVirtualMachineOptions() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(NATApi.class, "createIPForwardingRule", String.class, String.class, int.class,
CreateIPForwardingRuleOptions[].class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(7, "tcp", 22,
CreateIPForwardingRuleOptions.Builder.endPort(22)));
assertRequestLineEquals(httpRequest, createIpForwardingRuleOptions.getRequestLine());
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest);
}
public void testEnableStaticNATForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "enableStaticNATForVirtualMachine", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, 6));
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=enableStaticNat&virtualmachineid=5&ipaddressid=6 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest);
}
public void testDisableStaticNATOnPublicIP() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "disableStaticNATOnPublicIP", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=disableStaticNat&ipaddressid=5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest);
}
public void testDeleteIPForwardingRule() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(NATApi.class, "deleteIPForwardingRule", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));
assertRequestLineEquals(httpRequest,
"GET http://localhost:8080/client/api?response=json&command=deleteIpForwardingRule&id=5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(httpRequest);
}
}
| 52.492537 | 137 | 0.715003 |
6ab90c696368880bd86b1d5c32f41ca6d615a389 | 1,010 | /* Import1: A Maze-Solving Game */
package studio.ignitionigloogames.twistedtrek.import1.items.combat;
import studio.ignitionigloogames.twistedtrek.import1.effects.Effect;
import studio.ignitionigloogames.twistedtrek.import1.items.Item;
import studio.ignitionigloogames.twistedtrek.import1.items.ItemCategoryConstants;
public abstract class CombatUsableItem extends Item {
// Fields
private final char target;
protected Effect e;
protected String sound;
// Constructors
public CombatUsableItem(final String itemName, final int itemBuyPrice, final char itemTarget) {
super(itemName, ItemCategoryConstants.ITEM_CATEGORY_USABLE, 1, 0);
this.setCombatUsable(true);
this.setBuyPrice(itemBuyPrice);
this.target = itemTarget;
this.defineFields();
}
// Methods
public char getTarget() {
return this.target;
}
public Effect getEffect() {
return this.e;
}
public String getSound() {
return this.sound;
}
protected abstract void defineFields();
} | 27.297297 | 99 | 0.753465 |
38de7f1d70dd3c652182853c54a499f8eaf4a761 | 1,586 | package com.bigdata.datashops.server.worker.executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bigdata.datashops.common.utils.FileUtils;
import com.bigdata.datashops.common.utils.JSONUtils;
import com.bigdata.datashops.model.pojo.job.JobInstance;
import com.bigdata.datashops.protocol.GrpcRequest;
import com.bigdata.datashops.server.job.AbstractJob;
import com.bigdata.datashops.server.job.JobManager;
import com.bigdata.datashops.server.utils.LogUtils;
public class JobExecutor implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(JobExecutor.class);
private AbstractJob job;
private GrpcRequest.Request request;
private JobManager jobManager;
public JobExecutor(GrpcRequest.Request request, JobManager jobManager) {
this.request = request;
this.jobManager = jobManager;
}
@Override
public void run() {
LOG.info("Run job from={}, id={}", request.getIp(), request.getRequestId());
String body = request.getBody().toStringUtf8();
JobInstance instance = JSONUtils.parseObject(body, JobInstance.class);
Logger logger = LogUtils.getLogger("INFO", FileUtils.getJobExecLogDir(), instance.getInstanceId() + ".log",
instance.getInstanceId() + ".log.%d{yyyyMMdd}.gz");
logger.info("Run job from={}, id={}", request.getIp(), request.getRequestId());
job = jobManager.createJob(instance, logger);
try {
job.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 35.244444 | 115 | 0.701765 |
c96e7d6b5473356524c476e76790abeaab687fbb | 30,922 | package edu.cmu.ml.proppr.util;
import java.util.Arrays;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.log4j.Logger;
import edu.cmu.ml.proppr.learn.tools.FixedWeightRules;
import edu.cmu.ml.proppr.prove.wam.WamProgram;
import edu.cmu.ml.proppr.prove.wam.WamBaseProgram;
import edu.cmu.ml.proppr.prove.wam.plugins.FactsPlugin;
import edu.cmu.ml.proppr.prove.wam.plugins.GraphlikePlugin;
import edu.cmu.ml.proppr.prove.wam.plugins.LightweightGraphPlugin;
import edu.cmu.ml.proppr.prove.wam.plugins.SparseGraphPlugin;
import edu.cmu.ml.proppr.prove.wam.plugins.SplitFactsPlugin;
import edu.cmu.ml.proppr.prove.wam.plugins.WamPlugin;
import edu.cmu.ml.proppr.util.multithreading.Multithreading;
import java.io.*;
/**
* Configuration engine for input files, output files and (for whatever reason) constants/hyperparameters.
*
* For modules (prover, grounder, trainer, tester, etc) see ModuleConfiguration subclass.
* @author "Kathryn Mazaitis <[email protected]>"
*
*/
public class Configuration {
protected static final Logger log = Logger.getLogger(Configuration.class);
public static final int FORMAT_WIDTH=18;
public static final String FORMAT_STRING="%"+FORMAT_WIDTH+"s";
public static final String EXAMPLES_FORMAT = "f(A1,A2)\\t{+|-}f(a1,a2)\\t...";
/* set files */
/** file. */
public static final int USE_QUERIES = 0x1;
public static final int USE_GROUNDED = 0x2;
public static final int USE_ANSWERS = 0x4;
public static final int USE_TRAIN = 0x8;
public static final int USE_TEST = 0x10;
public static final int USE_PARAMS = 0x20;
public static final int USE_GRADIENT = 0x40;
public static final int USE_INIT_PARAMS = 0x80;
public static final String QUERIES_FILE_OPTION = "queries";
public static final String GROUNDED_FILE_OPTION = "grounded";
public static final String SOLUTIONS_FILE_OPTION = "solutions";
public static final String TRAIN_FILE_OPTION = "train";
public static final String TEST_FILE_OPTION = "test";
public static final String PARAMS_FILE_OPTION = "params";
public static final String INIT_PARAMS_FILE_OPTION = "initParams";
public static final String GRADIENT_FILE_OPTION = "gradient";
/* set constants */
/** constant. programFiles, ternaryIndex */
public static final int USE_WAM = 0x1;
/** constant. */
public static final int USE_THREADS = 0x2;
public static final int USE_EPOCHS = 0x4;
public static final int USE_FORCE = 0x10;
public static final int USE_ORDER = 0x20;
public static final int USE_DUPCHECK = 0x40;
public static final int USE_THROTTLE = 0x80;
public static final int USE_EMPTYGRAPHS = 0x100;
public static final int USE_FIXEDWEIGHTS = 0x200;
public static final int USE_COUNTFEATURES = 0x400;
private static final String PROGRAMFILES_CONST_OPTION = "programFiles";
private static final String TERNARYINDEX_CONST_OPTION = "ternaryIndex";
private static final String APR_CONST_OPTION = "apr";
private static final String THREADS_CONST_OPTION = "threads";
private static final String EPOCHS_CONST_OPTION = "epochs";
private static final String FORCE_CONST_OPTION = "force";
private static final String ORDER_CONST_OPTION = "order";
private static final String DUPCHECK_CONST_OPTION = "duplicateCheck";
private static final String THROTTLE_CONST_OPTION = "throttle";
private static final String EMPTYGRAPHS_CONST_OPTION = "includeEmptyGraphs";
private static final String FIXEDWEIGHTS_CONST_OPTION = "fixedWeights";
private static final String COUNTFEATURES_CONST_OPTION = "countFeatures";
// wwc: protected so that ModuleConfiguration can give warnings...
protected static final String PRUNEDPREDICATE_CONST_OPTION = "prunedPredicates";
/* set class for module. Options for this section are handled in ModuleConfiguration.java. */
/** module. */
public static final int USE_SQUASHFUNCTION = 0x1;
public static final int USE_GROUNDER = 0x2;
public static final int USE_SRW = 0x4;
public static final int USE_TRAINER = 0x8;
public static final int USE_PROVER = 0x10;
/** */
public static final String PROPFILE = "config.properties";
private static final boolean DEFAULT_COMBINE = true;
private static final int USE_APR = USE_WAM | USE_PROVER | USE_SRW;
private static final int USE_SMART_COUNTFEATURES = USE_COUNTFEATURES | USE_WAM;
public File queryFile = null;
public File testFile = null;
public File groundedFile = null;
public File paramsFile = null;
public File initParamsFile = null;
public File solutionsFile = null;
public File gradientFile = null;
public WamProgram program = null;
public WamPlugin[] plugins = null;
public String[] programFiles = null;
public int nthreads = -1;
public APROptions apr = new APROptions();
public int epochs = 5;
public boolean force = false;
public boolean ternaryIndex = false;
public boolean maintainOrder = true;
public boolean includeEmptyGraphs = false;
public int duplicates = (int) 1e6;
public int throttle = Multithreading.DEFAULT_THROTTLE;
public FixedWeightRules fixedWeightRules = null;
public FixedWeightRules prunedPredicateRules = null;
public boolean countFeatures = true;
private static Configuration instance;
public static Configuration getInstance() { return instance; }
public static void setInstance(Configuration i) {
// if (instance!=null) throw new IllegalStateException("Configuration is a singleton");
instance=i;
}
static boolean isOn(int flags, int flag) {
return (flags & flag) == flag;
}
static boolean anyOn(int flags, int flag) {
return (flags & flag) > 0;
}
protected int inputFiles(int[] flags) { return flags[0]; }
protected int outputFiles(int[] flags) { return flags[1]; }
protected int constants(int[] flags) { return flags[2]; }
protected int modules(int[] flags) { return flags[3]; }
private Configuration() {}
public Configuration(String[] args, int inputFiles, int outputFiles, int constants, int modules) {
setInstance(this);
System.out.println("");
boolean combine = DEFAULT_COMBINE;
int[] flags = {inputFiles, outputFiles, constants, modules};
Options options = new Options();
options.addOption(Option.builder().longOpt("profile")
.desc("Holds all computation & loading until the return key is pressed.")
.build());
addOptions(options, flags);
CommandLine line = null;
try {
DefaultParser parser = new DefaultParser();
// if the user specified a properties file, add those values at the beginning
// (so that command line args override them)
if(combine) args = combinedArgs(args);
// this is terrible: we just read a Properties from a file and serialized it to String[],
// and now we're going to put it back into a Properties object. But Commons CLI
// doesn't know how to handle unrecognized options, so ... that's what we gotta do.
Properties props = new Properties();
for (int i=0; i<args.length; i++) {
if (args[i].startsWith("--")) {
if (!options.hasOption(args[i])) {
System.err.println("Unrecognized option: "+args[i]);
continue; // skip unrecognized options
}
if (i+1 < args.length && !args[i+1].startsWith("--")) {
props.setProperty(args[i], args[i+1]);
i++;
} else props.setProperty(args[i], "true");
}
}
// parse the command line arguments
line = parser.parse(options, new String[0], props);
if (line.hasOption("profile")) {
System.out.println("Holding for profiler setup; press any key to proceed.");
System.in.read();
}
retrieveSettings(line,flags,options);
} catch( Exception exp ) {
if (args[0].equals("--help")) usageOptions(options, flags);
StringWriter sw = new StringWriter();
exp.printStackTrace(new PrintWriter(sw));
usageOptions(options,flags,exp.getMessage()+"\n"+sw.toString());
}
}
protected File getExistingFile(String filename) {
File value = new File(filename);
if (!value.exists()) throw new IllegalArgumentException("File '"+value.getName()+"' must exist");
return value;
}
protected void retrieveSettings(CommandLine line, int[] allFlags, Options options) throws IOException {
int flags;
if (line.hasOption("help")) usageOptions(options, allFlags);
// input files: must exist already
flags = inputFiles(allFlags);
if (isOn(flags,USE_QUERIES) && line.hasOption(QUERIES_FILE_OPTION)) this.queryFile = getExistingFile(line.getOptionValue(QUERIES_FILE_OPTION));
if (isOn(flags,USE_GROUNDED) && line.hasOption(GROUNDED_FILE_OPTION)) this.groundedFile = getExistingFile(line.getOptionValue(GROUNDED_FILE_OPTION));
if (isOn(flags,USE_ANSWERS) && line.hasOption(SOLUTIONS_FILE_OPTION)) this.solutionsFile = getExistingFile(line.getOptionValue(SOLUTIONS_FILE_OPTION));
if (isOn(flags,USE_TEST) && line.hasOption(TEST_FILE_OPTION)) this.testFile = getExistingFile(line.getOptionValue(TEST_FILE_OPTION));
if (isOn(flags,USE_TRAIN) && line.hasOption(TRAIN_FILE_OPTION)) this.queryFile = getExistingFile(line.getOptionValue(TRAIN_FILE_OPTION));
if (isOn(flags,USE_PARAMS) && line.hasOption(PARAMS_FILE_OPTION)) this.paramsFile = getExistingFile(line.getOptionValue(PARAMS_FILE_OPTION));
if (isOn(flags,USE_INIT_PARAMS) && line.hasOption(INIT_PARAMS_FILE_OPTION)) this.initParamsFile = getExistingFile(line.getOptionValue(INIT_PARAMS_FILE_OPTION));
if (isOn(flags,USE_GRADIENT) && line.hasOption(GRADIENT_FILE_OPTION)) this.gradientFile = getExistingFile(line.getOptionValue(GRADIENT_FILE_OPTION));
// output & intermediate files: may not exist yet
flags = outputFiles(allFlags);
if (isOn(flags,USE_QUERIES) && line.hasOption(QUERIES_FILE_OPTION)) this.queryFile = new File(line.getOptionValue(QUERIES_FILE_OPTION));
if (isOn(flags,USE_GROUNDED) && line.hasOption(GROUNDED_FILE_OPTION)) this.groundedFile = new File(line.getOptionValue(GROUNDED_FILE_OPTION));
if (isOn(flags,USE_ANSWERS) && line.hasOption(SOLUTIONS_FILE_OPTION)) this.solutionsFile = new File(line.getOptionValue(SOLUTIONS_FILE_OPTION));
if (isOn(flags,USE_TEST) && line.hasOption(TEST_FILE_OPTION)) this.testFile = new File(line.getOptionValue(TEST_FILE_OPTION));
if (isOn(flags,USE_TRAIN) && line.hasOption(TRAIN_FILE_OPTION)) this.queryFile = new File(line.getOptionValue(TRAIN_FILE_OPTION));
if (isOn(flags,USE_PARAMS) && line.hasOption(PARAMS_FILE_OPTION)) this.paramsFile = new File(line.getOptionValue(PARAMS_FILE_OPTION));
if (isOn(flags,USE_GRADIENT) && line.hasOption(GRADIENT_FILE_OPTION)) this.gradientFile = new File(line.getOptionValue(GRADIENT_FILE_OPTION));
// constants
flags = constants(allFlags);
if (isOn(flags,USE_WAM)) {
if (line.hasOption(PROGRAMFILES_CONST_OPTION)) this.programFiles = line.getOptionValues(PROGRAMFILES_CONST_OPTION);
if (line.hasOption(TERNARYINDEX_CONST_OPTION)) this.ternaryIndex = Boolean.parseBoolean(line.getOptionValue(TERNARYINDEX_CONST_OPTION));
if (line.hasOption(PRUNEDPREDICATE_CONST_OPTION)) {
this.prunedPredicateRules = new FixedWeightRules(line.getOptionValues(PRUNEDPREDICATE_CONST_OPTION));
}
}
if (anyOn(flags,USE_APR))
if (line.hasOption(APR_CONST_OPTION)) this.apr = new APROptions(line.getOptionValues(APR_CONST_OPTION));
if (isOn(flags,USE_THREADS) && line.hasOption(THREADS_CONST_OPTION)) this.nthreads = Integer.parseInt(line.getOptionValue(THREADS_CONST_OPTION));
if (isOn(flags,USE_EPOCHS) && line.hasOption(EPOCHS_CONST_OPTION)) this.epochs = Integer.parseInt(line.getOptionValue(EPOCHS_CONST_OPTION));
if (isOn(flags,USE_FORCE) && line.hasOption(FORCE_CONST_OPTION)) this.force = true;
if (isOn(flags,USE_ORDER) && line.hasOption(ORDER_CONST_OPTION)) {
String order = line.getOptionValue(ORDER_CONST_OPTION);
if (order.equals("same") || order.equals("maintain")) this.maintainOrder = true;
else this.maintainOrder = false;
}
if (anyOn(flags,USE_DUPCHECK|USE_WAM) && line.hasOption(DUPCHECK_CONST_OPTION)) this.duplicates = (int) Double.parseDouble(line.getOptionValue(DUPCHECK_CONST_OPTION));
if (isOn(flags,USE_THROTTLE) && line.hasOption(THROTTLE_CONST_OPTION)) this.throttle = Integer.parseInt(line.getOptionValue(THROTTLE_CONST_OPTION));
if (isOn(flags,USE_EMPTYGRAPHS) && line.hasOption(EMPTYGRAPHS_CONST_OPTION)) this.includeEmptyGraphs = true;
if (isOn(flags,USE_FIXEDWEIGHTS) && line.hasOption(FIXEDWEIGHTS_CONST_OPTION)) this.fixedWeightRules = new FixedWeightRules(line.getOptionValues(FIXEDWEIGHTS_CONST_OPTION));
if (anyOn(flags,USE_SMART_COUNTFEATURES)) {
if (line.hasOption(COUNTFEATURES_CONST_OPTION)) this.countFeatures = Boolean.parseBoolean(line.getOptionValue(COUNTFEATURES_CONST_OPTION));
else if (this.nthreads > 20) {
log.warn("Large numbers of threads (>20, so "+this.nthreads+" qualifies) can cause a bottleneck in FeatureDictWeighter. If you're "+
"seeing lower system loads than expected and you're sure your examples/query/param files are correct, you can reduce contention & increase speed performance by adding "+
"'--"+COUNTFEATURES_CONST_OPTION+" false' to your command line.");
}
}
if (this.programFiles != null) this.loadProgramFiles(line,allFlags,options);
}
/**
* Clears program and plugin list, then loads them from --programFiles option.
* @param flags
* @param options
* @throws IOException
*/
protected void loadProgramFiles(CommandLine line, int[] flags, Options options) throws IOException {
this.program = null;
int nplugins = programFiles.length;
for (String s : programFiles) if (s.endsWith(".wam")) nplugins--;
this.plugins = new WamPlugin[nplugins];
int i=0;
int wam,graph,facts;
wam = graph = facts = 0;
int iFacts = -1;
for (String s : programFiles) {
if (s.endsWith(".wam")) {
if (this.program != null) usageOptions(options,flags,PROGRAMFILES_CONST_OPTION+": Multiple WAM programs not supported");
this.program = WamBaseProgram.load(this.getExistingFile(s));
wam++;
} else if (i>=this.plugins.length) {
usageOptions(options,flags,PROGRAMFILES_CONST_OPTION+": Parser got very confused about how many plugins you specified. Send Katie a bug report!");
} else if (s.endsWith(GraphlikePlugin.FILE_EXTENSION)) {
this.plugins[i++] = LightweightGraphPlugin.load(this.apr, this.getExistingFile(s), this.duplicates);
graph++;
} else if (s.endsWith(FactsPlugin.FILE_EXTENSION)) {
FactsPlugin p = FactsPlugin.load(this.apr, this.getExistingFile(s), this.ternaryIndex, this.duplicates);
if (iFacts<0) {
iFacts = i;
this.plugins[i++] = p;
} else {
SplitFactsPlugin sf;
if (this.plugins[iFacts] instanceof FactsPlugin) {
sf = new SplitFactsPlugin(this.apr);
sf.add((FactsPlugin) this.plugins[iFacts]);
this.plugins[iFacts] = sf;
} else sf = (SplitFactsPlugin) this.plugins[iFacts];
sf.add(p);
}
facts++;
} else if (s.endsWith(SparseGraphPlugin.FILE_EXTENSION)) {
this.plugins[i++] = SparseGraphPlugin.load(this.apr, this.getExistingFile(s));
} else {
usageOptions(options,flags,PROGRAMFILES_CONST_OPTION+": Plugin type for "+s+" unsupported/unknown");
}
}
if (facts>1) { // trim array
this.plugins = Arrays.copyOfRange(this.plugins,0,i);
}
if (graph>1) {
log.warn("Consolidated graph files not yet supported! If the same functor exists in two files, facts in the later file will be hidden from the prover!");
}
}
protected Option checkOption(Option o) {
return o;
}
/**
* For all option flags as specified in this file, addOptions creates
* and adds Option objects to the Options object.
*/
protected void addOptions(Options options, int[] allFlags) {
int flags;
options.addOption(
OptionBuilder
.withLongOpt("help")
.withDescription("Print usage syntax.")
.create());
// input files
flags = inputFiles(allFlags);
if(isOn(flags, USE_QUERIES))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(QUERIES_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Queries. Format (discards after tab): "+EXAMPLES_FORMAT)
.create()));
if (isOn(flags, USE_GROUNDED))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(GROUNDED_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Grounded examples. Format: query\\tkeys,,\\tposList,,\\tnegList,,\\tgraph")
.create()));
if (isOn(flags, USE_TRAIN))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(TRAIN_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Training examples. Format: "+EXAMPLES_FORMAT)
.create()));
if (isOn(flags, USE_TEST))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(TEST_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Testing examples. Format: "+EXAMPLES_FORMAT)
.create()));
if (isOn(flags, USE_PARAMS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(PARAMS_FILE_OPTION)
.withArgName("file")
.hasArg()
.withDescription("Learned walker parameters. Format: feature\\t0.000000")
.create()));
if (isOn(flags, USE_INIT_PARAMS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(INIT_PARAMS_FILE_OPTION)
.withArgName("file")
.hasArg()
.withDescription("Learned walker parameters. Same format as --params, but used to warm-start a learner.")
.create()));
// output files
flags = outputFiles(allFlags);
if(isOn(flags, USE_ANSWERS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(SOLUTIONS_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output answers")
.create()));
if(isOn(flags, USE_QUERIES))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(QUERIES_FILE_OPTION)
.withArgName("file")
.hasArg()
.withDescription("Output queries")
.create()));
if (isOn(flags, USE_GROUNDED))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(GROUNDED_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output grounded examples.")
.create()));
if(isOn(flags, USE_GRADIENT))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(GRADIENT_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output gradient.")
.create()));
if (isOn(flags, USE_TRAIN))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(TRAIN_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output training examples.")
.create()));
if (isOn(flags, USE_TEST))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(TEST_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output testing examples.")
.create()));
if (isOn(flags, USE_PARAMS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(PARAMS_FILE_OPTION)
.isRequired()
.withArgName("file")
.hasArg()
.withDescription("Output learned walker parameters.")
.create()));
// constants
flags = constants(allFlags);
if (isOn(flags, USE_WAM)) {
options.addOption(checkOption(
OptionBuilder
.withLongOpt(PROGRAMFILES_CONST_OPTION)
.withArgName("file:...:file")
.hasArgs()
.withValueSeparator(':')
.withDescription("Description of the logic program. Permitted extensions: .wam, .cfacts, .graph, .sparse")
.create()));
options.addOption(checkOption(
OptionBuilder
.withLongOpt(TERNARYINDEX_CONST_OPTION)
.withArgName("true|false")
.hasArg()
.withDescription("Turn on A1A2 index for facts of arity >= 3.")
.create()));
options.addOption(checkOption(
Option.builder(PRUNEDPREDICATE_CONST_OPTION)
.hasArgs()
.argName("exact[={y|n}]:prefix*")
.valueSeparator(':')
.desc("Specify predicates names that will be pruned by PruningIdDprProver, specified in same format as fixedWeights")
.build()));
}
if (isOn(flags, USE_THREADS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(THREADS_CONST_OPTION)
.withArgName("integer")
.hasArg()
.withDescription("Use x worker threads. (Pls ensure x < #cores)")
.create()));
if (isOn(flags, USE_EPOCHS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(EPOCHS_CONST_OPTION)
.withArgName("integer")
.hasArg()
.withDescription("Use x training epochs (default = 5)")
.create()));
if (isOn(flags, USE_FORCE))
options.addOption(checkOption(
OptionBuilder
.withLongOpt("force")
.withDescription("Ignore errors and run anyway")
.create()));
if (anyOn(flags, USE_APR))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(APR_CONST_OPTION)
.withArgName("options")
.hasArgs()
.withValueSeparator(':')
.withDescription("Pagerank options. Default: eps=1e-4:alph=0.1:depth=5\n"
+ "Syntax: param=value:param=value...\n"
+ "Available parameters:\n"
+ "eps, alph, depth")
.create()));
if (isOn(flags, USE_ORDER))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(ORDER_CONST_OPTION)
.withArgName("o")
.hasArg()
.withDescription("Set ordering of outputs wrt inputs. Valid options:\n"
+"same, maintain (keep input ordering)\n"
+"anything else (reorder outputs to save time/memory)")
.create()
));
if (anyOn(flags, USE_DUPCHECK|USE_WAM))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(DUPCHECK_CONST_OPTION)
.withArgName("size")
.hasArg()
.withDescription("Default: "+duplicates+"\nCheck for duplicates, expecting <size> values. Increasing <size> is cheap.\n"
+"To turn off duplicate checking, set to -1.")
.create()));
if (isOn(flags, USE_THROTTLE))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(THROTTLE_CONST_OPTION)
.withArgName("integer")
.hasArg()
.withDescription("Default: -1\nPause buffering of new jobs if unfinished queue grows beyond x. -1 to disable.")
.create()));
if (isOn(flags, USE_EMPTYGRAPHS))
options.addOption(checkOption(
OptionBuilder
.withLongOpt(EMPTYGRAPHS_CONST_OPTION)
.withDescription("Include examples with no pos or neg labeled solutions")
.create()));
if (isOn(flags, USE_FIXEDWEIGHTS))
options.addOption(checkOption(
Option.builder()
.longOpt(FIXEDWEIGHTS_CONST_OPTION)
.hasArgs()
.argName("exact[={y|n}]:prefix*")
.valueSeparator(':')
.desc("Specify patterns of features to keep fixed at 1.0 or permit tuning. End in * for a prefix, otherwise uses exact match. Fixed by default; specify '=n' to permit tuning. First matching rule decides.")
.build()));
if (anyOn(flags, USE_SMART_COUNTFEATURES))
options.addOption(checkOption(
Option.builder(COUNTFEATURES_CONST_OPTION)
.hasArg()
.argName("true|false")
.desc("Default: true\nTrack feature usage and tell me when I've e.g. run queries with the wrong params file")
.build()));
}
protected void constructUsageSyntax(StringBuilder syntax, int[] allFlags) {
int flags;
//input files
flags = inputFiles(allFlags);
if (isOn(flags, USE_QUERIES)) syntax.append(" --").append(QUERIES_FILE_OPTION).append(" inputFile");
if (isOn(flags, USE_GROUNDED)) syntax.append(" --").append(GROUNDED_FILE_OPTION).append(" inputFile.grounded");
if (isOn(flags, USE_ANSWERS)) syntax.append(" --").append(SOLUTIONS_FILE_OPTION).append(" inputFile");
if (isOn(flags, USE_TRAIN)) syntax.append(" --").append(TRAIN_FILE_OPTION).append(" inputFile");
if (isOn(flags, USE_TEST)) syntax.append(" --").append(TEST_FILE_OPTION).append(" inputFile");
if (isOn(flags, USE_PARAMS)) syntax.append(" --").append(PARAMS_FILE_OPTION).append(" params.wts");
if (isOn(flags, USE_INIT_PARAMS)) syntax.append(" --").append(INIT_PARAMS_FILE_OPTION).append(" initParams.wts");
//output files
flags = outputFiles(allFlags);
if (isOn(flags, USE_QUERIES)) syntax.append(" --").append(QUERIES_FILE_OPTION).append(" outputFile");
if (isOn(flags, USE_GROUNDED)) syntax.append(" --").append(GROUNDED_FILE_OPTION).append(" outputFile.grounded");
if (isOn(flags, USE_ANSWERS)) syntax.append(" --").append(SOLUTIONS_FILE_OPTION).append(" outputFile");
if (isOn(flags, USE_TRAIN)) syntax.append(" --").append(TRAIN_FILE_OPTION).append(" outputFile");
if (isOn(flags, USE_TEST)) syntax.append(" --").append(TEST_FILE_OPTION).append(" outputFile");
if (isOn(flags, USE_PARAMS)) syntax.append(" --").append(PARAMS_FILE_OPTION).append(" params.wts");
if (isOn(flags, USE_GRADIENT)) syntax.append(" --").append(GRADIENT_FILE_OPTION).append(" gradient.dwts");
//constants
flags = constants(allFlags);
if (isOn(flags, USE_WAM)) syntax.append(" --").append(PROGRAMFILES_CONST_OPTION).append(" file.wam:file.cfacts:file.graph");
if (isOn(flags, USE_WAM)) syntax.append(" [--").append(TERNARYINDEX_CONST_OPTION).append(" true|false]");
if (isOn(flags, USE_WAM)) syntax.append(" [--").append(PRUNEDPREDICATE_CONST_OPTION).append(" predicate1:predicate2]");
if (isOn(flags, USE_THREADS)) syntax.append(" [--").append(THREADS_CONST_OPTION).append(" integer]");
if (isOn(flags, USE_EPOCHS)) syntax.append(" [--").append(EPOCHS_CONST_OPTION).append(" integer]");
if (isOn(flags, USE_FORCE)) syntax.append(" [--").append(FORCE_CONST_OPTION).append("]");
if (isOn(flags, USE_ORDER)) syntax.append(" [--").append(ORDER_CONST_OPTION).append(" same|reorder]");
if (anyOn(flags, USE_DUPCHECK|USE_WAM)) syntax.append(" [--").append(DUPCHECK_CONST_OPTION).append(" -1|integer]");
if (isOn(flags, USE_THROTTLE)) syntax.append(" [--").append(THROTTLE_CONST_OPTION).append(" integer]");
if (isOn(flags, USE_EMPTYGRAPHS)) syntax.append(" [--").append(EMPTYGRAPHS_CONST_OPTION).append("]");
if (isOn(flags, USE_FIXEDWEIGHTS)) syntax.append(" [--").append(FIXEDWEIGHTS_CONST_OPTION).append(" featureA:featureB()]");
if (anyOn(flags, USE_SMART_COUNTFEATURES)) syntax.append(" [--").append(COUNTFEATURES_CONST_OPTION).append(" true|false]");
}
/**
* Calls System.exit()
*/
protected void usageOptions(Options options, int inputFile, int outputFile, int constants, int modules, String msg) {
usageOptions(options,new int[] {inputFile, outputFile, constants, modules},msg);
}
/**
* Calls System.exit()
*/
protected void usageOptions(Options options, int[] flags) {
usageOptions(options,flags,null);
}
/**
* Calls System.exit()
*/
protected void usageOptions(Options options, int[] flags, String msg) {
HelpFormatter formatter = new HelpFormatter();
int width = 74;
String swidth = System.getenv("COLUMNS");
if (swidth != null) {
try {
width = Integer.parseInt(swidth);
} catch (NumberFormatException e) {}
}
// formatter.setWidth(width);
// formatter.setLeftPadding(0);
// formatter.setDescPadding(2);
StringBuilder syntax = new StringBuilder();
constructUsageSyntax(syntax, flags);
String printMsg = "";
if (msg != null) printMsg = ("\nBAD USAGE:\n" + msg +"\n");
// formatter.printHelp(syntax.toString(), options);
PrintWriter pw = new PrintWriter(System.err);
formatter.printHelp(pw, width, syntax.toString(), "", options, 0, 2, printMsg);
pw.write("\n");
pw.flush();
pw.close();
int stat = msg!=null ? 1 : 0;
System.exit(stat);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("\n");
String n = this.getClass().getCanonicalName();
if (n==null) sb.append("(custom configurator)");
else sb.append(n);
displayFile(sb, QUERIES_FILE_OPTION, queryFile);
displayFile(sb, TEST_FILE_OPTION, testFile);
displayFile(sb, GROUNDED_FILE_OPTION, groundedFile);
displayFile(sb, INIT_PARAMS_FILE_OPTION, initParamsFile);
displayFile(sb, PARAMS_FILE_OPTION, paramsFile);
displayFile(sb, SOLUTIONS_FILE_OPTION, solutionsFile);
displayFile(sb, GRADIENT_FILE_OPTION, gradientFile);
if (!maintainOrder) display(sb, "Output order","reordered");
if (this.programFiles != null) {
display(sb, "Duplicate checking", duplicates>0? ("up to "+duplicates) : "off");
}
display(sb, THREADS_CONST_OPTION,nthreads);
return sb.toString();
}
private void displayFile(StringBuilder sb, String name, File f) {
if (f != null) sb.append("\n")
.append(String.format("%"+(FORMAT_WIDTH-5)+"s file: ", name))
.append(f.getPath());
}
private void display(StringBuilder sb, String name, Object value) {
sb.append("\n")
.append(String.format("%"+(FORMAT_WIDTH)+"s: %s",name,value.toString()));
}
protected String[] combinedArgs(String[] origArgs) {
// if the user specified a properties file, add those values at the beginning
// (so that command line args override them)
if (System.getProperty(PROPFILE) != null) {
String[] propArgs = fakeCommandLine(System.getProperty(PROPFILE));
String[] args = new String[origArgs.length + propArgs.length];
int i = 0;
for (int j = 0; j < propArgs.length; j++) args[i++] = propArgs[j];
for (int j = 0; j < origArgs.length; j++) args[i++] = origArgs[j];
return args;
}
return origArgs;
}
protected String[] fakeCommandLine(String propsFile) {
Properties props = new Properties();
try {
props.load(new BufferedReader(new FileReader(propsFile)));
return fakeCommandLine(props);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
protected String[] fakeCommandLine(Properties props) {
StringBuilder sb = new StringBuilder();
for (String name : props.stringPropertyNames()) {
sb.append(" --").append(name);
if (props.getProperty(name) != null && !props.getProperty(name).equals("")) {
sb.append(" ").append(props.getProperty(name));
}
}
return sb.substring(1).split("\\s");
}
public static void missing(int options, int[] flags) {
StringBuilder sb = new StringBuilder("Missing required option:\n");
switch(options) {
case USE_WAM:sb.append("\tprogramFiles"); break;
default: throw new UnsupportedOperationException("Bad programmer! Add handling to Configuration.missing for flag "+options);
}
Configuration c = new Configuration();
Options o = new Options();
c.addOptions(o, flags);
c.usageOptions(o, flags, sb.toString());
}
}
| 42.243169 | 210 | 0.713052 |
a3931b82a819f4ae879f283aee9546ec7194ac0d | 1,095 | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.knn.plugin.transport;
import org.opensearch.action.support.DefaultShardOperationFailedException;
import org.opensearch.action.support.broadcast.BroadcastResponse;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.xcontent.ToXContentObject;
import java.io.IOException;
import java.util.List;
/**
* Response returned for k-NN Warmup. Returns total number of shards Warmup was performed on, as well as
* the number of shards that succeeded and the number of shards that failed.
*/
public class KNNWarmupResponse extends BroadcastResponse implements ToXContentObject {
public KNNWarmupResponse() {}
public KNNWarmupResponse(StreamInput in) throws IOException {
super(in);
}
public KNNWarmupResponse(int totalShards, int successfulShards, int failedShards,
List<DefaultShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
}
}
| 33.181818 | 104 | 0.76895 |
f1895c48530b91ffec4f13635e22127f95346cc2 | 618 | package com.algawork.pedidovenda.pesquisa;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class PesquisarGruposBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<Integer> gruposFiltrados;
public PesquisarGruposBean(){
gruposFiltrados = new ArrayList();
for(int i =0; i < 50; i++){
this.gruposFiltrados.add(i);
}
}
public List<Integer> getGruposFiltrados(){
return gruposFiltrados;
}
}
| 16.263158 | 58 | 0.7411 |
7e6ac4e1269b1d82d46a1cffa987abbe642ef749 | 1,545 | package com.example.algamoney.api.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jdk.jfr.Name;
import javax.persistence.*;
import java.util.Objects;
import java.util.UUID;
import javax.validation.constraints.*;
@Entity
@Table(name = "pessoa")
public class Pessoa {
//Atributos próprios
@Id
private UUID id;
@NotNull
private String nome;
@NotNull
private boolean ativo;
//Atributos Embedados
@Embedded
private Endereco endereco;
//Constructor
public Pessoa() {
this.id = UUID.randomUUID();
}
//Getters e Setters
public String getNome() {
return nome;
}
public UUID getId() {
return id;
}
public boolean isAtivo() {
return ativo;
}
public Endereco getEndereco() {
return endereco;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
//Métodos próprios
@JsonIgnore
@Transient
public boolean isInativo(){
return !this.ativo;
}
//Hash and equals para id
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pessoa pessoa = (Pessoa) o;
return id.equals(pessoa.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| 19.3125 | 66 | 0.60712 |
e6d80506934220fcb526ce6cda283b9d60fd2f56 | 798 | package com.tester.finder.core;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@AllArgsConstructor
@RequestMapping(path = "api/core/")
public class CoreDataController {
private final CoreDataFacade coreDataFacade;
@ResponseBody
@GetMapping(path = "countries")
public List<Country> getCountries() {
return coreDataFacade.findCountries(true);
}
@ResponseBody
@GetMapping(path = "devices")
public List<Device> getDevices() {
return coreDataFacade.findDevices(true);
}
}
| 25.741935 | 62 | 0.763158 |
0a632f1e7d61de886868e06492dcb043f1492024 | 4,820 | // --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// --------------------------------------------------------------------------------
package com.echothree.model.control.filter.common.transfer;
import com.echothree.util.common.transfer.BaseTransfer;
import com.echothree.util.common.transfer.ListWrapper;
public class FilterAdjustmentTransfer
extends BaseTransfer {
private FilterKindTransfer filterKind;
private String filterAdjustmentName;
private FilterAdjustmentSourceTransfer filterAdjustmentSource;
private FilterAdjustmentTypeTransfer filterAdjustmentType;
private Boolean isDefault;
private Integer sortOrder;
private String description;
private ListWrapper<FilterAdjustmentAmountTransfer> filterAdjustmentAmounts;
private ListWrapper<FilterAdjustmentFixedAmountTransfer> filterAdjustmentFixedAmounts;
private ListWrapper<FilterAdjustmentPercentTransfer> filterAdjustmentPercents;
/** Creates a new instance of FilterAdjustmentTransfer */
public FilterAdjustmentTransfer(FilterKindTransfer filterKind, String filterAdjustmentName,
FilterAdjustmentSourceTransfer filterAdjustmentSource, FilterAdjustmentTypeTransfer filterAdjustmentType,
Boolean isDefault, Integer sortOrder, String description) {
this.filterKind = filterKind;
this.filterAdjustmentName = filterAdjustmentName;
this.filterAdjustmentSource = filterAdjustmentSource;
this.filterAdjustmentType = filterAdjustmentType;
this.isDefault = isDefault;
this.sortOrder = sortOrder;
this.description = description;
}
public FilterKindTransfer getFilterKind() {
return filterKind;
}
public void setFilterKind(FilterKindTransfer filterKind) {
this.filterKind = filterKind;
}
public String getFilterAdjustmentName() {
return filterAdjustmentName;
}
public void setFilterAdjustmentName(String filterAdjustmentName) {
this.filterAdjustmentName = filterAdjustmentName;
}
public FilterAdjustmentSourceTransfer getFilterAdjustmentSource() {
return filterAdjustmentSource;
}
public void setFilterAdjustmentSource(FilterAdjustmentSourceTransfer filterAdjustmentSource) {
this.filterAdjustmentSource = filterAdjustmentSource;
}
public FilterAdjustmentTypeTransfer getFilterAdjustmentType() {
return filterAdjustmentType;
}
public void setFilterAdjustmentType(FilterAdjustmentTypeTransfer filterAdjustmentType) {
this.filterAdjustmentType = filterAdjustmentType;
}
public Boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(Boolean isDefault) {
this.isDefault = isDefault;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ListWrapper<FilterAdjustmentAmountTransfer> getFilterAdjustmentAmounts() {
return filterAdjustmentAmounts;
}
public void setFilterAdjustmentAmounts(ListWrapper<FilterAdjustmentAmountTransfer> filterAdjustmentAmounts) {
this.filterAdjustmentAmounts = filterAdjustmentAmounts;
}
public ListWrapper<FilterAdjustmentFixedAmountTransfer> getFilterAdjustmentFixedAmounts() {
return filterAdjustmentFixedAmounts;
}
public void setFilterAdjustmentFixedAmounts(ListWrapper<FilterAdjustmentFixedAmountTransfer> filterAdjustmentFixedAmounts) {
this.filterAdjustmentFixedAmounts = filterAdjustmentFixedAmounts;
}
public ListWrapper<FilterAdjustmentPercentTransfer> getFilterAdjustmentPercents() {
return filterAdjustmentPercents;
}
public void setFilterAdjustmentPercents(ListWrapper<FilterAdjustmentPercentTransfer> filterAdjustmentPercents) {
this.filterAdjustmentPercents = filterAdjustmentPercents;
}
}
| 37.076923 | 128 | 0.719502 |
7c1df141956df789b2ced83747e463bc60d709bb | 4,118 | package org.dmc.services.data.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "resource_projects")
public class ResourceProject extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "title")
private String title;
@Column(name = "image")
private String image;
@Column(name = "description")
private String description;
@Column(name = "date_created")
private String dateCreated;
@Column(name = "link")
private String link;
@Column(name = "contact")
private String contact;
@Column(name = "current")
private boolean current;
@Column(name = "highlighted")
private boolean highlighted;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public boolean isCurrent() {
return current;
}
public void setCurrent(boolean current) {
this.current = current;
}
public boolean isHighlighted() {
return highlighted;
}
public void setHighlighted(boolean highlighted) {
this.highlighted = highlighted;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contact == null) ? 0 : contact.hashCode());
result = prime * result + (current ? 1231 : 1237);
result = prime * result + ((dateCreated == null) ? 0 : dateCreated.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + (highlighted ? 1231 : 1237);
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((image == null) ? 0 : image.hashCode());
result = prime * result + ((link == null) ? 0 : link.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ResourceProject other = (ResourceProject) obj;
if (contact == null) {
if (other.contact != null) {
return false;
}
} else if (!contact.equals(other.contact)) {
return false;
}
if (current != other.current) {
return false;
}
if (dateCreated == null) {
if (other.dateCreated != null) {
return false;
}
} else if (!dateCreated.equals(other.dateCreated)) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (highlighted != other.highlighted) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (image == null) {
if (other.image != null) {
return false;
}
} else if (!image.equals(other.image)) {
return false;
}
if (link == null) {
if (other.link != null) {
return false;
}
} else if (!link.equals(other.link)) {
return false;
}
if (title == null) {
if (other.title != null) {
return false;
}
} else if (!title.equals(other.title)) {
return false;
}
return true;
}
}
| 20.186275 | 81 | 0.647159 |
b071eff7f00a722416150298d611ba8df4ee1214 | 654 | package alfredo.phx;
import alfredo.Component;
import alfredo.Entity;
import alfredo.Scene;
import alfredo.geom.Vector;
import java.util.ArrayList;
/**
*
* @author TheMonsterOfTheDeep
*/
public class Physics {
public static final Vector gravity = new Vector(0, 9.807f);
public static void tick() {
for(Entity e : Entity.all(Body.class)) {
e.getComponent(Body.class).acceleration.set(gravity);
}
Scene.getCurrent().tick();
for(Entity e : Entity.all()) {
for (Component c : e.getComponents()) {
c.tick();
}
}
}
}
| 21.8 | 65 | 0.568807 |
39141ed02badc78eab78a556fed2a720593d0984 | 200 | package com.yoyiyi.soleil.bean.app.support;
/**
* @author zzq 作者 E-mail: [email protected]
* @date 创建时间:2017/5/29 15:52
* 描述:
*/
public class SearchTagSelect {
public String title;
}
| 18.181818 | 51 | 0.68 |
636373f16fe48a6cc202c3c572f8ed0b8936883c | 749 | package grump;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.TerminalNode;
public class GrumPParseTree implements ParseTreeListener {
@Override
public void visitTerminal(TerminalNode terminalNode) {
}
@Override
public void visitErrorNode(ErrorNode errorNode) {
}
@Override
public void enterEveryRule(ParserRuleContext parserRuleContext) {
// System.out.println(parserRuleContext);
}
@Override
public void exitEveryRule(ParserRuleContext parserRuleContext) {
// System.out.println(parserRuleContext);
}
}
| 27.740741 | 72 | 0.700935 |
0e2daa23521b57cc4127fc15eb3af29ae22981ec | 20,985 | /*
* Copyright (c) 2007 Tom Parker <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package plugin.lsttokens.testsupport;
import java.net.URISyntaxException;
import java.util.Arrays;
import org.junit.Test;
import pcgen.cdom.base.CDOMObject;
import pcgen.cdom.base.CDOMReference;
import pcgen.cdom.base.ChoiceSet;
import pcgen.cdom.base.ConcretePersistentTransitionChoice;
import pcgen.cdom.base.FormulaFactory;
import pcgen.cdom.base.PersistentTransitionChoice;
import pcgen.cdom.choiceset.ReferenceChoiceSet;
import pcgen.cdom.enumeration.ListKey;
import pcgen.cdom.enumeration.Type;
import pcgen.persistence.PersistenceLayerException;
import pcgen.rules.context.LoadContext;
import pcgen.rules.persistence.token.CDOMSecondaryToken;
public abstract class AbstractSelectionTokenTestCase<T extends CDOMObject, TC extends CDOMObject>
extends AbstractTokenTestCase<T>
{
public abstract CDOMSecondaryToken<?> getSubToken();
public String getSubTokenName()
{
return getSubToken().getTokenName();
}
public abstract Class<TC> getTargetClass();
public abstract boolean isTypeLegal();
public abstract boolean isAllLegal();
public String getAllString()
{
return "ALL";
}
public String getTypePrefix()
{
return "";
}
public abstract boolean allowsParenAsSub();
public abstract boolean allowsFormula();
@Override
public void setUp() throws PersistenceLayerException, URISyntaxException
{
super.setUp();
TokenRegistration.register(getSubToken());
}
public char getJoinCharacter()
{
return ',';
}
protected TC construct(LoadContext loadContext, String one)
{
return loadContext.getReferenceContext().constructCDOMObject(getTargetClass(), one);
}
protected CDOMObject constructTyped(LoadContext loadContext, String one)
{
return loadContext.getReferenceContext().constructCDOMObject(getTargetClass(), one);
}
@Test
public void testInvalidInputEmptyString() throws PersistenceLayerException
{
assertFalse(parse(""));
assertNoSideEffects();
}
@Test
public void testInvalidInputOnlySubToken() throws PersistenceLayerException
{
assertFalse(parse(getSubTokenName()));
assertNoSideEffects();
}
@Test
public void testInvalidInputOnlySubTokenPipe()
throws PersistenceLayerException
{
assertFalse(parse(getSubTokenName() + '|'));
assertNoSideEffects();
}
@Test
public void testInvalidInputJoinOnly() throws PersistenceLayerException
{
assertFalse(parse(getSubTokenName() + '|'
+ Character.toString(getJoinCharacter())));
assertNoSideEffects();
}
@Test
public void testInvalidInputString() throws PersistenceLayerException
{
assertTrue(parse(getSubTokenName() + '|' + "String"));
assertConstructionError();
}
@Test
public void testInvalidInputType() throws PersistenceLayerException
{
assertTrue(parse(getSubTokenName() + '|' + "TestType"));
assertConstructionError();
}
// TODO Allow this once a method checks to exist if TestWP1 is a formula vs.
// an object
// @Test
// public void testInvalidInputJoinedPipe() throws PersistenceLayerException
// {
// construct(primaryContext, "TestWP1");
// construct(primaryContext, "TestWP2");
// boolean parse = parse(getSubTokenName() + '|' + "TestWP1|TestWP2");
// if (parse)
// {
// assertFalse(primaryContext.ref.validate());
// }
// else
// {
// assertNoSideEffects();
// }
// }
@Test
public void testInvalidTooManyPipe() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
boolean parse = parse(getSubTokenName() + "|Formula|TestWP1|TestWP2");
if (parse)
{
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
@Test
public void testInvalidInputJoinedDot() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1.TestWP2"));
assertConstructionError();
}
@Test
public void testInvalidInputNegativeFormula()
throws PersistenceLayerException
{
if (allowsFormula())
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + "-1|TestWP1"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputZeroFormula() throws PersistenceLayerException
{
if (allowsFormula())
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + "0|TestWP1"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputTypeEmpty() throws PersistenceLayerException
{
if (isTypeLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE="));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputTypeUnterminated()
throws PersistenceLayerException
{
if (isTypeLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=One."));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputClearDotTypeDoubleSeparator()
throws PersistenceLayerException
{
if (isTypeLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=One..Two"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputClearDotTypeFalseStart()
throws PersistenceLayerException
{
if (isTypeLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=.One"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputAll() throws PersistenceLayerException
{
if (!isAllLegal())
{
try
{
boolean parse = parse(getSubTokenName() + '|' + "ALL");
if (parse)
{
// Only need to check if parsed as true
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
catch (IllegalArgumentException e)
{
// This is okay too
assertNoSideEffects();
}
}
}
@Test
public void testInvalidInputTypeEquals() throws PersistenceLayerException
{
if (!isTypeLegal())
{
try
{
boolean parse = parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=Foo");
if (parse)
{
// Only need to check if parsed as true
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
catch (IllegalArgumentException e)
{
// This is okay too
assertNoSideEffects();
}
}
}
@Test
public void testInvalidInputAny() throws PersistenceLayerException
{
if (!isAllLegal())
{
try
{
boolean result = parse("ANY");
if (result)
{
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
catch (IllegalArgumentException e)
{
//This is okay too
assertNoSideEffects();
}
}
}
@Test
public void testInvalidInputCheckType() throws PersistenceLayerException
{
if (!isTypeLegal())
{
try
{
boolean result = getToken().parseToken(primaryContext, primaryProf,
"TYPE=TestType").passed();
if (result)
{
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
catch (IllegalArgumentException e)
{
// This is okay too
assertNoSideEffects();
}
}
}
@Test
public void testInvalidDoubleList() throws PersistenceLayerException
{
if (allowsParenAsSub())
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
boolean ret = parse(getSubTokenName() + '|'
+ "TestWP1 (Test,TestTwo)");
if (ret)
{
assertConstructionError();
}
else
{
assertNoSideEffects();
}
}
}
@Test
public void testInvalidListEnd() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter()));
assertNoSideEffects();
}
@Test
public void testInvalidListStart() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + getJoinCharacter()
+ "TestWP1"));
assertNoSideEffects();
}
@Test
public void testInvalidListDoubleJoin() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
assertFalse(parse(getSubTokenName() + '|' + "TestWP2"
+ getJoinCharacter() + getJoinCharacter() + "TestWP1"));
assertNoSideEffects();
}
@Test
public void testInvalidInputCheckMult() throws PersistenceLayerException
{
// Explicitly do NOT build TestWP2
construct(primaryContext, "TestWP1");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertConstructionError();
}
@Test
public void testInvalidInputCheckTypeEqualLength()
throws PersistenceLayerException
{
// Explicitly do NOT build TestWP2 (this checks that the TYPE= doesn't
// consume the |
if (isTypeLegal())
{
construct(primaryContext, "TestWP1");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + getTypePrefix() + "TYPE=TestType"
+ getJoinCharacter() + "TestWP2"));
assertConstructionError();
}
}
@Test
public void testInvalidInputCheckTypeDotLength()
throws PersistenceLayerException
{
// Explicitly do NOT build TestWP2 (this checks that the TYPE= doesn't
// consume the |
if (isTypeLegal())
{
construct(primaryContext, "TestWP1");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + getTypePrefix()
+ "TYPE.TestType.OtherTestType" + getJoinCharacter()
+ "TestWP2"));
assertConstructionError();
}
}
@Test
public void testValidInputTestDot() throws PersistenceLayerException
{
if (isTypeLegal())
{
CDOMObject a = constructTyped(primaryContext, "Typed1");
a.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
CDOMObject c = constructTyped(secondaryContext, "Typed1");
c.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
assertTrue(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE.TestType"));
assertCleanConstruction();
}
}
@Test
public void testRoundRobinOne() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
runRoundRobin(getSubTokenName() + '|' + "TestWP1");
}
@Test
public void testRoundRobinOnePreFooler() throws PersistenceLayerException
{
construct(primaryContext, "Prefool");
construct(secondaryContext, "Prefool");
runRoundRobin(getSubTokenName() + '|' + "Prefool");
}
@Test
public void testRoundRobinParen() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1 (Test)");
construct(secondaryContext, "TestWP1 (Test)");
runRoundRobin(getSubTokenName() + '|' + "TestWP1 (Test)");
}
@Test
public void testRoundRobinCount() throws PersistenceLayerException
{
if (allowsFormula())
{
construct(primaryContext, "TestWP1 (Test)");
construct(secondaryContext, "TestWP1 (Test)");
runRoundRobin(getSubTokenName() + '|' + "4|TestWP1 (Test)");
}
}
@Test
public void testRoundRobinFormulaCount() throws PersistenceLayerException
{
if (allowsFormula())
{
construct(primaryContext, "TestWP1 (Test)");
construct(secondaryContext, "TestWP1 (Test)");
runRoundRobin(getSubTokenName() + '|' + "INT|TestWP1 (Test)");
}
}
@Test
public void testRoundRobinHardFormulaCount() throws PersistenceLayerException
{
if (allowsFormula())
{
construct(primaryContext, "TestWP1 (Test)");
construct(secondaryContext, "TestWP1 (Test)");
runRoundRobin(getSubTokenName() + '|'
+ "if(var(\"SIZE==3||SIZE==4\"),5,0)|TestWP1 (Test)");
}
}
@Test
public void testRoundRobinParenSub() throws PersistenceLayerException
{
if (allowsParenAsSub())
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
runRoundRobin(getSubTokenName() + '|' + "TestWP1 (Test)");
}
}
@Test
public void testRoundRobinParenDoubleSub() throws PersistenceLayerException
{
if (allowsParenAsSub())
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
runRoundRobin(getSubTokenName() + '|' + "TestWP1 (Test(Two))");
}
}
@Test
public void testRoundRobinThree() throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
construct(primaryContext, "TestWP3");
construct(secondaryContext, "TestWP1");
construct(secondaryContext, "TestWP2");
construct(secondaryContext, "TestWP3");
runRoundRobin(getSubTokenName() + '|' + "TestWP1" + getJoinCharacter()
+ "TestWP2" + getJoinCharacter() + "TestWP3");
}
@Test
public void testRoundRobinWithEqualType() throws PersistenceLayerException
{
if (isTypeLegal())
{
construct(primaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
construct(secondaryContext, "TestWP1");
construct(secondaryContext, "TestWP2");
CDOMObject a = constructTyped(primaryContext, "Typed1");
a.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
CDOMObject b = constructTyped(primaryContext, "Typed2");
b.addToListFor(ListKey.TYPE, Type.getConstant("OtherTestType"));
CDOMObject c = constructTyped(secondaryContext, "Typed1");
c.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
CDOMObject d = constructTyped(secondaryContext, "Typed2");
d.addToListFor(ListKey.TYPE, Type.getConstant("OtherTestType"));
runRoundRobin(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2" + getJoinCharacter()
+ getTypePrefix() + "TYPE=OtherTestType"
+ getJoinCharacter() + getTypePrefix() + "TYPE=TestType");
}
}
@Test
public void testRoundRobinTestEquals() throws PersistenceLayerException
{
if (isTypeLegal())
{
CDOMObject a = constructTyped(primaryContext, "Typed1");
a.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
CDOMObject c = constructTyped(secondaryContext, "Typed1");
c.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
runRoundRobin(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=TestType");
}
}
@Test
public void testRoundRobinTestEqualThree() throws PersistenceLayerException
{
if (isTypeLegal())
{
CDOMObject a = constructTyped(primaryContext, "Typed1");
a.addToListFor(ListKey.TYPE, Type.getConstant("TestAltType"));
a.addToListFor(ListKey.TYPE, Type.getConstant("TestThirdType"));
a.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
CDOMObject c = constructTyped(secondaryContext, "Typed1");
c.addToListFor(ListKey.TYPE, Type.getConstant("TestAltType"));
c.addToListFor(ListKey.TYPE, Type.getConstant("TestThirdType"));
c.addToListFor(ListKey.TYPE, Type.getConstant("TestType"));
runRoundRobin(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=TestAltType.TestThirdType.TestType");
}
}
@Test
public void testInvalidInputAnyItem() throws PersistenceLayerException
{
if (isAllLegal())
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + getAllString()
+ getJoinCharacter() + "TestWP1"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputItemAny() throws PersistenceLayerException
{
if (isAllLegal())
{
construct(primaryContext, "TestWP1");
assertFalse(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + getAllString()));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputAnyType() throws PersistenceLayerException
{
if (isTypeLegal() && isAllLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getAllString()
+ getJoinCharacter() + getTypePrefix() + "TYPE=TestType"));
assertNoSideEffects();
}
}
@Test
public void testInvalidInputTypeAny() throws PersistenceLayerException
{
if (isTypeLegal() && isAllLegal())
{
assertFalse(parse(getSubTokenName() + '|' + getTypePrefix()
+ "TYPE=TestType" + getJoinCharacter() + getAllString()));
assertNoSideEffects();
}
}
@Test
public void testInputInvalidAddsTypeNoSideEffect()
throws PersistenceLayerException
{
if (isTypeLegal())
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
construct(secondaryContext, "TestWP2");
construct(primaryContext, "TestWP3");
construct(secondaryContext, "TestWP3");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertTrue(parseSecondary(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertFalse(parse(getSubTokenName() + '|' + "TestWP3"
+ getJoinCharacter() + getTypePrefix() + "TYPE="));
assertNoSideEffects();
}
}
@Test
public void testInputInvalidAddsBasicNoSideEffect()
throws PersistenceLayerException
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
construct(secondaryContext, "TestWP2");
construct(primaryContext, "TestWP3");
construct(secondaryContext, "TestWP3");
construct(primaryContext, "TestWP4");
construct(secondaryContext, "TestWP4");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertTrue(parseSecondary(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertFalse(parse(getSubTokenName() + '|' + "TestWP3"
+ getJoinCharacter() + getJoinCharacter() + "TestWP4"));
assertNoSideEffects();
}
@Test
public void testInputInvalidAddsAllNoSideEffect()
throws PersistenceLayerException
{
if (isAllLegal())
{
construct(primaryContext, "TestWP1");
construct(secondaryContext, "TestWP1");
construct(primaryContext, "TestWP2");
construct(secondaryContext, "TestWP2");
construct(primaryContext, "TestWP3");
construct(secondaryContext, "TestWP3");
assertTrue(parse(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertTrue(parseSecondary(getSubTokenName() + '|' + "TestWP1"
+ getJoinCharacter() + "TestWP2"));
assertFalse(parse(getSubTokenName() + '|' + "TestWP3"
+ getJoinCharacter() + getAllString()));
assertNoSideEffects();
}
}
@Test
public void testRoundRobinTestAll() throws PersistenceLayerException
{
if (isAllLegal())
{
construct(primaryContext, "Typed1");
construct(secondaryContext, "Typed1");
runRoundRobin(getSubTokenName() + '|' + getAllString());
}
}
@Override
protected String getAlternateLegalValue()
{
return getSubTokenName() + '|' + "TestWP1" + getJoinCharacter()
+ "TestWP2" + getJoinCharacter() + "TestWP3";
}
@Override
protected String getLegalValue()
{
return getSubTokenName() + '|' + "TestWP1" + getJoinCharacter()
+ "TestWP2";
}
protected PersistentTransitionChoice<TC> buildChoice(
CDOMReference<TC>... refs)
{
ReferenceChoiceSet<TC> rcs = buildRCS(refs);
assertTrue(rcs.getGroupingState().isValid());
return buildTC(rcs);
}
protected PersistentTransitionChoice<TC> buildTC(ReferenceChoiceSet<TC> rcs)
{
ChoiceSet<TC> cs = new ChoiceSet<TC>(getSubTokenName(), rcs);
cs.setTitle("Pick a " + getTargetClass().getSimpleName());
PersistentTransitionChoice<TC> tc = new ConcretePersistentTransitionChoice<TC>(
cs, FormulaFactory.ONE);
return tc;
}
protected ReferenceChoiceSet<TC> buildRCS(CDOMReference<TC>... refs)
{
ReferenceChoiceSet<TC> rcs = new ReferenceChoiceSet<TC>(Arrays.asList(refs));
return rcs;
}
@Override
protected ConsolidationRule getConsolidationRule()
{
return ConsolidationRule.SEPARATE;
}
}
| 27.182642 | 98 | 0.681487 |
3d6e1055e6a076154334659cf6740151bc9115a6 | 2,167 | package soot.dexpler.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.DoubleType;
import soot.LongType;
import soot.Type;
import soot.Value;
import soot.jimple.DoubleConstant;
import soot.jimple.LongConstant;
public class UntypedLongOrDoubleConstant extends UntypedConstant {
/**
*
*/
private static final long serialVersionUID = -3970057807907204253L;
public final long value;
private UntypedLongOrDoubleConstant(long value) {
this.value = value;
}
public static UntypedLongOrDoubleConstant v(long value) {
return new UntypedLongOrDoubleConstant(value);
}
public boolean equals(Object c) {
return c instanceof UntypedLongOrDoubleConstant && ((UntypedLongOrDoubleConstant) c).value == this.value;
}
/** Returns a hash code for this DoubleConstant object. */
public int hashCode() {
return (int) (value ^ (value >>> 32));
}
public DoubleConstant toDoubleConstant() {
return DoubleConstant.v(Double.longBitsToDouble(value));
}
public LongConstant toLongConstant() {
return LongConstant.v(value);
}
@Override
public Value defineType(Type t) {
if (t instanceof DoubleType) {
return this.toDoubleConstant();
} else if (t instanceof LongType) {
return this.toLongConstant();
} else {
throw new RuntimeException("error: expected Double type or Long type. Got " + t);
}
}
}
| 28.142857 | 109 | 0.715275 |
b5a62ded64c669fd543a0a08952da4ef992879bf | 13,889 | /*******************************************************************************
* Copyright 2016, 2018 vanilladb.org contributors
*
* 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.vanilladb.core.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
/**
* A non-agent-based CPU profiler similar to
*
* <pre>
* <code>java -agentlib:hprof=cpu=samples ToBeProfiledClass</code>
* </pre>
*
* but accepts filters and can be started/stopped at any time.
*/
public class Profiler implements Runnable {
private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
private static final int INTERVAL;
private static final int DEPTH;
private static final int MAX_PACKAGES;
private static final int MAX_METHODS;
private static final int MAX_LINES;
private static final String[] IGNORE_THREADS;
private static final String[] IGNORE_PACKAGES;
static {
INTERVAL = CoreProperties.getLoader().getPropertyAsInteger(Profiler.class.getName() + ".INTERVAL", 10);
DEPTH = CoreProperties.getLoader().getPropertyAsInteger(Profiler.class.getName() + ".DEPTH", 5);
MAX_PACKAGES = CoreProperties.getLoader().getPropertyAsInteger(Profiler.class.getName() + ".MAX_PACKAGES", 100);
MAX_METHODS = CoreProperties.getLoader().getPropertyAsInteger(Profiler.class.getName() + ".MAX_METHODS", 1000);
MAX_LINES = CoreProperties.getLoader().getPropertyAsInteger(Profiler.class.getName() + ".MAX_LINES", 1000);
String[] defaultIgnoreThreads = new String[] { "java.lang.Thread.dumpThreads", "java.lang.Thread.getThreads",
"java.net.PlainSocketImpl.socketAccept", "java.net.SocketInputStream.socketRead0",
"java.net.SocketOutputStream.socketWrite0", "java.lang.UNIXProcess.waitForProcessExit",
// "java.lang.Object.wait", "java.lang.Thread.sleep",
"un.awt.windows.WToolkit.eventLoop", "sun.misc.Unsafe.park",
"dalvik.system.VMStack.getThreadStackTrace", "dalvik.system.NativeStart.run" };
IGNORE_THREADS = CoreProperties.getLoader()
.getPropertyAsStringArray(Profiler.class.getName() + ".IGNORE_THREADS", defaultIgnoreThreads);
String[] defaultIgnorePackages = new String[] { "java.", "javax.", "sun.", "net." };
IGNORE_PACKAGES = CoreProperties.getLoader()
.getPropertyAsStringArray(Profiler.class.getName() + ".IGNORE_PACKAGES", defaultIgnorePackages);
}
private Thread thread;
private boolean started;
private boolean paused;
private long time;
private long pauseTime;
private CountMap<String> packages;
private CountMap<String> selfMethods;
private CountMap<String> stackMethods;
private CountMap<String> lines;
private int total;
/**
* Start collecting profiling data.
*/
public synchronized void startCollecting() {
paused = false;
if (thread != null)
return;
packages = new CountMap<String>(MAX_PACKAGES);
selfMethods = new CountMap<String>(MAX_METHODS);
stackMethods = new CountMap<String>(MAX_METHODS);
lines = new CountMap<String>(MAX_LINES);
total = 0;
started = true;
thread = new Thread(this);
thread.setName("Profiler");
thread.setDaemon(true);
thread.start();
}
/**
* Stop collecting.
*/
public synchronized void stopCollecting() {
started = false;
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
thread = null;
}
}
/**
* Pause collecting.
*/
public synchronized void pauseCollecting() {
paused = true;
}
@Override
public void run() {
time = System.nanoTime();
while (started) {
try {
tick();
} catch (Exception ex) {
ex.printStackTrace();
break;
}
}
time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - time);
}
private void tick() {
long ts = System.nanoTime();
if (INTERVAL > 0) {
try {
Thread.sleep(INTERVAL);
} catch (Exception e) {
// ignore
}
}
if (paused) {
pauseTime += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - ts);
return;
}
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
Thread t = entry.getKey();
if (t.getState() != Thread.State.RUNNABLE) {
continue;
}
StackTraceElement[] trace = entry.getValue();
if (trace == null || trace.length == 0) {
continue;
}
if (startsWithAny(trace[0].toString(), IGNORE_THREADS)) {
continue;
}
boolean relevant = tickPackages(trace);
tickMethods(trace);
tickLines(trace);
if (relevant)
total++;
}
}
private boolean tickPackages(StackTraceElement[] trace) {
for (int i = 0; i < trace.length; i++) {
StackTraceElement el = trace[i];
if (!startsWithAny(el.getClassName(), IGNORE_PACKAGES)) {
String packageName = getPackageName(el);
packages.increment(packageName);
return true;
}
}
return false;
}
private void tickMethods(StackTraceElement[] trace) {
boolean self = true;
StackTraceElement last = null;
for (int i = 0; i < trace.length; i++) {
StackTraceElement el = trace[i];
if (!startsWithAny(el.getClassName(), IGNORE_PACKAGES)) {
// ignore direct recursive calls
if (last == null || !(el.getClassName().equals(last.getClassName())
&& el.getMethodName().equals(last.getMethodName()))) {
last = el;
String methodName = getMethodName(el);
if (self) {
selfMethods.increment(methodName);
self = false;
}
stackMethods.increment(methodName);
}
}
}
}
private void tickLines(StackTraceElement[] trace) {
StringBuilder buff = new StringBuilder();
StackTraceElement last = null;
for (int i = 0, j = 0; i < trace.length && j < DEPTH; i++) {
StackTraceElement el = trace[i];
// ignore direct recursive calls
if (last == null || !(el.getClassName().equals(last.getClassName())
&& el.getMethodName().equals(last.getMethodName()))) {
if (!startsWithAny(el.getClassName(), IGNORE_PACKAGES)) {
if (last == null) {
buff.append(el.toString()).append("+").append(LINE_SEPARATOR);
} else if (startsWithAny(last.getClassName(), IGNORE_PACKAGES)) {
buff.append(last.toString()).append(LINE_SEPARATOR);
buff.append(el.toString()).append("+").append(LINE_SEPARATOR);
} else {
buff.append(el.toString()).append(LINE_SEPARATOR);
}
j++;
}
last = el;
}
}
if (buff.length() > 0)
lines.increment(buff.toString().trim());
}
private static boolean startsWithAny(String s, String[] prefixes) {
for (String p : prefixes) {
if (p.length() > 0 && s.startsWith(p)) {
return true;
}
}
return false;
}
private static String getPackageName(StackTraceElement el) {
String className = el.getClassName();
int ci = className.lastIndexOf('.');
if (ci > 0)
return className.substring(0, ci);
throw new IllegalArgumentException();
}
private static String getMethodName(StackTraceElement el) {
return el.getClassName() + "." + el.getMethodName();
}
/**
* Stop and obtain the top packages, ordered by their self execution time.
*
* @param num
* number of top packages
* @return the top packages
*/
public String getTopPackages(int num) {
stopCollecting();
CountMap<String> pkgs = new CountMap<String>(packages);
StringBuilder buff = new StringBuilder();
buff.append("Top packages over ").append(time).append(" ms (").append(pauseTime).append(" ms paused), with ")
.append(total).append(" counts:").append(LINE_SEPARATOR);
buff.append("Rank\tSelf\tPackage").append(LINE_SEPARATOR);
for (int i = 0, n = 0; pkgs.size() > 0 && n < num; i++) {
int highest = 0;
List<Map.Entry<String, Integer>> bests = new ArrayList<Map.Entry<String, Integer>>();
for (Map.Entry<String, Integer> el : pkgs.entrySet()) {
if (el.getValue() > highest) {
bests.clear();
bests.add(el);
highest = el.getValue();
} else if (el.getValue() == highest) {
bests.add(el);
}
}
for (Map.Entry<String, Integer> e : bests) {
pkgs.remove(e.getKey());
int percent = 100 * highest / Math.max(total, 1);
buff.append(i + 1).append("\t").append(percent).append("%\t").append(e.getKey()).append(LINE_SEPARATOR);
n++;
}
}
return buff.toString();
}
/**
* Stop and obtain the self execution time of packages, each as a row in CSV
* format.
*
* @return the execution time of packages in CSV format
*/
public String getPackageCsv() {
stopCollecting();
StringBuilder buff = new StringBuilder();
buff.append("Package,Self").append(LINE_SEPARATOR);
for (String k : new TreeSet<String>(packages.keySet())) {
int percent = 100 * packages.get(k) / Math.max(total, 1);
buff.append(k).append(",").append(percent).append(LINE_SEPARATOR);
}
return buff.toString();
}
/**
* Stop and obtain the top methods, ordered by their self execution time.
*
* @param num
* number of top methods
*
* @return the top methods
*/
public String getTopMethods(int num) {
stopCollecting();
CountMap<String> selfms = new CountMap<String>(selfMethods);
CountMap<String> stackms = new CountMap<String>(stackMethods);
StringBuilder buff = new StringBuilder();
buff.append("Top methods over ").append(time).append(" ms (").append(pauseTime).append(" ms paused), with ")
.append(total).append(" counts:").append(LINE_SEPARATOR);
buff.append("Rank\tSelf\tStack\tMethod").append(LINE_SEPARATOR);
for (int i = 0, n = 0; selfms.size() > 0 && n < num; i++) {
int highest = 0;
List<Map.Entry<String, Integer>> bests = new ArrayList<Map.Entry<String, Integer>>();
for (Map.Entry<String, Integer> el : selfms.entrySet()) {
if (el.getValue() > highest) {
bests.clear();
bests.add(el);
highest = el.getValue();
} else if (el.getValue() == highest) {
bests.add(el);
}
}
for (Map.Entry<String, Integer> e : bests) {
selfms.remove(e.getKey());
int selfPercent = 100 * highest / Math.max(total, 1);
int stackPercent = 100 * stackms.remove(e.getKey()) / Math.max(total, 1);
buff.append(i + 1).append("\t").append(selfPercent).append("%\t").append(stackPercent).append("%\t")
.append(e.getKey()).append(LINE_SEPARATOR);
n++;
}
}
return buff.toString();
}
/**
* Stop and obtain the self execution time of methods, each as a row in CSV
* format.
*
* @return the execution time of methods in CSV format
*/
public String getMethodCsv() {
stopCollecting();
StringBuilder buff = new StringBuilder();
buff.append("Method,Self").append(LINE_SEPARATOR);
for (String k : new TreeSet<String>(selfMethods.keySet())) {
int percent = 100 * selfMethods.get(k) / Math.max(total, 1);
buff.append(k).append(",").append(percent).append(LINE_SEPARATOR);
}
return buff.toString();
}
/**
* Stop and obtain the top lines, ordered by their execution time.
*
* @param num
* number of top lines
*
* @return the top lines
*/
public String getTopLines(int num) {
stopCollecting();
CountMap<String> ls = new CountMap<String>(lines);
StringBuilder buff = new StringBuilder();
buff.append("Top lines over ").append(time).append(" ms (").append(pauseTime).append(" ms paused), with ")
.append(total).append(" counts:").append(LINE_SEPARATOR);
for (int i = 0, n = 0; ls.size() > 0 && n < num; i++) {
int highest = 0;
List<Map.Entry<String, Integer>> bests = new ArrayList<Map.Entry<String, Integer>>();
for (Map.Entry<String, Integer> el : ls.entrySet()) {
if (el.getValue() > highest) {
bests.clear();
bests.add(el);
highest = el.getValue();
} else if (el.getValue() == highest) {
bests.add(el);
}
}
for (Map.Entry<String, Integer> e : bests) {
ls.remove(e.getKey());
int percent = 100 * highest / Math.max(total, 1);
buff.append("Rank: ").append(i + 1).append(", Self: ").append(percent).append("%, Trace: ")
.append(LINE_SEPARATOR).append(e.getKey()).append(LINE_SEPARATOR);
n++;
}
}
return buff.toString();
}
/**
* Stop and obtain the self execution time of methods, each as a row in CSV.
*/
private class CountMap<K> extends HashMap<K, Integer> {
private static final long serialVersionUID = 1L;
int limit;
int ignoreThreshold = 0;
CountMap(int limit) {
super(2 * limit);
this.limit = limit;
}
CountMap(CountMap<K> map) {
super(map);
this.limit = map.limit;
}
void increment(K key) {
Integer c = get(key);
put(key, (c == null ? 1 : c + 1));
while (size() > limit / 2) {
ignoreThreshold++;
Iterator<Map.Entry<K, Integer>> ei = entrySet().iterator();
while (ei.hasNext()) {
Integer ec = ei.next().getValue();
if (ec <= ignoreThreshold)
ei.remove();
}
}
}
}
}
| 32.225058 | 115 | 0.634963 |
cbd618a225242491413de9493c1b85288853b5dd | 1,635 | /*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atlasmap.converters;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import io.atlasmap.spi.AtlasConversionInfo;
import io.atlasmap.spi.AtlasConverter;
import io.atlasmap.v2.FieldType;
/**
* The type converter for {@link Calendar}.
*/
public class CalendarConverter implements AtlasConverter<Calendar> {
/**
* Converts to {@link Date}.
* @param calendar value
* @return converted
*/
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME)
public Date toDate(Calendar calendar) {
return calendar != null ? calendar.getTime() : null;
}
/**
* Converts to {@link ZonedDateTime}.
* @param calendar value
* @return converted
*/
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME_TZ)
public ZonedDateTime toZonedDateTime(Calendar calendar) {
return calendar == null ? null : DateTimeHelper.toZonedDateTime(calendar);
}
}
| 32.058824 | 98 | 0.715596 |
c172a64825a9a682a2d39fb27cefa85246270f04 | 1,250 | /*
* Copyright 2009 Inspire-Software.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yes.cart.bulkcommon.service.support.query;
/**
* Query object ready to be passed to ORM framework.
*
* User: denispavlov
* Date: 12-08-08
* Time: 8:49 AM
*/
public interface LookUpQuery {
String NATIVE = "NATIVE";
String HSQL = "HSQL";
String LUCENE = "LUCENE";
/**
* @return type of this query as defined by constants of this interface
*/
String getQueryType();
/**
* @return query string with parameters as ?1, ?2, ... ?n
*/
String getQueryString();
/**
* @return corresponding value of objects
*/
Object[] getParameters();
}
| 26.041667 | 78 | 0.66 |
615e72225bb8121a60cb1c06e39be3704a7f4f38 | 2,795 | package lt.hototya.team;
import java.util.ArrayList;
import java.util.List;
import cn.nukkit.Player;
import cn.nukkit.Server;
import lt.hototya.team.event.AddPlayerEvent;
import lt.hototya.team.event.RemovePlayerEvent;
import lt.hototya.team.interfaces.ITeam;
public class Team implements ITeam {
private String teamName;
private int maxPlayer;
private List<String> member = new ArrayList<String>();
public Team(String teamName, int maxPlayer) {
this.teamName = teamName;
this.maxPlayer = maxPlayer;
}
@Override
public boolean addPlayer(Player player) {
return addPlayer(player.getName(), false);
}
@Override
public boolean addPlayer(Player player, boolean force) {
return addPlayer(player.getName(), force);
}
@Override
public boolean addPlayer(String player) {
return addPlayer(player, false);
}
@Override
public boolean addPlayer(String player, boolean force) {
AddPlayerEvent event = new AddPlayerEvent(player, this);
Server.getInstance().getPluginManager().callEvent(event);
if (!force) {
if (!event.isCancelled() && getPlayers().size() < getMaxPlayer()) {
return member.add(player);
} else {
return false;
}
} else {
member.add(player);
return true;
}
}
@Override
public boolean containsPlayer(Player player) {
return containsPlayer(player.getName());
}
@Override
public boolean containsPlayer(String player) {
return member.contains(player);
}
@Override
public int getMaxPlayer() {
return maxPlayer;
}
@Override
public List<String> getPlayers() {
return member;
}
@Override
public String getTeamName() {
return teamName;
}
@Override
public boolean removeAllMember() {
for (String player : getPlayers()) {
removePlayer(player);
}
return member.isEmpty();
}
@Override
public boolean removeAllMember(boolean force) {
for (String player : getPlayers()) {
removePlayer(player, force);
}
return member.isEmpty();
}
@Override
public boolean removePlayer(Player player) {
return removePlayer(player.getName(), false);
}
@Override
public boolean removePlayer(Player player, boolean force) {
return removePlayer(player.getName(), force);
}
@Override
public boolean removePlayer(String player) {
return removePlayer(player, false);
}
@Override
public boolean removePlayer(String player, boolean force) {
RemovePlayerEvent event = new RemovePlayerEvent(player, this);
Server.getInstance().getPluginManager().callEvent(event);
if (!force) {
if (!event.isCancelled()) {
return member.remove(player);
} else {
return false;
}
} else {
member.remove(player);
return true;
}
}
@Override
public void setMaxPlayer(int max) {
maxPlayer = max;
}
@Override
public void setTeamName(String name) {
teamName = name;
}
}
| 20.40146 | 70 | 0.714132 |
ad42202316d628c637ea0cda47779b54a55dab6b | 1,908 | package chat.rocket.android;
import android.os.StrictMode;
import android.support.multidex.MultiDexApplication;
import com.facebook.stetho.Stetho;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import java.util.List;
import chat.rocket.android.helper.OkHttpHelper;
import chat.rocket.persistence.realm.RealmStore;
import chat.rocket.android.service.ConnectivityManager;
import chat.rocket.core.models.ServerInfo;
import chat.rocket.android.widget.RocketChatWidgets;
import chat.rocket.persistence.realm.RocketChatPersistenceRealm;
/**
* Customized Application-class for Rocket.Chat
*/
public class RocketChatApplication extends MultiDexApplication {
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
enableStrictMode();
}
super.onCreate();
RocketChatPersistenceRealm.init(this);
List<ServerInfo> serverInfoList = ConnectivityManager.getInstance(this).getServerList();
for (ServerInfo serverInfo : serverInfoList) {
RealmStore.put(serverInfo.getHostname());
}
if (BuildConfig.DEBUG) {
enableStetho();
}
RocketChatWidgets.initialize(this, OkHttpHelper.getClientForDownloadFile(this));
}
private void enableStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.build());
}
private void enableStetho() {
Stetho.initialize(Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
}
}
| 30.285714 | 92 | 0.73847 |
d825dc264bab4b97dce17e1c53b4386ed6ce8c52 | 1,501 | package org.vadimjprokopev.token;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.vadimjprokopev.token.TokenType.*;
public class Tokenizer {
private static Map<String, TokenType> TOKEN_MAP = new HashMap<>();
static {
TOKEN_MAP.put("AWOO", SET);
TOKEN_MAP.put("WOOF", ADD);
TOKEN_MAP.put("BARK", SUBTRACT);
TOKEN_MAP.put("ARF", MULTIPLY);
TOKEN_MAP.put("YIP", LESS);
TOKEN_MAP.put("YAP", MORE);
TOKEN_MAP.put("RUF?", IF);
TOKEN_MAP.put("VUH", THEN_IF);
TOKEN_MAP.put("ROWH", ELSE);
TOKEN_MAP.put("ARRUF", END_IF);
TOKEN_MAP.put("GRRR", WHILE);
TOKEN_MAP.put("BOW", THEN_WHILE);
TOKEN_MAP.put("BORF", END_WHILE);
TOKEN_MAP.put("EOF", EOF);
}
private Token convertStringToToken(String input) {
TokenType tokenType = TOKEN_MAP.get(input);
if (tokenType != null) {
return new Token(tokenType, null, null);
} else {
if (input.matches("\\d+")) {
return new Token(CONSTANT, null, Integer.parseInt(input));
} else {
return new Token(VARIABLE, input, null);
}
}
}
public List<Token> convertSourceCodeToTokens(List<String> sourceCode) {
return sourceCode.stream()
.map(this::convertStringToToken)
.collect(Collectors.toList());
}
}
| 27.796296 | 75 | 0.588941 |
6c085829e964f2f56ac07423030cc629428793e1 | 2,978 | /*
* 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.table.catalog;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.descriptors.GenericInMemoryCatalogValidator;
import org.apache.flink.table.factories.CatalogFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_DEFAULT_DATABASE;
import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_PROPERTY_VERSION;
import static org.apache.flink.table.descriptors.CatalogDescriptorValidator.CATALOG_TYPE;
import static org.apache.flink.table.descriptors.GenericInMemoryCatalogValidator.CATALOG_TYPE_VALUE_GENERIC_IN_MEMORY;
/**
* 生产{@link GenericInMemoryCatalog}的工厂类
* Catalog factory for {@link GenericInMemoryCatalog}.
*/
public class GenericInMemoryCatalogFactory implements CatalogFactory {
@Override
public Map<String, String> requiredContext() {
Map<String, String> context = new HashMap<>();
context.put(CATALOG_TYPE, CATALOG_TYPE_VALUE_GENERIC_IN_MEMORY); // generic_in_memory
context.put(CATALOG_PROPERTY_VERSION, "1"); // backwards compatibility
return context;
}
@Override
public List<String> supportedProperties() {
List<String> properties = new ArrayList<>();
// default database
properties.add(CATALOG_DEFAULT_DATABASE);
return properties;
}
@Override
public Catalog createCatalog(String name, Map<String, String> properties) {
final DescriptorProperties descriptorProperties = getValidatedProperties(properties);
final Optional<String> defaultDatabase = descriptorProperties.getOptionalString(CATALOG_DEFAULT_DATABASE);
return new GenericInMemoryCatalog(name, defaultDatabase.orElse(GenericInMemoryCatalog.DEFAULT_DB));
}
private static DescriptorProperties getValidatedProperties(Map<String, String> properties) {
final DescriptorProperties descriptorProperties = new DescriptorProperties(true);
descriptorProperties.putProperties(properties);
new GenericInMemoryCatalogValidator().validate(descriptorProperties);
return descriptorProperties;
}
}
| 38.179487 | 118 | 0.80591 |
2f1308280e56af76123bbdd3b046e951268d46b7 | 188 | package com.ntk.reactor;
public class ReactorConstants {
public static final String HOST = "http://pornreactor.cc";
// public static final String HOST = "http://joyreactor.com";
}
| 26.857143 | 64 | 0.718085 |
d59320d0773391bb0c55a36f7fe06922923dd109 | 8,082 | /**
* RELOAD TOOLS
*
* Copyright (c) 2004 Oleg Liber, Bill Olivier, Phillip Beauvoir
*
* 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.
*
* Project Management Contact:
*
* Oleg Liber
* Bolton Institute of Higher Education
* Deane Road
* Bolton BL3 5AB
* UK
*
* e-mail: [email protected]
*
*
* Technical Contact:
*
* Phillip Beauvoir
* e-mail: [email protected]
*
* Web: http://www.reload.ac.uk
*
*/
package uk.ac.reload.editor.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import uk.ac.reload.dweezil.gui.GradientPanel;
import uk.ac.reload.dweezil.gui.UIFactory;
import uk.ac.reload.dweezil.gui.layout.RelativeLayoutManager;
import uk.ac.reload.editor.datamodel.DataComponent;
import uk.ac.reload.editor.datamodel.DataModel;
import uk.ac.reload.editor.datamodel.IDataComponentIcon;
import uk.ac.reload.editor.datamodel.IDataModelListener;
import uk.ac.reload.editor.gui.widgets.TitleLabelTextField;
/**
* Editor Panel based on GradientPanel with Title and Description<br>
* Although this is not an abstract class, it is meant to be extended.
*
* @author Phillip Beauvoir
* @version $Id: TitledEditorPanel.java,v 1.1 1998/03/26 15:24:11 ynsingh Exp $
*/
public class TitledEditorPanel
extends GradientPanel
implements IDataModelListener, Scrollable
{
public final static String TOPPANEL_ID = "TitledEditorPanel.TOPPANEL_ID";
/**
* The DataModel
*/
private DataModel _dataModel;
/**
* The backing Component
*/
private DataComponent _dataComponent;
/**
* The RelativeLayoutManager used to set out this panel
*/
private RelativeLayoutManager _layoutManager;
/**
* The Title label Text Field
*/
private TitleLabelTextField _labelTitle;
/**
* The Description label
*/
private JLabel _labelDescription;
/**
* Default Constructor
*/
public TitledEditorPanel() {
super();
}
/**
* Set the backing Component
* @param dataComponent the backing Component
*/
public void setComponent(DataComponent dataComponent) {
_dataComponent = dataComponent;
if(dataComponent instanceof IDataComponentIcon) {
getTitleLabel().setIcon(((IDataComponentIcon)dataComponent).getIcon());
}
getTitleLabel().setComponent(dataComponent);
getDescriptionLabel().setText("<html>" + getDescription());
// Lazily set the DataModel and listen to changes
if(_dataModel == null) {
_dataModel = dataComponent.getDataModel();
if(_dataModel != null) {
_dataModel.addIDataModelListener(this);
}
}
}
/**
* @return the backing Component
*/
public DataComponent getComponent() {
return _dataComponent;
}
/**
* @return The Title LabelText Field
*/
public TitleLabelTextField getTitleLabel() {
if(_labelTitle == null) {
_labelTitle = new TitleLabelTextField("Title");
_labelTitle.setFont(_labelTitle.getFont().deriveFont(Font.BOLD, 16));
}
return _labelTitle;
}
/**
* @return The Description Label
*/
public JLabel getDescriptionLabel() {
if(_labelDescription == null) {
_labelDescription = new JLabel("Description");
_labelDescription.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
}
return _labelDescription;
}
/**
* @return The Title of this Panel
*/
public String getTitle() {
return (_dataComponent == null) ? "Title" : _dataComponent.getTitle();
}
/**
* @return The Description of this Panel
*/
public String getDescription() {
return (_dataComponent == null) ? "Description" : _dataComponent.getDescription();
}
/**
* @return The RelativeLayoutManager used to set out this panel
*/
public RelativeLayoutManager getRelativeLayoutManager() {
if(_layoutManager == null) {
_layoutManager = new RelativeLayoutManager(this);
}
return _layoutManager;
}
/**
* Set up the view
*/
protected void setupView() {
super.setupView();
setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 60));
RelativeLayoutManager layoutManager = getRelativeLayoutManager();
// Add Top Panel
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setOpaque(false);
topPanel.add(getTitleLabel(), BorderLayout.NORTH);
topPanel.add(UIFactory.createGradientUnderLineBar(), BorderLayout.CENTER);
topPanel.add(getDescriptionLabel(), BorderLayout.SOUTH);
layoutManager.addFromLeftToRightEdges(topPanel, TOPPANEL_ID, RelativeLayoutManager.ROOT_NAME,
RelativeLayoutManager.TOP, 0, 0);
}
/**
* Clean up
*/
public void cleanup() {
_dataComponent = null;
_dataModel = null;
}
// ======================= Scrollable Interface ==================================
/* (non-Javadoc)
* @see javax.swing.Scrollable#getScrollableTracksViewportHeight()
*/
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
return false;
}
/* (non-Javadoc)
* @see javax.swing.Scrollable#getScrollableTracksViewportWidth()
*/
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
return false;
}
/* (non-Javadoc)
* @see javax.swing.Scrollable#getPreferredScrollableViewportSize()
*/
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
/* (non-Javadoc)
* @see javax.swing.Scrollable#getScrollableBlockIncrement(java.awt.Rectangle, int, int)
*/
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 15;
}
/* (non-Javadoc)
* @see javax.swing.Scrollable#getScrollableUnitIncrement(java.awt.Rectangle, int, int)
*/
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 15;
}
// ======================= Data Model Listeners ==================================
public void componentAdded(DataComponent component) {
}
public void componentRemoved(DataComponent component) {
}
/**
* If this component changed, set Text
*/
public void componentChanged(DataComponent component) {
if(component == _dataComponent) {
getTitleLabel().setText(getTitle());
}
}
public void componentMoved(DataComponent component) {
}
}
| 28.659574 | 97 | 0.668151 |
059586da2c0c805180f2bbd81e1a19ee8a8b7879 | 1,339 | package de.adorsys.ledgers.middleware.impl.sca;
import de.adorsys.ledgers.middleware.api.domain.sca.ChallengeDataTO;
import de.adorsys.ledgers.middleware.api.domain.sca.ScaDataInfoTO;
import de.adorsys.ledgers.middleware.api.domain.um.ScaMethodTypeTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Slf4j
@Component
public class PhotoOtpScaChallengeData extends AbstractScaChallengeData {
private static final String IMAGE_TAN_PATH = "photo-tan-1.png"; // stub for testing purposes
@Override
public ChallengeDataTO getChallengeData(ScaDataInfoTO template) {
ChallengeDataTO data = super.getChallengeData(template);
data.setImage(resolveImage());
return data;
}
@Override
public ScaMethodTypeTO getScaMethodType() {
return ScaMethodTypeTO.PHOTO_OTP;
}
private byte[] resolveImage() {
try {
Resource resource = new ClassPathResource(IMAGE_TAN_PATH);
return IOUtils.toByteArray(resource.getInputStream());
} catch (IOException e) {
log.error("Can't read image tan", e);
}
return new byte[]{};
}
}
| 31.880952 | 96 | 0.728902 |
acc1f3247fd61192a6bbd35f530fe02100183f57 | 960 | package mysteryDungeon.patches;
import com.evacipated.cardcrawl.modthespire.lib.*;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import mysteryDungeon.interfaces.onDiscardInterface;
public class OnDiscardPatch
{
@SpirePatch(clz = CardGroup.class, method = "moveToDiscardPile", paramtypez = {AbstractCard.class})
public static class AddedCardPatch
{
@SpirePostfixPatch
public static void onDiscard()
{
AbstractDungeon.player.powers.stream()
.filter(power -> power instanceof onDiscardInterface)
.forEach(power -> ((onDiscardInterface)power).onDiscard());
AbstractDungeon.player.relics.stream()
.filter(relic -> relic instanceof onDiscardInterface)
.forEach(relic -> ((onDiscardInterface)relic).onDiscard());
}
}
} | 34.285714 | 103 | 0.694792 |
65761c05db02ab06ebaf6e6a27c994c719d15a2e | 611 | /**
* This package contains the Hibernate code - entities and repository.
*
* There's absolutely nothing GraphQL specific about anything in this package. It could very well be replace with
* other database library tools like QueryDSL, JDBC a NoSQL data repository, etc.
*
* Some might find that the entity relationship is not very trivial. We have an abstract entity `FilmCharacter` with
* two concrete implementations: `Droid` and `Human`. This is to make this example support the same Star Wars GraphQL
* Schema used on other examples in this repo.
*/
package com.graphql.java.hibernate.example.data; | 55.545455 | 117 | 0.772504 |
956f7708bc861bf8e417c1ba439ab6c5d333ac5b | 1,872 | package org.opensha.refFaultParamDb.vo;
/**
* <p>Title: Reference.java </p>
* <p>Description: This class has information about the references </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class Reference {
private int referenceId=-1; // reference ID
private String refAuth; // short citation
private String refYear;
private String fullBiblioReference; // full bibliographic reference
private int qfaultReferenceId = -1;
public Reference() {
}
public String toString() {
return "Reference Author="+refAuth+"\n"+
"Reference Year="+refYear+"\n"+
"Full Bibliographic Ref="+this.fullBiblioReference;
}
public Reference(int referenceId, String author, String year, String fullBiblioReference) {
this(author, year, fullBiblioReference);
setReferenceId(referenceId);
}
public Reference(String author, String year, String fullBiblioReference) {
this.setRefAuth(author);
this.setRefYear(year);
this.setFullBiblioReference(fullBiblioReference);
}
public int getReferenceId() {
return referenceId;
}
public void setReferenceId(int referenceId) {
this.referenceId = referenceId;
}
public int getQfaultReferenceId() {
return this.qfaultReferenceId;
}
public void setQfaultReferenceId(int qfaultRefId) {
this.qfaultReferenceId = qfaultRefId;
}
public String getFullBiblioReference() {
return fullBiblioReference;
}
public void setFullBiblioReference(String fullBiblioReference) {
this.fullBiblioReference = fullBiblioReference;
}
public String getRefAuth() {
return refAuth;
}
public void setRefAuth(String refAuth) {
this.refAuth = refAuth;
}
public void setRefYear(String refYear) {
this.refYear = refYear;
}
public String getRefYear() {
return refYear;
}
public String getSummary() {
return this.refAuth+" ("+refYear+")";
}
}
| 24.96 | 92 | 0.738782 |
2c099744815a1f16199449b6fa4d93468e2de37b | 5,325 | package com.hadoop.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import com.hadoop.mapreduce.PlayinputFormat;
import com.hadoop.mapreduce.TVplaydata;
import teacher.tvplay.TVPlayCount;
/**
* @input params 各类网站每天每部电视剧的点播量 收藏量 评论数 等数据的统计
* @ouput params 分别输出每个网站 每部电视剧总的统计数据
* @author yangjun
* @function 自定义FileInputFormat 将电视剧的统计数据 根据不同网站以MultipleOutputs 输出到不同的文件夹下
*/
public class TVPlayCountCopy extends Configured implements Tool {
/**
* @input Params Text TvPlayData
* @output Params Text TvPlayData
* @author yangjun
* @function 直接输出
*/
public static class TVPlayMapper extends
Mapper<Text, TVplaydata, Text, TVplaydata> {
public void map(Text key,TVplaydata value, Context context) throws IOException, InterruptedException {
context.write(key, value);
}
}
/**
* @input Params Text TvPlayData
* @output Params Text Text
* @author yangjun
* @fuction 统计每部电视剧的 点播数 收藏数等 按source输出到不同文件夹下
*/
public static class TVPlayReducer extends
Reducer<Text, TVplaydata, Text, Text> {
private Text m_key = new Text();
private Text m_value = new Text();
private MultipleOutputs<Text, Text> mos;
protected void setup(Context context) throws IOException,
InterruptedException {
mos = new MultipleOutputs<Text, Text>(context);
}
protected void reduce(Text key,Iterable<TVplaydata> values, Context context) throws IOException, InterruptedException{
int tvplaynum = 0;
int tvfavorite = 0;
int tvcomment = 0;
int tvvote = 0;
int tvdown = 0;
for (TVplaydata tv:values) {
tvplaynum += tv.getTvpalynum();
tvfavorite += tv.getTvfavorite();
tvcomment += tv.getTvcomment();
tvvote += tv.getTvvote();
tvdown += tv.getTvdown();
}
//读取电视剧名称以及播放网站
//通过制表符分割 成为数组
String[] records = key.toString().split("\t");
// 1优酷2搜狐3土豆4爱奇艺5迅雷看看
String source = records[1];//获取媒体名称
m_key.set(records[0]);
m_value.set(tvplaynum+"\t"+tvfavorite+"\t"+tvcomment+"\t"+tvdown+"\t"+tvvote);
//对类别进行判断,,如果是一个类别就输出到一个文件中
//mos.write(source, m_key, m_value);
if(source.equals("1")){
mos.write("youku", m_key, m_value);
}else if (source.equals("2")) {
mos.write("souhu", m_key, m_value);
}else if (source.equals("3")) {
mos.write("tudou",m_key, m_value);
}else if (source.equals("4")) {
mos.write("aiqiyi", m_key, m_value);
}else if (source.equals("5")) {
mos.write("xunlei", m_key, m_value);
}else{
mos.write("other", m_key, m_value);
}
}
protected void cleanup(Context context) throws IOException ,InterruptedException{
mos.close();
}
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = new Configuration();// 配置文件对象
Path mypath = new Path(args[1]);
FileSystem hdfs = mypath.getFileSystem(conf);// 创建输出路径
if (hdfs.isDirectory(mypath)) {
hdfs.delete(mypath, true);
}
Job job = new Job(conf, "tvplay");// 构造任务
job.setJarByClass(TVPlayCountCopy.class);// 设置主类
job.setMapperClass(TVPlayMapper.class);// 设置Mapper
job.setMapOutputKeyClass(Text.class);// key输出类型
job.setMapOutputValueClass(TVplaydata.class);// value输出类型
job.setInputFormatClass(PlayinputFormat.class);//自定义输入格式
job.setReducerClass(TVPlayReducer.class);// 设置Reducer
job.setOutputKeyClass(Text.class);// reduce key类型
job.setOutputValueClass(Text.class);// reduce value类型
// 自定义文件输出格式,通过路径名(pathname)来指定输出路径
MultipleOutputs.addNamedOutput(job, "youku", TextOutputFormat.class,
Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "souhu", TextOutputFormat.class,
Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "tudou", TextOutputFormat.class,
Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "aiqiyi", TextOutputFormat.class,
Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "xunlei", TextOutputFormat.class,
Text.class, Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));// 输入路径
FileOutputFormat.setOutputPath(job, new Path(args[1]));// 输出路径
job.waitForCompletion(true);
return 0;
}
public static void main(String[] args) throws Exception {
String[] paths = {"hdfs://wang:9000/mapreduce/tvplay.txt","hdfs://wang:9000/mapreduce/tvout/"};
int ec = ToolRunner.run(new Configuration(), new TVPlayCountCopy(), paths);
System.exit(ec);
//public static int run(Configuration conf,Tool tool, String[] args),可以在job运行的时候指定配置文件或其他参数
//这个方法调用tool的run(String[])方法,并使用conf中的参数,以及args中的参数,而args一般来源于命令行。
}
}
| 34.803922 | 120 | 0.711737 |
d69a10c1e1c0093bd11c16c4a045162e23d79336 | 4,040 | /*****************************************************************
* 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
*
* https://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.cayenne.modeler;
import org.apache.cayenne.configuration.DataNodeDescriptor;
import org.apache.cayenne.map.DataMap;
import org.apache.cayenne.modeler.action.LinkDataMapAction;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
public class TreeDropTarget implements DropTargetListener, Transferable {
private DropTarget target;
private JTree targetTree;
private ProjectController eventController;
private TreePath parentPath;
private TreePath targetPath;
public TreeDropTarget(JTree tree, ProjectController eventController, TreePath parentPath) {
targetTree = tree;
this.eventController = eventController;
this.parentPath = parentPath;
target = new DropTarget(targetTree, this);
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
Point p = dtde.getLocation();
targetPath = targetTree.getPathForLocation(p.x, p.y);
}
public void dragExit(DropTargetEvent dte) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void drop(DropTargetDropEvent dtde) {
if (targetPath != null) {
try {
dtde.acceptDrop(dtde.getDropAction());
DefaultMutableTreeNode target = (DefaultMutableTreeNode) targetPath.getLastPathComponent();
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentPath.getLastPathComponent();
if (target.getUserObject() instanceof DataNodeDescriptor && parent.getUserObject() instanceof DataMap) {
DataNodeDescriptor currentDataNode = (DataNodeDescriptor) target.getUserObject();
DataMap currentDataMap = (DataMap) parent.getUserObject();
LinkDataMapAction action = eventController.getApplication().getActionManager().getAction(LinkDataMapAction.class);
action.linkDataMap(currentDataMap, currentDataNode);
targetTree.makeVisible(targetPath.pathByAddingChild(target));
dtde.dropComplete(true);
}
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
}
public TreePath getPath() {
return this.targetPath;
}
public Object getTransferData(DataFlavor arg0) throws UnsupportedFlavorException, IOException {
return null;
}
public DataFlavor[] getTransferDataFlavors() {
return null;
}
public boolean isDataFlavorSupported(DataFlavor arg0) {
return false;
}
} | 37.06422 | 134 | 0.683416 |
bd60db2f9c11cebe1a04ebfa7f5afae0967232d3 | 4,852 | /*
* Copyright 2011, 2012:
* Tobias Fleig (tobifleig[AT]googlemail[DOT]com)
* Michael Haas (mekhar[AT]gmx[DOT]de)
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de
*
* - All rights reserved -
*
* 13ducks PROPRIETARY/CONFIDENTIAL - do not distribute
*/
package de._13ducks.spacebatz.client.sound;
import de._13ducks.spacebatz.shared.DefaultSettings;
import java.io.File;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import paulscode.sound.Library;
import paulscode.sound.SoundSystem;
import paulscode.sound.SoundSystemConfig;
import paulscode.sound.codecs.CodecJOrbis;
import paulscode.sound.libraries.LibraryJavaSound;
import paulscode.sound.libraries.LibraryLWJGLOpenAL;
/**
* Das OpenAL-Soundmodul.
* Lädt alle Ogg-Dateien im "sound"-Ordner beim Starten.
* Kann Soundeffekte und Musik abspielen, pausieren und stoppen.
*
* @author michael
*/
public class SoundEngine implements SoundProvider{
static {
// Hack, um nachträglich java.library.path zu setzen.
try {
System.setProperty("java.library.path", "native/");
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
System.out.println("[ERROR]: Failed to set library lookup path! Details:");
ex.printStackTrace();
}
}
private SoundSystem soundSystem;
private boolean loading = true;
/**
* Konstruktor.
*
* Lädt in einem neuen thread alle ogg-Sounds aus dem "sound"-Verzeichnis
*/
public SoundEngine() {
soundSystem = initSoundSystem();
loadSounds();
}
private void loadSounds() {
Thread soundLoader = new Thread(new Runnable() {
@Override
public void run() {
File soundFolder = new File("sound/effects/");
for (int i = 0; i < soundFolder.listFiles().length; i++) {
File sound = soundFolder.listFiles()[i];
if (sound.getName().contains(".ogg")) {
try {
soundSystem.loadSound(sound.toURL(), sound.getName());
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
}
loading = false;
}
});
soundLoader.setName("soundLoader");
soundLoader.start();
}
/**
* Spielt einen Soundeffekt einmal ab.
*
* @param filename
*/
public void soundEffect(String filename) {
if (!loading) {
soundSystem.quickPlay(false, filename, false, 0, 0, 0, SoundSystemConfig.ATTENUATION_NONE, 0);
soundSystem.removeTemporarySources();
}
}
/**
* Spielt Hintergrundmusik ab.
*
* @param identifier
* @param filename
*/
public void backgroundMusic(String filename, Boolean loop) {
if(DefaultSettings.CLIENT_SFX_DISABLE_MUSIC){
return;
}
File sound = new File(filename);
URL url = null;
try {
url = sound.toURL();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
soundSystem.newStreamingSource(true, sound.getName(), url, sound.getName(), loop, 0, 0, 0, SoundSystemConfig.ATTENUATION_NONE, 1);
soundSystem.play(sound.getName());
}
/**
* Initialisiert das Soundsystem.
*
* @return
*/
private SoundSystem initSoundSystem() {
try {
boolean openALCompatible = SoundSystem.libraryCompatible(LibraryLWJGLOpenAL.class);
boolean javaSoundCompatible = SoundSystem.libraryCompatible(LibraryJavaSound.class);
Class libraryType;
if (openALCompatible) {
libraryType = LibraryLWJGLOpenAL.class; // OpenAL
} else if (javaSoundCompatible) {
libraryType = LibraryJavaSound.class; // Java Sound
} else {
libraryType = Library.class; // "No Sound, Silent Mode"
}
SoundSystemConfig.setCodec("ogg", CodecJOrbis.class); // Ogg-Codec laden
SoundSystem mySoundSystem = new SoundSystem(libraryType); // Soundsystem initialisieren
return mySoundSystem;
} catch (Exception sse) {
sse.printStackTrace();
return null;
}
}
/**
* Gibt benutzten Speicher wieder frei.
*/
public void shutdown() {
soundSystem.cleanup();
}
public boolean isReady() {
return !loading;
}
}
| 31.303226 | 138 | 0.599547 |
57095d4d5a436899581f7c5e189b4f696fb9b311 | 1,319 | package mclaudio76.persistence.springjpajta.services;
import java.util.logging.Logger;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/****
* Provides a JTAPlatform concrete implementation to be set as hibernate.transaction.jta.platform property
* while configure EntityManagers.
*
*/
@Component("CustomJTAPlatform")
public class CustomJTAPlatform extends AbstractJtaPlatform {
private static final long serialVersionUID = 1L;
private static TransactionManager txManager;
private static UserTransaction userTx;
@Autowired
public void setJTAPlatformTXManager(TransactionManager txManager) {
this.txManager = txManager;
Logger.getLogger(this.getClass().getCanonicalName()).info("Inject TxManager "+txManager);
}
@Autowired
public void setJTAPlatformUserTransaction(UserTransaction userTx) {
this.userTx = userTx;
}
@Override
protected TransactionManager locateTransactionManager() {
return txManager;
}
@Override
protected UserTransaction locateUserTransaction() {
return userTx;
}
}
| 26.38 | 108 | 0.774071 |
62398f55edbe0588d20547c63c140cbadf19e80c | 482 | package com.xhh.demo.http.aop.spring;
import org.springframework.stereotype.Service;
/**
* BookServiceImpl
*
* @author tiger
* @version 1.0.0 createTime: 14-4-19
* @since 1.6
*/
@Service
public class BookServiceImpl {
public void save(String bookName) {
System.out.println("执行 save 方法");
}
public void update(String bookId) {
System.out.println("执行 update 方法");
}
public void list() {
System.out.println("执行 list 方法");
}
}
| 17.851852 | 46 | 0.634855 |
77632784ccf092a6e702e3089e121c23f2330830 | 4,726 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.ecsops.transform.v20160401;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.ecsops.model.v20160401.OpsQueryDetailImpactResponse;
import com.aliyuncs.ecsops.model.v20160401.OpsQueryDetailImpactResponse.ImpactDetailInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class OpsQueryDetailImpactResponseUnmarshaller {
public static OpsQueryDetailImpactResponse unmarshall(OpsQueryDetailImpactResponse opsQueryDetailImpactResponse, UnmarshallerContext _ctx) {
opsQueryDetailImpactResponse.setRequestId(_ctx.stringValue("OpsQueryDetailImpactResponse.RequestId"));
opsQueryDetailImpactResponse.setTotalCount(_ctx.integerValue("OpsQueryDetailImpactResponse.TotalCount"));
List<ImpactDetailInfo> impactDetailInfos = new ArrayList<ImpactDetailInfo>();
for (int i = 0; i < _ctx.lengthValue("OpsQueryDetailImpactResponse.ImpactDetailInfos.Length"); i++) {
ImpactDetailInfo impactDetailInfo = new ImpactDetailInfo();
impactDetailInfo.setAliUid(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].AliUid"));
impactDetailInfo.setInstanceId(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].InstanceId"));
impactDetailInfo.setCluster(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Cluster"));
impactDetailInfo.setPhysicalModel(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].PhysicalModel"));
impactDetailInfo.setInstanceType(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].InstanceType"));
impactDetailInfo.setAdditionalInfo(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].AdditionalInfo"));
impactDetailInfo.setNcIp(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].NcIp"));
impactDetailInfo.setAZone(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].AZone"));
impactDetailInfo.setZone(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Zone"));
impactDetailInfo.setStatus(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Status"));
impactDetailInfo.setAsw(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Asw"));
impactDetailInfo.setProductName(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].ProductName"));
impactDetailInfo.setReason(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Reason"));
impactDetailInfo.setIsLocalDisk(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].IsLocalDisk"));
impactDetailInfo.setRoom(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Room"));
impactDetailInfo.setExceptionTime(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].ExceptionTime"));
impactDetailInfo.setRegion(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Region"));
impactDetailInfo.setIdc(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Idc"));
impactDetailInfo.setIsPhysicalMachine(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].IsPhysicalMachine"));
impactDetailInfo.setGcLevel(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].GcLevel"));
impactDetailInfo.setCores(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Cores"));
impactDetailInfo.setGocCores(_ctx.floatValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].GocCores"));
impactDetailInfo.setWarningLevel(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].WarningLevel"));
impactDetailInfo.setRack(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].Rack"));
impactDetailInfo.setIsStorageNc(_ctx.stringValue("OpsQueryDetailImpactResponse.ImpactDetailInfos["+ i +"].IsStorageNc"));
impactDetailInfos.add(impactDetailInfo);
}
opsQueryDetailImpactResponse.setImpactDetailInfos(impactDetailInfos);
return opsQueryDetailImpactResponse;
}
} | 70.537313 | 141 | 0.801312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.