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
|
---|---|---|---|---|---|
f5fe0d78181bb5b02fe20dd8bf2ed9d7fcce64f1 | 2,190 | package com.example.algo1.sort.mergenquick;
import java.util.Comparator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.example.algo1.sort.Ticket;
public class MergeSortObjectStabilityTest {
MergeSortObject<Ticket> mergeSorttickets;
MergeSortObject<String> mergeString;
@BeforeEach
public void setup() {
Ticket t22 = Ticket.builder().ticket("2").location("ny").time("03:05").build();
Ticket t1 = Ticket.builder().ticket("1").location("chicago").time("09:05").build();
Ticket t21 = Ticket.builder().ticket("2").location("ny").time("10:15").build();
Ticket t12 = Ticket.builder().ticket("12").location("chicago").time("02:05").build();
Ticket t3 = Ticket.builder().ticket("3").location("la").time("11:15").build();
Ticket t33 = Ticket.builder().ticket("33").location("la").time("12:05").build();
Ticket t2 = Ticket.builder().ticket("2").location("ny").time("10:05").build();
Ticket t13 = Ticket.builder().ticket("13").location("chicago").time("01:05").build();
Ticket t32 = Ticket.builder().ticket("32").location("la").time("09:35").build();
Ticket t23 = Ticket.builder().ticket("2").location("ny").time("11:13").build();
Ticket t11 = Ticket.builder().ticket("11").location("chicago").time("09:25").build();
Ticket t31 = Ticket.builder().ticket("31").location("la").time("11:05").build();
mergeSorttickets = new MergeSortObject<Ticket>(new Ticket[] {t2,t22,t1,t3,t12,t21,t31,
t33,t11,t23,t3,t22,t32,t13});
}
@Test
public void testSortTicketsStability() {
mergeSorttickets.print();
//mergeSorttickets.sort(mergeSorttickets.arr, new Ticket[mergeSorttickets.arr.length],
// new SortByTime());
mergeSorttickets.print();
//mergeSorttickets.sort(mergeSorttickets.arr, new Ticket[mergeSorttickets.arr.length],
// new SortByLocation());
mergeSorttickets.print();
}
@Test
public void testString() {
mergeString = new MergeSortObject<String>(new String[] {
"this","is","not","how","i","see","it","going"
});
mergeString.print();
mergeString.sort(mergeString.arr , new String[mergeString.arr.length],
Comparator.comparing(String::toString));
mergeString.print();
}
}
| 38.421053 | 89 | 0.690411 |
371ac338cdb545a94f3100a9619eed541b573872 | 4,814 | package ameba.db.dsl;
import ameba.db.dsl.QueryExprMeta.Val;
import com.google.common.collect.Lists;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import java.util.Collections;
import java.util.List;
/**
* <p>QueryExprListener class.</p>
*
* @author icode
*
*/
public class QueryExprListener extends QueryBaseListener {
private ParseTreeProperty<QueryExprMeta> infoMap = new ParseTreeProperty<>();
private List<QueryExprMeta> queryExprMetaList = Lists.newArrayList();
private QueryExprMeta queryExprMeta;
/**
* <p>Getter for the field <code>queryExprMetaList</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<QueryExprMeta> getQueryExprMetaList() {
return queryExprMetaList;
}
/**
* {@inheritDoc}
*/
@Override
public void exitSourceElements(QueryParser.SourceElementsContext ctx) {
infoMap = null;
queryExprMeta = null;
queryExprMetaList = Collections.unmodifiableList(queryExprMetaList);
}
/** {@inheritDoc} */
@Override
public void exitSourceElement(QueryParser.SourceElementContext ctx) {
if (queryExprMeta != null) {
String op = queryExprMeta.operator();
if (op == null) {
String co = queryExprMeta.field();
if (co != null && queryExprMeta.arguments() == null) {
int offset = co.lastIndexOf('.');
if (offset == -1) {
if (queryExprMeta.parent() == null) {
queryExprMeta.operator(co);
queryExprMeta.field(null);
} else {
List<Val<?>> args = queryExprMeta.parent().arguments();
int argOffset = -1;
for (int i = 0; i < args.size(); i++) {
Val val = args.get(i);
if (queryExprMeta.equals(val.object())) {
argOffset = i;
break;
}
}
if (argOffset != -1) {
args.set(argOffset, Val.of(co));
queryExprMeta = null;
}
}
} else {
queryExprMeta.field(co.substring(0, offset));
queryExprMeta.operator(co.substring(offset + 1));
}
}
}
}
}
/** {@inheritDoc} */
@Override
public void enterSourceElement(QueryParser.SourceElementContext ctx) {
queryExprMeta = QueryExprMeta.create();
infoMap.put(ctx, queryExprMeta);
// root source element
if (ctx.getParent() instanceof QueryParser.SourceElementsContext) {
queryExprMetaList.add(queryExprMeta);
} else {
QueryExprMeta parentInfo = infoMap.get(getParentSourceElement(ctx)).arguments(queryExprMeta);
queryExprMeta.parent(parentInfo);
}
}
/** {@inheritDoc} */
@Override
public void exitIdentifierName(QueryParser.IdentifierNameContext ctx) {
queryExprMeta.operator(ctx.getText());
}
/** {@inheritDoc} */
@Override
public void exitFieldExpression(QueryParser.FieldExpressionContext ctx) {
queryExprMeta.field(ctx.getText());
}
/** {@inheritDoc} */
@Override
public void exitLiteral(QueryParser.LiteralContext ctx) {
String text = ctx.getText();
if (ctx.NullLiteral() != null) {
queryExprMeta.arguments(Val.of());
} else if (ctx.BooleanLiteral() != null) {
queryExprMeta.arguments(Val.ofBool(text));
} else if (ctx.DecimalLiteral() != null) {
queryExprMeta.arguments(Val.ofDecimal(text));
} else {
queryExprMeta.arguments(Val.of(text));
}
}
/** {@inheritDoc} */
@Override
public void exitIdentifierVal(QueryParser.IdentifierValContext ctx) {
queryExprMeta.arguments(Val.of(ctx.getText()));
}
/**
* <p>getParentSourceElement.</p>
*
* @param node a {@link org.antlr.v4.runtime.ParserRuleContext} object.
* @return a {@link org.antlr.v4.runtime.ParserRuleContext} object.
*/
protected ParserRuleContext getParentSourceElement(ParserRuleContext node) {
if (node == null) return null;
ParserRuleContext parent = node.getParent();
if (parent instanceof QueryParser.SourceElementContext) {
return parent;
}
return getParentSourceElement(parent);
}
}
| 34.141844 | 105 | 0.552763 |
a813567efb5b13b0700eff1d6c56f60b6fd4c763 | 1,395 | package com.oneandone.iocunitejb.ejbs;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.jms.Message;
import javax.jms.MessageListener;
import org.slf4j.Logger;
/**
* @author aschoerk
*/
@MessageDriven(name = "TMdbEjb", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "myTopic")
})
@ApplicationScoped
public class TMdbEjb implements MessageListener {
@Inject
Logger logger;
@Inject
private MdbEjbInfoSingleton mdbEjbInfoSingleton;
@Resource
MessageDrivenContext mdbContext;
private static AtomicInteger called = new AtomicInteger();
@Override
public void onMessage(Message message) {
try {
Thread.sleep(100 * new Random().nextInt(50));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
logger.info("Message in TMdbEjb: {} this is the {}. received message", message, called.addAndGet(1));
mdbEjbInfoSingleton.incrementNumberOfTCalls();
}
}
| 28.469388 | 109 | 0.729032 |
ff2ff294128430de5e50433294cd4c18f724694a | 388 | public class TimeTester
{
public static void main(String[] args)
{
Time currentTime = new Time(9,45);
Time secondTime = new Time(14, 30);
System.out.println(currentTime.getMilitaryTime());
System.out.println(secondTime.getMilitaryTime());
System.out.println(currentTime.getTime());
System.out.println(secondTime.getTime());
}
}
| 29.846154 | 58 | 0.646907 |
fde37e051e060d5fc1fd9d4aeffc6332a42f922f | 2,270 | package farsight.testing.utils.jexl;
import java.util.ArrayList;
import org.apache.commons.jexl3.JexlExpression;
import com.wm.data.IData;
import com.wm.data.IDataFactory;
import farsight.testing.utils.jexl.context.ResourceContext;
import farsight.testing.utils.jexl.context.WmIDataContext;
import farsight.testing.utils.jexl.functions.LoadFunction;
import farsight.testing.utils.jexl.legacy.JexlExpressionFactory;
public class JexlExpressionUtil {
public static IData executeValueExpressions(IData idata, String jexlValueExpressions, ResourceContext resourceContext) {
if(idata == null)
idata = IDataFactory.create();
IDataJexlContext ctx = new IDataJexlContext(idata);
ctx.registerNamespace("load", new LoadFunction(resourceContext, ctx));
int stmtCounter = 0;
try {
for (String expr : jexlValueExpressions.split(";")) {
JexlExpressionFactory.createExpression(expr).evaluate(ctx);
stmtCounter++;
}
} catch(Exception e) {
System.err.println("Error interpreting JexlExpression(" + stmtCounter + "):");
System.err.println(jexlValueExpressions);
e.printStackTrace(System.err);
throw e;
}
return idata;
}
public static boolean evaluatePipelineExpression(IData idata, String jexlPipelineExpression) {
try {
JexlExpression expression = JexlExpressionFactory.createExpression(jexlPipelineExpression);
return (Boolean) expression.evaluate(new IDataJexlContext(idata));
} catch (Exception e) {
System.err.println("parsing the expression '"+jexlPipelineExpression+"' failed");
e.printStackTrace(System.err);
throw e;
}
}
public static IData evaluateDocumentExpression(String expression, IData source) {
Object o = new IDataJexlContext(source).get(expression);
return o != null && o instanceof WmIDataContext ? ((WmIDataContext)o).getIData() : null;
}
//nameing!!!
public static String findFailedPath(String expression, IData source) {
ArrayList<String> result = new ArrayList<>();
WmIDataContext ctx = new WmIDataContext(source);
Object o = null;
for(String part: expression.split("\\.")) {
result.add(part);
o = ctx.get(part);
if(o instanceof WmIDataContext) {
ctx = (WmIDataContext) o;
} else {
break;
}
}
return String.join(".", result);
}
}
| 31.09589 | 121 | 0.740969 |
e0a0e74343d23f98702b9a45a772df5f5356fcaa | 757 | package com.ccy.blog.category;
import java.util.HashSet;
import java.util.Set;
import com.ccy.blog.blog.Blog;
public class Category {
private int id;
private String name;
private String description;
private Set<Blog> blogs = new HashSet<Blog>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Blog> getBlogs() {
return blogs;
}
public void setBlogs(Set<Blog> blogs) {
this.blogs = blogs;
}
}
| 17.604651 | 50 | 0.655218 |
9613189a1baa77720667eba3ac9d43ad8dbe02fe | 2,771 | package com.wolf.gamefix.ui;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import com.wolf.gamefix.R;
import com.wolf.gamefix.adapters.LeagueAdapter;
import com.wolf.gamefix.models.League;
import com.wolf.gamefix.services.LeagueService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.league_recycler_view)
RecyclerView leagueRecyclerView;
private LeagueAdapter leagueAdapter;
private ArrayList<League> mLeagues = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Leagues");
createProgressDialog();
ButterKnife.bind(this);
initRecyclerView();
}
public void initRecyclerView()
{
progressDialog.show();
final LeagueService leagueService = new LeagueService();
leagueService.getLeagues(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.hide();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
mLeagues= leagueService.processGetAllLeaguesResults(response);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.hide();
leagueAdapter = new LeagueAdapter(mLeagues,MainActivity.this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
leagueRecyclerView.setLayoutManager(layoutManager);
/* leagueRecyclerView.setAdapter(leagueAdapter);*/
}
});
}
});
}
private void createProgressDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Fetching Leagues...");
progressDialog.setCancelable(false);
}
}
| 30.788889 | 110 | 0.642367 |
8acc016fc0287db242aaaa79ecc91b46230cf23d | 249 | package io.github.likcoras.asuka.handler.response;
import io.github.likcoras.asuka.AsukaBot;
import io.github.likcoras.asuka.exception.ResponseException;
public interface BotResponse {
public void send(AsukaBot bot) throws ResponseException;
}
| 22.636364 | 60 | 0.823293 |
116df12af4bfd311105fb3901fdac3b49107ab71 | 407 | package com.stephenslatky.logic;
import com.stephenslatky.gui.Board_View;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Board_View board_view = new Board_View();
Board board = new Board(11,13);
Basic_Rules basic_Rules = new Basic_Rules();
board.init_board(basic_Rules);
board.toString();
}
}
| 22.611111 | 63 | 0.683047 |
4c76a6d733375908db7c87c9209370ea2e320fa0 | 47,953 | /*
* Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.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.
*/
/*
* JschNodeExecutor.java
*
* User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
* Created: 3/21/11 4:46 PM
*
*/
package com.dtolabs.rundeck.core.execution.impl.jsch;
import com.dtolabs.rundeck.core.Constants;
import com.dtolabs.rundeck.core.cli.CLIUtils;
import com.dtolabs.rundeck.core.common.Framework;
import com.dtolabs.rundeck.core.common.FrameworkProject;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.dispatcher.DataContextUtils;
import com.dtolabs.rundeck.core.execution.ExecutionContext;
import com.dtolabs.rundeck.core.execution.ExecutionListener;
import com.dtolabs.rundeck.core.execution.impl.common.AntSupport;
import com.dtolabs.rundeck.core.execution.service.NodeExecutor;
import com.dtolabs.rundeck.core.execution.service.NodeExecutorResult;
import com.dtolabs.rundeck.core.execution.service.NodeExecutorResultImpl;
import com.dtolabs.rundeck.core.execution.utils.LeadPipeOutputStream;
import com.dtolabs.rundeck.core.execution.utils.Responder;
import com.dtolabs.rundeck.core.execution.utils.ResponderTask;
import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason;
import com.dtolabs.rundeck.core.execution.workflow.steps.StepFailureReason;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepFailureReason;
import com.dtolabs.rundeck.core.plugins.configuration.*;
import com.dtolabs.rundeck.core.storage.ResourceMeta;
import com.dtolabs.rundeck.core.tasks.net.ExtSSHExec;
import com.dtolabs.rundeck.core.tasks.net.SSHTaskBuilder;
import com.dtolabs.rundeck.core.utils.IPropertyLookup;
import com.dtolabs.rundeck.plugins.util.DescriptionBuilder;
import com.dtolabs.rundeck.plugins.util.PropertyBuilder;
import com.jcraft.jsch.JSchException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.rundeck.storage.api.Path;
import org.rundeck.storage.api.PathUtil;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Pattern;
/**
* JschNodeExecutor is ...
*
* @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
*/
public class JschNodeExecutor implements NodeExecutor, Describable {
public static final Logger logger = Logger.getLogger(JschNodeExecutor.class.getName());
public static final String SERVICE_PROVIDER_TYPE = "jsch-ssh";
public static final String FWK_PROP_AUTH_CANCEL_MSG = "framework.messages.error.ssh.authcancel";
public static final String FWK_PROP_AUTH_CANCEL_MSG_DEFAULT =
"Authentication failure connecting to node: \"{0}\". Make sure your resource definitions and credentials are up to date.";
public static final String FWK_PROP_AUTH_FAIL_MSG = "framework.messages.error.ssh.authfail";
public static final String FWK_PROP_AUTH_FAIL_MSG_DEFAULT =
"Authentication failure connecting to node: \"{0}\". Password incorrect.";
public static final String NODE_ATTR_SSH_KEYPATH = "ssh-keypath";
public static final String NODE_ATTR_SSH_KEY_RESOURCE = "ssh-key-storage-path";
public static final String PROJ_PROP_PREFIX = "project.";
public static final String FWK_PROP_PREFIX = "framework.";
public static final String FWK_PROP_SSH_KEYPATH = FWK_PROP_PREFIX + NODE_ATTR_SSH_KEYPATH;
public static final String PROJ_PROP_SSH_KEYPATH = PROJ_PROP_PREFIX + NODE_ATTR_SSH_KEYPATH;
public static final String FWK_PROP_SSH_KEY_RESOURCE = FWK_PROP_PREFIX + NODE_ATTR_SSH_KEY_RESOURCE;
public static final String PROJ_PROP_SSH_KEY_RESOURCE = PROJ_PROP_PREFIX + NODE_ATTR_SSH_KEY_RESOURCE;
public static final String NODE_ATTR_SSH_AUTHENTICATION = "ssh-authentication";
public static final String NODE_ATTR_SSH_PASSWORD_OPTION = "ssh-password-option";
public static final String DEFAULT_SSH_PASSWORD_OPTION = "option.sshPassword";
public static final String SUDO_OPT_PREFIX = "sudo-";
public static final String SUDO2_OPT_PREFIX = "sudo2-";
public static final String NODE_ATTR_SUDO_PASSWORD_OPTION = "password-option";
public static final String DEFAULT_SUDO_PASSWORD_OPTION = "option.sudoPassword";
public static final String DEFAULT_SUDO2_PASSWORD_OPTION = "option.sudo2Password";
public static final String NODE_ATTR_SSH_KEY_PASSPHRASE_OPTION = "ssh-key-passphrase-option";
public static final String DEFAULT_SSH_KEY_PASSPHRASE_OPTION = "option.sshKeyPassphrase";
public static final String FWK_PROP_SSH_AUTHENTICATION = FWK_PROP_PREFIX + NODE_ATTR_SSH_AUTHENTICATION;
public static final String PROJ_PROP_SSH_AUTHENTICATION = PROJ_PROP_PREFIX + NODE_ATTR_SSH_AUTHENTICATION;
public static final String NODE_ATTR_SUDO_COMMAND_ENABLED = "command-enabled";
public static final String NODE_ATTR_SUDO_PROMPT_PATTERN = "prompt-pattern";
public static final String DEFAULT_SUDO_PROMPT_PATTERN = "^\\[sudo\\] password for .+: .*";
public static final String NODE_ATTR_SUDO_FAILURE_PATTERN = "failure-pattern";
public static final String DEFAULT_SUDO_FAILURE_PATTERN = "^.*try again.*";
public static final String NODE_ATTR_SUDO_COMMAND_PATTERN = "command-pattern";
public static final String DEFAULT_SUDO_COMMAND_PATTERN = "^sudo$";
public static final String DEFAULT_SUDO2_COMMAND_PATTERN = "^sudo .+? sudo .*$";
public static final String NODE_ATTR_SUDO_PROMPT_MAX_LINES = "prompt-max-lines";
public static final int DEFAULT_SUDO_PROMPT_MAX_LINES = 12;
public static final String NODE_ATTR_SUDO_RESPONSE_MAX_LINES = "response-max-lines";
public static final int DEFAULT_SUDO_RESPONSE_MAX_LINES = 2;
public static final String NODE_ATTR_SUDO_PROMPT_MAX_TIMEOUT = "prompt-max-timeout";
public static final long DEFAULT_SUDO_PROMPT_MAX_TIMEOUT = 5000;
public static final String NODE_ATTR_SUDO_RESPONSE_MAX_TIMEOUT = "response-max-timeout";
public static final long DEFAULT_SUDO_RESPONSE_MAX_TIMEOUT = 5000;
public static final String NODE_ATTR_SUDO_FAIL_ON_PROMPT_MAX_LINES = "fail-on-prompt-max-lines";
public static final boolean DEFAULT_SUDO_FAIL_ON_PROMPT_MAX_LINES = false;
public static final String NODE_ATTR_SUDO_FAIL_ON_PROMPT_TIMEOUT = "fail-on-prompt-timeout";
public static final boolean DEFAULT_SUDO_FAIL_ON_PROMPT_TIMEOUT = true;
public static final String NODE_ATTR_SUDO_FAIL_ON_RESPONSE_TIMEOUT = "fail-on-response-timeout";
public static final boolean DEFAULT_SUDO_FAIL_ON_RESPONSE_TIMEOUT = false;
public static final String NODE_ATTR_SUDO_SUCCESS_ON_PROMPT_THRESHOLD = "success-on-prompt-threshold";
public static final boolean DEFAULT_SUDO_SUCCESS_ON_PROMPT_THRESHOLD = true;
public static final String PROJECT_SSH_USER = PROJ_PROP_PREFIX + "ssh.user";
public static final String SSH_CONFIG_PREFIX = "ssh-config-";
public static final String FWK_SSH_CONFIG_PREFIX = FWK_PROP_PREFIX + SSH_CONFIG_PREFIX;
public static final String PROJ_SSH_CONFIG_PREFIX = PROJ_PROP_PREFIX + SSH_CONFIG_PREFIX;
private Framework framework;
public JschNodeExecutor(final Framework framework) {
this.framework = framework;
}
public static final String CONFIG_KEYPATH = "keypath";
public static final String CONFIG_KEYSTORE_PATH = "keystoragepath";
public static final String CONFIG_AUTHENTICATION = "authentication";
static final Description DESC ;
static final Property SSH_KEY_FILE_PROP = PropertyUtil.string(CONFIG_KEYPATH, "SSH Key File path",
"File Path to the SSH Key to use",
false, null);
static final Property SSH_KEY_STORAGE_PROP = PropertyBuilder.builder()
.string(CONFIG_KEYSTORE_PATH)
.required(false)
.title("SSH Key Storage Path")
.description("Path to the SSH Key to use within Rundeck Storage. E.g. \"keys/path/key1.pem\"")
.renderingOption(StringRenderingConstants.SELECTION_ACCESSOR_KEY,
StringRenderingConstants.SelectionAccessor.STORAGE_PATH)
.renderingOption(StringRenderingConstants.STORAGE_PATH_ROOT_KEY, "keys")
.renderingOption(StringRenderingConstants.STORAGE_FILE_META_FILTER_KEY, "Rundeck-key-type=private")
.build();
public static final Property SSH_AUTH_TYPE_PROP = PropertyUtil.select(CONFIG_AUTHENTICATION, "SSH Authentication",
"Type of SSH Authentication to use",
true, SSHTaskBuilder.AuthenticationType.privateKey.toString(), Arrays.asList(SSHTaskBuilder
.AuthenticationType.values()), null, null);
static {
DescriptionBuilder builder = DescriptionBuilder.builder();
builder.name(SERVICE_PROVIDER_TYPE)
.title("SSH")
.description("Executes a command on a remote node via SSH.")
;
builder.property(SSH_KEY_FILE_PROP);
builder.property(SSH_KEY_STORAGE_PROP);
builder.property(SSH_AUTH_TYPE_PROP);
builder.mapping(CONFIG_KEYPATH, PROJ_PROP_SSH_KEYPATH);
builder.frameworkMapping(CONFIG_KEYPATH, FWK_PROP_SSH_KEYPATH);
builder.mapping(CONFIG_KEYSTORE_PATH, PROJ_PROP_SSH_KEY_RESOURCE);
builder.frameworkMapping(CONFIG_KEYSTORE_PATH, FWK_PROP_SSH_KEY_RESOURCE);
builder.mapping(CONFIG_AUTHENTICATION, PROJ_PROP_SSH_AUTHENTICATION);
builder.frameworkMapping(CONFIG_AUTHENTICATION, FWK_PROP_SSH_AUTHENTICATION);
DESC=builder.build();
}
public Description getDescription() {
return DESC;
}
public NodeExecutorResult executeCommand(final ExecutionContext context, final String[] command,
final INodeEntry node) {
if (null == node.getHostname() || null == node.extractHostname()) {
return NodeExecutorResultImpl.createFailure(
StepFailureReason.ConfigurationFailure,
"Hostname must be set to connect to remote node '" + node.getNodename() + "'",
node
);
}
final ExecutionListener listener = context.getExecutionListener();
final Project project = new Project();
AntSupport.addAntBuildListener(listener, project);
boolean success = false;
final ExtSSHExec sshexec;
//perform jsch sssh command
final NodeSSHConnectionInfo nodeAuthentication = new NodeSSHConnectionInfo(node, framework,
context);
final int timeout = nodeAuthentication.getSSHTimeout();
try {
sshexec = SSHTaskBuilder.build(node, command, project, context.getDataContext(),
nodeAuthentication, context.getLoglevel(),listener);
} catch (SSHTaskBuilder.BuilderException e) {
return NodeExecutorResultImpl.createFailure(StepFailureReason.ConfigurationFailure,
e.getMessage(), node);
}
//Sudo support
final ExecutorService executor = Executors.newSingleThreadExecutor(
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(null, r, "SudoResponder " + node.getNodename() + ": "
+ System.currentTimeMillis());
}
}
);
final Future<ResponderTask.ResponderResult> responderFuture;
final SudoResponder sudoResponder = SudoResponder.create(node, framework, context);
Runnable responderCleanup=null;
if (sudoResponder.isSudoEnabled() && sudoResponder.matchesCommandPattern(command[0])) {
final DisconnectResultHandler resultHandler = new DisconnectResultHandler();
//configure two piped i/o stream pairs, to connect to the input/output of the SSH connection
final PipedInputStream responderInput = new PipedInputStream();
final PipedOutputStream responderOutput = new PipedOutputStream();
final PipedInputStream jschInput = new PipedInputStream();
//lead pipe allows connected inputstream to close and not hang the writer to this stream
final PipedOutputStream jschOutput = new LeadPipeOutputStream();
try {
responderInput.connect(jschOutput);
jschInput.connect(responderOutput);
} catch (IOException e) {
return NodeExecutorResultImpl.createFailure(StepFailureReason.IOFailure, e.getMessage(), node);
}
//first sudo prompt responder
ResponderTask responder = new ResponderTask(sudoResponder, responderInput, responderOutput, resultHandler);
/**
* Callable will be executed by the ExecutorService
*/
final Callable<ResponderTask.ResponderResult> responderResultCallable;
//if 2nd responder
final SudoResponder sudoResponder2 = SudoResponder.create(node, framework, context, SUDO2_OPT_PREFIX,
DEFAULT_SUDO2_PASSWORD_OPTION,
DEFAULT_SUDO2_COMMAND_PATTERN);
if (sudoResponder2.isSudoEnabled()
&& sudoResponder2.matchesCommandPattern(CLIUtils.generateArgline(null, command, false))) {
logger.debug("Enable second sudo responder");
sudoResponder2.setDescription("Second " + SudoResponder.DEFAULT_DESCRIPTION);
sudoResponder.setDescription("First " + SudoResponder.DEFAULT_DESCRIPTION);
//sequence of the first then the second sudo responder
responderResultCallable = responder.createSequence(sudoResponder2);
} else {
responderResultCallable = responder;
}
//set up SSH execution
sshexec.setAllocatePty(true);
sshexec.setInputStream(jschInput);
sshexec.setSecondaryStream(jschOutput);
sshexec.setDisconnectHolder(resultHandler);
responderFuture = executor.submit(responderResultCallable);
//close streams after responder is finished
responderCleanup = new Runnable() {
public void run() {
logger.debug("SudoResponder shutting down...");
try {
responderInput.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
responderOutput.flush();
responderOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
//executor pool shutdown
executor.shutdownNow();
}
};
executor.submit(responderCleanup);
}else {
responderFuture = null;
}
if (null != context.getExecutionListener()) {
context.getExecutionListener().log(3,
"Starting SSH Connection: " + nodeAuthentication.getUsername() + "@"
+ node.getHostname() + " ("
+ node.getNodename() + ")");
}
String errormsg = null;
FailureReason failureReason=null;
try {
sshexec.execute();
success = true;
} catch (BuildException e) {
final ExtractFailure extractJschFailure = extractFailure(e,node, timeout, framework);
errormsg = extractJschFailure.getErrormsg();
failureReason = extractJschFailure.getReason();
context.getExecutionListener().log(0, errormsg);
}
if (null != responderCleanup) {
responderCleanup.run();
}
shutdownAndAwaitTermination(executor);
if (null != responderFuture) {
try {
logger.debug("Waiting 5 seconds for responder future result");
final ResponderTask.ResponderResult result = responderFuture.get(5, TimeUnit.SECONDS);
logger.debug("Responder result: " + result);
if (!result.isSuccess() && !result.isInterrupted()) {
context.getExecutionListener().log(0,
result.getResponder().toString() + " failed: "
+ result.getFailureReason());
}
} catch (InterruptedException e) {
//ignore
} catch (java.util.concurrent.ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
//ignore
}
}
final int resultCode = sshexec.getExitStatus();
if (success) {
return NodeExecutorResultImpl.createSuccess(node);
} else {
return NodeExecutorResultImpl.createFailure(failureReason, errormsg, node, resultCode);
}
}
static enum JschFailureReason implements FailureReason {
/**
* A problem with the SSH connection
*/
SSHProtocolFailure
}
static ExtractFailure extractFailure(BuildException e, INodeEntry node, int timeout, Framework framework) {
String errormsg;
FailureReason failureReason;
if (e.getMessage().contains("Timeout period exceeded, connection dropped")) {
errormsg =
"Failed execution for node: " + node.getNodename() + ": Execution Timeout period exceeded (after "
+ timeout + "ms), connection dropped";
failureReason = NodeStepFailureReason.ConnectionTimeout;
} else if (null != e.getCause() && e.getCause() instanceof JSchException) {
JSchException jSchException = (JSchException) e.getCause();
return extractJschFailure(node, timeout, jSchException, framework);
} else if (e.getMessage().contains("Remote command failed with exit status")) {
errormsg = e.getMessage();
failureReason = NodeStepFailureReason.NonZeroResultCode;
} else {
failureReason = StepFailureReason.Unknown;
errormsg = e.getMessage();
}
return new ExtractFailure(errormsg, failureReason);
}
static ExtractFailure extractJschFailure(final INodeEntry node,
final int timeout,
final JSchException jSchException, final Framework framework) {
String errormsg;
FailureReason reason;
if (null == jSchException.getCause()) {
if (jSchException.getMessage().contains("Auth cancel")) {
String msgformat = FWK_PROP_AUTH_CANCEL_MSG_DEFAULT;
if (framework.getPropertyLookup().hasProperty(FWK_PROP_AUTH_CANCEL_MSG)) {
msgformat = framework.getProperty(FWK_PROP_AUTH_CANCEL_MSG);
}
errormsg = MessageFormat.format(msgformat, node.getNodename(), jSchException.getMessage());
reason = NodeStepFailureReason.AuthenticationFailure;
} else if (jSchException.getMessage().contains("Auth fail")) {
String msgformat = FWK_PROP_AUTH_FAIL_MSG_DEFAULT;
if (framework.getPropertyLookup().hasProperty(FWK_PROP_AUTH_FAIL_MSG)) {
msgformat = framework.getProperty(FWK_PROP_AUTH_FAIL_MSG);
}
errormsg = MessageFormat.format(msgformat, node.getNodename(), jSchException.getMessage());
reason = NodeStepFailureReason.AuthenticationFailure;
} else {
reason = JschFailureReason.SSHProtocolFailure;
errormsg = jSchException.getMessage();
}
} else {
Throwable cause = ExceptionUtils.getRootCause(jSchException);
errormsg = cause.getMessage();
if (cause instanceof NoRouteToHostException) {
reason = NodeStepFailureReason.ConnectionFailure;
} else if (cause instanceof UnknownHostException) {
reason = NodeStepFailureReason.HostNotFound;
} else if (cause instanceof SocketTimeoutException) {
errormsg = "Connection Timeout (after " + timeout + "ms): " + cause.getMessage();
reason = NodeStepFailureReason.ConnectionTimeout;
} else if (cause instanceof SocketException) {
reason = NodeStepFailureReason.ConnectionFailure;
} else {
reason = StepFailureReason.Unknown;
}
}
return new ExtractFailure(errormsg, reason);
}
/**
* Shutdown the ExecutorService
*/
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdownNow(); // Disable new tasks from being submitted
try {
logger.debug("Waiting up to 30 seconds for ExecutorService to shut down");
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
logger.debug("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
final static class NodeSSHConnectionInfo implements SSHTaskBuilder.SSHConnectionInfo {
final INodeEntry node;
final Framework framework;
final ExecutionContext context;
FrameworkProject frameworkProject;
NodeSSHConnectionInfo(final INodeEntry node, final Framework framework, final ExecutionContext context) {
this.node = node;
this.framework = framework;
this.context = context;
this.frameworkProject = framework.getFrameworkProjectMgr().getFrameworkProject(
context.getFrameworkProject());
}
public SSHTaskBuilder.AuthenticationType getAuthenticationType() {
if (null != node.getAttributes().get(NODE_ATTR_SSH_AUTHENTICATION)) {
return SSHTaskBuilder.AuthenticationType.valueOf(node.getAttributes().get(
NODE_ATTR_SSH_AUTHENTICATION));
}
if (frameworkProject.hasProperty(PROJ_PROP_SSH_AUTHENTICATION)) {
return SSHTaskBuilder.AuthenticationType.valueOf(frameworkProject.getProperty(
PROJ_PROP_SSH_AUTHENTICATION));
} else if (framework.hasProperty(FWK_PROP_SSH_AUTHENTICATION)) {
return SSHTaskBuilder.AuthenticationType.valueOf(framework.getProperty(FWK_PROP_SSH_AUTHENTICATION));
} else {
return SSHTaskBuilder.AuthenticationType.privateKey;
}
}
public String getPrivateKeyfilePath() {
String path = null;
if (null != nonBlank(node.getAttributes().get(NODE_ATTR_SSH_KEYPATH))) {
path = node.getAttributes().get(NODE_ATTR_SSH_KEYPATH);
} else if (frameworkProject.hasProperty(PROJ_PROP_SSH_KEYPATH)) {
path = frameworkProject.getProperty(PROJ_PROP_SSH_KEYPATH);
} else if (framework.hasProperty(FWK_PROP_SSH_KEYPATH)) {
path = framework.getProperty(FWK_PROP_SSH_KEYPATH);
} else if (framework.hasProperty(Constants.SSH_KEYPATH_PROP)) {
//return default framework level
path = framework.getProperty(Constants.SSH_KEYPATH_PROP);
}
//expand properties in path
if (path != null && path.contains("${")) {
path = DataContextUtils.replaceDataReferences(path, context.getDataContext());
}
return path;
}
public InputStream getPrivateKeyResourceData() throws IOException{
String privateKeyResourcePath = getPrivateKeyResourcePath();
if (null == privateKeyResourcePath) {
return null;
}
Path path = PathUtil.asPath(privateKeyResourcePath);
ResourceMeta contents = context.getStorageTree().getResource(path)
.getContents();
return contents.getInputStream();
}
public String getPrivateKeyResourcePath() {
String path = null;
if (null != nonBlank(node.getAttributes().get(NODE_ATTR_SSH_KEY_RESOURCE))) {
path = node.getAttributes().get(NODE_ATTR_SSH_KEY_RESOURCE);
} else if (frameworkProject.hasProperty(PROJ_PROP_SSH_KEY_RESOURCE)) {
path = frameworkProject.getProperty(PROJ_PROP_SSH_KEY_RESOURCE);
} else if (framework.hasProperty(FWK_PROP_SSH_KEY_RESOURCE)) {
path = framework.getProperty(FWK_PROP_SSH_KEY_RESOURCE);
} else if (framework.hasProperty(Constants.SSH_KEYRESOURCE_PROP)) {
//return default framework level
path = framework.getProperty(Constants.SSH_KEYRESOURCE_PROP);
}
//expand properties in path
if (path != null && path.contains("${")) {
path = DataContextUtils.replaceDataReferences(path, context.getDataContext());
}
return path;
}
public String getPrivateKeyPassphrase() {
if (null != node.getAttributes().get(NODE_ATTR_SSH_KEY_PASSPHRASE_OPTION)) {
return evaluateSecureOption(node.getAttributes().get(NODE_ATTR_SSH_KEY_PASSPHRASE_OPTION), context);
} else {
return evaluateSecureOption(DEFAULT_SSH_KEY_PASSPHRASE_OPTION, context);
}
}
static String evaluateSecureOption(final String optionName, final ExecutionContext context) {
if (null == optionName) {
logger.debug("option name was null");
return null;
}
if (null == context.getPrivateDataContext()) {
logger.debug("private context was null");
return null;
}
final String[] opts = optionName.split("\\.", 2);
if (null != opts && 2 == opts.length) {
final Map<String, String> option = context.getPrivateDataContext().get(opts[0]);
if (null != option) {
final String value = option.get(opts[1]);
if (null == value) {
logger.debug("private context '" + optionName + "' was null");
}
return value;
} else {
logger.debug("private context '" + opts[0] + "' was null");
}
}
return null;
}
public String getPassword() {
if (null != node.getAttributes().get(NODE_ATTR_SSH_PASSWORD_OPTION)) {
return evaluateSecureOption(node.getAttributes().get(NODE_ATTR_SSH_PASSWORD_OPTION), context);
} else {
return evaluateSecureOption(DEFAULT_SSH_PASSWORD_OPTION, context);
}
}
public int getSSHTimeout() {
int timeout = 0;
if (framework.getPropertyLookup().hasProperty(Constants.SSH_TIMEOUT_PROP)) {
final String val = framework.getProperty(Constants.SSH_TIMEOUT_PROP);
try {
timeout = Integer.parseInt(val);
} catch (NumberFormatException e) {
}
}
return timeout;
}
/**
* Return null if the input is null or empty or whitespace, otherwise return the input string trimmed.
*/
public static String nonBlank(final String input) {
if (null == input || "".equals(input.trim())) {
return null;
} else {
return input.trim();
}
}
public String getUsername() {
String user;
if (null != nonBlank(node.getUsername()) || node.containsUserName()) {
user = nonBlank(node.extractUserName());
} else if (frameworkProject.hasProperty(PROJECT_SSH_USER)
&& null != nonBlank(frameworkProject.getProperty(PROJECT_SSH_USER))) {
user = nonBlank(frameworkProject.getProperty(PROJECT_SSH_USER));
} else {
user = nonBlank(framework.getProperty(Constants.SSH_USER_PROP));
}
if (null != user && user.contains("${")) {
return DataContextUtils.replaceDataReferences(user, context.getDataContext());
}
return user;
}
public static Map<String, String> sshConfigFromFramework(Framework framework) {
HashMap<String, String> config = new HashMap<String, String>();
IPropertyLookup propertyLookup = framework.getPropertyLookup();
for (Object o : propertyLookup.getPropertiesMap().keySet()) {
String key = (String) o;
if (key.startsWith(FWK_SSH_CONFIG_PREFIX)) {
String name = key.substring(FWK_SSH_CONFIG_PREFIX.length());
config.put(name, propertyLookup.getProperty(key));
}
}
return config;
}
public static Map<String, String> sshConfigFromProject(FrameworkProject frameworkProject) {
HashMap<String, String> config = new HashMap<String, String>();
for (Object o : frameworkProject.getProperties().keySet()) {
String key = (String) o;
if (key.startsWith(PROJ_SSH_CONFIG_PREFIX)) {
String name = key.substring(PROJ_SSH_CONFIG_PREFIX.length());
config.put(name, frameworkProject.getProperty(key));
}
}
return config;
}
public static Map<String, String> sshConfigFromNode(INodeEntry node) {
HashMap<String, String> config = new HashMap<String, String>();
for (String s : node.getAttributes().keySet()) {
if (s.startsWith(SSH_CONFIG_PREFIX)) {
String name = s.substring(SSH_CONFIG_PREFIX.length());
config.put(name, node.getAttributes().get(s));
}
}
return config;
}
@Override
public Map<String, String> getSshConfig() {
Map<String, String> config = new HashMap<String, String>();
Map<String, String> fwkConfig = sshConfigFromFramework(framework);
Map<String, String> projConfig = sshConfigFromProject(frameworkProject);
Map<String, String> nodeConfig = sshConfigFromNode(node);
if(null!=fwkConfig){
config.putAll(fwkConfig);
}
if(null!=projConfig){
config.putAll(projConfig);
}
if(null!=nodeConfig){
config.putAll(nodeConfig);
}
return config;
}
}
/**
* Resolve a node/project/framework property by first checking node attributes named X, then project properties
* named "project.X", then framework properties named "framework.X". If none of those exist, return the default
* value
*/
private static String resolveProperty(final String nodeAttribute, final String defaultValue, final INodeEntry node,
final FrameworkProject frameworkProject, final Framework framework) {
if (null != node.getAttributes().get(nodeAttribute)) {
return node.getAttributes().get(nodeAttribute);
} else if (frameworkProject.hasProperty(PROJ_PROP_PREFIX + nodeAttribute)
&& !"".equals(frameworkProject.getProperty(PROJ_PROP_PREFIX + nodeAttribute))) {
return frameworkProject.getProperty(PROJ_PROP_PREFIX + nodeAttribute);
} else if (framework.hasProperty(FWK_PROP_PREFIX + nodeAttribute)) {
return framework.getProperty(FWK_PROP_PREFIX + nodeAttribute);
} else {
return defaultValue;
}
}
private static int resolveIntProperty(final String attribute, final int defaultValue, final INodeEntry iNodeEntry,
final FrameworkProject frameworkProject, final Framework framework) {
int value = defaultValue;
final String string = resolveProperty(attribute, null, iNodeEntry, frameworkProject, framework);
if (null != string) {
try {
value = Integer.parseInt(string);
} catch (NumberFormatException e) {
}
}
return value;
}
private static long resolveLongProperty(final String attribute, final long defaultValue,
final INodeEntry iNodeEntry,
final FrameworkProject frameworkProject, final Framework framework) {
long value = defaultValue;
final String string = resolveProperty(attribute, null, iNodeEntry, frameworkProject, framework);
if (null != string) {
try {
value = Long.parseLong(string);
} catch (NumberFormatException e) {
}
}
return value;
}
private static boolean resolveBooleanProperty(final String attribute, final boolean defaultValue,
final INodeEntry iNodeEntry,
final FrameworkProject frameworkProject, final Framework framework) {
boolean value = defaultValue;
final String string = resolveProperty(attribute, null, iNodeEntry, frameworkProject, framework);
if (null != string) {
value = Boolean.parseBoolean(string);
}
return value;
}
/**
* Disconnects the SSH connection if the result was not successful.
*/
private static class DisconnectResultHandler implements ResponderTask.ResultHandler,
ExtSSHExec.DisconnectHolder {
private volatile ExtSSHExec.Disconnectable disconnectable;
private volatile boolean needsDisconnect=false;
public void setDisconnectable(final ExtSSHExec.Disconnectable disconnectable) {
this.disconnectable = disconnectable;
checkAndDisconnect();
}
public void handleResult(final boolean success, final String reason) {
needsDisconnect=!success;
checkAndDisconnect();
}
/**
* synchronize to prevent race condition on setDisconnectable and handleResult
*/
private synchronized void checkAndDisconnect() {
if (null != disconnectable && needsDisconnect) {
disconnectable.disconnect();
needsDisconnect = false;
}
}
}
/**
* Sudo responder that determines response patterns from node attributes and project properties. Also handles
* responder thread result by closing the SSH connection on failure. The mechanism for sudo response: <ol> <li>look
* for "[sudo] password for <username>: " (inputSuccessPattern)</li> <li>if not seen in 12 lines, then assume
* password is not needed (isSuccessOnInputThreshold=true)</li> <li>if fewer than 12 lines, and no new input in 5000
* milliseconds, then fail (isFailOnInputTimeoutThreshold=true)</li> <li>if seen, output password and carriage
* return (inputString)</li> <li>look for "Sorry, try again" (responseFailurePattern)</li> <li>if not seen in 3
* lines, or 5000 milliseconds, then assume success (isFailOnResponseThreshold)</li> <li>if seen, then fail</li>
* </ol>
*/
private static class SudoResponder implements Responder {
public static final String DEFAULT_DESCRIPTION = "Sudo execution password response";
private String sudoCommandPattern;
private String inputSuccessPattern;
private String inputFailurePattern;
private String responseSuccessPattern;
private String responseFailurePattern;
private int inputMaxLines = -1;
private long inputMaxTimeout = -1;
private boolean failOnInputLinesThreshold = false;
private boolean failOnInputTimeoutThreshold = true;
private boolean successOnInputThreshold = true;
private int responseMaxLines = -1;
private long responseMaxTimeout = -1;
private boolean failOnResponseThreshold = false;
private String inputString;
private String configPrefix;
private String description;
private String defaultSudoPasswordOption;
private String defaultSudoCommandPattern;
private SudoResponder() {
description = DEFAULT_DESCRIPTION;
defaultSudoPasswordOption = DEFAULT_SUDO_PASSWORD_OPTION;
defaultSudoCommandPattern = DEFAULT_SUDO_COMMAND_PATTERN;
configPrefix = SUDO_OPT_PREFIX;
}
private SudoResponder(final String configPrefix,
final String defaultSudoPasswordOption,
final String defaultSudoCommandPattern) {
this();
if (null != configPrefix) {
this.configPrefix = configPrefix;
}
if (null != defaultSudoPasswordOption) {
this.defaultSudoPasswordOption = defaultSudoPasswordOption;
}
if (null != defaultSudoCommandPattern) {
this.defaultSudoCommandPattern = defaultSudoCommandPattern;
}
}
static SudoResponder create(final INodeEntry node, final Framework framework, final ExecutionContext context) {
return create(node, framework, context, null, null, null);
}
static SudoResponder create(final INodeEntry node,
final Framework framework,
final ExecutionContext context,
final String configPrefix,
final String defaultSudoPasswordOption, final String defaultSudoCommandPattern) {
final SudoResponder sudoResponder = new SudoResponder(configPrefix, defaultSudoPasswordOption,
defaultSudoCommandPattern);
sudoResponder.init(node, framework.getFrameworkProjectMgr().getFrameworkProject(
context.getFrameworkProject()), framework, context);
return sudoResponder;
}
public boolean matchesCommandPattern(final String command) {
final String sudoCommandPattern1 = getSudoCommandPattern();
if (null != sudoCommandPattern1) {
return Pattern.compile(sudoCommandPattern1).matcher(command).matches();
} else {
return false;
}
}
private void init(final INodeEntry node, final FrameworkProject frameworkProject,
final Framework framework, final ExecutionContext context) {
sudoEnabled = resolveBooleanProperty(configPrefix + NODE_ATTR_SUDO_COMMAND_ENABLED,
false,
node,
frameworkProject,
framework);
if (sudoEnabled) {
final String sudoPassOptname = resolveProperty(configPrefix + NODE_ATTR_SUDO_PASSWORD_OPTION,
null,
node,
frameworkProject,
framework);
final String sudoPassword = NodeSSHConnectionInfo.evaluateSecureOption(
null != sudoPassOptname ? sudoPassOptname : defaultSudoPasswordOption, context);
inputString = (null != sudoPassword ? sudoPassword : "") + "\n";
sudoCommandPattern = resolveProperty(configPrefix + NODE_ATTR_SUDO_COMMAND_PATTERN,
defaultSudoCommandPattern,
node,
frameworkProject,
framework);
inputSuccessPattern = resolveProperty(configPrefix + NODE_ATTR_SUDO_PROMPT_PATTERN,
DEFAULT_SUDO_PROMPT_PATTERN,
node,
frameworkProject,
framework);
inputFailurePattern = null;
responseFailurePattern = resolveProperty(configPrefix + NODE_ATTR_SUDO_FAILURE_PATTERN,
DEFAULT_SUDO_FAILURE_PATTERN,
node,
frameworkProject,
framework);
responseSuccessPattern = null;
inputMaxLines = resolveIntProperty(configPrefix + NODE_ATTR_SUDO_PROMPT_MAX_LINES,
DEFAULT_SUDO_PROMPT_MAX_LINES,
node,
frameworkProject,
framework);
inputMaxTimeout = resolveLongProperty(configPrefix + NODE_ATTR_SUDO_PROMPT_MAX_TIMEOUT,
DEFAULT_SUDO_PROMPT_MAX_TIMEOUT,
node, frameworkProject, framework);
responseMaxLines = resolveIntProperty(configPrefix + NODE_ATTR_SUDO_RESPONSE_MAX_LINES,
DEFAULT_SUDO_RESPONSE_MAX_LINES,
node, frameworkProject, framework);
responseMaxTimeout = resolveLongProperty(configPrefix + NODE_ATTR_SUDO_RESPONSE_MAX_TIMEOUT,
DEFAULT_SUDO_RESPONSE_MAX_TIMEOUT,
node,
frameworkProject,
framework);
failOnInputLinesThreshold = resolveBooleanProperty(
configPrefix + NODE_ATTR_SUDO_FAIL_ON_PROMPT_MAX_LINES,
DEFAULT_SUDO_FAIL_ON_PROMPT_MAX_LINES, node, frameworkProject, framework);
failOnInputTimeoutThreshold = resolveBooleanProperty(
configPrefix + NODE_ATTR_SUDO_FAIL_ON_PROMPT_TIMEOUT,
DEFAULT_SUDO_FAIL_ON_PROMPT_TIMEOUT, node, frameworkProject, framework);
failOnResponseThreshold = resolveBooleanProperty(configPrefix + NODE_ATTR_SUDO_FAIL_ON_RESPONSE_TIMEOUT,
DEFAULT_SUDO_FAIL_ON_RESPONSE_TIMEOUT,
node,
frameworkProject,
framework);
successOnInputThreshold = resolveBooleanProperty(
configPrefix + NODE_ATTR_SUDO_SUCCESS_ON_PROMPT_THRESHOLD,
DEFAULT_SUDO_SUCCESS_ON_PROMPT_THRESHOLD, node, frameworkProject, framework);
}
}
private boolean sudoEnabled = false;
/**
* Return true if sudo should be used for the command execution on this node
*/
public boolean isSudoEnabled() {
return sudoEnabled;
}
public String getInputString() {
return inputString;
}
public boolean isFailOnInputLinesThreshold() {
return failOnInputLinesThreshold;
}
public boolean isFailOnInputTimeoutThreshold() {
return failOnInputTimeoutThreshold;
}
public boolean isFailOnResponseThreshold() {
return failOnResponseThreshold;
}
public boolean isSuccessOnInputThreshold() {
return successOnInputThreshold;
}
/**
* Return the regular expression to use to match the command to determine if Sudo should be used.
*/
public String getSudoCommandPattern() {
return sudoCommandPattern;
}
public String getInputFailurePattern() {
return inputFailurePattern;
}
public String getInputSuccessPattern() {
return inputSuccessPattern;
}
public String getResponseSuccessPattern() {
return responseSuccessPattern;
}
public String getResponseFailurePattern() {
return responseFailurePattern;
}
public int getInputMaxLines() {
return inputMaxLines;
}
public long getInputMaxTimeout() {
return inputMaxTimeout;
}
public int getResponseMaxLines() {
return responseMaxLines;
}
public long getResponseMaxTimeout() {
return responseMaxTimeout;
}
@Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
static class ExtractFailure {
private String errormsg;
private FailureReason reason;
private ExtractFailure(String errormsg, FailureReason reason) {
this.errormsg = errormsg;
this.reason = reason;
}
public String getErrormsg() {
return errormsg;
}
public FailureReason getReason() {
return reason;
}
}
}
| 46.966699 | 130 | 0.613059 |
e41e41c9b8956148542a6bb2f33c62b40045554b | 1,134 | package gcode.fixer.file;
import java.util.ArrayList;
import java.util.List;
public class TracesFile extends AbstractFile {
public TracesFile(String fileNameAndPath) {
super(fileNameAndPath);
}
@Override
protected List<String> filter(List<String> gcodeToFilter) {
// Copy everything from the 2nd tool section until we reach the M999 code
List<String> retval = new ArrayList<String>();
int percentCount = 0;
boolean copying = false;
for(String gcodeLine : gcodeToFilter) {
// Skip everything until we reach the 2nd tool section
if(!copying && gcodeLine.startsWith("%")) {
percentCount++;
// The 3rd time we see that symbol is because we reached the 2nd tools section of the file.
if(percentCount >= 3) {
copying = true;
}
}
// If we have already reached the 2nd tool section, copy until we find a M999 code
if(copying) {
if(!gcodeLine.startsWith("M999")) {
retval.add(gcodeLine);
}
else {
break;
}
}
}
return retval;
}
@Override
protected float getFeedRate() {
return 200.0f;
}
}
| 23.142857 | 96 | 0.645503 |
2658c2c31a5fe4ec03c13b07af0495f243b0f544 | 611 | package mkii.mkblock.common;
import org.apache.commons.codec.binary.Base64;
/**
* convert Stirng to base64
*/
public class Base64Util {
/**
* encode String
* @param str
* @return
*/
public static String getEncodeString(String str) {
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
return new String(bytesEncoded);
}
/**
* decode String
* @param str
* @return
*/
public static String getDecodeString(byte[] str) {
byte[] valueDecoded = Base64.decodeBase64(str);
return new String(valueDecoded);
}
}
| 20.366667 | 66 | 0.613748 |
143161a5e7aa8f733e1e6452fd5ae9de133e7fa9 | 2,278 | /*
Copyright (c) 2022 Daniel McCoy Stephenson
Apache License 2.0
*/
package dansapps.interakt.factories;
import dansapps.interakt.data.PersistentData;
import dansapps.interakt.objects.Actor;
import java.util.Map;
import java.util.Random;
/**
* @author Daniel McCoy Stephenson
* @since January 15th, 2022
*/
public class ActorFactory {
private static ActorFactory instance;
private ActorFactory() {
}
public static ActorFactory getInstance() {
if (instance == null) {
instance = new ActorFactory();
}
return instance;
}
public Actor createActorWithRandomName(String name) {
if (isNameTaken(name)) {
return null;
}
Actor actor = new Actor(name);
PersistentData.getInstance().addActor(actor);
return actor;
}
public Actor createActorFromParents(Actor parent1, Actor parent2) {
Actor child = createActorWithRandomName();
// genealogy
child.addParent(parent1.getUUID());
child.addParent(parent2.getUUID());
parent1.addChild(child.getUUID());
parent2.addChild(child.getUUID());
// relations
child.setRelation(parent1, 100);
child.setRelation(parent2, 100);
parent1.setRelation(child, 100);
parent2.setRelation(child, 100);
return child;
}
public Actor createActorWithRandomName() {
String name;
do {
name = generateRandomString(5);
} while (isNameTaken(name));
return createActorWithRandomName(name);
}
public void createActorWithRandomName(Map<String, String> data) {
Actor actor = new Actor(data);
PersistentData.getInstance().addActor(actor);
}
private boolean isNameTaken(String name) {
return PersistentData.getInstance().isActor(name);
}
private String generateRandomString(int length) {
final char[] alphabetArray = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Random random = new Random();
StringBuilder toReturn = new StringBuilder();
for (int i = 0; i < length; i++) {
toReturn.append(alphabetArray[random.nextInt(alphabetArray.length)]);
}
return toReturn.toString();
}
} | 27.119048 | 81 | 0.638718 |
daf21ec2bc001d6f5b19a9671df17b3bb3b13f19 | 1,538 | /*
* Copyright (c) 2019 Gili Tzabari
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
package org.bitbucket.cowwoc.requirements.java.internal;
import org.bitbucket.cowwoc.requirements.java.PrimitiveBooleanValidator;
import org.bitbucket.cowwoc.requirements.java.ValidationFailure;
import org.bitbucket.cowwoc.requirements.java.internal.extension.AbstractComparableValidatorNoOp;
import java.util.List;
/**
* A {@code PrimitiveBooleanValidator} that does nothing.
*/
public final class PrimitiveBooleanValidatorNoOp
extends AbstractComparableValidatorNoOp<PrimitiveBooleanValidator, Boolean>
implements PrimitiveBooleanValidator
{
/**
* @param failures the list of validation failures
* @throws AssertionError if {@code failures} is null
*/
public PrimitiveBooleanValidatorNoOp(List<ValidationFailure> failures)
{
super(failures);
}
@Override
protected PrimitiveBooleanValidator getThis()
{
return this;
}
@Override
public PrimitiveBooleanValidator isTrue()
{
return this;
}
@Override
public PrimitiveBooleanValidator isFalse()
{
return this;
}
@Override
@Deprecated
public PrimitiveBooleanValidator isNotNull()
{
// Suppress warning about extending class with deprecated methods
return super.isNotNull();
}
@Override
@Deprecated
public PrimitiveBooleanValidator isNull()
{
// Suppress warning about extending class with deprecated methods
return super.isNull();
}
}
| 24.412698 | 98 | 0.750975 |
4ce1d9fb93e3d14ed64aa49b26cff5d6894f912b | 3,058 | package org.mx.comps.notify.online;
import com.alibaba.fastjson.JSONObject;
/**
* 在线设备对象定义
*
* @author : john.peng created on date : 2018/1/3
*/
public class OnlineDevice {
private String deviceId, state, connectKey;
private long registryTime, lastTime;
private double lastLongitude, lastLatitude;
private JSONObject extraData;
/**
* 更新设备信息
*
* @param state 状态
* @param lastTime 时间
* @param lastLongitude 经度
* @param lastLatitude 纬度
*/
public void update(String state, long lastTime, double lastLongitude, double lastLatitude) {
this.state = state;
this.lastTime = lastTime;
this.lastLongitude = lastLongitude;
this.lastLatitude = lastLatitude;
}
/**
* 获取设备ID
*
* @return 设备ID
*/
public String getDeviceId() {
return deviceId;
}
/**
* 设置设备ID
*
* @param deviceId 设备ID
*/
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
/**
* 获取状态
*
* @return 状态
*/
public String getState() {
return state;
}
/**
* 设置状态
*
* @param state 状态
*/
public void setState(String state) {
this.state = state;
}
/**
* 获取连接关键字
*
* @return 连接关键字
*/
public String getConnectKey() {
return connectKey;
}
/**
* 设置连接关键字
*
* @param connectKey 连接关键字
*/
public void setConnectKey(String connectKey) {
this.connectKey = connectKey;
}
/**
* 获取注册时间
*
* @return 注册时间
*/
public long getRegistryTime() {
return registryTime;
}
/**
* 设置注册时间
*
* @param registryTime 时间
*/
public void setRegistryTime(long registryTime) {
this.registryTime = registryTime;
}
/**
* 获取时间
*
* @return 时间
*/
public long getLastTime() {
return lastTime;
}
/**
* 设置时间
*
* @param lastTime 时间
*/
public void setLastTime(long lastTime) {
this.lastTime = lastTime;
}
/**
* 获取经度
*
* @return 经度
*/
public double getLastLongitude() {
return lastLongitude;
}
/**
* 设置经度
*
* @param lastLongitude 经度
*/
public void setLastLongitude(double lastLongitude) {
this.lastLongitude = lastLongitude;
}
/**
* 获取纬度
*
* @return 纬度
*/
public double getLastLatitude() {
return lastLatitude;
}
/**
* 设置纬度
*
* @param lastLatitude 纬度
*/
public void setLastLatitude(double lastLatitude) {
this.lastLatitude = lastLatitude;
}
/**
* 获取附加JSON数据对象
*
* @return 附加JSON数据对象
*/
public JSONObject getExtraData() {
return extraData;
}
/**
* 设置附加JSON数据对象
*
* @param extraData 附加JSON数据对象
*/
public void setExtraData(JSONObject extraData) {
this.extraData = extraData;
}
}
| 17.474286 | 96 | 0.533355 |
a7a695042578041f7c8ee74e321b8c7bf33cbac3 | 3,893 | /*
* 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 server.buffs.buffclasses.nova;
import client.MapleBuffStat;
import client.MapleJob;
import client.MonsterStatus;
import server.MapleStatEffect;
import server.MapleStatInfo;
import server.buffs.AbstractBuffClass;
/**
*
* @author Dismal
*/
public class KaiserBuff extends AbstractBuffClass {
public KaiserBuff() {
buffs = new int[]{
60001216, // 洗牌交換: 防禦模式
60001217, // 洗牌交換: 攻擊模式
61101002, // 意志之劍
61101004, // 怒火中燒
61111002, // 地龍襲擊
61111003, // 龍爆走
61111004, // 加強戰力
61111008, // 終極型態
61120007, // 進階意志之劍
61120008, // 進階終極形態
61121009, // 堅韌護甲
61121014, // 超新星勇士
61121053, // 超.終極型態
61121054, // 凱撒王權
//61121015, // 超新星勇士意志
//61100005, // 防禦模式
//61100008, // 攻擊模式
//61110005, // 二階防禦模式
//61110010, // 二階攻擊模式
//61120010, // 三階防禦模式
//61120013, // 三階攻擊模式
};
}
@Override
public boolean containsJob(int job) {
return MapleJob.is凱撒(job);
}
@Override
public void handleBuff(MapleStatEffect eff, int skill) {
switch (skill) {
case 61111003: //龍爆走
eff.statups.put(MapleBuffStat.ABNORMAL_STATUS_R, eff.info.get(MapleStatInfo.asrR));
eff.statups.put(MapleBuffStat.ELEMENTAL_STATUS_R, eff.info.get(MapleStatInfo.terR));
break;
case 60001216: //洗牌交換: 防禦模式
case 60001217: //洗牌交換: 攻擊模式
eff.info.put(MapleStatInfo.time, 2100000000);
eff.statups.put(MapleBuffStat.KAISER_MODE_CHANGE, 0);
case 61101002: // 意志之劍
case 61120007: // 進階意志之劍
eff.info.put(MapleStatInfo.time, 2100000000);
eff.statups.put(MapleBuffStat.TEMPEST_BLADES, 0);
break;
case 61101004: // 怒火中燒
eff.statups.put(MapleBuffStat.BOOSTER, eff.info.get(MapleStatInfo.x));
eff.statups.put(MapleBuffStat.INDIE_PAD, eff.info.get(MapleStatInfo.indiePad));
break;
case 61111002: // 地龍襲擊
eff.statups.put(MapleBuffStat.SUMMON, 1);
eff.monsterStatus.put(MonsterStatus.STUN, 1);
break;
case 61111004: // 加強戰力
eff.statups.put(MapleBuffStat.INDIE_DAM_R, eff.info.get(MapleStatInfo.indieDamR));
break;
case 61111008: // 終極型態
case 61120008: // 進階終極形態
case 61121053: // 超.終極型態
eff.statups.put(MapleBuffStat.INDIE_DAM_R, eff.info.get(MapleStatInfo.indieDamR));
eff.statups.put(MapleBuffStat.INDIE_BOOSTER, -2);
eff.statups.put(MapleBuffStat.SPEED, eff.info.get(MapleStatInfo.speed));
eff.statups.put(MapleBuffStat.MORPH, eff.info.get(MapleStatInfo.morph));
eff.statups.put(MapleBuffStat.STANCE, eff.info.get(MapleStatInfo.prop));
eff.statups.put(MapleBuffStat.CRITICAL_RATE, eff.info.get(MapleStatInfo.cr));
break;
case 61121009: // 堅韌護甲
eff.statups.put(MapleBuffStat.GRAND_ARMOR, eff.info.get(MapleStatInfo.ignoreMobpdpR));
break;
case 61121014: // 超新星勇士
eff.statups.put(MapleBuffStat.MAPLE_WARRIOR, eff.info.get(MapleStatInfo.x));
break;
case 61121054: // 凱撒王權
break;
default:
System.out.println("未知的 狂龙战士(6100) Buff: " + skill);
break;
}
}
}
| 37.432692 | 104 | 0.562291 |
ff23ba6a71d0b2adb38875aea0edbbb4163d8ff9 | 996 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor;
import com.intellij.core.CoreBundle;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class ReadOnlyModificationException extends RuntimeException {
private final Document myDocument;
/**
* @deprecated use {@link ReadOnlyModificationException#ReadOnlyModificationException(Document, String)} instead
*/
@Deprecated
public ReadOnlyModificationException(@NotNull Document document) {
this(document, CoreBundle.message("attempt.to.modify.read.only.document.error.message"));
}
public ReadOnlyModificationException(@NotNull Document document, @Nullable String message) {
super(message);
myDocument = document;
}
@NotNull
public Document getDocument() {
return myDocument;
}
}
| 33.2 | 140 | 0.779116 |
b9b626c1e7feaca3aadda413041a6f8d567cbedf | 19,217 | /*
* Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.engine.table;
import io.deephaven.base.log.LogOutput;
import io.deephaven.base.log.LogOutputAppendable;
import io.deephaven.io.log.impl.LogOutputStringImpl;
import io.deephaven.vector.*;
import io.deephaven.time.DateTime;
import io.deephaven.qst.column.header.ColumnHeader;
import io.deephaven.qst.type.ArrayType;
import io.deephaven.qst.type.BooleanType;
import io.deephaven.qst.type.ByteType;
import io.deephaven.qst.type.CharType;
import io.deephaven.qst.type.CustomType;
import io.deephaven.qst.type.GenericVectorType;
import io.deephaven.qst.type.PrimitiveVectorType;
import io.deephaven.qst.type.DoubleType;
import io.deephaven.qst.type.FloatType;
import io.deephaven.qst.type.GenericType;
import io.deephaven.qst.type.InstantType;
import io.deephaven.qst.type.IntType;
import io.deephaven.qst.type.LongType;
import io.deephaven.qst.type.NativeArrayType;
import io.deephaven.qst.type.PrimitiveType;
import io.deephaven.qst.type.ShortType;
import io.deephaven.qst.type.StringType;
import io.deephaven.qst.type.Type;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Objects;
/**
* Column definition for all Deephaven columns.
*/
public class ColumnDefinition<TYPE> implements LogOutputAppendable {
public static final ColumnDefinition<?>[] ZERO_LENGTH_COLUMN_DEFINITION_ARRAY = new ColumnDefinition[0];
public enum ColumnType {
/**
* A normal column, with no special considerations.
*/
Normal,
/**
* A column that has "grouping" metadata associated with it, possibly allowing for indexed filters, joins, and
* aggregations.
*/
Grouping,
/**
* A column that helps define underlying partitions in the storage of the data, which consequently may also be
* used for very efficient filtering.
*/
Partitioning
}
public static ColumnDefinition<Boolean> ofBoolean(@NotNull final String name) {
return new ColumnDefinition<>(name, Boolean.class);
}
public static ColumnDefinition<Byte> ofByte(@NotNull final String name) {
return new ColumnDefinition<>(name, byte.class);
}
public static ColumnDefinition<Character> ofChar(@NotNull final String name) {
return new ColumnDefinition<>(name, char.class);
}
public static ColumnDefinition<Short> ofShort(@NotNull final String name) {
return new ColumnDefinition<>(name, short.class);
}
public static ColumnDefinition<Integer> ofInt(@NotNull final String name) {
return new ColumnDefinition<>(name, int.class);
}
public static ColumnDefinition<Long> ofLong(@NotNull final String name) {
return new ColumnDefinition<>(name, long.class);
}
public static ColumnDefinition<Float> ofFloat(@NotNull final String name) {
return new ColumnDefinition<>(name, float.class);
}
public static ColumnDefinition<Double> ofDouble(@NotNull final String name) {
return new ColumnDefinition<>(name, double.class);
}
public static ColumnDefinition<String> ofString(@NotNull final String name) {
return new ColumnDefinition<>(name, String.class);
}
public static ColumnDefinition<DateTime> ofTime(@NotNull final String name) {
return new ColumnDefinition<>(name, DateTime.class);
}
public static ColumnDefinition<?> of(String name, Type<?> type) {
return type.walk(new Adapter(name)).out();
}
public static ColumnDefinition<?> of(String name, PrimitiveType<?> type) {
final Adapter adapter = new Adapter(name);
type.walk((PrimitiveType.Visitor) adapter);
return adapter.out();
}
public static ColumnDefinition<?> of(String name, GenericType<?> type) {
final Adapter adapter = new Adapter(name);
type.walk((GenericType.Visitor) adapter);
return adapter.out();
}
public static <T extends Vector<?>> ColumnDefinition<T> ofVector(
@NotNull final String name, @NotNull final Class<T> vectorType) {
return new ColumnDefinition<>(name, vectorType, baseComponentTypeForVector(vectorType), ColumnType.Normal);
}
public static <T> ColumnDefinition<T> fromGenericType(@NotNull final String name,
@NotNull final Class<T> dataType) {
return fromGenericType(name, dataType, null);
}
public static <T> ColumnDefinition<T> fromGenericType(
@NotNull final String name, @NotNull final Class<T> dataType, @Nullable final Class<?> componentType) {
return fromGenericType(name, dataType, componentType, ColumnType.Normal);
}
public static <T> ColumnDefinition<T> fromGenericType(
@NotNull final String name,
@NotNull final Class<T> dataType,
@Nullable final Class<?> componentType,
@NotNull final ColumnType columnType) {
return new ColumnDefinition<>(
name, dataType, checkAndMaybeInferComponentType(dataType, componentType), columnType);
}
/**
* Base component type class for each {@link Vector} type. Note that {@link BooleanVector} is deprecated, superseded
* by {@link ObjectVector}.
*/
private static Class<?> baseComponentTypeForVector(@NotNull final Class<? extends Vector<?>> vectorType) {
if (BooleanVector.class.isAssignableFrom(vectorType)) {
return Boolean.class;
}
if (CharVector.class.isAssignableFrom(vectorType)) {
return char.class;
}
if (ByteVector.class.isAssignableFrom(vectorType)) {
return byte.class;
}
if (ShortVector.class.isAssignableFrom(vectorType)) {
return short.class;
}
if (IntVector.class.isAssignableFrom(vectorType)) {
return int.class;
}
if (LongVector.class.isAssignableFrom(vectorType)) {
return long.class;
}
if (FloatVector.class.isAssignableFrom(vectorType)) {
return float.class;
}
if (DoubleVector.class.isAssignableFrom(vectorType)) {
return double.class;
}
if (ObjectVector.class.isAssignableFrom(vectorType)) {
return Object.class;
}
throw new IllegalArgumentException("Unrecognized Vector type " + vectorType);
}
private static void assertComponentTypeValid(
@NotNull final Class<?> dataType, @Nullable final Class<?> componentType) {
if (!Vector.class.isAssignableFrom(dataType) && !dataType.isArray()) {
return;
}
if (componentType == null) {
throw new IllegalArgumentException("Required component type not specified for data type " + dataType);
}
if (dataType.isArray()) {
final Class<?> arrayComponentType = dataType.getComponentType();
if (!arrayComponentType.isAssignableFrom(componentType)) {
throw new IllegalArgumentException(
"Invalid component type " + componentType + " for array data type " + dataType);
}
return;
}
// noinspection unchecked
final Class<?> baseComponentType = baseComponentTypeForVector((Class<? extends Vector<?>>) dataType);
if (!baseComponentType.isAssignableFrom(componentType)) {
throw new IllegalArgumentException(
"Invalid component type " + componentType + " for Vector data type " + dataType);
}
}
private static Class<?> checkAndMaybeInferComponentType(
@NotNull final Class<?> dataType, @Nullable final Class<?> inputComponentType) {
if (dataType.isArray()) {
final Class<?> arrayComponentType = dataType.getComponentType();
if (inputComponentType == null) {
return arrayComponentType;
}
if (!arrayComponentType.isAssignableFrom(inputComponentType)) {
throw new IllegalArgumentException(
"Invalid component type " + inputComponentType + " for array data type " + dataType);
}
return inputComponentType;
}
if (Vector.class.isAssignableFrom(dataType)) {
// noinspection unchecked
final Class<?> vectorComponentType =
baseComponentTypeForVector((Class<? extends Vector<?>>) dataType);
if (inputComponentType == null) {
/*
* TODO (https://github.com/deephaven/deephaven-core/issues/817): Allow formula results returning Vector
* to know component type if (Vector.class.isAssignableFrom(dataType)) { throw new
* IllegalArgumentException("Missing required component type for Vector data type " + dataType); }
*/
return vectorComponentType;
}
if (!vectorComponentType.isAssignableFrom(inputComponentType)) {
throw new IllegalArgumentException(
"Invalid component type " + inputComponentType + " for Vector data type " + dataType);
}
return inputComponentType;
}
return inputComponentType;
}
public static ColumnDefinition<?> from(ColumnHeader<?> header) {
return header.componentType().walk(new Adapter(header.name())).out();
}
private static class Adapter implements Type.Visitor, PrimitiveType.Visitor, GenericType.Visitor {
private final String name;
private ColumnDefinition<?> out;
public Adapter(String name) {
this.name = Objects.requireNonNull(name);
}
public ColumnDefinition<?> out() {
return Objects.requireNonNull(out);
}
@Override
public void visit(PrimitiveType<?> primitiveType) {
primitiveType.walk((PrimitiveType.Visitor) this);
}
@Override
public void visit(GenericType<?> genericType) {
genericType.walk((GenericType.Visitor) this);
}
@Override
public void visit(BooleanType booleanType) {
out = ofBoolean(name);
}
@Override
public void visit(ByteType byteType) {
out = ofByte(name);
}
@Override
public void visit(CharType charType) {
out = ofChar(name);
}
@Override
public void visit(ShortType shortType) {
out = ofShort(name);
}
@Override
public void visit(IntType intType) {
out = ofInt(name);
}
@Override
public void visit(LongType longType) {
out = ofLong(name);
}
@Override
public void visit(FloatType floatType) {
out = ofFloat(name);
}
@Override
public void visit(DoubleType doubleType) {
out = ofDouble(name);
}
@Override
public void visit(StringType stringType) {
out = ofString(name);
}
@Override
public void visit(InstantType instantType) {
out = ofTime(name);
}
@Override
public void visit(ArrayType<?, ?> arrayType) {
arrayType.walk(new ArrayType.Visitor() {
@Override
public void visit(NativeArrayType<?, ?> nativeArrayType) {
out = fromGenericType(name, nativeArrayType.clazz(), nativeArrayType.componentType().clazz());
}
@Override
public void visit(PrimitiveVectorType<?, ?> vectorPrimitiveType) {
// noinspection unchecked
out = ofVector(name, (Class<? extends Vector>) vectorPrimitiveType.clazz());
}
@Override
public void visit(GenericVectorType<?, ?> genericVectorType) {
out = fromGenericType(name, ObjectVector.class, genericVectorType.componentType().clazz());
}
});
}
@Override
public void visit(CustomType<?> customType) {
out = fromGenericType(name, customType.clazz());
}
}
@NotNull
private final String name;
@NotNull
private final Class<TYPE> dataType;
@Nullable
private final Class<?> componentType;
@NotNull
private final ColumnType columnType;
private ColumnDefinition(@NotNull final String name, @NotNull final Class<TYPE> dataType) {
this(name, dataType, null, ColumnType.Normal);
}
private ColumnDefinition(
@NotNull final String name,
@NotNull final Class<TYPE> dataType,
@Nullable final Class<?> componentType,
@NotNull final ColumnType columnType) {
this.name = Objects.requireNonNull(name);
this.dataType = Objects.requireNonNull(dataType);
this.componentType = componentType;
this.columnType = Objects.requireNonNull(columnType);
}
@NotNull
public String getName() {
return name;
}
@NotNull
public Class<TYPE> getDataType() {
return dataType;
}
@Nullable
public Class<?> getComponentType() {
return componentType;
}
@NotNull
public ColumnType getColumnType() {
return columnType;
}
public ColumnDefinition<TYPE> withPartitioning() {
return isPartitioning() ? this : new ColumnDefinition<>(name, dataType, componentType, ColumnType.Partitioning);
}
public ColumnDefinition<TYPE> withGrouping() {
return isGrouping() ? this : new ColumnDefinition<>(name, dataType, componentType, ColumnType.Grouping);
}
public ColumnDefinition<TYPE> withNormal() {
return columnType == ColumnType.Normal
? this
: new ColumnDefinition<>(name, dataType, componentType, ColumnType.Normal);
}
public <Other> ColumnDefinition<Other> withDataType(@NotNull final Class<Other> newDataType) {
// noinspection unchecked
return dataType == newDataType
? (ColumnDefinition<Other>) this
: fromGenericType(name, newDataType, componentType, columnType);
}
public ColumnDefinition<?> withName(@NotNull final String newName) {
return newName.equals(name) ? this : new ColumnDefinition<>(newName, dataType, componentType, columnType);
}
public boolean isGrouping() {
return (columnType == ColumnType.Grouping);
}
public boolean isPartitioning() {
return (columnType == ColumnType.Partitioning);
}
public boolean isDirect() {
return (columnType == ColumnType.Normal || columnType == ColumnType.Grouping);
}
/**
* Compares two ColumnDefinitions somewhat more permissively than equals, disregarding matters of storage and
* derivation. Checks for equality of {@code name}, {@code dataType}, and {@code componentType}. As such, this
* method has an equivalence relation, ie {@code A.isCompatible(B) == B.isCompatible(A)}.
*
* @param other - The ColumnDefinition to compare to.
* @return True if the ColumnDefinition defines a column whose data is compatible with this ColumnDefinition.
*/
public boolean isCompatible(ColumnDefinition<?> other) {
if (this == other) {
return true;
}
return this.name.equals(other.name)
&& this.dataType == other.dataType
&& this.componentType == other.componentType;
}
/**
* Describes the column definition with respect to the fields that are checked in
* {@link #isCompatible(ColumnDefinition)}.
*
* @return the description for compatibility
*/
public String describeForCompatibility() {
if (componentType == null) {
return String.format("(%s, %s)", name, dataType);
}
return String.format("[%s, %s, %s]", name, dataType, componentType);
}
/**
* Enumerate the differences between this ColumnDefinition, and another one. Lines will be of the form "lhs
* attribute 'value' does not match rhs attribute 'value'.
*
* @param differences an array to which differences can be added
* @param other the ColumnDefinition under comparison
* @param lhs what to call "this" definition
* @param rhs what to call the other definition
* @param prefix begin each difference with this string
* @param includeColumnType whether to include {@code columnType} comparisons
*/
public void describeDifferences(@NotNull List<String> differences, @NotNull final ColumnDefinition<?> other,
@NotNull final String lhs, @NotNull final String rhs, @NotNull final String prefix,
final boolean includeColumnType) {
if (this == other) {
return;
}
if (!name.equals(other.name)) {
differences.add(prefix + lhs + " name '" + name + "' does not match " + rhs + " name '" + other.name + "'");
}
if (dataType != other.dataType) {
differences.add(prefix + lhs + " dataType '" + dataType + "' does not match " + rhs + " dataType '"
+ other.dataType + "'");
} else {
if (componentType != other.componentType) {
differences.add(prefix + lhs + " componentType '" + componentType + "' does not match " + rhs
+ " componentType '" + other.componentType + "'");
}
if (includeColumnType && columnType != other.columnType) {
differences.add(prefix + lhs + " columnType " + columnType + " does not match " + rhs + " columnType "
+ other.columnType);
}
}
}
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ColumnDefinition)) {
return false;
}
final ColumnDefinition<?> otherCD = (ColumnDefinition<?>) other;
return name.equals(otherCD.name)
&& dataType == otherCD.dataType
&& componentType == otherCD.componentType
&& columnType == otherCD.columnType;
}
@Override
public int hashCode() {
return (((31
+ name.hashCode()) * 31
+ dataType.hashCode()) * 31
+ Objects.hashCode(componentType)) * 31
+ columnType.hashCode();
}
@Override
public String toString() {
return new LogOutputStringImpl().append(this).toString();
}
@Override
public LogOutput append(LogOutput logOutput) {
return logOutput.append("ColumnDefinition {")
.append("name=").append(name)
.append(", dataType=").append(String.valueOf(dataType))
.append(", componentType=").append(String.valueOf(componentType))
.append(", columnType=").append(columnType.name())
.append('}');
}
}
| 36.60381 | 120 | 0.622105 |
e64f9c8c0d074d01c90966a6e0e1120cc9703a05 | 1,732 | package edu.theinterests.cellsim;
import java.util.ArrayList;
import java.util.List;
public class Cell {
private float gene;
private int energy;
private Coords coords;
private List<Cell> neighbors = new ArrayList<Cell>();
public Cell(float gene, int energy, Coords coords) {
this.gene = gene;
this.energy = energy;
this.coords = coords;
}
public void analyzeNeighbors() {
// y-1 y y+1
// x-1 [1][2][3]
// x [0][C][4]
// x+1 [7][6][5]
neighbors.clear();
neighbors.add(Main.torus.getCell(coords.getX() + 0, coords.getY() - 1));
neighbors.add(Main.torus.getCell(coords.getX() - 1, coords.getY() - 1));
neighbors.add(Main.torus.getCell(coords.getX() - 1, coords.getY() + 0));
neighbors.add(Main.torus.getCell(coords.getX() - 1, coords.getY() + 1));
neighbors.add(Main.torus.getCell(coords.getX() + 0, coords.getY() + 1));
neighbors.add(Main.torus.getCell(coords.getX() + 1, coords.getY() + 1));
neighbors.add(Main.torus.getCell(coords.getX() + 1, coords.getY() + 0));
neighbors.add(Main.torus.getCell(coords.getX() + 1, coords.getY() - 1));
}
public Coords getCoords() {
return this.coords;
}
public float getGene() {
return this.gene;
}
public int getEnergy() {
return this.energy;
}
public List<Cell> getNeighbors() {
return this.neighbors;
}
public Cell getRandomNeighbor() {
return this.neighbors.get(Utils.randInt(0, 7));
}
public void setEnergy(int energy) {
this.energy = energy;
}
public void setGene(float gene) {
this.gene = gene;
}
}
| 27.0625 | 80 | 0.584296 |
3538fdb56dfe4000334d362e23472c45ff86b1ca | 507 | package erogenousbeef.bigreactors.common.multiblock.block;
import net.minecraft.util.IStringSerializable;
public enum FuelRodState implements IStringSerializable {
Disassembled,
AssembledUD,
AssembledEW,
AssembledSN;
FuelRodState() {
this._name = this.name().toLowerCase();
}
@Override
public String toString() {
return this._name;
}
@Override
public String getName() {
return this._name;
}
private final String _name;
}
| 16.354839 | 58 | 0.664694 |
23cfd98c618900bceb8fc3b58c87ee9158a1b909 | 3,311 | package org.lockss.plugin.hindawi;
import org.lockss.config.Configuration;
import org.lockss.daemon.ConfigParamDescr;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.ajax.AjaxRequestResponse;
import org.lockss.plugin.definable.DefinableArchivalUnit;
import org.lockss.plugin.definable.DefinablePlugin;
import org.lockss.test.ConfigurationUtil;
import org.lockss.test.LockssTestCase;
import org.lockss.test.MockLockssDaemon;
import org.lockss.test.MockLockssUrlConnection;
import org.lockss.util.Logger;
import org.lockss.util.urlconn.CacheException;
import org.lockss.util.urlconn.HttpResultMap;
import java.util.Properties;
public class TestHindawi2020HttpResponseHandler extends LockssTestCase {
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String DOWNLOAD_URL_KEY = "download_url";
static final String JID_KEY = ConfigParamDescr.JOURNAL_ID.getKey();
static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey();
private static final Logger log = Logger.getLogger(TestHindawi2020HttpResponseHandler.class);
static final String PLUGIN_ID = "org.lockss.plugin.hindawi.HindawiPlugin";
static final String ROOT_URL = "https://www.hindawi.com/";
static final String DOWNLOAD_URL = "http://downloads.hindawi.com/lockss.html";
private MockLockssDaemon theDaemon;
private DefinablePlugin plugin;
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
theDaemon = getMockLockssDaemon();
theDaemon.getHashService();
theDaemon.getRepositoryManager();
plugin = new DefinablePlugin();
plugin.initPlugin(theDaemon, PLUGIN_ID);
}
public void tearDown() throws Exception {
super.tearDown();
}
private DefinableArchivalUnit makeAuFromProps(Properties props)
throws ArchivalUnit.ConfigurationException {
Configuration config = ConfigurationUtil.fromProps(props);
return (DefinableArchivalUnit)plugin.configureAu(config, null);
}
public void testHandlesExceptionResult() throws Exception {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(DOWNLOAD_URL_KEY, DOWNLOAD_URL);
props.setProperty(YEAR_KEY, "2013");
props.setProperty(JID_KEY, "ppar");
DefinableArchivalUnit au = makeAuFromProps(props);
String data_url = "https://www.hindawi.com/journals/ppar/2013/612971/'data:image/svg+xml";
String non_data_url = "https://www.hindawi.com/journals/ppar/2013/612971/foo.bar";
MockLockssUrlConnection conn = new MockLockssUrlConnection();
conn.setURL("http://www.hindawi.com/");
CacheException exc =
((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn,
new javax.net.ssl.SSLHandshakeException("BAD"), "foo");
// make sure it's a retryable
assertClass(CacheException.RetryableException.class, exc);
conn.setURL(data_url);
log.info(" " + data_url.contains("'data:"));
exc = ((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn, 500, "foo");
assertTrue(exc instanceof CacheException.NoRetryDeadLinkException);
conn.setURL(non_data_url);
exc = ((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn, 500, "foo");
assertTrue(exc instanceof CacheException.RetrySameUrlException);
}
}
| 39.416667 | 95 | 0.766234 |
b9f7e27ab3ee6e52a64ebf3fdcde54120c1ed9a5 | 5,875 | /*
* Copyright (C) 2012 onwards University of Deusto
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* This software consists of contributions made by many individuals,
* listed below:
*
* Author: Pablo Orduña <[email protected]>
*
*/
package es.deusto.weblab.client.experiments.binary.ui;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.comm.exceptions.CommException;
import es.deusto.weblab.client.dto.experiments.ResponseCommand;
import es.deusto.weblab.client.i18n.IWebLabI18N;
import es.deusto.weblab.client.lab.comm.callbacks.IResponseCommandCallback;
import es.deusto.weblab.client.lab.experiments.IBoardBaseController;
import es.deusto.weblab.client.ui.widgets.WlTimer;
import es.deusto.weblab.client.ui.widgets.WlWebcam;
@SuppressWarnings("unqualified-field-access")
class MainPanel extends Composite {
private static final int IS_READY_QUERY_TIMER = 1000;
private static final String STATE_NOT_READY = "not_ready";
private static final String STATE_PROGRAMMING = "programming";
private static final String STATE_READY = "ready";
private static final String STATE_FAILED = "failed";
// GWT UiBinder stuff
interface MainPanelUiBinder extends UiBinder<Widget, MainPanel> { }
private static MainPanelUiBinder uiBinder = GWT.create(MainPanelUiBinder.class);
private static IWebLabI18N i18n = GWT.create(IWebLabI18N.class);
// Mapped fields
@UiField WlWebcam camera;
@UiField WlTimer timer;
@UiField Label messages;
@UiField HorizontalPanel contentPanel;
// Local fields
private final IBoardBaseController controller;
private final String [] labels;
private final Button [] buttons;
private Timer readyTimer;
public MainPanel(IBoardBaseController controller, String [] labels) {
this.controller = controller;
initWidget(uiBinder.createAndBindUi(this));
this.labels = (labels == null)?new String[]{"sample", "content"}:labels;
this.buttons = new Button[this.labels.length];
loadButtons();
}
public WlWebcam getWebcam() {
return this.camera;
}
public WlTimer getTimer() {
return this.timer;
}
void loadButtons() {
this.messages.setText(i18n.selectACode());
this.contentPanel.clear();
for (int i = 0; i < this.labels.length; ++i) {
final String label = this.labels[i];
final Button b = new Button(label, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
disableButtons(label);
controller.sendCommand("label:" + label, new IResponseCommandCallback() {
@Override
public void onSuccess(ResponseCommand responseCommand) {
loadTimer(label);
}
@Override
public void onFailure(CommException e) {
e.printStackTrace();
onDeviceProgrammingFailed(": " + e.getMessage(), label);
}
});
}
});
this.buttons[i] = b;
this.contentPanel.add(b);
}
}
void onDeviceReady(String label) {
enableButtons();
loadInteractivePanel(label);
}
void onDeviceProgrammingFailed(String errorMessage, String label) {
Window.alert("Command " + label + " failed" + errorMessage);
enableButtons();
}
private void loadTimer(final String label) {
this.readyTimer = new Timer() {
@Override
public void run() {
// Send the command and react to the response
controller.sendCommand("STATE", new IResponseCommandCallback() {
@Override
public void onFailure(CommException e) {
messages.setText("There was an error while trying to find out whether the experiment is ready");
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
// Read the full message returned by the exp server and ensure it's not empty
final String resp = responseCommand.getCommandString();
if(resp.length() == 0)
messages.setText("The STATE query returned an empty result");
// The command follows the format STATE=ready
// Extract both parts
final String [] tokens = resp.split("=", 2);
if(tokens.length != 2 || !tokens[0].equals("STATE")) {
messages.setText("Unexpected response ot the STATE query: " + resp);
return;
}
final String state = tokens[1];
if(state.equals(STATE_NOT_READY)) {
readyTimer.schedule(IS_READY_QUERY_TIMER);
} else if(state.equals(STATE_READY)) {
// Ready
onDeviceReady(label);
} else if(state.equals(STATE_PROGRAMMING)) {
readyTimer.schedule(IS_READY_QUERY_TIMER);
} else if(state.equals(STATE_FAILED)) {
onDeviceProgrammingFailed("", label);
} else {
messages.setText("Received unexpected response to the STATE query");
}
}
});
}
};
this.readyTimer.schedule(IS_READY_QUERY_TIMER);
}
private void disableButtons(String label) {
this.messages.setText(i18n.loading(label) + "...");
for(Button b : this.buttons)
b.setEnabled(false);
}
private void enableButtons() {
this.messages.setText("");
for(Button b : this.buttons)
b.setEnabled(true);
}
private void loadInteractivePanel(String label) {
this.contentPanel.clear();
final InteractivePanel panel = new InteractivePanel(this, this.controller, label);
this.contentPanel.add(panel);
}
}
| 30.921053 | 102 | 0.71166 |
b29bca0e2a0de0e4d496148439878b6ab1e1bb58 | 1,224 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dimitStore.proto
package dimit.store;
public interface ChannelRecvStatOrBuilder extends
// @@protoc_insertion_point(interface_extends:ChannelRecvStat)
com.google.protobuf.MessageOrBuilder {
/**
* <code>uint32 v = 1;</code>
*/
int getV();
/**
* <code>string id = 2;</code>
*/
java.lang.String getId();
/**
* <code>string id = 2;</code>
*/
com.google.protobuf.ByteString
getIdBytes();
/**
* <pre>
* Channel's id
* </pre>
*
* <code>string channel = 3;</code>
*/
java.lang.String getChannel();
/**
* <pre>
* Channel's id
* </pre>
*
* <code>string channel = 3;</code>
*/
com.google.protobuf.ByteString
getChannelBytes();
/**
* <code>uint64 succCount = 4;</code>
*/
long getSuccCount();
/**
* <code>uint64 failCount = 5;</code>
*/
long getFailCount();
/**
* <code>double tps = 8;</code>
*/
double getTps();
/**
* <pre>
* timestamp
* </pre>
*
* <code>uint64 ct = 9;</code>
*/
long getCt();
/**
* <pre>
* modify timestamp
* </pre>
*
* <code>uint64 mt = 10;</code>
*/
long getMt();
}
| 16.105263 | 66 | 0.547386 |
922a1ef083d3fa0a5102aa0535f3d3ea0334028b | 7,547 | /*
* 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.ignite.ml.math.primitives.vector;
import org.apache.ignite.ml.math.exceptions.IndexException;
import org.apache.ignite.ml.math.primitives.matrix.Matrix;
import org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix;
import org.apache.ignite.ml.math.primitives.vector.impl.VectorizedViewMatrix;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link VectorizedViewMatrix}.
*/
public class MatrixVectorViewTest {
/** */
private static final String UNEXPECTED_VALUE = "Unexpected value";
/** */
private static final int SMALL_SIZE = 3;
/** */
private static final int IMPOSSIBLE_SIZE = -1;
/** */
private Matrix parent;
/** */
@Before
public void setup() {
parent = newMatrix(SMALL_SIZE, SMALL_SIZE);
}
/** */
@Test
public void testDiagonal() {
Vector vector = parent.viewDiagonal();
for (int i = 0; i < SMALL_SIZE; i++)
assertView(i, i, vector, i);
}
/** */
@Test
public void testRow() {
for (int i = 0; i < SMALL_SIZE; i++) {
Vector viewRow = parent.viewRow(i);
for (int j = 0; j < SMALL_SIZE; j++)
assertView(i, j, viewRow, j);
}
}
/** */
@Test
public void testCols() {
for (int i = 0; i < SMALL_SIZE; i++) {
Vector viewCol = parent.viewColumn(i);
for (int j = 0; j < SMALL_SIZE; j++)
assertView(j, i, viewCol, j);
}
}
/** */
@Test
public void basicTest() {
for (int rowSize : new int[] {1, 2, 3, 4})
for (int colSize : new int[] {1, 2, 3, 4})
for (int row = 0; row < rowSize; row++)
for (int col = 0; col < colSize; col++)
for (int rowStride = 0; rowStride < rowSize; rowStride++)
for (int colStride = 0; colStride < colSize; colStride++)
if (rowStride != 0 || colStride != 0)
assertMatrixVectorView(newMatrix(rowSize, colSize), row, col, rowStride, colStride);
}
/** */
@Test(expected = AssertionError.class)
public void parentNullTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(null, 1, 1, 1, 1).size());
}
/** */
@Test(expected = IndexException.class)
public void rowNegativeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, -1, 1, 1, 1).size());
}
/** */
@Test(expected = IndexException.class)
public void colNegativeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, -1, 1, 1).size());
}
/** */
@Test(expected = IndexException.class)
public void rowTooLargeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, parent.rowSize() + 1, 1, 1, 1).size());
}
/** */
@Test(expected = IndexException.class)
public void colTooLargeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, parent.columnSize() + 1, 1, 1).size());
}
/** */
@Test(expected = AssertionError.class)
public void rowStrideNegativeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, 1, -1, 1).size());
}
/** */
@Test(expected = AssertionError.class)
public void colStrideNegativeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, 1, 1, -1).size());
}
/** */
@Test(expected = AssertionError.class)
public void rowStrideTooLargeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, 1, parent.rowSize() + 1, 1).size());
}
/** */
@Test(expected = AssertionError.class)
public void colStrideTooLargeTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, 1, 1, parent.columnSize() + 1).size());
}
/** */
@Test(expected = AssertionError.class)
public void bothStridesZeroTest() {
//noinspection ConstantConditions
assertEquals(IMPOSSIBLE_SIZE,
new VectorizedViewMatrix(parent, 1, 1, 0, 0).size());
}
/** */
private void assertMatrixVectorView(Matrix parent, int row, int col, int rowStride, int colStride) {
VectorizedViewMatrix view = new VectorizedViewMatrix(parent, row, col, rowStride, colStride);
String desc = "parent [" + parent.rowSize() + "x" + parent.columnSize() + "], view ["
+ row + "x" + col + "], strides [" + rowStride + ", " + colStride + "]";
final int size = view.size();
final int sizeByRows = rowStride == 0 ? IMPOSSIBLE_SIZE : (parent.rowSize() - row) / rowStride;
final int sizeByCols = colStride == 0 ? IMPOSSIBLE_SIZE : (parent.columnSize() - col) / colStride;
assertTrue("Size " + size + " differs from expected for " + desc,
size == sizeByRows || size == sizeByCols);
for (int idx = 0; idx < size; idx++) {
final int rowIdx = row + idx * rowStride;
final int colIdx = col + idx * colStride;
assertEquals(UNEXPECTED_VALUE + " at view index " + idx + desc,
parent.get(rowIdx, colIdx), view.get(idx), 0d);
}
}
/** */
private Matrix newMatrix(int rowSize, int colSize) {
Matrix res = new DenseMatrix(rowSize, colSize);
for (int i = 0; i < res.rowSize(); i++)
for (int j = 0; j < res.columnSize(); j++)
res.set(i, j, i * res.rowSize() + j);
return res;
}
/** */
private void assertView(int row, int col, Vector view, int viewIdx) {
assertValue(row, col, view, viewIdx);
parent.set(row, col, parent.get(row, col) + 1);
assertValue(row, col, view, viewIdx);
view.set(viewIdx, view.get(viewIdx) + 2);
assertValue(row, col, view, viewIdx);
}
/** */
private void assertValue(int row, int col, Vector view, int viewIdx) {
assertEquals(UNEXPECTED_VALUE + " at row " + row + " col " + col, parent.get(row, col), view.get(viewIdx), 0d);
}
}
| 33.246696 | 120 | 0.601431 |
f2f9249b19b626901515a7546f13224bd6b2254f | 15,144 | package com.bergerkiller.mountiplex.reflection.declarations;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Level;
import com.bergerkiller.mountiplex.MountiplexUtil;
import com.bergerkiller.mountiplex.reflection.util.StringBuffer;
/**
* A list of package paths and imports, combined with class definitions
*/
public class SourceDeclaration extends Declaration {
public final ClassDeclaration[] classes;
private SourceDeclaration(ClassResolver resolver, ClassLoader classLoader, File sourceDirectory, StringBuffer declaration) {
super(resolver, preprocess(declaration));
trimWhitespace(0);
// Parse all segments
StringBuffer postfix;
String templatefile = "";
LinkedList<ClassDeclaration> classes = new LinkedList<ClassDeclaration>();
while ((postfix = this.getPostfix()) != null && postfix.length() > 0) {
if (nextInternal()) {
continue;
}
boolean is_package = false;
boolean is_import = false;
boolean is_include = false;
boolean is_setpath = false;
boolean is_setvar = false;
if (postfix.startsWith("package ")) {
trimWhitespace(8);
is_package = true;
} else if (postfix.startsWith("import ")) {
trimWhitespace(7);
is_import = true;
} else if (postfix.startsWith("#include ")) {
trimWhitespace(9);
is_include = true;
} else if (postfix.startsWith("#setpath ")) {
trimWhitespace(9);
is_setpath = true;
} else if (postfix.startsWith("#set ")) {
trimWhitespace(5);
is_setvar = true;
}
// Parse package or import name, or include another source file
if (is_setvar) {
postfix = this.getPostfix();
int nameEndIdx = postfix.indexOf(' ');
if (nameEndIdx == -1) {
setPostfix(StringBuffer.EMPTY);
break;
}
String varName = postfix.substringToString(0, nameEndIdx);
String varValue = "";
trimWhitespace(nameEndIdx + 1);
postfix = this.getPostfix();
for (int cidx = 0; cidx < postfix.length(); cidx++) {
char c = postfix.charAt(cidx);
if (MountiplexUtil.containsChar(c, invalid_name_chars)) {
varValue = postfix.substringToString(0, cidx);
break;
}
}
if (varValue == null) {
varValue = postfix.toString();
}
this.trimLine();
this.getResolver().setVariable(varName, varValue);
continue;
} else if (is_package || is_import || is_include || is_setpath) {
String name = null;
postfix = this.getPostfix();
for (int cidx = 0; cidx < postfix.length(); cidx++) {
char c = postfix.charAt(cidx);
if (MountiplexUtil.containsChar(c, invalid_name_chars)) {
name = postfix.substringToString(0, cidx);
break;
}
}
if (name == null) {
name = postfix.toString();
}
this.trimLine();
if (is_package) {
this.getResolver().setPackage(name);
}
if (is_import) {
this.getResolver().addImport(name);
}
if (is_include) {
if (name.startsWith(".") || name.startsWith("/")) {
// Trim everything after the last / in the old template path
int lastPathIdx = templatefile.lastIndexOf('/');
if (lastPathIdx != -1) {
name = templatefile.substring(0, lastPathIdx) + "/" + name;
} else {
name = templatefile + "/" + name;
}
// Repeatedly remove the word in front of /../
int moveUpIdx;
while ((moveUpIdx = name.indexOf("/../")) != -1) {
int before = name.lastIndexOf('/', moveUpIdx - 1);
if (before == -1) {
name = name.substring(moveUpIdx + 4);
} else {
name = name.substring(0, before) + "/" + name.substring(moveUpIdx + 4);
}
}
// Clean up the path
name = name.replace("/./", "/").replace("//", "/");
}
// Load the resource pointed to by this name
InputStream is;
if (sourceDirectory == null) {
if (classLoader == null) {
classLoader = SourceDeclaration.class.getClassLoader();
}
is = classLoader.getResourceAsStream(name);
} else {
try {
String path = sourceDirectory.getAbsolutePath() + File.separator + name.replace("/", File.separator);
is = new FileInputStream(path);
} catch (FileNotFoundException e) {
is = null;
}
}
if (is == null) {
MountiplexUtil.LOGGER.warning("Could not resolve include while parsing template: " + name);
MountiplexUtil.LOGGER.warning("Template file: " + templatefile);
} else {
String inclSourceStr;
try {
try (ByteArrayOutputStream result = new ByteArrayOutputStream()) {
int length;
byte[] buffer = new byte[1024];
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
inclSourceStr = result.toString("UTF-8");
}
} catch (Throwable t) {
MountiplexUtil.LOGGER.log(Level.WARNING, "Failed to load template " + name, t);
inclSourceStr = "";
}
if (!inclSourceStr.isEmpty()) {
// Load this source file
StringBuilder subSource = new StringBuilder();
subSource.append(getResolver().saveDeclaration()).append("\n");
subSource.append("#setpath ").append(name).append("\n");
subSource.append(inclSourceStr);
SourceDeclaration inclSource = new SourceDeclaration(this.getResolver(), classLoader, sourceDirectory, StringBuffer.of(subSource));
classes.addAll(Arrays.asList(inclSource.classes));
}
}
}
if (is_setpath) {
templatefile = name;
}
continue;
}
// Read classes
ClassDeclaration cDec = nextClass();
if (cDec.isValid()) {
classes.add(cDec);
} else {
MountiplexUtil.LOGGER.warning("Invalid class declaration parsed:\n" + cDec);
this.setInvalid();
this.classes = new ClassDeclaration[0];
return;
}
}
this.classes = classes.toArray(new ClassDeclaration[classes.size()]);
}
public static StringBuffer preprocess(StringBuffer declaration) {
return StringBuffer.of(preprocess(declaration.toString()));
}
/// pre-processes the source file, keeping the parts that pass variable evaluation
public static String preprocess(String declaration) {
return preprocess(declaration, new ClassResolver());
}
/// pre-processes the source file, keeping the parts that pass variable evaluation
public static String preprocess(String declaration, ClassResolver resolver) {
return (new SourcePreprocessor(resolver)).preprocess(declaration);
}
/**
* Corrects space indentation in text, making sure the minimal indentation is 0.
*
* @param text to correct
* @return corrected text
*/
public static String trimIndentation(String text) {
String[] lines = text.split("\\r?\\n", -1);
// Find the indent of the text section
int minIndent = 20;
for (String line : lines) {
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) != ' ') {
if (i < minIndent) {
minIndent = i;
}
break;
}
}
}
// Trim indentation off the section and add the lines
StringBuilder result = new StringBuilder(text.length());
for (String line : lines) {
if (line.length() >= minIndent) {
line = line.substring(minIndent);
}
result.append(line).append('\n');
}
return result.toString();
}
@Override
public boolean isResolved() {
return false;
}
@Override
public boolean match(Declaration declaration) {
return false; // don't care
}
@Override
public String toString(boolean identity) {
String pkg = getResolver().getPackage();
String str = "";
if (pkg.length() > 0) {
str += "package " + pkg + ";\n\n";
}
for (String imp : getResolver().getImports()) {
str += "import " + imp + ";\n";
}
str += "\n";
for (ClassDeclaration c : classes) {
str += c.toString(identity) + "\n\n";
}
return str;
}
@Override
protected void debugString(StringBuilder str, String indent) {
}
@Override
public double similarity(Declaration other) {
return 0.0; // not implemented
}
/**
* Parses the full source contents into a Source Declaration from a String.
* The class resolver root can be specified.
*
* @param resolver to use as base for resolving types and classes
* @param source to parse
* @return Source Declaration
*/
public static SourceDeclaration parse(ClassResolver resolver, String source) {
return new SourceDeclaration(resolver, null, null, StringBuffer.of(source));
}
/**
* Parses the full source contents into a Source Declaration from a String
*
* @param source to parse
* @return Source Declaration
*/
public static SourceDeclaration parse(String source) {
return new SourceDeclaration(new ClassResolver(), null, null, StringBuffer.of(source));
}
private static String saveVars(Map<String, String> variables) {
if (variables == null || variables.isEmpty()) {
return "";
}
StringBuilder str = new StringBuilder();
for (Map.Entry<String, String> entry : variables.entrySet()) {
str.append("#set ").append(entry.getKey()).append(' ').append(entry.getValue()).append('\n');
}
return str.toString();
}
/**
* Parses the full source contents by reading a bundled resource file
*
* @param classLoader to use when resolving loaded and included resources
* @param sourceInclude resource file to load
* @param variables to use while loading the source files
* @return Source Declaration
*/
public static SourceDeclaration parseFromResources(ClassLoader classLoader, String sourceInclude, Map<String, String> variables) {
return new SourceDeclaration(new ClassResolver(), classLoader, null, StringBuffer.of(saveVars(variables) + "\n" + "#include " + sourceInclude));
}
/**
* Parses the full source contents by reading from files on disk
*
* @param sourceDirectory relative to which included files are resolved
* @param sourceInclude relative file path to load
* @param variables to use while loading the source files
* @param isGenerating sets the class resolver 'isGenerating' option
* @return Source Declaration
*/
public static SourceDeclaration loadFromDisk(File sourceDirectory, String sourceInclude, Map<String, String> variables, boolean isGenerating) {
ClassResolver resolver = new ClassResolver();
resolver.setGenerating(isGenerating);
return new SourceDeclaration(resolver, null, sourceDirectory, StringBuffer.of(saveVars(variables) + "\n" + "#include " + sourceInclude));
}
/**
* Parses the full source contents by reading from files on disk
*
* @param sourceDirectory relative to which included files are resolved
* @param sourceInclude relative file path to load
* @param variables to use while loading the source files
* @return Source Declaration
*/
public static SourceDeclaration loadFromDisk(File sourceDirectory, String sourceInclude, Map<String, String> variables) {
return new SourceDeclaration(new ClassResolver(), null, sourceDirectory, StringBuffer.of(saveVars(variables) + "\n" + "#include " + sourceInclude));
}
/**
* Parses the full source contents by reading a bundled resource file
*
* @param classLoader to use when resolving loaded and included resources
* @param sourceInclude resource file to load
* @return Source Declaration
*/
public static SourceDeclaration parseFromResources(ClassLoader classLoader, String sourceInclude) {
return new SourceDeclaration(new ClassResolver(), classLoader, null, StringBuffer.of("#include " + sourceInclude));
}
/**
* Parses the full source contents by reading from files on disk
*
* @param sourceDirectory relative to which included files are resolved
* @param sourceInclude relative file path to load
* @return Source Declaration
*/
public static SourceDeclaration loadFromDisk(File sourceDirectory, String sourceInclude) {
return new SourceDeclaration(new ClassResolver(), null, sourceDirectory, StringBuffer.of("#include " + sourceInclude));
}
}
| 40.384 | 159 | 0.538893 |
1271cc4015b0d15e0819bff1e5fcd7799ba8d2d3 | 2,332 | package me.senseiwells.arucas.tokens;
import me.senseiwells.arucas.api.ISyntax;
import me.senseiwells.arucas.utils.Position;
import java.util.Map;
import java.util.Set;
public class Token {
public final Type type;
public final String content;
public final ISyntax syntaxPosition;
public Token(Type type, String content, Position startPos, Position endPos) {
this.type = type;
this.content = content;
this.syntaxPosition = ISyntax.of(startPos, endPos);
}
public Token(Type type, String content, ISyntax syntaxPosition) {
this(type, content, syntaxPosition.getStartPos(), syntaxPosition.getEndPos());
}
public Token(Type type, ISyntax startPos, ISyntax endPos) {
this(type, "", startPos.getStartPos(), endPos.getEndPos());
}
public Token(Type type, ISyntax syntaxPosition) {
this(type, "", syntaxPosition.getStartPos(), syntaxPosition.getEndPos());
}
@Override
public String toString() {
return "Token{type=%s, content='%s'}".formatted(this.type, this.content);
}
public enum Type {
// Delimiters
WHITESPACE,
SEMICOLON,
COLON,
IDENTIFIER,
COMMA,
FINISH,
// Atoms
NUMBER,
BOOLEAN,
STRING,
NULL,
LIST,
MAP,
SCOPE,
// Arithmetics
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
POWER,
// Boolean operators
NOT,
AND,
OR,
// Brackets
LEFT_BRACKET,
RIGHT_BRACKET,
LEFT_SQUARE_BRACKET,
RIGHT_SQUARE_BRACKET,
LEFT_CURLY_BRACKET,
RIGHT_CURLY_BRACKET,
// Memory Operator
ASSIGN_OPERATOR,
INCREMENT,
DECREMENT,
// Comparisons
EQUALS,
NOT_EQUALS,
LESS_THAN,
MORE_THAN,
LESS_THAN_EQUAL,
MORE_THAN_EQUAL,
// Statements
IF,
WHILE,
ELSE,
CONTINUE,
BREAK,
VAR,
RETURN,
FUN,
TRY,
CATCH,
FOREACH,
FOR,
SWITCH,
CASE,
DEFAULT,
CLASS,
THIS,
NEW,
STATIC,
OPERATOR,
// Dot
DOT,
POINTER
;
public static final Set<Type> COMPARISON_TOKEN_TYPES = Set.of(
EQUALS,
NOT_EQUALS,
LESS_THAN,
MORE_THAN,
LESS_THAN_EQUAL,
MORE_THAN_EQUAL
);
public static final Set<Type> OVERRIDABLE_UNARY_OPERATORS = Set.of(
NOT,
MINUS
);
public static final Set<Type> OVERRIDABLE_BINARY_OPERATORS = Set.of(
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
POWER,
LESS_THAN,
LESS_THAN_EQUAL,
MORE_THAN,
MORE_THAN_EQUAL,
EQUALS,
NOT_EQUALS
);
}
}
| 16.194444 | 80 | 0.683962 |
e4f319af625d05cfd1d1d60c043a22aeedc2a39e | 4,757 | package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import org.codehaus.plexus.util.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class Pratice1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","C:\\Users\\NikhilAditi\\.m2\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//driver.get("https://www.amazon.com/Luciana-American-Girl-Year-2018/dp/1338186485");
// driver.findElement(By.xpath(ByxpathExpression))
/* driver.findElement(By.xpath("//*[@name='username']")).sendKeys("[email protected]");
driver.findElement(By.xpath("//*[@name='password']")).sendKeys("test1234");
driver.findElement(By.xpath("//*[type='submit']")).click();*/
/* Select select= new Select(driver.findElement(By.xpath("//*[@name='birthday_month']")));
//select.selectByIndex(3);
select.deselectByVisibleText("Oct");*/
/*WebElement moveToElement= driver.findElement(By.xpath("//*[@id='nav-link-accountList']/span[1]"));;
Actions act = new Actions(driver);
act.moveToElement(moveToElement).build().perform()*/
// driver.get("https://www.rocketmortgage.com/?logout=timeout");
/* WebElement element = driver.findElement(By.xpath("//*[@name='email']"));
Actions act= new Actions(driver);
act.moveToElement(element).doubleClick().build().perform();*/
/* TakesScreenshot ts= ((TakesScreenshot )driver);
File source =ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source,new File(".//ScreenShot"));
System.out.println("source");*/
//@parameters("browser")
/* public void setUp (String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver= new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver","C:\\Users\\NikhilAditi\\.m2\\chromedriver.exe");
driver= new ChromeDriver();
}
else if (browser.equalsIgnoreCase("edge")) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\NikhilAditi\\.m2\\chromedriver.exe");
driver= new EdgeDriver();
}
else {
System.out.println("browser is not correct");
}
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}*/
//Arraylist
// ArrayList<String> list=new ArrayList<String>();//Creating arraylist
/* List<String> obj = new ArrayList<String>();
obj.add("suman");
obj.add("poddar");
// System.out.println(obj);
for(int i=0;i<obj.size();i++) {
System.out.println(obj.get(i));
}
obj.remove(0);
System.out.println("obj:"+obj.size());*/
/*List<Integer> list1 = new ArrayList<Integer>();
list1.add(3);
list1.add(7);
System.out.println(list1.size());
for(int i=0;i<list1.size();i++) {
System.out.println(list1.get(i));
}*/
//fibnoc stories---
int fib1=0;
int fib2=1;
int fib3;
System.out.println(fib1);
System.out.println(fib2);
for(int i=0;i<8;i++) {
fib3=fib2+fib2;
System.out.println(fib3);
fib1=fib2;
fib2=fib3;
}
//even or add'
/*Scanner sc= new Scanner(System.in);
int i = sc.nextInt();
for (int x=0;x<i;x++) {
System.out.println(x);
}
if (i==0) {
System.out.println(i+" is even number");
}
else {
System.out.println(i +" is odd number");
}
}*/
int i=9;
for(int x=0;x<i;x++) {
System.out.println(x);
}
if (i%2==0) {
System.out.println(i+" is even number");
}
else {
System.out.println(i+" is odd number");
}
// factorial
Scanner sc = new Scanner (System.in);
System.out.println("Enter a number...");
int x = sc.nextInt();
i=5;
System.out.println("++i = " + ++i);
i=5;
System.out.println("i++ = " + i++);
/*
int fact = 1;
for (int a = 1; a < x; ++ a)
fact = fact * a;
}*/
}
}
| 31.503311 | 104 | 0.600799 |
d4998c91423521c24e3de5fa433469e6df26e53a | 2,054 | /*******************************************************************************
* Copyright (c) 2004, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Camelon (IBM) - Initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast.cpp;
import org.eclipse.cdt.core.dom.ast.ASTNodeProperty;
import org.eclipse.cdt.core.dom.ast.IASTAttributeOwner;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNameOwner;
/**
* This interface represents a using declaration.
*
* @noextend This interface is not intended to be extended by clients.
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface ICPPASTUsingDeclaration extends IASTDeclaration, IASTNameOwner, IASTAttributeOwner {
/**
* <code>NAME</code> is the qualified name brought into scope.
*/
public static final ASTNodeProperty NAME = new ASTNodeProperty("ICPPASTUsingDeclaration.NAME - Qualified Name brought into scope"); //$NON-NLS-1$
/**
* Was the typename keyword used?
*
* @param value
* boolean
*/
public void setIsTypename(boolean value);
/**
* Set that the typename keyword was/wasn't used.
*
* @return boolean
*/
public boolean isTypename();
/**
* Get the name.
*
* @return <code>IASTName</code>
*/
public IASTName getName();
/**
* Set the name.
*
* @param name
* <code>IASTName</code>
*/
public void setName(IASTName name);
/**
* @since 5.1
*/
@Override
public ICPPASTUsingDeclaration copy();
/**
* @since 5.3
*/
@Override
public ICPPASTUsingDeclaration copy(CopyStyle style);
}
| 27.756757 | 146 | 0.652386 |
b0760faa22b86795ee88d440459bc205a666e0ad | 10,361 | /*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* TypeHolderDefault
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class TypeHolderDefault {
public static final String SERIALIZED_NAME_STRING_ITEM = "string_item";
@SerializedName(SERIALIZED_NAME_STRING_ITEM)
private String stringItem = "what";
public static final String SERIALIZED_NAME_NUMBER_ITEM = "number_item";
@SerializedName(SERIALIZED_NAME_NUMBER_ITEM)
private BigDecimal numberItem;
public static final String SERIALIZED_NAME_INTEGER_ITEM = "integer_item";
@SerializedName(SERIALIZED_NAME_INTEGER_ITEM)
private Integer integerItem;
public static final String SERIALIZED_NAME_BOOL_ITEM = "bool_item";
@SerializedName(SERIALIZED_NAME_BOOL_ITEM)
private Boolean boolItem = true;
public static final String SERIALIZED_NAME_ARRAY_ITEM = "array_item";
@SerializedName(SERIALIZED_NAME_ARRAY_ITEM)
private List<Integer> arrayItem = new ArrayList<Integer>();
public TypeHolderDefault() {
}
public TypeHolderDefault stringItem(String stringItem) {
this.stringItem = stringItem;
return this;
}
/**
* Get stringItem
* @return stringItem
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public String getStringItem() {
return stringItem;
}
public void setStringItem(String stringItem) {
this.stringItem = stringItem;
}
public TypeHolderDefault numberItem(BigDecimal numberItem) {
this.numberItem = numberItem;
return this;
}
/**
* Get numberItem
* @return numberItem
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public BigDecimal getNumberItem() {
return numberItem;
}
public void setNumberItem(BigDecimal numberItem) {
this.numberItem = numberItem;
}
public TypeHolderDefault integerItem(Integer integerItem) {
this.integerItem = integerItem;
return this;
}
/**
* Get integerItem
* @return integerItem
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public Integer getIntegerItem() {
return integerItem;
}
public void setIntegerItem(Integer integerItem) {
this.integerItem = integerItem;
}
public TypeHolderDefault boolItem(Boolean boolItem) {
this.boolItem = boolItem;
return this;
}
/**
* Get boolItem
* @return boolItem
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public Boolean getBoolItem() {
return boolItem;
}
public void setBoolItem(Boolean boolItem) {
this.boolItem = boolItem;
}
public TypeHolderDefault arrayItem(List<Integer> arrayItem) {
this.arrayItem = arrayItem;
return this;
}
public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) {
this.arrayItem.add(arrayItemItem);
return this;
}
/**
* Get arrayItem
* @return arrayItem
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public List<Integer> getArrayItem() {
return arrayItem;
}
public void setArrayItem(List<Integer> arrayItem) {
this.arrayItem = arrayItem;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o;
return Objects.equals(this.stringItem, typeHolderDefault.stringItem) &&
Objects.equals(this.numberItem, typeHolderDefault.numberItem) &&
Objects.equals(this.integerItem, typeHolderDefault.integerItem) &&
Objects.equals(this.boolItem, typeHolderDefault.boolItem) &&
Objects.equals(this.arrayItem, typeHolderDefault.arrayItem);
}
@Override
public int hashCode() {
return Objects.hash(stringItem, numberItem, integerItem, boolItem, arrayItem);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TypeHolderDefault {\n");
sb.append(" stringItem: ").append(toIndentedString(stringItem)).append("\n");
sb.append(" numberItem: ").append(toIndentedString(numberItem)).append("\n");
sb.append(" integerItem: ").append(toIndentedString(integerItem)).append("\n");
sb.append(" boolItem: ").append(toIndentedString(boolItem)).append("\n");
sb.append(" arrayItem: ").append(toIndentedString(arrayItem)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("string_item");
openapiFields.add("number_item");
openapiFields.add("integer_item");
openapiFields.add("bool_item");
openapiFields.add("array_item");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("string_item");
openapiRequiredFields.add("number_item");
openapiRequiredFields.add("integer_item");
openapiRequiredFields.add("bool_item");
openapiRequiredFields.add("array_item");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to TypeHolderDefault
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (TypeHolderDefault.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in TypeHolderDefault is not found in the empty JSON string", TypeHolderDefault.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!TypeHolderDefault.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `TypeHolderDefault` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : TypeHolderDefault.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!TypeHolderDefault.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'TypeHolderDefault' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<TypeHolderDefault> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(TypeHolderDefault.class));
return (TypeAdapter<T>) new TypeAdapter<TypeHolderDefault>() {
@Override
public void write(JsonWriter out, TypeHolderDefault value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public TypeHolderDefault read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of TypeHolderDefault given an JSON string
*
* @param jsonString JSON string
* @return An instance of TypeHolderDefault
* @throws IOException if the JSON string is invalid with respect to TypeHolderDefault
*/
public static TypeHolderDefault fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, TypeHolderDefault.class);
}
/**
* Convert an instance of TypeHolderDefault to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
| 30.119186 | 199 | 0.708136 |
26685469400a51c829aa114210867cf8251117d6 | 6,270 | package com.datafibers.model;
import com.datafibers.util.HelpFunc;
import io.vertx.core.json.JsonObject;
import java.time.LocalTime;
import java.util.HashMap;
/** Meta Objects Response for REST API. */
public class DFModelPOPJ {
/** Id as pk, which is also used as model id. */
private String id;
/** Name of the ml model. */
private String name;
/** Type of the ml model, such as sparkml, scikit-learn, tensorflow, xgboost, dl4j. */
private String type;
/** Model category, such as classification, recommendation, etc. */
private String category;
/** Description about model. */
private String description;
/** The model path in hdfs. */
private String path;
/** The spark sql/hive udf name for the model. */
private String udf;
/** The creation date for the model. */
private String createDate;
/** The creation date for the model. */
private String updateDate;
/** Ordered input parameters for the model // TODO check if useful. */
private HashMap<String, String> modelInputPara;
/** Output parameters for the model // TODO check if useful. */
private String modelOutputPara;
/** Job id which trains and persist the model if avaliable. */
private String idTrained;
public DFModelPOPJ() {
this.id = "";
}
public DFModelPOPJ(String id, String name, String type, String category, String description,
String path, String udf, String createDate, String updateDate,
HashMap<String, String> modelInputPara, String modelOutputPara, String idTrained) {
this.id = id;
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.path = path;
this.udf = udf;
this.createDate = !createDate.isEmpty() ? createDate : LocalTime.now().toString();
this.updateDate = !updateDate.isEmpty() ? updateDate : LocalTime.now().toString();
this.modelInputPara = modelInputPara;
this.modelOutputPara = modelOutputPara;
this.idTrained = idTrained;
}
/** Used by. */
public DFModelPOPJ(JsonObject json) {
this.id = json.getString("_id");
this.name = json.getString("name");
this.type = json.getString("type");
this.category = json.getString("category");
this.description = json.getString("description");
this.path = json.getString("path");
this.udf = json.getString("udf");
this.createDate = json.getString("createDate");
this.updateDate = json.getString("updateDate");
this.modelInputPara = !json.containsKey("modelInputPara") || json.getValue("modelInputPara") == null ? null
: HelpFunc.mapToHashMapFromJson(json.getJsonObject("modelInputPara"));
this.modelOutputPara = json.getString("modelOutputPara");
this.idTrained = json.getString("idTrained");
}
public JsonObject toJson() {
JsonObject json = new JsonObject()
.put("name", name)
.put("type", type)
.put("category", category)
.put("description", description)
.put("path", path)
.put("udf", udf)
.put("createDate", createDate)
.put("updateDate", updateDate)
.put("jobConfig", modelInputPara == null ? null : HelpFunc.mapToJsonFromHashMapD2U(modelInputPara))
.put("modelOutputPara", modelOutputPara)
.put("idTrained", idTrained)
;
if (id != null && !id.isEmpty()) {
json.put("_id", id);
}
return json;
}
public JsonObject toPostJson() {
JsonObject json = new JsonObject()
.put("name", name)
.put("type", type)
.put("category", category)
.put("description", description)
.put("path", path)
.put("udf", udf)
.put("createDate", createDate)
.put("updateDate", updateDate)
.put("jobConfig", modelInputPara == null ? null : HelpFunc.mapToJsonFromHashMapD2U(modelInputPara))
.put("modelOutputPara", modelOutputPara)
.put("idTrained", idTrained)
;
if (id != null && !id.isEmpty()) {
json.put("id", id);
}
return json;
}
public String getId() {
return id;
}
public DFModelPOPJ setId(String id) {
this.id = id;
return this;
}
public String getType() {
return type;
}
public DFModelPOPJ setType(String type) {
this.type = type;
return this;
}
public String getCategory() {
return category;
}
public DFModelPOPJ setCategory(String category) {
this.category = category;
return this;
}
public String getPath() {
return path;
}
public DFModelPOPJ setPath(String path) {
this.path = path;
return this;
}
public String getUdf() {
return udf;
}
public DFModelPOPJ setUdf(String udf) {
this.udf = udf;
return this;
}
public String getCreateDate() {
return createDate;
}
public DFModelPOPJ setCreateDate(String createDate) {
this.createDate = createDate;
return this;
}
public String getUpdateDate() {
return updateDate;
}
public DFModelPOPJ setUpdateDate(String updateDate) {
this.updateDate = updateDate;
return this;
}
public HashMap<String, String> getModelInputPara() {
return modelInputPara;
}
public DFModelPOPJ setModelInputPara(HashMap<String, String> modelInputPara) {
this.modelInputPara = modelInputPara;
return this;
}
public String getModelOutputPara() {
return modelOutputPara;
}
public DFModelPOPJ setModelOutputPara(String modelOutputPara) {
this.modelOutputPara = modelOutputPara;
return this;
}
public String getIdTrained() {
return idTrained;
}
public DFModelPOPJ setIdTrained(String idTrained) {
this.idTrained = idTrained;
return this;
}
} | 30.735294 | 115 | 0.596172 |
64b0ebfe786fe0b8eaecf96c80fcf15d8450f762 | 1,351 | package space.pxls.data;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import space.pxls.App;
import space.pxls.user.User;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBFactionMembership {
public final int fid;
public final int uid;
public final boolean displayed;
private DBFaction _cachedFaction = null;
private User _cachedUser = null;
public DBFactionMembership(int fid, int uid, boolean displayed) {
this.fid = fid;
this.uid = uid;
this.displayed = displayed;
}
public DBFaction fetchFaction() {
if (_cachedFaction == null) {
_cachedFaction = App.getDatabase().getFactionByID(this.fid);
}
return _cachedFaction;
}
public User fetchUser() {
if (_cachedUser == null) {
_cachedUser = App.getUserManager().getByID(this.uid);
}
return _cachedUser;
}
public static class Mapper implements RowMapper<DBFactionMembership> {
@Override
public DBFactionMembership map(ResultSet rs, StatementContext ctx) throws SQLException {
return new DBFactionMembership(
rs.getInt("fid"),
rs.getInt("uid"),
rs.getBoolean("displayed")
);
}
}
}
| 26.490196 | 96 | 0.635825 |
ccd4af931dc309fe29e6ba375e12f560c623f896 | 693 | package br.com.zupacademy.saulo.mercadolivre.categoria.entidade;
import br.com.zupacademy.saulo.mercadolivre.categoria.RepositoryCategoriaJPA;
public class CategoriaRequest {
private String nome;
private String nomeCategoriaMae;
public CategoriaResponse cadastrar(final RepositoryCategoriaJPA repositoryCategoriaJPA){
Categoria categoria = new Categoria(nome).cadastrar(repositoryCategoriaJPA, nomeCategoriaMae);
return new CategoriaResponse(categoria);
}
public void setNome(final String nome) {
this.nome = nome;
}
public void setNomeCategoriaMae(String nomeCategoriaMae) {
this.nomeCategoriaMae = nomeCategoriaMae;
}
}
| 28.875 | 102 | 0.759019 |
6c67dfd64ac59a50723aaf7bb9bb931a5dfe34d1 | 3,116 | /*
* Copyright 2021 Siphalor
*
* 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 de.siphalor.bouncylife.mixin;
import de.siphalor.bouncylife.BouncyLife;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.item.ItemStack;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(LivingEntity.class)
public abstract class MixinLivingEntity extends Entity {
@Shadow public abstract Iterable<ItemStack> getArmorItems();
@Shadow @Final private DefaultedList<ItemStack> equippedArmor;
public MixinLivingEntity(EntityType<?> entityType_1, World world_1) {
super(entityType_1, world_1);
}
private float bouncylife$damageAmount = 0.0F;
@Inject(method = "handleFallDamage", at = @At("HEAD"), cancellable = true)
public void handleFallDamage(float float_1, float float_2, CallbackInfoReturnable<Boolean> callbackInfo) {
for(ItemStack stack : getArmorItems()) {
if(stack.getItem() == BouncyLife.shoes) {
callbackInfo.setReturnValue(super.handleFallDamage(float_1, float_2));
return;
}
}
}
@Inject(method = "applyDamage", at = @At("HEAD"))
public void onApplyDamageHead(DamageSource damageSource, float amount, CallbackInfo callbackInfo) {
bouncylife$damageAmount = amount;
}
@Inject(method = "applyDamage", at = @At(value = "TAIL", target = "Lnet/minecraft/entity/LivingEntity;getHealth()F"))
public void onApplyDamageTail(DamageSource damageSource, float amount, CallbackInfo callbackInfo) {
BouncyLife.applySlimeThorns(this, damageSource, bouncylife$damageAmount, amount);
}
@Inject(method = "damage", at = @At("HEAD"), cancellable = true)
public void damage(DamageSource damageSource, float amount, CallbackInfoReturnable<Boolean> callbackInfoReturnable) {
if(!world.isClient()) {
if(damageSource == DamageSource.FLY_INTO_WALL) {
if(BouncyLife.isSlimeArmor(equippedArmor.get(EquipmentSlot.HEAD.getEntitySlotId()))) {
callbackInfoReturnable.setReturnValue(false);
}
}
}
}
}
| 39.443038 | 118 | 0.758023 |
61701bc8be71c9faa7fc24370248f454362473d4 | 4,410 | package com.dianwoda.usercenter.vera.namer.routeinfo;
import com.dianwoda.usercenter.vera.common.SystemClock;
import com.dianwoda.usercenter.vera.common.protocol.ResponseCode;
import com.dianwoda.usercenter.vera.namer.dto.Action;
import com.dianwoda.usercenter.vera.namer.dto.InterResponse;
import com.dianwoda.usercenter.vera.namer.enums.ActionStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author seam
*/
public class ActionRecordManager {
protected static final Logger log = LoggerFactory.getLogger(ActionRecordManager.class);
private Map<Integer, Action> actionMap = new ConcurrentHashMap<>();
private ReadWriteLock actionLock = new ReentrantReadWriteLock();
public ActionRecordManager() {
}
public Action getAction(int id) {
return this.actionMap.get(id);
}
public boolean containAction(int id) {
return this.actionMap.containsKey(id);
}
public InterResponse addAction(Action action) {
InterResponse interResponse = new InterResponse();
try {
actionLock.writeLock().lockInterruptibly();
actionMap.put(action.getId(), action);
interResponse.setCode(ResponseCode.SUCCESS);
} catch (Exception e) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("add action error: " + e.getMessage());
log.error("add action error", e);
} finally {
actionLock.writeLock().unlock();
}
return interResponse;
}
public InterResponse actonAgree(int actionId) {
InterResponse interResponse = new InterResponse();
try {
actionLock.writeLock().lockInterruptibly();
Action action = this.actionMap.get(actionId);
if (action == null || action.getActionStateEnum().isFinalState()) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("记录信息不一致");
} else {
action.setActionStateEnum(ActionStateEnum.AGREE);
action.setUpdateTime(SystemClock.now());
interResponse.setCode(ResponseCode.SUCCESS);
}
} catch (Exception e) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("action agree error, " + e.getMessage());
log.error("action agree error", e);
} finally {
actionLock.writeLock().unlock();
}
return interResponse;
}
public InterResponse actonStart(int actionId) {
InterResponse interResponse = new InterResponse();
try {
actionLock.writeLock().lockInterruptibly();
Action action = this.actionMap.get(actionId);
if (action == null || !action.getActionStateEnum().isAgree()) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("记录信息不一致");
} else {
action.setActionStateEnum(ActionStateEnum.FINISH);
action.setUpdateTime(SystemClock.now());
interResponse.setCode(ResponseCode.SUCCESS);
}
} catch (Exception e) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("action start error, " + e.getMessage());
log.error("action start error", e);
} finally {
actionLock.writeLock().unlock();
}
return interResponse;
}
public InterResponse actionReject(int actionId) {
InterResponse interResponse = new InterResponse();
try {
actionLock.writeLock().lockInterruptibly();
Action action = this.actionMap.get(actionId);
if (action == null) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("记录信息不一致");
} else {
action.setActionStateEnum(ActionStateEnum.REJECT);
action.setUpdateTime(SystemClock.now());
interResponse.setCode(ResponseCode.SUCCESS);
}
} catch (Exception e) {
interResponse.setCode(ResponseCode.SYSTEM_ERROR);
interResponse.setRemark("action reject error, " + e.getMessage());
log.error("action reject error", e);
} finally {
actionLock.writeLock().unlock();
}
return interResponse;
}
public Map<Integer, Action> getActionMap() {
return actionMap;
}
public void setActionMap(Map<Integer, Action> actionMap) {
this.actionMap = actionMap;
}
}
| 33.157895 | 89 | 0.703628 |
5ec99f7e3098038770ed1bf4b5e59276b2dbe51a | 8,286 | /*
* Copyright (c) 2020 eSOL Co.,Ltd.
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
package org.multicore_association.shim.edit.gui.jface;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.ui.action.CopyAction;
import org.eclipse.emf.edit.ui.action.CutAction;
import org.eclipse.emf.edit.ui.action.DeleteAction;
import org.eclipse.emf.edit.ui.action.PasteAction;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.TreeItem;
import org.multicore_association.shim.edit.log.ShimLoggerUtil;
import org.multicore_association.shim.edit.model.ShimUtils;
import org.multicore_association.shim.edit.model.search.PropertyCompareUtil;
import org.multicore_association.shim.edit.model.search.SearchOptions;
import org.multicore_association.shim.edit.model.search.ShimSearchResult;
/**
* Implementation of Shim TreeViewer which can search.
*/
public class ShimTreeViewer extends TreeViewer {
private static final Logger log = ShimLoggerUtil
.getLogger(ShimTreeViewer.class);
/**
* Constructs a new instance of SearchableTreeViewer.
*
* @param parent
* the parent composite
*/
public ShimTreeViewer(Composite parent) {
super(parent);
getTree().addKeyListener(new KeyListener() {
/**
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
@Override
public void keyReleased(KeyEvent e) {
// NOOP
}
/**
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
@Override
public void keyPressed(KeyEvent e) {
if (!(getSelection() instanceof IStructuredSelection)) {
return;
}
IStructuredSelection selection = (IStructuredSelection) getSelection();
if (selection.isEmpty()) {
return;
}
EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(selection.getFirstElement());
if (editingDomain == null) {
return;
}
if ((e.keyCode == SWT.DEL && e.stateMask != SWT.CTRL)
|| (e.keyCode == 'd' && e.stateMask == SWT.CTRL)) {
// press DELET or CTRL+D key.
DeleteAction delete = new DeleteAction(editingDomain, true);
delete.selectionChanged(selection);
if (delete.isEnabled()) {
delete.run();
}
} else if (e.keyCode == 'x' && e.stateMask == SWT.CTRL) {
// press CTRL+C key.
CutAction cut = new CutAction(editingDomain);
cut.selectionChanged(selection);
if (cut.isEnabled()) {
cut.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.CTRL) {
// press CTRL+C key.
CopyAction copy = new CopyAction(editingDomain);
copy.selectionChanged(selection);
if (copy.isEnabled()) {
copy.run();
}
} else if (e.keyCode == 'v' && e.stateMask == SWT.CTRL) {
// press CTRL+V key.
PasteAction paste = new PasteAction(editingDomain);
paste.selectionChanged(selection);
if (paste.isEnabled()) {
paste.run();
}
}
}
});
}
/**
* Finds and select the specified element.
*
* @param element
* the element which find from TreeViewer.
* @return Returns true if the element is found, and false otherwise.
*/
public boolean findAndSelect(Object element) {
Object input = getInput();
if (input instanceof List) {
List<?> list = (List<?>) input;
if (list.isEmpty()) {
return false;
}
input = list.get(0);
}
return findAndSelect(input, element);
}
/**
* Finds and select the specified element.
*
* @param root
* the starting point element to search
* @param element
* the element which find from TreeViewer.
* @return Returns true if the element is found, and false otherwise.
*/
public boolean findAndSelect(Object root, Object element) {
ITreeContentProvider provider = (ITreeContentProvider) getContentProvider();
Set<Object> route = new HashSet<Object>();
if (findElement(route, root, element, provider)) {
route.remove(element);
// If route is empty, element is root element.So no need to expand.
if (!route.isEmpty()) {
setExpandedElements(route.toArray());
}
TreeItem selectedTreeItem = findTreeItem(element);
assert selectedTreeItem != null;
setSelection(new StructuredSelection(element), true);
getTree().showSelection();
// send selection event to SelectionListner
Event event = new Event();
event.item = selectedTreeItem;
getTree().notifyListeners(SWT.Selection, event);
return true;
}
log.info("Search is failed. : element=" + element);
return false;
}
/**
* Returns the TreeItem of the specified element.
*
* @param element
* the element to find
* @return the TreeItem
*/
public TreeItem findTreeItem(Object element) {
return (TreeItem) findItem(element);
}
/**
* @param route
* the set of parent object
* @param input
*
* @param element
* the element which find from TreeViewer.
* @param provider
* ITreeContentProvider of TreeViewer
* @return Returns true if the element is found, and false otherwise.
*/
private static boolean findElement(Set<Object> route, Object input,
Object element, ITreeContentProvider provider) {
if (element.equals(input)) {
route.add(input);
return true;
}
Object[] children = provider.getChildren(input);
if (children.length > 0) {
for (Object child : children) {
if (child.equals(input)) {
continue;
}
if (findElement(route, child, element, provider)) {
route.add(input);
return true;
}
}
}
return false;
}
/**
* Searches TreeViewer by the specified text.
*
* @param searchText
* the text to search
* @param isCaseSensitive
* if true, case sensitive search was performed
* @param isWholeWord
* if true, only whole words were searched
* @param isRegExp
* if true, regular expression search was performed
* @return the list of search result
*/
public List<ShimSearchResult> search(String searchText,
SearchOptions options) {
List<ShimSearchResult> searchResultList = new ArrayList<ShimSearchResult>();
ITreeContentProvider provider = (ITreeContentProvider) getContentProvider();
Object input = getInput();
if (input instanceof List) {
input = ((List<?>) input).get(0);
}
searchObject(searchResultList, provider, (EObject) input, searchText, options,
null);
return searchResultList;
}
/**
* Searches TreeViewer by the specified text.
*
* @param searchResultList
* @param provider
* @param input
* @param searchText
* @param options
* @param parentName
*/
private void searchObject(List<ShimSearchResult> searchResultList,
ITreeContentProvider provider, EObject input, String searchText,
SearchOptions options, String parentName) {
List<EStructuralFeature> matchFeatures = PropertyCompareUtil.getMatchFeatures(
searchText, input, options);
if (!matchFeatures.isEmpty()) {
for (EStructuralFeature matchFeature : matchFeatures) {
searchResultList.add(new ShimSearchResult(input, matchFeature,
parentName));
}
}
Object[] children = provider.getChildren(input);
if (children.length > 0) {
String nameProperty = ShimUtils.getName(input);
if (nameProperty == null) {
nameProperty = parentName;
}
for (Object child : children) {
if (child.equals(input)) {
continue;
}
searchObject(searchResultList, provider, (EObject) child, searchText,
options, nameProperty);
}
}
}
}
| 28.972028 | 111 | 0.6902 |
bf9396f6e07daf8c0499a61764a4b37224a1ba8f | 9,470 | package edu.stanford.nlp.process;
// Copyright 2010, Stanford University, GPLv2
import junit.framework.TestCase;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.SentenceUtils;
/** Test the effects of various operations using a DocumentPreprocessor.
*
* @author John Bauer
* @version 2010
*/
public class DocumentPreprocessorTest extends TestCase {
private static void runTest(String input, String[] expected) {
runTest(input, expected, null, false);
}
private static void runTest(String input, String[] expected, String[] sentenceFinalPuncWords, boolean whitespaceTokenize) {
List<String> results = new ArrayList<>();
DocumentPreprocessor document =
new DocumentPreprocessor(new BufferedReader(new StringReader(input)));
if (sentenceFinalPuncWords != null) {
document.setSentenceFinalPuncWords(sentenceFinalPuncWords);
}
if (whitespaceTokenize) {
document.setTokenizerFactory(null);
document.setSentenceDelimiter("\n");
}
for (List<HasWord> sentence : document) {
results.add(SentenceUtils.listToString(sentence));
}
assertEquals("Should be " + expected.length + " sentences but got " + results.size() + ": " + results,
expected.length, results.size());
for (int i = 0; i < results.size(); ++i) {
assertEquals("Failed on sentence " + i, expected[i], results.get(i));
}
}
/** Test to see if it is correctly splitting text readers. */
public void testText() {
String test = "This is a test of the preprocessor2. It should split this text into sentences. I like resting my feet on my desk. Hopefully the people around my office don't hear me singing along to my music, and if they do, hopefully they aren't annoyed. My test cases are probably terrifying looks into my psyche.";
String[] expectedResults = {"This is a test of the preprocessor2 .",
"It should split this text into sentences .",
"I like resting my feet on my desk .",
"Hopefully the people around my office do n't hear me singing along to my music , and if they do , hopefully they are n't annoyed .",
"My test cases are probably terrifying looks into my psyche ."};
runTest(test, expectedResults);
}
/** Test if fails with punctuation near end. We did at one point. */
public void testNearFinalPunctuation() {
String test = "Mount. Annaguan";
String[] expectedResults = {"Mount .",
"Annaguan", };
runTest(test, expectedResults);
}
/** Test if fails with punctuation near end. We did at one point. */
public void testNearFinalPunctuation2() {
String test = "(I lied.)";
String[] expectedResults = { "-LRB- I lied . -RRB-" };
runTest(test, expectedResults);
}
public void testSetSentencePunctWords() {
String test = "This is a test of the preprocessor2... it should split this text into sentences? This should be a different sentence.This should be attached to the previous sentence, though.";
String[] expectedResults = {"This is a test of the preprocessor2 ...",
"it should split this text into sentences ?","This should be a different sentence.This should be attached to the previous sentence , though ."};
String[] sentenceFinalPuncWords = {".", "?","!","...","\n"};
runTest(test, expectedResults, sentenceFinalPuncWords, false);
}
public void testWhitespaceTokenization() {
String test = "This is a whitespace tokenized test case . \n This should be the second sentence . \n \n \n\n This should be the third sentence . \n This should be one sentence . The period should not break it . \n This is the fifth sentence , with a weird period at the end.";
String[] expectedResults = {"This is a whitespace tokenized test case .",
"This should be the second sentence .",
"This should be the third sentence .",
"This should be one sentence . The period should not break it .",
"This is the fifth sentence , with a weird period at the end."};
runTest(test, expectedResults, null, true);
}
private static void compareXMLResults(String input,
String element,
String ... expectedResults) {
ArrayList<String> results = new ArrayList<>();
DocumentPreprocessor document = new DocumentPreprocessor(new BufferedReader(new StringReader(input)), DocumentPreprocessor.DocType.XML);
document.setElementDelimiter(element);
for (List<HasWord> sentence : document) {
results.add(SentenceUtils.listToString(sentence));
}
assertEquals(expectedResults.length, results.size());
for (int i = 0; i < results.size(); ++i) {
assertEquals(expectedResults[i], results.get(i));
}
}
private static final String BASIC_XML_TEST = "<xml><text>The previous test was a lie. I didn't make this test in my office; I made it at home.</text>\nMy home currently smells like dog vomit.\n<text apartment=\"stinky\">My dog puked everywhere after eating some carrots the other day.\n Hopefully I have cleaned the last of it, though.</text>\n\nThis tests to see what happens on an empty tag:<text></text><text>It shouldn't include a blank sentence, but it should include this sentence.</text>this is madness...<text>no, this <text> is </text> NESTED!</text>This only prints 'no, this is' instead of 'no, this is NESTED'. Doesn't do what i would expect, but it's consistent with the old behavior.</xml>";
/** Tests various ways of finding sentences with an XML
* DocumentPreprocessor2. We test to make sure it does find the
* text between {@code <text>} tags and that it doesn't find any text if we
* look for {@code <zzzz>} tags.
*/
public void testXMLBasic() {
// This subsequent block of code can be uncommented to demonstrate
// that the results from the new DP are the same as from the old DP.
//
// System.out.println("\nThis is the old behavior\n");
// DocumentPreprocessor p = new DocumentPreprocessor();
// List<List<? extends HasWord>> r = p.getSentencesFromXML(new BufferedReader(new StringReader(test)), "text", null, false);
// System.out.println(r.size());
// for (List<? extends HasWord> s : r) {
// System.out.println("\"" + Sentence.listToString(s) + "\"");
// }
//
// System.out.println("\nThis is the new behavior\n");
// DocumentPreprocessor2 d = new DocumentPreprocessor2(new BufferedReader(new StringReader(test)), DocumentPreprocessor2.DocType.XML);
// d.setElementDelimiter("text");
// for (List<HasWord> sentence : d) {
// System.out.println("\"" + Sentence.listToString(sentence) + "\"");
// }
String []expectedResults = {"The previous test was a lie .",
"I did n't make this test in my office ; I made it at home .",
"My dog puked everywhere after eating some carrots the other day .",
"Hopefully I have cleaned the last of it , though .",
"It should n't include a blank sentence , but it should include this sentence .",
"no , this is"};
compareXMLResults(BASIC_XML_TEST, "text", expectedResults);
}
public void testXMLNoResults() {
compareXMLResults(BASIC_XML_TEST, "zzzz");
}
/** Yeah... a bug that failed this test bug not the NotInText test
* was part of the preprocessor for a while.
*/
public void testXMLElementInText() {
String TAG_IN_TEXT = "<xml><wood>There are many trees in the woods</wood></xml>";
compareXMLResults(TAG_IN_TEXT, "wood",
"There are many trees in the woods");
}
public void testXMLElementNotInText() {
String TAG_IN_TEXT = "<xml><wood>There are many trees in the forest</wood></xml>";
compareXMLResults(TAG_IN_TEXT, "wood",
"There are many trees in the forest");
}
public void testPlainTextIterator() {
String test = "This is a one line test . \n";
String[] expectedResults = {"This", "is", "a", "one", "line", "test", "."};
DocumentPreprocessor document =
new DocumentPreprocessor(new BufferedReader(new StringReader(test)));
document.setTokenizerFactory(null);
document.setSentenceDelimiter("\n");
Iterator<List<HasWord>> iterator = document.iterator();
// we test twice because this call should not eat any text
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
List<HasWord> words = iterator.next();
assertEquals(expectedResults.length, words.size());
for (int i = 0; i < expectedResults.length; ++i) {
assertEquals(expectedResults[i], words.get(i).word());
}
// we test twice to make sure we don't blow up on multiple calls
assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
try {
iterator.next();
throw new AssertionError("iterator.next() should have blown up");
} catch (NoSuchElementException e) {
// yay, this is what we want
}
// just in case
assertFalse(iterator.hasNext());
}
}
| 46.421569 | 710 | 0.657445 |
0f0c067a98aeb1886603191df873fd69da40373e | 1,279 | // Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.alcatel.as.service.appmbeans.implstandalone;
import java.util.Dictionary;
import org.apache.felix.dm.DependencyManager;
import org.apache.log4j.Logger;
import org.osgi.framework.BundleContext;
import com.alcatel.as.service.appmbeans.ApplicationMBeanFactory;
import com.alcatel.as.util.osgi.DependencyActivatorHelper;
/**
* Creates a NullObject for ApplicationMBeanFactory service.
*/
public class Activator extends DependencyActivatorHelper {
private final static Logger _logger = Logger.getLogger("as.service.appmbeans.Activator");
public Activator() {
super(_logger);
}
@Override
public void init(BundleContext ctx, DependencyManager dm) throws Exception {
super.init(ctx, dm);
//
// Application MBeans service
//
addService(createService()
.setInterface(ApplicationMBeanFactory.class.getName(), null)
.setImplementation(ApplicationMBeanFactoryImpl.class)
.add(createServiceDependency()
.setService(Dictionary.class, "(service.pid=system)")
.setCallbacks("bind", null)
.setRequired(true)));
}
}
| 29.744186 | 91 | 0.704457 |
1e0fc9b8dd9a81a7e0c1cdfa75dfab0e6270e971 | 13,274 | /*
* 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.ignite.startup;
import java.io.File;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteState;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.IgnitionListener;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteVersionUtils;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.logger.GridTestLog4jLogger;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.varia.NullAppender;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import static org.apache.ignite.IgniteState.STOPPED;
/**
* This class defines random command-line Ignite loader. This loader can be used
* to randomly start and stop Ignite from command line for tests. This loader is a Java
* application with {@link #main(String[])} method that accepts command line arguments.
* See below for details.
*/
public final class GridRandomCommandLineLoader {
/** Name of the system property defining name of command line program. */
private static final String IGNITE_PROG_NAME = "IGNITE_PROG_NAME";
/** Copyright text. Ant processed. */
private static final String COPYRIGHT = IgniteVersionUtils.COPYRIGHT;
/** Version. Ant processed. */
private static final String VER = "x.x.x";
/** */
private static final String OPTION_HELP = "help";
/** */
private static final String OPTION_CFG = "cfg";
/** */
private static final String OPTION_MIN_TTL = "minTtl";
/** */
private static final String OPTION_MAX_TTL = "maxTtl";
/** */
private static final String OPTION_DURATION = "duration";
/** */
private static final String OPTION_LOG_CFG = "logCfg";
/** Minimal value for timeout in milliseconds. */
private static final long DFLT_MIN_TIMEOUT = 1000;
/** Maximum value for timeout in milliseconds. */
private static final long DFLT_MAX_TIMEOUT = 1000 * 20;
/** Work timeout in milliseconds. */
private static final long DFLT_RUN_TIMEOUT = 1000 * 60 * 5;
/** Latch. */
private static CountDownLatch latch;
/**
* Enforces singleton.
*/
private GridRandomCommandLineLoader() {
// No-op.
}
/**
* Echos the given messages.
*
* @param msg Message to echo.
*/
private static void echo(String msg) {
assert msg != null;
System.out.println(msg);
}
/**
* Echos exception stack trace.
*
* @param e Exception to print.
*/
private static void echo(IgniteCheckedException e) {
assert e != null;
System.err.println(e);
}
/**
* Exists with optional error message, usage show and exit code.
*
* @param errMsg Optional error message.
* @param options Command line options to show usage information.
* @param exitCode Exit code.
*/
private static void exit(@Nullable String errMsg, @Nullable Options options, int exitCode) {
if (errMsg != null)
echo("ERROR: " + errMsg);
String runner = System.getProperty(IGNITE_PROG_NAME, "randignite.{sh|bat}");
int space = runner.indexOf(' ');
runner = runner.substring(0, space == -1 ? runner.length() : space);
if (options != null) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(runner, options);
}
System.exit(exitCode);
}
/**
* Prints logo.
*/
private static void logo() {
echo("Ignite Random Command Line Loader, ver. " + VER);
echo(COPYRIGHT);
echo("");
}
/**
* Main entry point.
*
* @param args Command line arguments.
*/
@SuppressWarnings({"BusyWait"})
public static void main(String[] args) {
System.setProperty(IgniteSystemProperties.IGNITE_UPDATE_NOTIFIER, "false");
logo();
Options options = createOptions();
// Create the command line parser.
CommandLineParser parser = new PosixParser();
String cfgPath = null;
long minTtl = DFLT_MIN_TIMEOUT;
long maxTtl = DFLT_MAX_TIMEOUT;
long duration = DFLT_RUN_TIMEOUT;
String logCfgPath = null;
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption(OPTION_HELP))
exit(null, options, 0);
if (!cmd.hasOption(OPTION_LOG_CFG))
exit("-log should be set", options, -1);
else
logCfgPath = cmd.getOptionValue(OPTION_LOG_CFG);
if (cmd.hasOption(OPTION_CFG))
cfgPath = cmd.getOptionValue(OPTION_CFG);
try {
if (cmd.hasOption(OPTION_DURATION))
duration = Long.parseLong(cmd.getOptionValue(OPTION_DURATION));
}
catch (NumberFormatException ignored) {
exit("Invalid argument for option: " + OPTION_DURATION, options, -1);
}
try {
if (cmd.hasOption(OPTION_MIN_TTL))
minTtl = Long.parseLong(cmd.getOptionValue(OPTION_MIN_TTL));
}
catch (NumberFormatException ignored) {
exit("Invalid argument for option: " + OPTION_MIN_TTL, options, -1);
}
try {
if (cmd.hasOption(OPTION_MAX_TTL))
maxTtl = Long.parseLong(cmd.getOptionValue(OPTION_MAX_TTL));
}
catch (NumberFormatException ignored) {
exit("Invalid argument for option: " + OPTION_MAX_TTL, options, -1);
}
if (minTtl >= maxTtl)
exit("Invalid arguments for options: " + OPTION_MAX_TTL + ", " + OPTION_MIN_TTL, options, -1);
}
catch (ParseException e) {
exit(e.getMessage(), options, -1);
}
System.out.println("Configuration path: " + cfgPath);
System.out.println("Log4j configuration path: " + logCfgPath);
System.out.println("Duration: " + duration);
System.out.println("Minimum TTL: " + minTtl);
System.out.println("Maximum TTL: " + maxTtl);
G.addListener(new IgnitionListener() {
@Override public void onStateChange(String name, IgniteState state) {
if (state == STOPPED && latch != null)
latch.countDown();
}
});
Random rand = new Random();
long now = System.currentTimeMillis();
long end = duration + System.currentTimeMillis();
try {
while (now < end) {
G.start(getConfiguration(cfgPath, logCfgPath));
long delay = rand.nextInt((int)(maxTtl - minTtl)) + minTtl;
delay = (now + delay > end) ? (end - now) : delay;
now = System.currentTimeMillis();
echo("Time left (ms): " + (end - now));
echo("Going to sleep for (ms): " + delay);
Thread.sleep(delay);
G.stopAll(false);
now = System.currentTimeMillis();
}
}
catch (IgniteCheckedException e) {
echo(e);
exit("Failed to start grid: " + e.getMessage(), null, -1);
}
catch (InterruptedException e) {
echo("Loader was interrupted (exiting): " + e.getMessage());
}
latch = new CountDownLatch(G.allGrids().size());
try {
while (latch.getCount() > 0)
latch.await();
}
catch (InterruptedException e) {
echo("Loader was interrupted (exiting): " + e.getMessage());
}
System.exit(0);
}
/**
* Initializes configurations.
*
* @param springCfgPath Configuration file path.
* @param logCfgPath Log file name.
* @return List of configurations.
* @throws IgniteCheckedException If an error occurs.
*/
private static IgniteConfiguration getConfiguration(String springCfgPath, @Nullable String logCfgPath)
throws IgniteCheckedException {
assert springCfgPath != null;
File path = GridTestUtils.resolveIgnitePath(springCfgPath);
if (path == null)
throw new IgniteCheckedException("Spring XML configuration file path is invalid: " + new File(springCfgPath) +
". Note that this path should be either absolute path or a relative path to IGNITE_HOME.");
if (!path.isFile())
throw new IgniteCheckedException("Provided file path is not a file: " + path);
// Add no-op logger to remove no-appender warning.
Appender app = new NullAppender();
Logger.getRootLogger().addAppender(app);
ApplicationContext springCtx;
try {
springCtx = new FileSystemXmlApplicationContext(path.toURI().toURL().toString());
}
catch (BeansException | MalformedURLException e) {
throw new IgniteCheckedException("Failed to instantiate Spring XML application context: " + e.getMessage(), e);
}
Map cfgMap;
try {
// Note: Spring is not generics-friendly.
cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
}
catch (BeansException e) {
throw new IgniteCheckedException("Failed to instantiate bean [type=" + IgniteConfiguration.class + ", err=" +
e.getMessage() + ']', e);
}
if (cfgMap == null)
throw new IgniteCheckedException("Failed to find a single grid factory configuration in: " + path);
// Remove previously added no-op logger.
Logger.getRootLogger().removeAppender(app);
if (cfgMap.size() != 1)
throw new IgniteCheckedException("Spring configuration file should contain exactly 1 grid configuration: " + path);
IgniteConfiguration cfg = (IgniteConfiguration)F.first(cfgMap.values());
assert cfg != null;
if (logCfgPath != null)
cfg.setGridLogger(new GridTestLog4jLogger(U.resolveIgniteUrl(logCfgPath)));
return cfg;
}
/**
* Creates cli options.
*
* @return Command line options
*/
private static Options createOptions() {
Options options = new Options();
Option help = new Option(OPTION_HELP, "print this message");
Option cfg = new Option(null, OPTION_CFG, true, "path to Spring XML configuration file.");
cfg.setValueSeparator('=');
cfg.setType(String.class);
Option minTtl = new Option(null, OPTION_MIN_TTL, true, "node minimum time to live.");
minTtl.setValueSeparator('=');
minTtl.setType(Long.class);
Option maxTtl = new Option(null, OPTION_MAX_TTL, true, "node maximum time to live.");
maxTtl.setValueSeparator('=');
maxTtl.setType(Long.class);
Option duration = new Option(null, OPTION_DURATION, true, "run timeout.");
duration.setValueSeparator('=');
duration.setType(Long.class);
Option log = new Option(null, OPTION_LOG_CFG, true, "path to log4j configuration file.");
log.setValueSeparator('=');
log.setType(String.class);
options.addOption(help);
OptionGroup grp = new OptionGroup();
grp.setRequired(true);
grp.addOption(cfg);
grp.addOption(minTtl);
grp.addOption(maxTtl);
grp.addOption(duration);
grp.addOption(log);
options.addOptionGroup(grp);
return options;
}
}
| 32.218447 | 127 | 0.628221 |
202abc88fb938c6175bd88bc34621028fd9dcc54 | 1,068 | package datatypes;
import java.util.*;
import services.*;
public class Corescope {
public static Stack<String> scope_variables = new Stack<String>();
public static Stack<Integer> current_scope = new Stack<Integer>();
public static Stack<Integer> scope_stack= new Stack<Integer>();
public void Enterscope(String ch)
{
// int chh=ch;
scope_variables.push(ch);
// scope_stack.push(scope);
if(!(scope_stack.isEmpty()) && Precore.scope==(Integer)scope_stack.peek())
{
current_scope.pop();
current_scope.push(Precore.scope+1);
}
else
{
current_scope.push(1);
}
scope_stack.push(Precore.scope);
}
public void Removescope()
{
int num = (Integer)current_scope.peek();
// System.out.println("nummm");
// System.out.println((Integer)scope_variables.peek());
for(int i=0;i<num;i++)
{
scope_variables.pop(); scope_stack.pop();
}
current_scope.pop();
}
} | 24.272727 | 82 | 0.579588 |
4176568fa95527ac88dfec692fed4a22e631f500 | 3,309 | package com.hedgehogsmind.springcouchrest.workers.security;
import com.hedgehogsmind.springcouchrest.annotations.security.CrudSecurity;
import com.hedgehogsmind.springcouchrest.configuration.CouchRestConfiguration;
import com.hedgehogsmind.springcouchrest.workers.mapping.entity.MappedEntityResource;
import org.springframework.expression.Expression;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* <p>
* This class represents a handler, which is capable of checking crud security rules for a {@link MappedEntityResource}.
* In any case, the base security rule {@link CouchRestConfiguration#getBaseSecurityRule()} must be true.
* </p>
*
* <p>
* Then endpoint security rules will be checked. If a crud method has no security method defined via
* the annotation {@link CrudSecurity}, then {@link CouchRestConfiguration#getDefaultEndpointSecurityRule()}
* will be used instead.
* </p>
*/
public class ResourceCrudSecurityHandler extends ResourceSecurityHandler {
private final Optional<Expression> readRule;
private final Optional<Expression> saveUpdateRule;
private final Optional<Expression> deleteRule;
/**
* Extracts the core to later evaluate the base security rule and extracts optional overwriting
* rules (defined via an {@link CrudSecurity} annotation). Max. 1 such annotation is allowed.
*
* @param entityResource Entity resource which this security handler shall handle.
*/
public ResourceCrudSecurityHandler(final MappedEntityResource entityResource) {
super(entityResource);
final Optional<CrudSecurity> crudSecurityAnnotation =
entityResource
.getMappingSource()
.getOptionalCouchRestModifierAnnotation(CrudSecurity.class);
if ( crudSecurityAnnotation.isPresent() ) {
final CrudSecurity securityRules = crudSecurityAnnotation.get();
readRule = securityRules.read().isBlank() ?
Optional.empty() :
Optional.of(getCore().parseSpelExpression(securityRules.read()));
saveUpdateRule = securityRules.saveUpdate().isBlank() ?
Optional.empty() :
Optional.of(getCore().parseSpelExpression(securityRules.saveUpdate()));
deleteRule = securityRules.delete().isBlank() ?
Optional.empty() :
Optional.of(getCore().parseSpelExpression(securityRules.delete()));
} else {
readRule = Optional.empty();
saveUpdateRule = Optional.empty();
deleteRule = Optional.empty();
}
}
/**
* Calls {@link #assertBaseAndEndpointLevelRule(Optional)} with optional read rule.
*/
public void assertReadAccess() {
assertBaseAndEndpointLevelRule(readRule);
}
/**
* Calls {@link #assertBaseAndEndpointLevelRule(Optional)} with optional saveUpdate rule.
*/
public void assertSaveUpdateAccess() {
assertBaseAndEndpointLevelRule(saveUpdateRule);
}
/**
* Calls {@link #assertBaseAndEndpointLevelRule(Optional)} with optional delete rule.
*/
public void assertDeleteAccess() {
assertBaseAndEndpointLevelRule(deleteRule);
}
}
| 36.766667 | 120 | 0.689332 |
e64cacd44ff1f25bfe4f92db506a5cf43c36c62c | 4,618 | /*
* Copyright (C) 2013-2015 RoboVM AB
*
* 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.bugvm.apple.coremidi;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import com.bugvm.objc.*;
import com.bugvm.objc.annotation.*;
import com.bugvm.objc.block.*;
import com.bugvm.rt.*;
import com.bugvm.rt.annotation.*;
import com.bugvm.rt.bro.*;
import com.bugvm.rt.bro.annotation.*;
import com.bugvm.rt.bro.ptr.*;
import com.bugvm.apple.foundation.*;
import com.bugvm.apple.corefoundation.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*/@Library("CoreMIDI")/*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/MIDIEndpoint/*</name>*/
extends /*<extends>*/MIDIObject/*</extends>*/
/*<implements>*//*</implements>*/ {
/*<ptr>*/public static class MIDIEndpointPtr extends Ptr<MIDIEndpoint, MIDIEndpointPtr> {}/*</ptr>*/
private static java.util.concurrent.atomic.AtomicLong refconId = new java.util.concurrent.atomic.AtomicLong();
private static LongMap<MIDIReadProc> readProcs = new LongMap<>();
private static final java.lang.reflect.Method cbReadProc;
static {
try {
cbReadProc = MIDIEndpoint.class.getDeclaredMethod("cbReadProc", MIDIPacketList.class, long.class, long.class);
} catch (Throwable e) {
throw new Error(e);
}
}
/*<bind>*/static { Bro.bind(MIDIEndpoint.class); }/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*//*</constructors>*/
/*<properties>*//*</properties>*/
/*<members>*//*</members>*/
@Callback
private static void cbReadProc(MIDIPacketList pktlist, @Pointer long readProcRefCon, @Pointer long srcConnRefCon) {
MIDIReadProc callback = null;
synchronized (readProcs) {
callback = readProcs.get(readProcRefCon);
}
callback.read(pktlist);
}
public MIDIEntity getEntity() {
MIDIEntity.MIDIEntityPtr ptr = new MIDIEntity.MIDIEntityPtr();
getEntity(ptr);
return ptr.get();
}
public static MIDIEndpoint createDestination(MIDIClient client, String name, MIDIReadProc readProc) {
long refconId = MIDIEndpoint.refconId.getAndIncrement();
MIDIEndpointPtr ptr = new MIDIEndpointPtr();
MIDIError err = createDestination(client, name, new FunctionPtr(cbReadProc), refconId, ptr);
if (err == MIDIError.No) {
synchronized (readProcs) {
readProcs.put(refconId, readProc);
}
return ptr.get();
}
return null;
}
public static MIDIEndpoint createSource(MIDIClient client, String name) {
MIDIEndpointPtr ptr = new MIDIEndpointPtr();
createSource(client, name, ptr);
return ptr.get();
}
/*<methods>*/
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDIEndpointGetEntity", optional=true)
protected native MIDIError getEntity(MIDIEntity.MIDIEntityPtr outEntity);
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDIDestinationCreate", optional=true)
protected static native MIDIError createDestination(MIDIClient client, String name, FunctionPtr readProc, @Pointer long refCon, MIDIEndpoint.MIDIEndpointPtr outDest);
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDISourceCreate", optional=true)
protected static native MIDIError createSource(MIDIClient client, String name, MIDIEndpoint.MIDIEndpointPtr outSrc);
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDIEndpointDispose", optional=true)
public native MIDIError dispose();
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDIReceived", optional=true)
public native MIDIError received(MIDIPacketList pktlist);
/**
* @since Available in iOS 4.2 and later.
*/
@Bridge(symbol="MIDIEndpointSetRefCons", optional=true)
protected native MIDIError setRefCons(@Pointer long ref1, @Pointer long ref2);
/*</methods>*/
}
| 38.165289 | 170 | 0.66977 |
e3347a557a61b93758b0b5a1f1308303d3c0a55d | 1,319 | package xyz.lamergameryt.allen4j.namesearch;
import org.json.JSONArray;
import org.json.JSONObject;
import xyz.lamergameryt.allen4j.templates.Student;
import java.util.ArrayList;
import java.util.List;
/**
* The response received after searching for a student by his name.
*/
public class NameSearchResponse {
/**
* The number of students found with their name similar to the name provided.
*/
private final int totalResults;
/**
* The list of students received from allen's server.
*/
private final List<Student> students = new ArrayList<>();
/**
* Parse the json response received from the server.
*
* @param json The response received from the server in the form of a JSONObject.
*/
public NameSearchResponse(JSONObject json) {
this.totalResults = json.has("total") ? json.getInt("total") : -1;
JSONArray results = json.has("results") ? json.getJSONArray("results") : null;
if (results != null) {
for (int i = 0; i < results.length(); i++) {
students.add(Student.getFromJSONObject(results.getJSONObject(i)));
}
}
}
public int getTotalResults() {
return totalResults;
}
public List<Student> getStudents() {
return students;
}
}
| 27.479167 | 86 | 0.638362 |
ac3583285417c9c6223b7d2d2edeb53e3ebc59ba | 17,359 | package com.reedelk.runtime.rest.api;
import com.reedelk.runtime.rest.api.health.v1.HealthGETRes;
import com.reedelk.runtime.rest.api.hotswap.v1.HotSwapPOSTReq;
import com.reedelk.runtime.rest.api.hotswap.v1.HotSwapPOSTRes;
import com.reedelk.runtime.rest.api.hotswap.v1.HotSwapPOSTResNotFound;
import com.reedelk.runtime.rest.api.module.v1.*;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import static com.reedelk.runtime.rest.api.InternalAPI.Health;
import static com.reedelk.runtime.rest.api.InternalAPI.HotSwap;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
class InternalAPITest {
@Nested
@DisplayName("Health API")
class HealthAPI {
@Test
void shouldHealthGETResSerializeCorrectly() {
// Given
HealthGETRes dto = new HealthGETRes();
dto.setStatus("UP");
dto.setVersion("2.1.3-SNAPSHOT");
// When
String actual = Health.V1.GET.Res.serialize(dto);
// Then
String expected = JSONS.HealthGETRes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldHealthGETResDeserializeCorrectly() {
// Given
String json = JSONS.HealthGETRes.string();
// When
HealthGETRes actual = Health.V1.GET.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getStatus()).isEqualTo("UP");
assertThat(actual.getVersion()).isEqualTo("2.1.3-SNAPSHOT");
}
}
@Nested
@DisplayName("Module API")
class ModuleAPI {
@Test
void shouldModulesGETResSerializeCorrectly() {
// Given
FlowGETRes flow1 = new FlowGETRes();
flow1.setId("aabbccdd");
flow1.setTitle("Flow1 title");
FlowGETRes flow2 = new FlowGETRes();
flow2.setId("eeffgghh");
flow2.setTitle("Flow2 title");
ErrorGETRes error1 = new ErrorGETRes();
error1.setStacktrace("error1 stacktrace");
error1.setMessage("error1");
ErrorGETRes error2 = new ErrorGETRes();
error2.setStacktrace("error2 stacktrace");
error2.setMessage("error2");
ErrorGETRes error3 = new ErrorGETRes();
error3.setStacktrace("error3 stacktrace");
error3.setMessage("error3");
ErrorGETRes error4 = new ErrorGETRes();
error4.setStacktrace("error4 stacktrace");
error4.setMessage("error4");
ModuleGETRes module1 = new ModuleGETRes();
module1.setName("HttpComponents");
module1.setState("INSTALLED");
module1.setModuleId(234L);
module1.setVersion("0.9.0");
module1.setModuleFilePath("file:/Users/test/testingflows/target/HttpComponents-0.9.0.jar");
module1.setFlows(asList(flow1, flow2));
module1.setErrors(asList(error1, error2));
module1.setResolvedComponents(asList("com.reedelk.runtime.component.1", "com.reedelk.runtime.component.2"));
module1.setUnresolvedComponents(asList("com.reedelk.runtime.component.3", "com.reedelk.runtime.component.4"));
ModuleGETRes module2 = new ModuleGETRes();
module2.setName("MyFlows");
module2.setState("STARTED");
module2.setModuleId(12L);
module2.setVersion("0.9.0");
module2.setModuleFilePath("file:/Users/test/testingflows/target/myflows-0.9.0.jar");
module2.setErrors(asList(error3, error4));
module2.setResolvedComponents(asList("com.reedelk.runtime.component.X1", "com.reedelk.runtime.component.X2"));
module2.setUnresolvedComponents(asList("com.reedelk.runtime.component.X4", "com.reedelk.runtime.component.X5"));
Set<ModuleGETRes> modules = new HashSet<>();
modules.add(module1);
modules.add(module2);
ModulesGETRes dto = new ModulesGETRes();
dto.setModules(modules);
// When
String actual = InternalAPI.Module.V1.GET.Res.serialize(dto);
// Then
String expected = JSONS.ModulesGETRes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT);
}
@Test
void shouldModulesGETResDeserializeCorrectly() {
// Given
ErrorGETRes error1 = new ErrorGETRes();
error1.setStacktrace("error1 stacktrace");
error1.setMessage("error1");
ErrorGETRes error2 = new ErrorGETRes();
error2.setStacktrace("error2 stacktrace");
error2.setMessage("error2");
ErrorGETRes error3 = new ErrorGETRes();
error3.setStacktrace("error3 stacktrace");
error3.setMessage("error3");
ErrorGETRes error4 = new ErrorGETRes();
error4.setStacktrace("error4 stacktrace");
error4.setMessage("error4");
String json = JSONS.ModulesGETRes.string();
// When
ModulesGETRes actual = InternalAPI.Module.V1.GET.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
Collection<ModuleGETRes> modules = actual.getModules();
assertThat(modules).hasSize(2);
ModuleGETRes module1 = new ModuleGETRes();
module1.setName("HttpComponents");
module1.setState("INSTALLED");
module1.setVersion("0.9.0");
module1.setModuleId(234L);
module1.setModuleFilePath("file:/Users/test/testingflows/target/HttpComponents-0.9.0.jar");
module1.setErrors(asList(error1, error2));
module1.setResolvedComponents(asList("com.reedelk.runtime.component.1", "com.reedelk.runtime.component.2"));
module1.setUnresolvedComponents(asList("com.reedelk.runtime.component.3", "com.reedelk.runtime.component.4"));
assertExistsModule(modules, module1);
ModuleGETRes module2 = new ModuleGETRes();
module2.setName("MyFlows");
module2.setState("STARTED");
module2.setVersion("0.9.0");
module2.setModuleId(12L);
module2.setModuleFilePath("file:/Users/test/testingflows/target/myflows-0.9.0.jar");
module2.setErrors(asList(error3, error4));
module2.setResolvedComponents(asList("com.reedelk.runtime.component.X1", "com.reedelk.runtime.component.X2"));
module2.setUnresolvedComponents(asList("com.reedelk.runtime.component.X4", "com.reedelk.runtime.component.X5"));
assertExistsModule(modules, module2);
}
@Test
void shouldModulePUTReqSerializeCorrectly() {
// Given
ModulePUTReq dto = new ModulePUTReq();
dto.setModuleFilePath("file://my/file/path");
// When
String actual = InternalAPI.Module.V1.PUT.Req.serialize(dto);
// Then
String expected = JSONS.ModulePUTReq.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModulePUTReqDeserializeCorrectly() {
// Given
String json = JSONS.ModulePUTReq.string();
// When
ModulePUTReq actual = InternalAPI.Module.V1.PUT.Req.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleFilePath()).isEqualTo("file://my/file/path");
}
@Test
void shouldModulePUTResSerializeCorrectly() {
// Given
ModulePUTRes dto = new ModulePUTRes();
dto.setModuleId(665L);
// When
String actual = InternalAPI.Module.V1.PUT.Res.serialize(dto);
// Then
String expected = JSONS.ModulePUTRes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModulePUTResDeserializeCorrectly() {
// Given
String json = JSONS.ModulePUTRes.string();
ModulePUTRes actual = InternalAPI.Module.V1.PUT.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleId()).isEqualTo(665L);
}
@Test
void shouldModulePOSTReqSerializeCorrectly() {
// Given
ModulePOSTReq dto = new ModulePOSTReq();
dto.setModuleFilePath("file://my/file/path");
// When
String actual = InternalAPI.Module.V1.POST.Req.serialize(dto);
// Then
String expected = JSONS.ModulePOSTReq.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModulePOSTReqDeserializeCorrectly() {
// Given
String json = JSONS.ModulePOSTReq.string();
// When
ModulePOSTReq actual = InternalAPI.Module.V1.POST.Req.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleFilePath()).isEqualTo("file://my/file/path");
}
@Test
void shouldModulePOSTResSerializeCorrectly() {
// Given
ModulePOSTRes dto = new ModulePOSTRes();
dto.setModuleId(485L);
// When
String actual = InternalAPI.Module.V1.POST.Res.serialize(dto);
// Then
String expected = JSONS.ModulePOSTRes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModulePOSTResDeserializeCorrectly() {
// Given
String json = JSONS.ModulePOSTRes.string();
ModulePOSTRes actual = InternalAPI.Module.V1.POST.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleId()).isEqualTo(485L);
}
@Test
void shouldModuleDELETEReqSerializeCorrectly() {
// Given
ModuleDELETEReq dto = new ModuleDELETEReq();
dto.setModuleFilePath("file://my/file/path");
// When
String actual = InternalAPI.Module.V1.DELETE.Req.serialize(dto);
// Then
String expected = JSONS.ModuleDELETEReq.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModuleDELETEReqDeserializeCorrectly() {
// Given
String json = JSONS.ModuleDELETEReq.string();
// When
ModuleDELETEReq actual = InternalAPI.Module.V1.DELETE.Req.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleFilePath()).isEqualTo("file://my/file/path");
}
@Test
void shouldModuleDELETEResSerializeCorrectly() {
// Given
ModuleDELETERes dto = new ModuleDELETERes();
dto.setModuleId(23L);
// When
String actual = InternalAPI.Module.V1.DELETE.Res.serialize(dto);
// Then
String expected = JSONS.ModuleDELETERes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldModuleDELETEResDeserializeCorrectly() {
// Given
String json = JSONS.ModuleDELETERes.string();
ModuleDELETERes actual = InternalAPI.Module.V1.DELETE.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleId()).isEqualTo(23L);
}
}
@Nested
@DisplayName("HotSwap API")
class HotSwapAPI {
@Test
void shouldHotSwapPOSTReqSerializeCorrectly() {
// Given
HotSwapPOSTReq dto = new HotSwapPOSTReq();
dto.setModuleFilePath("/my/file/path/my-module.jar");
dto.setResourcesRootDirectory("/users/john/projects/src/main/resources");
// When
String actual = HotSwap.V1.POST.Req.serialize(dto);
// Then
String expected = JSONS.HotSwapPOSTReq.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldHotSwapPOSTReqDeserializeCorrectly() {
// Given
String json = JSONS.HotSwapPOSTReq.string();
// When
HotSwapPOSTReq actual = HotSwap.V1.POST.Req.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleFilePath()).isEqualTo("/my/file/path/my-module.jar");
assertThat(actual.getResourcesRootDirectory()).isEqualTo("/users/john/projects/src/main/resources");
}
@Test
void shouldHotSwapPOSTResSerializeCorrectly() {
// Given
HotSwapPOSTRes dto = new HotSwapPOSTRes();
dto.setModuleId(10L);
// When
String actual = HotSwap.V1.POST.Res.serialize(dto);
// Then
String expected = JSONS.HotSwapPOSTRes.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldHotSwapPOSTResDeserializeCorrectly() {
// Given
String json = JSONS.HotSwapPOSTRes.string();
// When
HotSwapPOSTRes actual = HotSwap.V1.POST.Res.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleId()).isEqualTo(10L);
}
@Test
void shouldHotSwapPOSTResNotFoundSerializeCorrectly() {
// Given
HotSwapPOSTResNotFound dto = new HotSwapPOSTResNotFound();
dto.setModuleFilePath("/my/not/found/file/path/my-module.jar");
dto.setResourcesRootDirectory("/users/john/projects/src/main/resources/not/found");
// When
String actual = HotSwap.V1.POST.ResNotFound.serialize(dto);
// Then
String expected = JSONS.HotSwapPOSTResNotFound.string();
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
@Test
void shouldHotSwapPOSTResNotFoundDeserializeCorrectly() {
// Given
String json = JSONS.HotSwapPOSTResNotFound.string();
// When
HotSwapPOSTResNotFound actual = HotSwap.V1.POST.ResNotFound.deserialize(json);
// Then
assertThat(actual).isNotNull();
assertThat(actual.getModuleFilePath()).isEqualTo("/my/not/found/file/path/my-module.jar");
assertThat(actual.getResourcesRootDirectory()).isEqualTo("/users/john/projects/src/main/resources/not/found");
}
}
private void assertExistsModule(Collection<ModuleGETRes> modules, ModuleGETRes expected) {
for (ModuleGETRes module : modules) {
String name = module.getName();
if (expected.getName().equals(name)) {
Collection<ErrorGETRes> actualErrors = module.getErrors();
Collection<ErrorGETRes> expectedErrors = expected.getErrors();
assertSameErrors(actualErrors, expectedErrors);
assertThatContainsInAnyOrder(module.getUnresolvedComponents(), expected.getUnresolvedComponents());
assertThatContainsInAnyOrder(module.getResolvedComponents(), expected.getResolvedComponents());
assertThat(module.getState()).isEqualTo(expected.getState());
return;
}
}
Assertions.fail("Could not find matching module");
}
private void assertSameErrors(Collection<ErrorGETRes> actualErrors, Collection<ErrorGETRes> expectedErrors) {
for (ErrorGETRes actualError : actualErrors) {
boolean found = expectedErrors
.stream()
.anyMatch(errorGETRes -> isSameError(actualError, errorGETRes));
if (!found) fail("Could not find matching error");
}
}
private boolean isSameError(ErrorGETRes error1, ErrorGETRes error2) {
String message1 = error1.getMessage();
String message2 = error2.getMessage();
String stacktrace1 = error1.getStacktrace();
String stacktrace2 = error2.getStacktrace();
return Objects.equals(message1, message2) && Objects.equals(stacktrace1, stacktrace2);
}
private void assertThatContainsInAnyOrder(Collection<String> actual, Collection<String> expected) {
String[] array = expected.toArray(new String[]{});
assertThat(actual).containsExactlyInAnyOrder(array);
}
}
| 36.392034 | 124 | 0.61242 |
fb0c26ac2640818065030795a89389c4afcb4e2e | 3,454 | package ca.ualberta.cmput301f17t08.habitrabbit;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* The activity for signup when user don't have an account
*/
public class SignupActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
final EditText usernameField = (EditText) findViewById(R.id.username_input_field);
Button signupButton = (Button) findViewById(R.id.signup_button);
final Activity activity = this;
signupButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
// TODO handle signup here
String username = usernameField.getText().toString();
System.out.println("Sign Up Button Clicked - Username:" + username);
// TODO test username is not empty
DatabaseManager.getInstance().createUser(username, new DatabaseManager.OnUserDataListener() {
@Override
public void onUserData(User user) {
// TODO use loginmanager to set as logged in, initialize app
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Your account was successfully created! Please log in.")
.setTitle("Signup success")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
activity.finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onUserDataFailed(String message) {
Log.e("SignupActivity", "User creation failed: " + message);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message)
.setTitle("Signup error")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
});
}
}
| 41.614458 | 109 | 0.498552 |
f46cc683003f4b8b50b17b309686fbd49b36d949 | 688 | package no.gorandalum.fluentresult;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
class BooleanResult_MapToOptional_Test {
@Test
void mapToOptional_success_successfullyMapValue() {
OptionalResult<Integer, String> result =
BooleanResult.<String>success(true)
.mapToOptional(val -> Optional.of(val ? 5 : 3));
result.consumeEither(
val -> assertThat(val).isEqualTo(5),
() -> fail("Should not be empty"),
err -> fail("Should not be error"));
}
} | 31.272727 | 72 | 0.642442 |
994573d179662453fea14053534332f68d1e7f8c | 4,247 | // 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.cloudstack.api.command.admin.acl;
import com.cloud.user.Account;
import org.apache.cloudstack.acl.Role;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.ApiArgValidator;
import org.apache.cloudstack.api.response.RoleResponse;
import org.apache.cloudstack.context.CallContext;
@APICommand(name = CreateRoleCmd.APINAME, description = "Creates a role", responseObject = RoleResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false,
since = "4.9.0",
authorized = {RoleType.Admin})
public class CreateRoleCmd extends BaseCmd {
public static final String APINAME = "createRole";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true,
description = "creates a role with this unique name", validations = {ApiArgValidator.NotNullOrEmpty})
private String roleName;
@Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, required = true,
description = "The type of the role, valid options are: Admin, ResourceAdmin, DomainAdmin, User",
validations = {ApiArgValidator.NotNullOrEmpty})
private String roleType;
@Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "The description of the role")
private String roleDescription;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getRoleName() {
return roleName;
}
public RoleType getRoleType() {
return RoleType.fromString(roleType);
}
public String getRoleDescription() {
return roleDescription;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
private void setupResponse(final Role role) {
final RoleResponse response = new RoleResponse();
response.setId(role.getUuid());
response.setRoleName(role.getName());
response.setRoleType(role.getRoleType());
response.setResponseName(getCommandName());
response.setObjectName("role");
setResponseObject(response);
}
@Override
public void execute() {
CallContext.current().setEventDetails("Role: " + getRoleName() + ", type:" + getRoleType() + ", description: " + getRoleDescription());
final Role role = roleService.createRole(getRoleName(), getRoleType(), getRoleDescription());
if (role == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create role");
}
setupResponse(role);
}
}
| 40.066038 | 143 | 0.639746 |
9e49b94c4e9b0fffa912f7a12810473e5f83f51f | 1,706 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2012, 2013, 2014 Zimbra, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.jaxb;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
/** Test JAXB class with a String XmlAttribute and int XmlValue */
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="string-attr-int-value")
public class StringAttribIntValue {
@XmlAttribute(name="attr1", required=true)
private String attrib1;
@XmlValue()
private int myValue;
public StringAttribIntValue() {}
public StringAttribIntValue(String a, int v) {
setAttrib1(a);
setMyValue(v);
}
public String getAttrib1() { return attrib1; }
public void setAttrib1(String attrib1) { this.attrib1 = attrib1; }
public int getMyValue() { return myValue; }
public void setMyValue(int myValue) { this.myValue = myValue; }
}
| 37.911111 | 93 | 0.731536 |
9c6fc4ce0848d3dc8297ce1ed5dbc499ed652222 | 17,431 | package communications;
import entities.BrokerState;
import entities.HorseJockeyState;
import entities.SpectatorState;
import hippodrome.actions.Race;
import java.io.Serializable;
/**
* Definition of the processing of information relative to the Message's exchanges between clients
* (also known as {@code entities}) and the servers (also known as {@code hippodrome regions}).
*
* @author Hugo Fragata
* @author Rui Lopes
* @since 2.0
* @version 2.0
*/
public class Message implements Serializable {
/**
* Constructs a message which is only defined by its type (as an object of type {@link MessageType}).
*
* @param type the type of this message.
*/
public Message(MessageType type) {
this.type = type;
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType})
* and a boolean value.
*
* @param type the type of this message.
* @param value the {@code boolean} value which must be saved with the message.
*/
public Message(MessageType type, boolean value) {
this.type = type;
switch (type) {
case GENERAL_INFORMATION_REPOSITORY_SET_WERE_WAITING_THE_HORSES:
this.value = value;
break;
case PADDOCK_GO_CHECK_HORSES_WITH_LAST_SPECTATOR:
this.value = value;
break;
case REPLY_BETTING_CENTRE_ARE_THERE_ANY_WINNERS:
this.value = value;
break;
case REPLY_BETTING_CENTRE_HAVE_I_WON:
this.value = value;
break;
case REPLY_CONTROL_CENTRE_WAIT_FOR_NEXT_RACE:
this.value = value;
break;
case REPLY_PADDOCK_GO_CHECK_HORSES_WITH_LAST_SPECTATOR:
this.value = value;
break;
case REPLY_RACING_TRACK_HAS_FINISH_LINE_BEEN_CROSSED:
this.value = value;
break;
default:
throw new IllegalArgumentException();
}
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType})
* and one integer value.
*
* @param type the type of this message.
* @param value the {@code integer} value which must be saved with the message.
*/
public Message(MessageType type, int value) {
this.type = type;
switch (type) {
case BETTING_CENTRE_HAVE_I_WON:
spectatorID = value;
break;
case BETTING_CENTRE_ARE_THERE_ANY_WINNERS:
winner = value;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_RACE_NUMBER:
raceNumber = value;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_RACE_DISTANCE:
raceDistance = value;
break;
case GENERAL_INFORMATION_REPOSITORY_GET_HORSE_JOCKEY_NUMBER_OF_INCREMENTS_DID:
horseID = value;
break;
case PADDOCK_PROCEED_TO_PADDOCK:
raceNumber = value;
break;
case RACING_TRACK_MAKE_A_MOVE:
horseID = value;
break;
case RACING_TRACK_HAS_FINISH_LINE_BEEN_CROSSED:
horseID = value;
break;
case STABLE_PROCEED_TO_STABLE:
raceNumber = value;
break;
case STABLE_PROCEED_TO_STABLE_WITH_RACE_ID:
raceNumber = value;
break;
case STABLE_SUMMON_HORSES_TO_PADDOCK:
raceNumber = value;
break;
case REPLY_BETTING_CENTRE_GET_NUMBER_OF_HORSES:
horses = value;
break;
case REPLY_BETTING_CENTRE_GO_COLLECT_THE_GAINS:
gains = value;
break;
case REPLY_BETTING_CENTRE_PLACE_A_BET:
bet = value;
break;
case REPLY_CONTROL_CENTRE_REPORT_RESULTS:
results = value;
break;
case REPLY_GENERAL_INFORMATION_REPOSITORY_GET_CURRENT_RACE_DISTANCE:
raceDistance = value;
break;
case REPLY_GENERAL_INFORMATION_REPOSITORY_GET_HORSE_JOCKEY_NUMBER_OF_INCREMENTS_DID:
increments = value;
break;
case REPLY_GENERAL_INFORMATION_REPOSITORY_GET_RACE_NUMBER:
raceNumber = value;
break;
case REPLY_RACING_TRACK_GET_WINNER:
winner = value;
break;
default:
throw new IllegalArgumentException();
}
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType})
* and two integer values.
*
* @param type the type of this message.
* @param value1 the first {@code integer} value which must be saved with the message.
* @param value2 the second {@code integer} value which must be saved with the message.
*/
public Message(MessageType type, int value1, int value2) {
this.type = type;
switch (type) {
case BETTING_CENTRE_SET_ABILITY:
horseID = value1;
ability = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_SPECTATOR_AMOUNT_OF_MONEY:
spectatorID = value1;
spectatorAmountOfMoney = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_SPECTATOR_BET_SELECTION:
spectatorID = value1;
spectatorBetSelection = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_SPECTATOR_BET_AMOUNT:
spectatorID = value1;
bet = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_HORSE_JOCKEY_ABILITY:
horseID = value1;
ability = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_HORSE_JOCKEY_PROBABILITY_TO_WIN:
horseID = value1;
horseProbability = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_HORSE_JOCKEY_NUMBER_OF_INCREMENTS_DID:
horseID = value1;
horseIteration = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_HORSE_JOCKEY_POSITION_ON_TRACK:
horseID = value1;
horsePosition = value2;
break;
case GENERAL_INFORMATION_REPOSITORY_SET_HORSE_JOCKEY_FINAL_STAND_POSITION:
horseID = value1;
horsePosition = value2;
break;
default:
throw new IllegalArgumentException();
}
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType})
* and two integer values.
*
* @param type the type of this message.
* @param value1 the first {@code integer} value which must be saved with the message.
* @param value2 the second {@code integer} value which must be saved with the message.
* @param value3 the third {@code integer} value which must be saved with the message.
*/
public Message(MessageType type, int value1, int value2, int value3) {
this.type = type;
switch (type) {
case BETTING_CENTRE_PLACE_A_BET:
spectatorID = value1;
bet = value2;
horseID = value3;
break;
default:
throw new IllegalArgumentException();
}
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType})
* and one Broker state value defined as {@link BrokerState}.
*
* @param type the type of this message.
* @param state the {@code BrokerState} state of the Broker to be updated.
*/
public Message(MessageType type, BrokerState state) {
this.type = type;
brokerState = state;
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType}),
* one pair Horse/Jockey identification and one pair Horse/Jockey state value defined as {@link HorseJockeyState}.
*
* @param type the type of this message.
* @param horseID the identification of the pair Horse/Jockey.
* @param state the {@code HorseJockeyState} state of the pair Horse/Jockey to be updated.
*/
public Message(MessageType type, int horseID, HorseJockeyState state) {
this.type = type;
this.horseID = horseID;
this.horseJockeyState = state;
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType}),
* one Spectator identification and one Spectator state value defined as {@link SpectatorState}.
*
* @param type the type of this message.
* @param spectatorID the identification of the Spectator.
* @param state the {@code SpectatorState} state of the Spectator to be updated.
*/
public Message(MessageType type, int spectatorID, SpectatorState state) {
this.type = type;
this.spectatorID = spectatorID;
this.spectatorState = state;
}
/**
* Constructs a message which is defined by its type (as an object of type {@link MessageType}
* and a {@link Race}.
*
* @param type the type of this message.
* @param race the new Race.
*/
public Message(MessageType type, Race race) {
this.type = type;
this.race = race;
}
/**
* Gets the type of this Message.
*
* @return the type of this message as {@link MessageType}.
*/
public MessageType getType() {
return type;
}
/**
* Gets the state of the Broker.
*
* @return the state of the Broker as {@link BrokerState}.
*/
public BrokerState getBrokerState() {
return brokerState;
}
/**
* Gets the state of the pair Horse/Jockey.
*
* @return the state of the pair Horse/Jockey as {@link HorseJockeyState}.
*/
public HorseJockeyState getHorseJockeyState() {
return horseJockeyState;
}
/**
* Gets the state of the Spectator.
*
* @return the state of the Spectator as {@link SpectatorState}.
*/
public SpectatorState getSpectatorState() {
return spectatorState;
}
/**
* Gets the identification of a Spectator.
*
* @return the identification as an {@code int}.
*/
public int getSpectatorID() {
return spectatorID;
}
/**
* Gets the bet of a Spectator.
*
* @return the bet as an {@code int}.
*/
public int getBet() {
return bet;
}
/**
* Gets the identification of a pair Horse/Jockey.
*
* @return the identification as an {@code int}.
*/
public int getHorseID() {
return horseID;
}
/**
* Gets the identification of a Winner.
*
* @return the winner as an {@code int}.
*/
public int getWinner() {
return winner;
}
/**
* Gets the ability of a pair Horse/Jockey.
*
* @return the ability as an {@code int}.
*/
public int getAbility() {
return ability;
}
/**
* Gets the identification of a Race.
*
* @return the race number as an {@code int}.
*/
public int getRaceNumber() {
return raceNumber;
}
/**
* Gets the distance of a Race.
*
* @return the distance as an {@code int}.
*/
public int getRaceDistance() {
return raceDistance;
}
/**
* Gets the amount of money of a Spectator.
*
* @return the amount of money as an {@code int}.
*/
public int getSpectatorAmountOfMoney() {
return spectatorAmountOfMoney;
}
/**
* Gets the bet selection of a Spectator.
*
* @return the bet selection as an {@code int}.
*/
public int getSpectatorBetSelection() {
return spectatorBetSelection;
}
/**
* Gets the odds of a pair Horse/Jockey.
*
* @return the odds as an {@code int}.
*/
public int getHorseProbability() {
return horseProbability;
}
/**
* Gets the iterations of a pair Horse/Jockey.
*
* @return the iterations as an {@code int}.
*/
public int getHorseIteration() {
return horseIteration;
}
/**
* Gets the position of a pair Horse/Jockey.
*
* @return the position as an {@code int}.
*/
public int getHorsePosition() {
return horsePosition;
}
/**
* Gets the value of a boolean variable.
*
* @return the value as an {@code boolean}.
*/
public boolean getValue() {
return value;
}
/**
* Gets the gains of a Spectator.
*
* @return the gains as an {@code int}.
*/
public int getGains() {
return gains;
}
/**
* Gets the number of pairs Horse/Jockey.
*
* @return the number as an {@code int}.
*/
public int getHorses() {
return horses;
}
/**
* Gets the gains of a Spectator.
*
* @return the gains as an {@code int}.
*/
public int getResults() {
return results;
}
/**
* Gets the increments of a pair Horse/Jockey.
*
* @return the increments as an {@code int}.
*/
public int getIncrements() {
return increments;
}
/**
* Gets a race.
*
* @return the race as an {@code Race}.
*/
public Race getRace() {
return race;
}
/**
* Sets a new Broker state.
*
* @param brokerState the new state.
*/
public void setBrokerState(BrokerState brokerState) {
this.brokerState = brokerState;
}
/**
* Sets a new pair Horse/Jockey state.
*
* @param horseJockeyState the new state.
*/
public void setHorseJockeyState(HorseJockeyState horseJockeyState) {
this.horseJockeyState = horseJockeyState;
}
/**
* Sets a new Spectator state.
*
* @param spectatorState the new state.
*/
public void setSpectatorState(SpectatorState spectatorState) {
this.spectatorState = spectatorState;
}
/**
* Sets a new Spectator identification.
*
* @param spectatorID the new identification.
*/
public void setSpectatorID(int spectatorID) {
this.spectatorID = spectatorID;
}
/**
* Sets a new pair Horse/Jockey identification.
*
* @param horseID the new identification.
*/
public void setHorseID(int horseID) {
this.horseID = horseID;
}
/**
* Sets a new pair Horse/Jockey ability.
*
* @param ability the new ability.
*/
public void setAbility(int ability) {
this.ability = ability;
}
/**
* Sets a new race identification.
*
* @param raceNumber the new identification.
*/
public void setRaceNumber(int raceNumber) {
this.raceNumber = raceNumber;
}
/**
* Sets a new boolean variable value.
*
* @param value the new value.
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Sets a new Race.
*
* @param race the new race.
*/
public void setRace(Race race) {
this.race = race;
}
/** The type of this message */
private MessageType type;
/** The state of this message's Broker */
private BrokerState brokerState;
/** The state of this message's pair Horse/Jockey */
private HorseJockeyState horseJockeyState;
/** The state of this message's spectator */
private SpectatorState spectatorState;
/** This message's spectator identification */
private int spectatorID;
/** This message's bet */
private int bet;
/** This message's gains */
private int gains;
/** This message's number of horses */
private int horses;
/** This message's results */
private int results;
/** This message's increments */
private int increments;
/** This message's identification of a pair Horse/Jockey */
private int horseID;
/** This message's identification of the winner */
private int winner;
/** This message's pair Horse/Jockey's ability */
private int ability;
/** This message's number of the race */
private int raceNumber;
/** This message's distance of the race */
private int raceDistance;
/** This message's amount of money */
private int spectatorAmountOfMoney;
/** This message's bet selection */
private int spectatorBetSelection;
/** This message's odds for the pair Horse/Jockey */
private int horseProbability;
/** This message's pair Horse/Jockey iteration */
private int horseIteration;
/** This message's pair Horse/Jockey position */
private int horsePosition;
/** This message's boolean variable value */
private boolean value;
/** This message's race */
private Race race;
}
| 28.622332 | 118 | 0.585566 |
4f1fa15517e8370b7478a4ef846e0100d01ebb56 | 1,447 | package com.example.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.example.R;
import com.example.utility.Preferences;
import org.alfonz.utility.Logcat;
import org.alfonz.utility.VersionUtility;
public class ExampleActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
checkNewVersion();
checkRateCounter();
}
private void checkNewVersion() {
Preferences preferences = new Preferences();
String currentVersion = VersionUtility.getVersionName(this);
String lastVersion = preferences.getVersion();
// new version is available
if (!currentVersion.equals(lastVersion)) {
// TODO: do something
// set new version in preferences
preferences.setVersion(currentVersion);
}
}
private void checkRateCounter() {
// get current rate counter
Preferences preferences = new Preferences();
final int rateCounter = preferences.getRateCounter();
Logcat.d("" + rateCounter);
// check rate counter
boolean showMessage = false;
if (rateCounter != -1) {
if (rateCounter >= 10 && rateCounter % 10 == 0) showMessage = true;
} else {
return;
}
// show rate message
if (showMessage) {
// TODO: show message
// TODO: set rate counter to -1
}
// increment rate counter
preferences.setRateCounter(rateCounter + 1);
}
}
| 24.525424 | 70 | 0.731168 |
d3913081143cd7f134e0008b76f9b3ed4403efe5 | 1,386 | package org.qwli.rowspot.model.aggregate;
import org.qwli.rowspot.model.enums.BaseEntity;
import org.qwli.rowspot.model.Collect;
import java.io.Serializable;
import java.util.Date;
public class CollectAggregate extends BaseEntity implements Serializable {
private Long id;
private Long categoryId;
private String categoryName;
private String categoryAlias;
private Date createAt;
public CollectAggregate(Collect collect) {
this.id = collect.getId();
this.categoryId = collect.getCategoryId();
this.createAt = collect.getCreateAt();
}
public Long getId() {
return id;
}
public String getCategoryAlias() {
return categoryAlias;
}
public void setCategoryAlias(String categoryAlias) {
this.categoryAlias = categoryAlias;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
| 20.382353 | 74 | 0.660173 |
a9ab24e240f28c634313471df44396d783bd792a | 370 | package com.example.hades.dagger2._10_subgraphs._subclass._plus;
import dagger.Component;
import javax.inject.Singleton;
@Singleton
@Component(modules = {AppModule.class, DebugAppModule.class})
public interface AppComponent {
void inject(App app);
void inject(DebugApp debugApp);
App app();
// void plus(DebugAppModule debugAppModule); // not need
} | 21.764706 | 64 | 0.754054 |
7f9cb2d9639cbea1cf44c79763b5545fffbc8096 | 696 | package com.sang.law.controller;
import com.sang.law.pojo.Admin;
import com.sang.law.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private AdminService adminService;
@RequestMapping("/loginAdmin") //登录
public Admin loginAdmin(String admin_username, String admin_password) {
return adminService.loginAdmin(admin_username, admin_password);
}
}
| 31.636364 | 75 | 0.800287 |
6ffcf61c0ca51d6e2c106cddfe5063152d56db42 | 377 | package streams.algebras;
import streams.higher.App;
import java.util.function.BinaryOperator;
/**
* Authors:
* Aggelos Biboudis (@biboudis)
* Nick Palladinos (@NickPalladinos)
*/
public interface ExecStreamAlg<E, C> extends StreamAlg<C> {
<T> App<E, Long> count(App<C, T> app);
<T> App<E, T> reduce(T identity, BinaryOperator<T> accumulator, App<C, T> app);
}
| 22.176471 | 83 | 0.69496 |
af974b5accc6642f41d0395612bc82763ac3f914 | 5,974 | package com.hhd2002.universaladapter;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by hhd on 2017-09-22.
*/
public class UniversalAdapter extends RecyclerView.Adapter {
private ArrayList<Object> _items = new ArrayList<>();
private RecyclerView _rcView;
private ArrayList<Class> _itemTypes;
private ArrayList<Class<? extends UniversalViewHolder>> _vhTypes;
private IUniversalListener _listener;
private Object _additionalCallback;
private boolean _useLoadMore = false;
private UniversalViewHolder _loadMoreVh;
public UniversalAdapter(
RecyclerView rcView,
ArrayList<Class> itemTypes,
ArrayList<Class<? extends UniversalViewHolder>> vhTypes) {
_rcView = rcView;
_itemTypes = itemTypes;
_vhTypes = vhTypes;
_init();
}
private void _init() {
Handler uiHandler = new Handler();
_rcView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int itemsSize = _items.size();
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
if (lm instanceof LinearLayoutManager) {
LinearLayoutManager llm = (LinearLayoutManager) lm;
int lvp = llm.findLastCompletelyVisibleItemPosition();
if (lvp == (itemsSize - 1)) {
_fireOnLastItem();
}
} else if (lm instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager slm = (StaggeredGridLayoutManager) lm;
int spanCount = slm.getSpanCount();
int[] into = new int[spanCount];
for (int i = 0; i < spanCount; i++) {
into[i] = i;
}
int[] lcvp = slm.findLastCompletelyVisibleItemPositions(into);
for (int i : lcvp) {
if (i == (itemsSize - 1)) {
_fireOnLastItem();
break;
}
}
}
}//public void onScrolled
private void _fireOnLastItem() {
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (_listener == null)
return;
_listener.onLastItem();
}
}, 100);
}
}); //_rcView.addOnScrollListener
}
@Override
public int getItemCount() {
int size = _items.size();
if (_useLoadMore) {
return size + 1;
} else {
return size;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
try {
Class<? extends UniversalViewHolder> vhType = _vhTypes.get(viewType);
View convertView =
vhType.getDeclaredConstructor(View.class)
.newInstance(parent)
.inflateConvertView(parent);
UniversalViewHolder vh =
vhType.getDeclaredConstructor(View.class)
.newInstance(convertView);
vh.findAllViews(_additionalCallback);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (_listener == null)
return;
_listener.onClickItem(
vh.item,
vh.position,
convertView);
}
});
if (_useLoadMore &&
(viewType == _itemTypes.size() - 1)) {
_loadMoreVh = vh;
}
return vh;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
UniversalViewHolder vh = (UniversalViewHolder) holder;
if (position < _items.size()) {
Object item = _items.get(position);
vh.item = item;
vh.position = position;
}
vh.onBindViewHolder();
}
@Override
public int getItemViewType(int position) {
if (_useLoadMore &&
position == _items.size()) {
return _itemTypes.size() - 1;
}
int viewType = 0;
Object item = _items.get(position);
int size = _itemTypes.size();
for (int i = 0; i < size; i++) {
Class cls = _itemTypes.get(i);
if (item.getClass() == cls) {
viewType = i;
break;
}
}
return viewType;
}
public ArrayList<Object> getItems() {
return _items;
}
public void setListener(IUniversalListener listener) {
_listener = listener;
}
public void setAdditionalCallback(Object additionalCallback) {
_additionalCallback = additionalCallback;
}
public void setLoadMoreVhType(Class<? extends UniversalViewHolder> loadMoreVhType) {
_useLoadMore = true;
_itemTypes.add(UniversalLodeMoreItem.class);
_vhTypes.add(loadMoreVhType);
}
public UniversalViewHolder getLoadMoreVh() {
return _loadMoreVh;
}
} | 28.179245 | 88 | 0.532139 |
da497f1b3b87dcfb970e58aab46ead029025c037 | 6,862 | package org.ksoong.weibo4j.publisher.parser;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.ksoong.weibo4j.publisher.Post;
import org.ksoong.weibo4j.publisher.Post.Img;
import org.ksoong.weibo4j.tools.IOUtils;
import twitter4j.MediaEntity;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
import twitter4j.UserMentionEntity;
import twitter4j.auth.AccessToken;
public class TestTwitterSearchParse {
static {
System.setProperty("http.proxyHost", "squid.apac.redhat.com");
System.setProperty("http.proxyPort", "3128");
}
@Test
public void testTopicConvert() {
String sample_1 = "What #BigData";
String sample_2 = "What #BigData.";
String sample_3 = "What #BigData,";
String sample_4 = "What #BigData. ";
String sample_5 = "What #BigData, ";
String sample_6 = "What #BigData can tell us about";
helpTest(sample_1);
helpTest(sample_2);
helpTest(sample_3);
helpTest(sample_4);
helpTest(sample_5);
helpTest(sample_6);
}
private void helpTest(String sample) {
String[] array = sample.split(" ");
String[] newArray = new String[array.length];
for(int i = 0 ; i < array.length ; i ++) {
String item = array[i];
if(item.startsWith("#")){
if(item.endsWith(".") || item.endsWith(",") || item.endsWith("!") || item.endsWith("?")){
char symbol = item.charAt(item.length() -1);
item = item.substring(0, item.length() -1) + "#" + symbol;
} else {
item = item + "#";
}
}
newArray[i] = item;
}
String txt = "";
for(int i = 0 ; i < newArray.length ; i ++){
String item = newArray[i];
txt += item;
if(i != (newArray.length -1)) {
txt += " ";
}
}
assertTrue(txt.contains("#BigData#"));
}
@Ignore
@Test
public void testImgDownload() throws IOException {
String urlPath = "http://pbs.twimg.com/media/CyCK3FeWIAE0RUS.jpg";
Path file = Files.createFile(Paths.get("target", "CyCK3FeWIAE0RUS.jpg"));
IOUtils.downloadImg(urlPath, file.toFile());
}
@Ignore
@Test
public void testParser() throws Exception {
List<Post> posts = new TwitterSearchParser().parse();
posts.forEach(p -> {
StringBuffer sb = new StringBuffer();
sb.append("Type: " + p.getType() + ", Souce content: " + p.getStatus());
if(p.getPic() != null) {
sb.append(", Img URL: " + p.getPic());
} else {
Img img = p.getImg();
if(img != null){
sb.append(", Img URL: " + img.getSrc());
}
}
System.out.println(sb.toString());
});
}
@Test
public void testCreateTempFile() throws IOException {
String pic = "http://pbs.twimg.com/media/CyFu8KAUUAAC0ZW.jpg";
String name = pic.substring(pic.lastIndexOf(File.separator) + 1, pic.length());
Path base = Paths.get(System.getProperty("java.io.tmpdir"), "twitter_search");
if(!Files.exists(base)) {
Files.createDirectory(base);
}
Path tmpFile = Paths.get(base.toString(), name);
Files.deleteIfExists(tmpFile);
Files.createFile(tmpFile);
assertTrue(Files.exists(tmpFile));
assertEquals(0, tmpFile.toFile().length());
assertEquals("/tmp/twitter_search/CyFu8KAUUAAC0ZW.jpg", tmpFile.toString());
assertEquals("CyFu8KAUUAAC0ZW.jpg", tmpFile.toFile().getName());
// IOUtils.download(pic, tmpFile.toFile());
// assertTrue(tmpFile.toFile().length() > 0);
System.out.println(tmpFile);
}
@Ignore
@Test
public void testGrabing() throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken("209490245-KrmA9T6OfdI3syd5ryJl9jwJJumvhK69Cnxnv1Vr", "CJlREMM8dUwV3h6A8I0zw2MFFuUWBqjeWEfyXERIdYf6b");
twitter.setOAuthConsumer("ieNoRaTmSTzos8fvDxQ9CyEJr", "GC2f6ugQCiR3RSP5VkUGbqo9lPQw984YXBxNLZrPTOuaNhpM8G");
twitter.setOAuthAccessToken(accessToken);
Query query = new Query("Big Data");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
System.out.println(tweets.size());
for (Status tweet : tweets) {
if(tweet.getMediaEntities().length > 0 && tweet.getLang().equals("en")){
for(MediaEntity media : tweet.getMediaEntities()){
if(!media.getType().equals("photo")){
continue;
}
String mediaURL = media.getMediaURL();
String txt = tweet.getText();
txt = txt.replace(media.getText(), "");
if(tweet.getUserMentionEntities().length > 0){
txt = getOriginalTweet(tweet.getUserMentionEntities(), txt);
}
System.out.println(mediaURL);
if(tweet.getURLEntities().length > 0){
for(URLEntity urlEntity : tweet.getURLEntities()){
System.out.println(urlEntity.getDisplayURL());
System.out.println(urlEntity.getExpandedURL());
System.out.println(urlEntity.getURL());
if(txt.contains(urlEntity.getURL())){
txt = txt.replace(urlEntity.getURL(), urlEntity.getExpandedURL());
}
}
}
System.out.println(txt);
break;
}
}
}
}
private String getOriginalTweet(UserMentionEntity[] userMentionEntities, String txt) {
for(UserMentionEntity entity : userMentionEntities) {
String startMention = "RT @" + entity.getText() + ": ";
if(txt.contains(startMention)) {
txt = txt.replace(startMention, "");
} else {
txt = txt.replace("@" + entity.getText(), entity.getText());
}
}
return txt;
}
}
| 36.695187 | 153 | 0.55392 |
157e9dd8eeafddef9426e8eceec58b92404fdca4 | 851 | package top.ahdx.utils;
import java.io.Serializable;
/**
* @author YangYe
* @email [email protected]
* @date 2021/1/19
*/
public class Res implements Serializable {
private Boolean flag;
private String message;
private Object data;
public Res() {
}
public Res(Boolean flag, String message, Object data) {
this.flag = flag;
this.message = message;
this.data = data;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
| 17.367347 | 59 | 0.59342 |
be9951355312d6040f43b4ae163b567b3fbc427c | 2,916 | /*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mockftpserver.fake.filesystem;
import java.util.Date;
/**
* Interface for an entry within a fake file system, representing a single file or directory.
*
* @author Chris Mair
* @version $Revision$ - $Date$
*/
public interface FileSystemEntry {
/**
* Return true if this entry represents a directory, false otherwise
*
* @return true if this file system entry is a directory, false otherwise
*/
public boolean isDirectory();
/**
* Return the path for this file system entry
*
* @return the path for this file system entry
*/
public String getPath();
/**
* Return the file name or directory name (no path) for this entry
*
* @return the file name or directory name (no path) for this entry
*/
public String getName();
/**
* Return the size of this file system entry
*
* @return the file size in bytes
*/
public long getSize();
/**
* Return the timestamp Date for the last modification of this file system entry
*
* @return the last modified timestamp Date for this file system entry
*/
public Date getLastModified();
/**
* Set the timestamp Date for the last modification of this file system entry
*
* @param lastModified - the lastModified value, as a Date
*/
public void setLastModified(Date lastModified);
/**
* @return the username of the owner of this file system entry
*/
public String getOwner();
/**
* @return the name of the owning group for this file system entry
*/
public String getGroup();
/**
* @return the Permissions for this file system entry
*/
public Permissions getPermissions();
/**
* Return a new FileSystemEntry that is a clone of this object, except having the specified path
*
* @param path - the new path value for the cloned file system entry
* @return a new FileSystemEntry that has all the same values as this object except for its path
*/
public FileSystemEntry cloneWithNewPath(String path);
/**
* Lock down the path so it cannot be changed
*/
public void lockPath();
} | 29.454545 | 101 | 0.643004 |
fad93333430a61ff64a3740b2810fc5556adc0f4 | 1,218 | package com.gmail.antonsyzko.doctoradministrationpanel.utils;
/**
* Created by Admin on 06.08.2016.
*/
/*
demo use
*/
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
//not really used - hardcoded at DB
public class QuickPasswordEncodingGenerator {
/**
* @param args
*/
private PasswordEncoder passwordEncoder;
public static void main(String[] args) {
String password = "testAdmin";
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode(password));
/*
INSERT INTO APP_USER(sso_id, password, first_name, last_name, email)
VALUES ('bob','$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC', 'bob','bob','[email protected]');
*/
//$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC
//$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC
}
}
// //$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC
// //$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC
// //$2a$10$pF61kw77wUhDZyYoiJrQzuLB3JfRfvl4x8mIAxtD4FXBBjpQF43KC | 25.375 | 105 | 0.743021 |
73df9b5f5af4db52c837cca42593f0af0a9bf0ee | 1,103 | package com.thieu.setup.services;
import com.thieu.setup.mappers.RoleMapper;
import com.thieu.setup.models.Role;
import com.thieu.tool.shared.CommonStrings;
import com.thieu.tool.shared.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class UserRoleService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);
@Autowired
private RoleMapper roleMapper;
public void getRoleForUser(int userID){
try {
roleMapper.getRoleForUser(userID,new Date());
}catch (Exception e){
LOGGER.error("Error when call registerUser in UserService class: .", e);
}
}
public Role findRoleByName(String roleName){
Role roles = new Role();
try{
roles= roleMapper.findRoleByName(roleName);
}catch(Exception e){
LOGGER.error("Fail when call loginUser.", e);
}
return roles;
}
}
| 25.651163 | 84 | 0.690843 |
1870ebae750a43db950041443420c5fc413107d7 | 1,499 | package com.coolweather.app.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtil {
public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream inputStream = connection.getInputStream();
/* BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null){
response.append(line);
}*/
if(listener!=null){
listener.onFinish(inputStream);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
if(listener!=null){
listener.onError(e);
}
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
| 25.844828 | 94 | 0.679119 |
18c884ec3aef3361f46f74b97d1d69c26e31df3d | 465 | public class MalformedCardException extends RuntimeException {
/**
* Create the exception with the default message.
*/
public MalformedCardException() {
super("Invalid card.");
}
/**
* Create the exception and add the entered string to the message.
*
* @param card what the user attempted to convert to a card
*/
public MalformedCardException(String card) {
super("Invalid card: " + card);
}
}
| 25.833333 | 70 | 0.632258 |
cfe368a7c849e06e71da0b5acd6e5a6f99c0fecc | 3,199 | package com.venky.swf.plugins.collab.util;
import com.venky.geo.GeoCoder;
import com.venky.geo.GeoCoordinate;
import com.venky.geo.GeoDistance;
import com.venky.geo.GeoLocation;
import com.venky.swf.db.model.Model;
import com.venky.swf.db.model.reflection.ModelReflector;
import com.venky.swf.sql.Conjunction;
import com.venky.swf.sql.Expression;
import com.venky.swf.sql.Operator;
import com.venky.swf.sql.Select;
import java.math.BigDecimal;
import java.util.List;
public class BoundingBox {
private GeoCoordinate min;
private GeoCoordinate max;
private GeoCoordinate closeTo;
public BoundingBox(GeoCoordinate closeTo, double accuracyKM, double withinKms){
this.closeTo = closeTo;
double lat = closeTo.getLat().doubleValue();
double lng = closeTo.getLng().doubleValue();
double F = (withinKms + accuracyKM)/ GeoCoordinate.R;
double deltaLat = F * 180 / Math.PI;
double maxLat = lat + deltaLat;
double minLat = lat - deltaLat;
double cosdeltaLng = (Math.cos(F) - Math.pow(Math.sin(lat * Math.PI/180.0),2)) / Math.pow(Math.cos(lat * Math.PI / 180.0), 2);
cosdeltaLng = Math.max(Math.min(1,cosdeltaLng),-1);
double deltaLng = Math.acos(cosdeltaLng) * 180 / Math.PI ;
double maxLng = lng + deltaLng ;
double minLng = lng - deltaLng ;
min = new GeoCoordinate(new BigDecimal(minLat),new BigDecimal(minLng));
max = new GeoCoordinate(new BigDecimal(maxLat),new BigDecimal(maxLng));
}
public GeoCoordinate getMin(){
return min;
}
public GeoCoordinate getMax() {
return max;
}
/**
* Find Records of modelClass that lie within the bounding box.
* @param modelClass
* @param <T>
* @return
*/
public <T extends GeoLocation & Model> List<T> find(Class<T> modelClass, int limit){
return find(modelClass,limit,null);
}
public <T extends GeoLocation & Model> List<T> find(Class<T> modelClass, int limit, Expression additionalWhereClause) {
Expression where = getWhereClause(modelClass);
if (additionalWhereClause != null) {
where.add(additionalWhereClause);
}
Select select = new Select().from(modelClass).where(where);
select.add(" ORDER BY ABS(LAT - "+this.closeTo.getLat() + ") , ABS(LNG - "+this.closeTo.getLng() + ")");
List<T> objects = select.execute(modelClass,limit);
return objects;
}
public <T extends GeoLocation & Model> Expression getWhereClause(Class<T> modelClass){
ModelReflector<T> ref = ModelReflector.instance(modelClass) ;
Expression where = new Expression(ref.getPool(),Conjunction.AND);
String LAT = ref.getColumnDescriptor("LAT").getName();
String LNG = ref.getColumnDescriptor("LNG").getName();
where.add(new Expression(ref.getPool(),LAT, Operator.GE, min.getLat()));
where.add(new Expression(ref.getPool(),LAT, Operator.LT, max.getLat()));
where.add(new Expression(ref.getPool(),LNG, Operator.GE, min.getLng()));
where.add(new Expression(ref.getPool(),LNG, Operator.LT, max.getLng()));
return where;
}
}
| 35.544444 | 134 | 0.66302 |
4daa46d4fd1da0857eaad44f8674603012028abd | 2,169 | import org.sql2o.*;
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class ClientTest {
@Before
public void setUp() {
DB.sql2o = new Sql2o("jdbc:postgresql://localhost:5432/hair_salon_test", null, null);
}
@After
public void tearDown() {
try(Connection con = DB.sql2o.open()) {
String deleteRestaurantQuery = "DELETE FROM clients *;";
String deleteCategoriesQuery = "DELETE FROM stylists *;";
con.createQuery(deleteRestaurantQuery).executeUpdate();
con.createQuery(deleteCategoriesQuery).executeUpdate();
}
}
@Test public void client_exists_true(){
Client testCli = new Client("Sleepy Gary", 0);
assertEquals(true, testCli instanceof Client);
}
@Test public void getName_InstantiatesWithName_String() {
Client testCli = new Client("Hamurai", 0);
assertEquals("Hamurai", testCli.cliName());
}
@Test public void all_emptyAtFirst() {
assertEquals(Client.all().size(), 0);
}
@Test public void equals_returnsTrueIfDescriptionsAretheSame() {
Client firstCli = new Client("Ms.Sullivan", 0);
Client secondCli = new Client("Ms.Sullivan", 0);
assertTrue(firstCli.equals(secondCli));
}
@Test public void save_returnsTrueIfDescriptionsAretheSame() {
Client testCli = new Client("Baby Wizard", 0);
testCli.save();
assertTrue(Client.all().get(0).equals(testCli));
}
@Test public void save_assignsIdToObject() {
Client testCli = new Client("King Jellybean", 0);
testCli.save();
Client savedCli = Client.all().get(0);
assertEquals(testCli.cliId(), savedCli.cliId());
}
@Test public void find_findsCliInDatabase_true() {
Client testCli = new Client("Jan Michael Vincent", 0);
testCli.save();
Client savedCli = Client.find(testCli.cliId());
assertTrue(testCli.equals(savedCli));
}
@Test public void save_savesIdIntoDB_true() {
Stylist testSty = new Stylist("Scary Terry");
testSty.save();
Client testCli = new Client("Stealy" ,testSty.getId());
testCli.save();
Client savedCli = Client.find(testCli.cliId());
assertEquals(savedCli.styId(), testSty.getId());
}
}
| 29.310811 | 89 | 0.685569 |
3e66a97dd4e981879dea0d86026aaa04c94a07d4 | 829 | import javax.swing.*;
import java.awt.*;
public class GUISetup extends JFrame
{
// window variable
private Container window;
private int screenHeight = (int)(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getHeight());
private int screenWidth = (int)(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth());
private int sizeX = (screenWidth * 3) / 4;
private int sizeY = (screenHeight * 3) / 4;
//
public void makeTheWindow()
{
window = getContentPane();
window.setLayout(null);
window.setBackground(Color.WHITE);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Seat Randomizer");
setSize(sizeX, sizeY);
setLocation(screenWidth / 2 - sizeX / 2, screenHeight / 2 - sizeY / 2);
setResizable(false);
}
}
| 27.633333 | 103 | 0.651387 |
58124157e1c14f6f9bdbf0d5c9fb82bc1a3f0503 | 323 | package reform.core.procedure.instructions;
public abstract class BaseInstruction implements Instruction
{
private InstructionGroup _parent;
@Override
final public InstructionGroup getParent()
{
return _parent;
}
@Override
final public void setParent(final InstructionGroup parent)
{
_parent = parent;
}
}
| 16.15 | 60 | 0.780186 |
9614d1d51d5d652d2f44b17c8f1be12594fcdfd6 | 409 | package com.ttyd.videoplayer.videolib.render.view.listener;
import android.view.Surface;
/**
* Surface 状态变化回调
* Created by guoshuyu on 2018/1/29.
*/
public interface IGSYSurfaceListener {
void onSurfaceAvailable(Surface surface);
void onSurfaceSizeChanged(Surface surface, int width, int height);
boolean onSurfaceDestroyed(Surface surface);
void onSurfaceUpdated(Surface surface);
}
| 21.526316 | 70 | 0.762836 |
fb24e9638d27d48fc429b6fa437f1bdbc15479b4 | 799 | package com.bihell.dice.system.convert;
import com.bihell.dice.system.entity.SysDepartment;
import com.bihell.dice.system.vo.SysDepartmentTreeVo;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 部门对象属性转换器
*
* @author geekidea
* @date 2019-11-01
**/
@Mapper
public interface SysDepartmentConvert {
SysDepartmentConvert INSTANCE = Mappers.getMapper(SysDepartmentConvert.class);
/**
* SysDepartment转换成SysDepartmentTreeVo对象
*
* @param sysDepartment
* @return
*/
SysDepartmentTreeVo entityToTreeVo(SysDepartment sysDepartment);
/**
* SysDepartment列表转换成SysDepartmentTreeVo列表
*
* @param list
* @return
*/
List<SysDepartmentTreeVo> listToTreeVoList(List<SysDepartment> list);
}
| 21.026316 | 82 | 0.720901 |
2d7c021f2e6bf7900a8159681165b59eb5ad3dd1 | 422 | package me.prettyprint.hector.api.beans;
import java.util.List;
/**
* Return type from get_range_slices for simple columns
* @author Ran Tavory
*
* @param <N> column name type
* @param <V> column value type
*/
public interface OrderedRows<K, N, V> extends Rows<K, N, V>{
/**
* Preserves rows order
* @return an unmodifiable list of Rows
*/
List<Row<K, N, V>> getList();
Row<K, N, V> peekLast();
} | 19.181818 | 60 | 0.654028 |
5c59a98c9cc1b1fcacd6f6b4798e42200efd1d7a | 2,580 | /*
Copyright 2014-2016 Intel Corporation
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 apple.gss.struct;
import org.moe.natj.c.StructObject;
import org.moe.natj.c.ann.Structure;
import org.moe.natj.c.ann.StructureField;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
@Generated
@Structure()
public final class gss_channel_bindings_struct extends StructObject {
private static long __natjCache;
static {
NatJ.register();
}
@Generated
public gss_channel_bindings_struct() {
super(gss_channel_bindings_struct.class);
}
@Generated
protected gss_channel_bindings_struct(Pointer peer) {
super(peer);
}
@Generated
@StructureField(order = 0, isGetter = true)
public native int initiator_addrtype();
@Generated
@StructureField(order = 0, isGetter = false)
public native void setInitiator_addrtype(int value);
@Generated
@StructureField(order = 1, isGetter = true)
@ByValue
public native gss_buffer_desc_struct initiator_address();
@Generated
@StructureField(order = 1, isGetter = false)
public native void setInitiator_address(@ByValue gss_buffer_desc_struct value);
@Generated
@StructureField(order = 2, isGetter = true)
public native int acceptor_addrtype();
@Generated
@StructureField(order = 2, isGetter = false)
public native void setAcceptor_addrtype(int value);
@Generated
@StructureField(order = 3, isGetter = true)
@ByValue
public native gss_buffer_desc_struct acceptor_address();
@Generated
@StructureField(order = 3, isGetter = false)
public native void setAcceptor_address(@ByValue gss_buffer_desc_struct value);
@Generated
@StructureField(order = 4, isGetter = true)
@ByValue
public native gss_buffer_desc_struct application_data();
@Generated
@StructureField(order = 4, isGetter = false)
public native void setApplication_data(@ByValue gss_buffer_desc_struct value);
}
| 28.988764 | 83 | 0.73876 |
7d71d809a282cb66bda9512af8c11f1ec83b2a48 | 2,856 | import java.util.Comparator;
public class Merge {
public static void sort (Point[] a, Comparator comparator) {
Point[] aux = new Point[a.length];
sort (a, aux, comparator, 0, a.length - 1);
}
private static void sort (Point[] a, Point[] aux,
Comparator comparator, int low, int high) {
// Merging the two arrays by comparison // edge case
if (high <= low) {
return;
}
// Finding mid
int mid = (low + high) / 2;
// Sorting left half
sort(a, aux, comparator, low, mid);
// Sorting the right half
sort(a, aux, comparator, mid + 1, high);
// Merging the two arrays
merge(a, aux, comparator, low, mid, high);
}
private static void merge (Point[] a, Point[] aux, Comparator comparator,
int low, int mid, int high) {
// Assert that the left subArray is sorted
assert isSorted(comparator, a, low, mid);
// Assert that the right subArray is sorted
assert isSorted(comparator, a, mid + 1, high);
// Copying the array to auxillary array, not creating aux in recursive
// subroutine as it adds to additional complexity.
for (int i = low; i <= high; i++) {
aux[i] = a[i];
}
int i = 0;
int j = mid + 1;
for (int k = 0; k <= high; k++) {
// If the first subArray is exhausted, copy 2nd subArray to merged Array
if (i > mid) {
a[k] = aux[j++];
}
// If the second subArray is exhausted, copy the 1st subArray to merged Array
else if (j > high) {
a[k] = aux[i++];
}
// If the element of the first subArray is less than the item of the second SubArray
else if (less(comparator, aux[j], aux[i])) {
a[k] = aux[j++];
}
// If the element of the second subArray is less than the item of the first SubArray
else {
a[k] = aux[i++];
}
}
// Assert that the final merged array is sorted
assert isSorted(comparator, a, low, high);
}
private static boolean less(Comparator comparator, Point x, Point y) {
if (x == null || y == null) {
throw new IllegalArgumentException("instances cannot be null");
}
return comparator.compare(x, y) < 0;
}
private static boolean isSorted(Comparator comparator, Point[] a, int low, int high) {
for (int index = low+1; index <= high; index++) {
if (less(comparator, a[index], a[index - 1])) {
return false;
}
}
return true;
}
} | 34.829268 | 96 | 0.507703 |
b9fe8e80707e278dd1479224faa39d5d6d36737f | 761 | public class Solution {
public boolean isScramble(String s1, String s2) {
if (s1.equals(s2)) return true;
int[] letters = new int[26];
for (int i=0; i<s1.length(); i++) {
letters[s1.charAt(i)-'a']++;
letters[s2.charAt(i)-'a']--;
}
for (int i=0; i<26; i++) if (letters[i]!=0) return false;
for (int i=1; i<s1.length(); i++) {
if (isScramble(s1.substring(0,i), s2.substring(0,i))
&& isScramble(s1.substring(i), s2.substring(i))) return true;
if (isScramble(s1.substring(0,i), s2.substring(s2.length()-i))
&& isScramble(s1.substring(i), s2.substring(0,s2.length()-i))) return true;
}
return false;
}
} | 38.05 | 88 | 0.516426 |
3d024c319de67e8ad7e4afb10902fbfbd7dfd6e2 | 18,824 | package io.metadew.iesi.metadata.configuration.component.trace;
import io.metadew.iesi.common.configuration.metadata.repository.MetadataRepositoryConfiguration;
import io.metadew.iesi.common.configuration.metadata.tables.MetadataTablesConfiguration;
import io.metadew.iesi.connection.tools.SQLTools;
import io.metadew.iesi.metadata.configuration.Configuration;
import io.metadew.iesi.metadata.definition.component.trace.ComponentTrace;
import io.metadew.iesi.metadata.definition.component.trace.ComponentTraceKey;
import io.metadew.iesi.metadata.definition.component.trace.http.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
@Log4j2
public class ComponentTraceConfiguration extends Configuration<ComponentTrace, ComponentTraceKey> {
private static ComponentTraceConfiguration INSTANCE;
public synchronized static ComponentTraceConfiguration getInstance() {
if (INSTANCE == null) {
INSTANCE = new ComponentTraceConfiguration();
}
return INSTANCE;
}
private ComponentTraceConfiguration() {
setMetadataRepository(MetadataRepositoryConfiguration.getInstance().getTraceMetadataRepository());
}
@Override
public Optional<ComponentTrace> get(ComponentTraceKey metadataKey) {
try {
Map<String, ComponentHttpTraceBuilder> componentTraceBuilderMap = new LinkedHashMap<>();
String query = "select TraceComponent.ID as TraceComponent_ID, TraceComponent.RUN_ID as TraceComponent_RUN_ID, TraceComponent.PRC_ID as TraceComponent_PRC_ID," +
" TraceComponent.ACTION_PAR_NM as TraceComponent_ACTION_PAR_NM, " +
" TraceComponent.COMP_TYP_NM as TraceComponent_COMP_TYP_NM, TraceComponent.COMP_NM as TraceComponent_COMP_NM, " +
"TraceComponent.COMP_DSC as TraceComponent_COMP_DSC, TraceComponent.COMP_VRS_NB as TraceComponent_COMP_VRS_NB, " +
" TraceHttpComponent.ID as TraceHttpComponent_ID, TraceHttpComponent.CONN_NM as TraceHttpComponent_CONN_NM, TraceHttpComponent.TYPE as TraceHttpComponent_TYPE, TraceHttpComponent.ENDPOINT as TraceHttpComponent_ENDPOINT," +
" TraceHttpComponentHeader.ID as TraceHttpComponentHeader_ID, TraceHttpComponentHeader.HTTP_COMP_ID as TraceHttpComponentHeader_HTTP_COMP_ID, TraceHttpComponentHeader.NAME as TraceHttpComponentHeader_NAME , TraceHttpComponentHeader.VALUE as TraceHttpComponentHeader_VALUE," +
" TraceHttpComponentQuery.ID as TraceHttpComponentQuery_ID, TraceHttpComponentQuery.HTTP_COMP_ID as TraceHttpComponentQuery_HTTP_COMP_ID, TraceHttpComponentQuery.NAME as TraceHttpComponentQuery_NAME, TraceHttpComponentQuery.VALUE as TraceHttpComponentQuery_VALUE" +
" FROM " +
getMetadataRepository().getTableNameByLabel("TraceComponent") + " TraceComponent " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponent") + " TraceHttpComponent " +
"on TraceComponent.ID=TraceHttpComponent.ID " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponentHeader") + " TraceHttpComponentHeader " +
"on TraceHttpComponent.ID=TraceHttpComponentHeader.HTTP_COMP_ID " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponentQuery") + " TraceHttpComponentQuery " +
"on TraceHttpComponent.ID=TraceHttpComponentQuery.HTTP_COMP_ID " +
" WHERE TraceComponent.ID = " + SQLTools.getStringForSQL(metadataKey.getUuid().toString()) + ";";
CachedRowSet cachedRowSet = getMetadataRepository().executeQuery(query, "reader");
while (cachedRowSet.next()) {
mapRow(cachedRowSet, componentTraceBuilderMap);
}
return componentTraceBuilderMap.values().stream()
.findFirst()
.map(ComponentHttpTraceBuilder::build);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<ComponentTrace> getAll() {
try {
Map<String, ComponentHttpTraceBuilder> componentTraceBuilderMap = new LinkedHashMap<>();
String query = "select TraceComponent.ID as TraceComponent_ID, TraceComponent.RUN_ID as TraceComponent_RUN_ID, TraceComponent.PRC_ID as TraceComponent_PRC_ID," +
" TraceComponent.ACTION_PAR_NM as TraceComponent_ACTION_PAR_NM, " +
" TraceComponent.COMP_TYP_NM as TraceComponent_COMP_TYP_NM, TraceComponent.COMP_NM as TraceComponent_COMP_NM, " +
"TraceComponent.COMP_DSC as TraceComponent_COMP_DSC, TraceComponent.COMP_VRS_NB as TraceComponent_COMP_VRS_NB, " +
" TraceHttpComponent.ID as TraceHttpComponent_ID, TraceHttpComponent.CONN_NM as TraceHttpComponent_CONN_NM, TraceHttpComponent.TYPE as TraceHttpComponent_TYPE, TraceHttpComponent.ENDPOINT as TraceHttpComponent_ENDPOINT," +
" TraceHttpComponentHeader.ID as TraceHttpComponentHeader_ID, TraceHttpComponentHeader.HTTP_COMP_ID as TraceHttpComponentHeader_HTTP_COMP_ID, TraceHttpComponentHeader.NAME as TraceHttpComponentHeader_NAME , TraceHttpComponentHeader.VALUE as TraceHttpComponentHeader_VALUE," +
" TraceHttpComponentQuery.ID as TraceHttpComponentQuery_ID, TraceHttpComponentQuery.HTTP_COMP_ID as TraceHttpComponentQuery_HTTP_COMP_ID, TraceHttpComponentQuery.NAME as TraceHttpComponentQuery_NAME, TraceHttpComponentQuery.VALUE as TraceHttpComponentQuery_VALUE" +
" FROM " +
getMetadataRepository().getTableNameByLabel("TraceComponent") + " TraceComponent " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponent") + " TraceHttpComponent " +
"on TraceComponent.ID=TraceHttpComponent.ID " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponentHeader") + " TraceHttpComponentHeader " +
"on TraceHttpComponent.ID=TraceHttpComponentHeader.HTTP_COMP_ID " +
"left outer join " + getMetadataRepository().getTableNameByLabel("TraceHttpComponentQuery") + " TraceHttpComponentQuery " +
"on TraceHttpComponent.ID=TraceHttpComponentQuery.HTTP_COMP_ID " + ";";
CachedRowSet cachedRowSet = getMetadataRepository().executeQuery(query, "reader");
while (cachedRowSet.next()) {
mapRow(cachedRowSet, componentTraceBuilderMap);
}
return componentTraceBuilderMap.values().stream()
.map(ComponentHttpTraceBuilder::build)
.collect(Collectors.toList());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void delete(ComponentTraceKey metadataKey) {
log.trace("deleting " + metadataKey.toString());
String deleteTraceComponent = "DELETE FROM " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceComponent").getName() +
" WHERE ID = " + SQLTools.getStringForSQL(metadataKey.getUuid().toString()) + ";";
getMetadataRepository().executeUpdate(deleteTraceComponent);
String deleteTraceHttpComponent = "DELETE FROM " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponent").getName() +
" WHERE ID = " + SQLTools.getStringForSQL(metadataKey.getUuid().toString()) + ";";
getMetadataRepository().executeUpdate(deleteTraceHttpComponent);
String deleteTraceHttpComponentHeader = "DELETE FROM " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponentHeader").getName() +
" WHERE HTTP_COMP_ID = " + SQLTools.getStringForSQL(metadataKey.getUuid().toString()) + ";";
getMetadataRepository().executeUpdate(deleteTraceHttpComponentHeader);
String deleteTraceHttpComponentQuery = "DELETE FROM " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponentQuery").getName() +
" WHERE HTTP_COMP_ID = " + SQLTools.getStringForSQL(metadataKey.getUuid().toString()) + ";";
getMetadataRepository().executeUpdate(deleteTraceHttpComponentQuery);
}
@Override
public void insert(ComponentTrace metadata) {
log.trace(MessageFormat.format("Inserting {0}.", metadata.toString()));
String insertStatementTraceComponent = "INSERT INTO " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceComponent").getName() +
" (ID, RUN_ID, PRC_ID, ACTION_PAR_NM, COMP_TYP_NM, COMP_NM, COMP_DSC, COMP_VRS_NB ) VALUES (" +
SQLTools.getStringForSQL(metadata.getMetadataKey().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(metadata.getRunId()) + ", " +
SQLTools.getStringForSQL(metadata.getProcessId()) + ", " +
SQLTools.getStringForSQL(metadata.getActionParameter()) + ", " +
SQLTools.getStringForSQL(metadata.getComponentTypeParameter()) + ", " +
SQLTools.getStringForSQL(metadata.getComponentName()) + ", " +
SQLTools.getStringForSQL(metadata.getComponentDescription()) + ", " +
SQLTools.getStringForSQL(metadata.getComponentVersion()) +
");";
getMetadataRepository().executeUpdate(insertStatementTraceComponent);
if (metadata instanceof HttpComponentTrace) {
String insertStatementHttpTraceComponent = "INSERT INTO " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponent").getName() +
" (ID, CONN_NM, TYPE, ENDPOINT ) VALUES ( "
+
SQLTools.getStringForSQL(metadata.getMetadataKey().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(((HttpComponentTrace) metadata).getConnectionName()) + ", " +
SQLTools.getStringForSQL(((HttpComponentTrace) metadata).getType()) + ", " +
SQLTools.getStringForSQL(((HttpComponentTrace) metadata).getEndpoint()) + ") ";
getMetadataRepository().executeUpdate(insertStatementHttpTraceComponent);
((HttpComponentTrace) metadata).getHttpComponentHeaderTrace().forEach(httpComponentHeaderTrace ->
getMetadataRepository().executeUpdate(
"INSERT INTO " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponentHeader").getName() +
" (ID, HTTP_COMP_ID, NAME, VALUE ) VALUES ( " +
SQLTools.getStringForSQL(httpComponentHeaderTrace.getMetadataKey().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(httpComponentHeaderTrace.getHttpComponentHeaderID().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(httpComponentHeaderTrace.getName()) + ", " +
SQLTools.getStringForSQLClob(httpComponentHeaderTrace.getValue(),
getMetadataRepository().getRepositoryCoordinator().getDatabases().values().stream()
.findFirst()
.orElseThrow(RuntimeException::new)) + ") "));
((HttpComponentTrace) metadata).getHttpComponentQueries().forEach(httpComponentTrace ->
getMetadataRepository().executeUpdate(
"INSERT INTO " + MetadataTablesConfiguration.getInstance().getMetadataTableNameByLabel("TraceHttpComponentQuery").getName() +
" (ID, HTTP_COMP_ID, NAME, VALUE ) VALUES ( " +
SQLTools.getStringForSQL(httpComponentTrace.getMetadataKey().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(httpComponentTrace.getHttpComponentQueryID().getUuid().toString()) + ", " +
SQLTools.getStringForSQL(httpComponentTrace.getName()) + ", " +
SQLTools.getStringForSQLClob(httpComponentTrace.getValue(),
getMetadataRepository().getRepositoryCoordinator().getDatabases().values().stream()
.findFirst()
.orElseThrow(RuntimeException::new)) + ") "));
}
}
private void mapRow(CachedRowSet cachedRowSet, Map<String, ComponentHttpTraceBuilder> componentTraceBuilderMap) throws SQLException {
String componentTraceBuilderId = cachedRowSet.getString("TraceComponent_ID");
ComponentHttpTraceBuilder componentTraceBuilder = componentTraceBuilderMap.get(componentTraceBuilderId);
if (componentTraceBuilder == null) {
componentTraceBuilder = mapHttpComponentTraces(cachedRowSet);
componentTraceBuilderMap.put(componentTraceBuilderId, componentTraceBuilder);
}
mapHttpComponentHeader(cachedRowSet, componentTraceBuilder);
mapHttpComponentQuery(cachedRowSet, componentTraceBuilder);
}
private ComponentHttpTraceBuilder mapHttpComponentTraces(CachedRowSet cachedRowSet) throws SQLException {
return new ComponentHttpTraceBuilder(
new ComponentTraceKey(UUID.fromString(cachedRowSet.getString("TraceComponent_ID"))),
cachedRowSet.getString("TraceComponent_RUN_ID"),
cachedRowSet.getLong("TraceComponent_PRC_ID"),
cachedRowSet.getString("TraceComponent_ACTION_PAR_NM"),
cachedRowSet.getString("TraceComponent_COMP_TYP_NM"),
cachedRowSet.getString("TraceComponent_COMP_NM"),
cachedRowSet.getString("TraceComponent_COMP_DSC"),
cachedRowSet.getLong("TraceComponent_COMP_VRS_NB"),
cachedRowSet.getString("TraceHttpComponent_CONN_NM"),
cachedRowSet.getString("TraceHttpComponent_TYPE"),
cachedRowSet.getString("TraceHttpComponent_ENDPOINT"),
new LinkedHashMap<>(),
new LinkedHashMap<>());
}
private void mapHttpComponentHeader(CachedRowSet cachedRowSet, ComponentHttpTraceBuilder componentTraceBuilder) throws SQLException {
String mapHttpComponentHeaderId = cachedRowSet.getString("TraceHttpComponentHeader_ID");
if (mapHttpComponentHeaderId != null) {
componentTraceBuilder.getHttpComponentHeader().put(
mapHttpComponentHeaderId,
new HttpComponentHeaderTrace(
new HttpComponentHeaderTraceKey(UUID.fromString(mapHttpComponentHeaderId)),
new ComponentTraceKey(UUID.fromString(cachedRowSet.getString("TraceHttpComponentHeader_HTTP_COMP_ID"))),
cachedRowSet.getString("TraceHttpComponentHeader_NAME"),
SQLTools.getStringFromSQLClob(cachedRowSet, "TraceHttpComponentHeader_VALUE")
)
);
}
}
private void mapHttpComponentQuery(CachedRowSet cachedRowSet, ComponentHttpTraceBuilder componentTraceBuilder) throws SQLException {
String httpComponentQueryId = cachedRowSet.getString("TraceHttpComponentQuery_ID");
if (httpComponentQueryId != null) {
componentTraceBuilder.getHttpComponentQueries().put(
httpComponentQueryId,
new HttpComponentQueryParameterTrace(
new HttpComponentQueryParameterTraceKey(UUID.fromString(httpComponentQueryId)),
new ComponentTraceKey(UUID.fromString(cachedRowSet.getString("TraceHttpComponentQuery_HTTP_COMP_ID"))),
cachedRowSet.getString("TraceHttpComponentQuery_NAME"),
SQLTools.getStringFromSQLClob(cachedRowSet, "TraceHttpComponentQuery_VALUE")
)
);
}
}
@AllArgsConstructor
@Getter
private abstract class ComponentTraceBuilder {
private final ComponentTraceKey metadataKey;
private final String runId;
private final Long processId;
private final String actionParameter;
private final String componentTypeParameter;
private final String componentName;
private final String componentDescription;
private final Long componentVersion;
public abstract ComponentTrace build();
}
@Getter
@ToString
private class ComponentHttpTraceBuilder extends ComponentTraceBuilder {
public ComponentHttpTraceBuilder(ComponentTraceKey metadataKey, String runId, Long processId, String actionParameter, String componentTypeParameter, String componentName, String componentDescription, Long componentVersion, String connectionName, String type, String endpoint, Map<String, HttpComponentHeaderTrace> httpComponentHeader, Map<String, HttpComponentQueryParameterTrace> httpComponentQueries) {
super(metadataKey, runId, processId, actionParameter, componentTypeParameter, componentName, componentDescription, componentVersion);
this.connectionName = connectionName;
this.type = type;
this.endpoint = endpoint;
this.httpComponentHeader = httpComponentHeader;
this.httpComponentQueries = httpComponentQueries;
}
private final String connectionName;
private final String type;
private final String endpoint;
private Map<String, HttpComponentHeaderTrace> httpComponentHeader;
private Map<String, HttpComponentQueryParameterTrace> httpComponentQueries;
public HttpComponentTrace build() {
return new HttpComponentTrace(
getMetadataKey(), getRunId(), getProcessId(), getActionParameter(),
getComponentTypeParameter(), getComponentName()
, getComponentDescription(), getComponentVersion()
, connectionName, type, endpoint,
new ArrayList<>(getHttpComponentHeader().values()),
new ArrayList<>(getHttpComponentQueries().values())
);
}
}
}
| 67.956679 | 412 | 0.679292 |
d2774007cd4a367c2e96134de7cee96dbb902760 | 1,561 | package problems.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/copy-list-with-random-pointer/
*/
public class CopyListWithRandomPointer {
private static class Node {
final int val;
Node next;
Node random;
Node(int val, Node next, Node random) {
this.val = val;
this.next = next;
this.random = random;
}
}
public static Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Map<Node, Node> oldToNew = new HashMap<>();
Node copyHead = copyRandomList(head, oldToNew);
Node orgCurr = head, copyCurr = copyHead;
for (int i = 0; i < oldToNew.size(); i++) {
copyCurr.random = oldToNew.get(orgCurr.random);
orgCurr = orgCurr.next;
copyCurr = copyCurr.next;
}
return copyHead;
}
private static Node copyRandomList(Node node, Map<Node, Node> oldToNew) {
if (node == null) {
return null;
}
Node copyHead = new Node(node.val, null, null), copyTail = copyHead;
oldToNew.put(node, copyHead);
while (node != null) {
Node next = node.next;
if (next != null) {
Node copy = new Node(next.val, null, null);
copyTail.next = copy;
copyTail = copy;
oldToNew.put(next, copy);
}
node = next;
}
return copyHead;
}
}
| 24.015385 | 77 | 0.525304 |
e31aed0d25f1fb38f5ff71f59f27636096a91493 | 469 | package com.Thiiamas.SpringCourse.Repository;
import com.Thiiamas.SpringCourse.Models.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
| 26.055556 | 71 | 0.818763 |
cbc2f04de49b2192dac43289cbeb5b481e8035ff | 2,995 | package com.hsiao.security.config;
import com.hsiao.security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Security 配置类
*/
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
com.hsiao.security.config.BackdoorAuthenticationProvider backdoorAuthenticationProvider;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
* 在内存中创建一个名为 "user" 的用户,密码为 "pwd",拥有 "USER" 权限,密码使用BCryptPasswordEncoder加密
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("user").password(new BCryptPasswordEncoder().encode("pwd")).roles("USER");
/**
* 在内存中创建一个名为 "admin" 的用户,密码为 "pwd",拥有 "USER" 和"ADMIN"权限
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("pwd")).roles("USER","ADMIN");
//将自定义验证类注册进去
auth.authenticationProvider(backdoorAuthenticationProvider);
//加入数据库验证类,下面的语句实际上在验证链中加入了一个DaoAuthenticationProvider
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
// JDBC 验证
/*auth.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("user").roles("USER").and()
.withUser("admin").password("admin").roles("ADMIN");*/
}
/**
* 匹配 "/","/index" 路径,不需要权限即可访问
* 匹配 "/user" 及其以下所有路径,都需要 "USER" 权限
* 匹配 "/admin" 及其以下所有路径,都需要 "ADMIN" 权限
* 登录地址为 "/login",登录成功默认跳转到页面 "/user"
* 退出登录的地址为 "/logout",退出成功后跳转到页面 "/login"
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/index","/error").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/user")
//1.自定义参数名称,与login.html中的参数对应
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login");
}
}
| 42.785714 | 109 | 0.666444 |
bd31eea2b384d7dad6fa82be56b0e9d4efcb29d5 | 2,530 | /*! ******************************************************************************
*
* Hop : The Hop Orchestration Platform
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.apache.hop.ui.i18n;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.logging.ILogChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Read the messages files for the source folders of the specified locale.
*
* @author matt
*/
public class SourceStore {
private Map<String, Map<String, List<KeyOccurrence>>> sourcePackageOccurrences;
/**
* message package - MessageStore
*/
private Map<String, MessagesStore> messagesMap;
private String locale;
protected ILogChannel log;
private String sourceFolder;
public SourceStore( ILogChannel log, String locale, String sourceFolder,
Map<String, Map<String, List<KeyOccurrence>>> sourcePackageOccurrences ) {
this.log = log;
this.locale = locale;
this.sourceFolder = sourceFolder;
this.sourcePackageOccurrences = sourcePackageOccurrences;
messagesMap = new HashMap<String, MessagesStore>();
}
public void read( List<String> directories ) throws HopException {
Map<String, List<KeyOccurrence>> po = sourcePackageOccurrences.get( sourceFolder );
for ( String messagesPackage : po.keySet() ) {
MessagesStore messagesStore =
new MessagesStore( locale, sourceFolder, messagesPackage, sourcePackageOccurrences );
try {
messagesStore.read( directories );
messagesMap.put( messagesPackage, messagesStore );
} catch ( Exception e ) {
// e.printStackTrace();
}
}
}
public Map<String, MessagesStore> getMessagesMap() {
return messagesMap;
}
}
| 32.025316 | 96 | 0.644664 |
767696855429fdfd812cf2a00be1a81c5f657b7a | 1,301 | package gov.fda.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CountrySeriousIncidents {
int deathCount;
int congCount;
int disabilityCount;
int hospitalizationCount;
int lifeThreateningCount;
int unclassifiedCount;
public int getDeathCount() {
return deathCount;
}
public void setDeathCount(int deathCount) {
this.deathCount = deathCount;
}
public int getCongCount() {
return congCount;
}
public void setCongCount(int congCount) {
this.congCount = congCount;
}
public int getDisabilityCount() {
return disabilityCount;
}
public void setDisabilityCount(int disabilityCount) {
this.disabilityCount = disabilityCount;
}
public int getHospitalizationCount() {
return hospitalizationCount;
}
public void setHospitalizationCount(int hospitalizationCount) {
this.hospitalizationCount = hospitalizationCount;
}
public int getLifeThreateningCount() {
return lifeThreateningCount;
}
public void setLifeThreateningCount(int lifeThreateningCount) {
this.lifeThreateningCount = lifeThreateningCount;
}
public int getUnclassifiedCount() {
return unclassifiedCount;
}
public void setUnclassifiedCount(int unclassifiedCount) {
this.unclassifiedCount = unclassifiedCount;
}
}
| 24.54717 | 64 | 0.790161 |
852fd1fcc3738abb3427ff5f752e4a30b3d90560 | 2,960 | package com.dimensiondata.cloud.client.http;
import com.dimensiondata.cloud.client.Filter;
import com.dimensiondata.cloud.client.NodeService;
import com.dimensiondata.cloud.client.OrderBy;
import com.dimensiondata.cloud.client.Param;
import com.dimensiondata.cloud.client.model.*;
import javax.ws.rs.client.Entity;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NodeServiceImpl extends AbstractRestfulService implements NodeService
{
public static final List<String> ORDER_BY_PARAMETERS = Collections.unmodifiableList(Arrays.asList(
PARAMETER_DATACENTER_ID,
PARAMETER_NAME,
PARAMETER_CREATE_TIME));
public static final List<String> FILTER_PARAMETERS = Collections.unmodifiableList(Arrays.asList(
PARAMETER_ID,
PARAMETER_NETWORKDOMAIN_ID,
PARAMETER_DATACENTER_ID,
PARAMETER_NAME,
PARAMETER_STATE,
PARAMETER_CREATE_TIME,
PARAMETER_IPV4ADDRESS,
PARAMETER_IPV6ADDRESS));
public NodeServiceImpl(String baseUrl)
{
super(baseUrl);
}
@Override
public ResponseType createNode(CreateNodeType createNode)
{
return httpClient.post("networkDomainVip/createNode",
new JAXBElement<>(new QName(HttpClient.DEFAULT_NAMESPACE, "createNode"), CreateNodeType.class, createNode),
ResponseType.class);
}
@Override
public Nodes listNodes(int pageSize, int pageNumber, OrderBy orderBy, Filter filter)
{
orderBy.validate(ORDER_BY_PARAMETERS);
filter.validate(FILTER_PARAMETERS);
return httpClient.get("networkDomainVip/node", Nodes.class,
filter.concatenateParameters(
new Param(Param.PAGE_SIZE, pageSize),
new Param(Param.PAGE_NUMBER, pageNumber),
new Param(Param.ORDER_BY, orderBy.concatenateParameters())));
}
@Override
public NodeType getNode(String id)
{
return httpClient.get("networkDomainVip/node/" + id, NodeType.class);
}
@Override
public ResponseType editNode(EditNode editNode)
{
return httpClient.post("networkDomainVip/editNode",
new JAXBElement<>(new QName(HttpClient.DEFAULT_NAMESPACE, "editNode"), EditNode.class, editNode),
ResponseType.class);
}
@Override
public ResponseType deleteNode(String id)
{
return httpClient.post("networkDomainVip/deleteNode",
Entity.xml("<deleteNode xmlns=\"" + HttpClient.DEFAULT_NAMESPACE + "\" id=\"" + id + "\"/>"),
ResponseType.class);
}
@Override
public String getState(String id)
{
return getNode(id).getState();
}
}
| 34.022989 | 124 | 0.651689 |
8bcceb29a152d4516d4f3945c7dde971aeb5ff52 | 1,600 | package com.iba.iot.datasimulator.session.dao;
import com.iba.iot.datasimulator.common.util.ModelEntityUtil;
import com.iba.iot.datasimulator.session.model.Session;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public class SessionDaoImpl implements SessionDao {
/** **/
private static final Logger logger = LoggerFactory.getLogger(SessionDaoImpl.class);
@Autowired
Datastore dataStore;
@Override
public Session save(Session session) {
ModelEntityUtil.updateModified(session);
dataStore.save(session);
return session;
}
@Override
public Collection<Session> get() {
return dataStore.createQuery(Session.class).asList();
}
@Override
public Session get(String sessionId) {
return dataStore.get(Session.class, new ObjectId(sessionId));
}
@Override
public Session update(Session session) {
ModelEntityUtil.updateModified(session);
dataStore.save(session);
return session;
}
@Override
public void remove(String sessionId) {
dataStore.delete(Session.class, new ObjectId(sessionId));
}
@Override
public Collection<Session> getByDataDefinitionId(String dataDefinitionId) {
return dataStore.createQuery(Session.class).field("dataDefinition").equal(new ObjectId(dataDefinitionId)).asList();
}
}
| 27.118644 | 123 | 0.725 |
de2f2ab6c766350dc845d87712a8c9686c01c8db | 10,812 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2021.12.09 um 11:30:16 AM CET
//
package isoxml.iso11783;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlID;
import jakarta.xml.bind.annotation.XmlIDREF;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter;
import jakarta.xml.bind.annotation.adapters.HexBinaryAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{}PRN" maxOccurs="unbounded" minOccurs="0"/>
* </choice>
* <attribute name="A" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}ID">
* <minLength value="4"/>
* <maxLength value="14"/>
* <pattern value="(PDT|PDT-)([0-9])+"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="B" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="32"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="C">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}IDREF">
* <minLength value="4"/>
* <maxLength value="14"/>
* <pattern value="(PGP|PGP-)([0-9])+"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="D">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}IDREF">
* <minLength value="4"/>
* <maxLength value="14"/>
* <pattern value="(VPN|VPN-)([0-9])+"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="E">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}hexBinary">
* <length value="2"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="F">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <enumeration value="1"/>
* <enumeration value="2"/>
* <enumeration value="3"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="G">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}long">
* <minInclusive value="0"/>
* <maxInclusive value="2147483647"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="H">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}long">
* <minInclusive value="0"/>
* <maxInclusive value="2147483647"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="I">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}long">
* <minInclusive value="0"/>
* <maxInclusive value="2147483647"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="J">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}long">
* <minInclusive value="0"/>
* <maxInclusive value="2147483647"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"prn"
})
@XmlRootElement(name = "PDT")
public class PDT {
@XmlElement(name = "PRN")
protected List<PRN> prn;
@XmlAttribute(name = "A", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String a;
@XmlAttribute(name = "B", required = true)
protected String b;
@XmlAttribute(name = "C")
@XmlIDREF
protected Object c;
@XmlAttribute(name = "D")
@XmlIDREF
protected Object d;
@XmlAttribute(name = "E")
@XmlJavaTypeAdapter(HexBinaryAdapter.class)
protected byte[] e;
@XmlAttribute(name = "F")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String f;
@XmlAttribute(name = "G")
protected Integer g;
@XmlAttribute(name = "H")
protected Integer h;
@XmlAttribute(name = "I")
protected Integer i;
@XmlAttribute(name = "J")
protected Integer j;
/**
* Gets the value of the prn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPRN().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PRN }
*
*
*/
public List<PRN> getPRN() {
if (prn == null) {
prn = new ArrayList<PRN>();
}
return this.prn;
}
/**
* Ruft den Wert der a-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getA() {
return a;
}
/**
* Legt den Wert der a-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setA(String value) {
this.a = value;
}
/**
* Ruft den Wert der b-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getB() {
return b;
}
/**
* Legt den Wert der b-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setB(String value) {
this.b = value;
}
/**
* Ruft den Wert der c-Eigenschaft ab.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getC() {
return c;
}
/**
* Legt den Wert der c-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setC(Object value) {
this.c = value;
}
/**
* Ruft den Wert der d-Eigenschaft ab.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getD() {
return d;
}
/**
* Legt den Wert der d-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setD(Object value) {
this.d = value;
}
/**
* Ruft den Wert der e-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public byte[] getE() {
return e;
}
/**
* Legt den Wert der e-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setE(byte[] value) {
this.e = value;
}
/**
* Ruft den Wert der f-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getF() {
return f;
}
/**
* Legt den Wert der f-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setF(String value) {
this.f = value;
}
/**
* Ruft den Wert der g-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getG() {
return g;
}
/**
* Legt den Wert der g-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setG(Integer value) {
this.g = value;
}
/**
* Ruft den Wert der h-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getH() {
return h;
}
/**
* Legt den Wert der h-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setH(Integer value) {
this.h = value;
}
/**
* Ruft den Wert der i-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getI() {
return i;
}
/**
* Legt den Wert der i-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setI(Integer value) {
this.i = value;
}
/**
* Ruft den Wert der j-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getJ() {
return j;
}
/**
* Legt den Wert der j-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setJ(Integer value) {
this.j = value;
}
}
| 24.912442 | 127 | 0.517851 |
3c154fa9468cd87ecd80451203c4f99923445758 | 852 | package me.rayentwickler.flashcard;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyReader {
private Properties prop = new Properties();
public String getProperty(String key){
return prop.getProperty(key);
}
public PropertyReader() {
InputStream input = null;
try {
String filename = "project.properties";
input = PropertyReader.class.getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
// load a properties file from class path, inside static method
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 20.780488 | 79 | 0.674883 |
d47760b88c0adaa0f69cd86b4687cbc6c54d4475 | 1,142 | package seawave.day21.chario;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Demo4_Buffered {
/**
* @param args
* 带缓冲区的流中的特殊方法
* readLine()
* newLine();
*
* newLine()与\r\n的区别
* newLine()是跨平台的方法
* \r\n只支持的是windows系统
* @throws IOException
*/
public static void main(String[] args) throws IOException {
demo1();
demo2();
}
public static void demo2() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("zzz.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("aaa.txt"));
String line;
while((line = br.readLine()) != null) {
bw.write(line);
//bw.newLine(); //写出回车换行符
//bw.write("\r\n");
}
br.close();
bw.close();
}
public static void demo1() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("zzz.txt"));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
| 20.392857 | 71 | 0.676007 |
23fd1c688e6f6a569e325839ff860a4211cb8dc1 | 2,868 | package com.poianitibaldizhou.trackme.apigateway.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.poianitibaldizhou.trackme.apigateway.assembler.UserAssembler;
import com.poianitibaldizhou.trackme.apigateway.entity.User;
import com.poianitibaldizhou.trackme.apigateway.service.UserAuthenticationService;
import com.poianitibaldizhou.trackme.apigateway.service.UserAccountManagerService;
import com.poianitibaldizhou.trackme.apigateway.util.Constants;
import com.poianitibaldizhou.trackme.apigateway.util.Views;
import org.springframework.hateoas.Resource;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotNull;
/**
* Entry point for accessing the service that regards the account of users that are secured.
* Indeed, authentication is needed in order to access the methods provided here.
*/
@RestController
@RequestMapping(path = Constants.SECURED_USER_API)
public class SecuredUserController {
private final UserAccountManagerService service;
private final UserAssembler userAssembler;
private final UserAuthenticationService userAuthenticationService;
/**
* Creates a new entry point for accessing the services that regard the accounts
* of users
*
* @param userAccountManagerService service that manages the user accounts: needed
* in order to access the business function of the service
* @param userAssembler assembler for user that adds hal content
* @param userAuthenticationService service that manages the authentication of users
*/
SecuredUserController(UserAccountManagerService userAccountManagerService,
UserAssembler userAssembler,
UserAuthenticationService userAuthenticationService) {
this.service = userAccountManagerService;
this.userAssembler = userAssembler;
this.userAuthenticationService = userAuthenticationService;
}
/**
* This method will return information the specified user
*
* @param user user that will be returned
* @return resource containing the user and useful links
*/
@JsonView(Views.Public.class)
@GetMapping(Constants.GET_USER_INFO_API)
public @ResponseBody Resource<User> getUser(@NotNull @AuthenticationPrincipal final User user) {
return userAssembler.toResource(service.getUserBySsn(user.getSsn()));
}
/**
* Logout the user that has called the method
*
* @param user user to logout
* @return true
*/
@PostMapping(Constants.LOGOUT_USER_API)
public @ResponseBody boolean logout(@NotNull @AuthenticationPrincipal final User user) {
userAuthenticationService.userLogout(user);
return true;
}
}
| 40.394366 | 100 | 0.751743 |
557bace7ea983597e6572399ca4c05f3ef9e3590 | 3,866 | package com.kl.tradingbot.user.infrastructure.common.model;
import com.kl.tradingbot.user.infrastructure.common.annotations.Password;
import com.kl.tradingbot.user.infrastructure.common.annotations.PasswordMatching;
import com.kl.tradingbot.user.infrastructure.common.annotations.UniqueEmail;
import com.kl.tradingbot.user.infrastructure.common.annotations.UniqueUsername;
import java.io.Serializable;
import java.util.Objects;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.core.style.ToStringCreator;
@PasswordMatching
public class UserRegisterBindingModel implements Serializable {
public static final String USER_INVALID_EMAIL_MESSAGE = "Invalid e-mail address.";
public static final String USER_INVALID_USERNAME_MESSAGE = "Username should be at least 4 and maximum 16 characters long.";
public static final String USER_INVALID_FIRST_NAME_MESSAGE = "First Name must start with a capital letter and must contain only letters.";
public static final String USER_INVALID_LAST_NAME_MESSAGE = "Last Name must start with a capital letter and must contain only letters.";
public static final String USER_INVALID_PASSWORD_MESSAGE = "Invalid Password format.";
private String username;
private String email;
private String password;
private String confirmPassword;
private String firstName;
private String lastName;
private String profilePicUrl;
public UserRegisterBindingModel() {
}
@Pattern(regexp = "^([a-zA-Z0-9]+)$")
@Size(min = 4, max = 16, message = USER_INVALID_USERNAME_MESSAGE)
@UniqueUsername
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$", message = USER_INVALID_EMAIL_MESSAGE)
@UniqueEmail
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Password(minLength = 4, maxLength = 16, containsOnlyLettersAndDigits = true, message = USER_INVALID_PASSWORD_MESSAGE)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return this.confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
@Pattern(regexp = "^[A-Z]([a-zA-Z]+)?$", message = USER_INVALID_FIRST_NAME_MESSAGE)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Pattern(regexp = "^[A-Z]([a-zA-Z]+)?$", message = USER_INVALID_LAST_NAME_MESSAGE)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getProfilePicUrl() {
return this.profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserRegisterBindingModel that = (UserRegisterBindingModel) o;
return username.equals(that.username) && email.equals(that.email);
}
@Override
public int hashCode() {
return Objects.hash(username, email);
}
@Override
public String toString() {
return new ToStringCreator(this)
.append("username", username)
.append("email", email)
.append("password", password)
.append("confirmPassword", confirmPassword)
.append("firstName", firstName)
.append("lastName", lastName)
.append("profilePicUrl", profilePicUrl)
.toString();
}
}
| 30.203125 | 140 | 0.724521 |
c5206d694220a45200355f97f606005e0f97cd36 | 1,642 | package us.ihmc.robotics.geometry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Disabled;
import us.ihmc.euclid.geometry.ConvexPolygon2D;
import us.ihmc.euclid.geometry.interfaces.Vertex2DSupplier;
import us.ihmc.euclid.referenceFrame.FrameConvexPolygon2D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.tools.ReferenceFrameTools;
public class FrameConvexPolygon2dTest
{
private final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame();
private ConvexPolygon2D convexPolygon2d;
private FrameConvexPolygon2D frameConvexPolygon2d;
@BeforeEach
public void setUp()
{
convexPolygon2d = createSomeValidPolygon();
frameConvexPolygon2d = new FrameConvexPolygon2D(worldFrame, convexPolygon2d);
}
@AfterEach
public void tearDown()
{
ReferenceFrameTools.clearWorldFrameTree();
}
@Test
public void thereIsNoTestHere()
{
}
private ConvexPolygon2D createSomeValidPolygon()
{
double[][] polygonPoints = new double[][]
{
{-0.05107802536335158, 0.04155594197133163}, {-0.05052044462374434, 0.1431544119584275}, {0.12219695435431863, 0.14220652470109518},
{0.12219695435431865, -0.041946248489056696}, {0.12163937361471142, -0.1435447184761526}, {-0.05107802536335154, -0.14259683121882027}
};
ConvexPolygon2D polygon = new ConvexPolygon2D(Vertex2DSupplier.asVertex2DSupplier(polygonPoints));
return polygon;
}
}
| 30.407407 | 149 | 0.746041 |
200a1189f835a2f190b16c57449cab7707043165 | 1,665 | package cn.exrick.sso.service.impl;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.common.utils.QiniuUtil;
import cn.exrick.manager.dto.front.Member;
import cn.exrick.manager.mapper.TbMemberMapper;
import cn.exrick.manager.pojo.TbMember;
import cn.exrick.sso.service.LoginService;
import cn.exrick.sso.service.MemberService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* @author Exrickx
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private LoginService loginService;
@Autowired
private TbMemberMapper tbMemberMapper;
@Autowired
private JedisClient jedisClient;
@Value("${SESSION_EXPIRE}")
private Integer SESSION_EXPIRE;
@Override
public String imageUpload(Long userId,String token,String imgData) {
//过滤data:URL
String base64=QiniuUtil.base64Data(imgData);
String imgPath= QiniuUtil.qiniuBase64Upload(base64);
TbMember tbMember=tbMemberMapper.selectByPrimaryKey(userId);
if(tbMember==null){
throw new XmallException("通过id获取用户失败");
}
tbMember.setFile(imgPath);
if(tbMemberMapper.updateByPrimaryKey(tbMember)!=1){
throw new XmallException("更新用户头像失败");
}
//更新缓存
Member member=loginService.getUserByToken(token);
member.setFile(imgPath);
jedisClient.set("SESSION:" + token, new Gson().toJson(member));
return imgPath;
}
}
| 30.833333 | 72 | 0.727327 |
9c775f1eb389732257e450fa1951692af304f2ea | 10,096 | package ga.findparty.findparty.profile;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import ga.findparty.findparty.BaseActivity;
import ga.findparty.findparty.Information;
import ga.findparty.findparty.R;
import ga.findparty.findparty.StartActivity;
import ga.findparty.findparty.util.ParsePHP;
public class RecommendListActivity extends BaseActivity {
private MyHandler handler = new MyHandler();
private final int MSG_MESSAGE_MAKE_LIST = 500;
private final int MSG_MESSAGE_SHOW_LOADING = 501;
private final int MSG_MESSAGE_REFRESH_LIST = 502;
private final int MSG_MESSAGE_ERROR = 503;
private final int MSG_MESSAGE_SUCCESS_RECOMMEND = 504;
private final int MSG_MESSAGE_SUCCESS_UNRECOMMEND = 505;
private FrameLayout root;
private Button closeBtn;
private LinearLayout li_recommendField;
private AVLoadingIndicatorView loading;
private MaterialDialog progressDialog;
private String userId;
private HashMap<String, String> recommendedInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recommend_list);
Intent intent = getIntent();
userId = intent.getStringExtra("userId");
//recommendedList = new ArrayList<>();
recommendedInfo = new HashMap<>();
init();
getRecommendedList();
}
private void init(){
progressDialog = new MaterialDialog.Builder(this)
.content("잠시만 기다려주세요.")
.progress(true, 0)
.progressIndeterminateStyle(true)
.theme(Theme.LIGHT)
.build();
root = (FrameLayout)findViewById(R.id.root);
root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RecommendListActivity.super.onBackPressed();
}
});
closeBtn = (Button)findViewById(R.id.close_btn);
closeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RecommendListActivity.super.onBackPressed();
}
});
li_recommendField = (LinearLayout)findViewById(R.id.li_recommend_field);
loading = (AVLoadingIndicatorView)findViewById(R.id.loading);
}
private void makeList(){
li_recommendField.removeAllViews();
for(String f : Information.RECOMMEND_FIELD_LIST){
View v = getLayoutInflater().inflate(R.layout.detail_board_custom_item, null, false);
RelativeLayout rl_background = (RelativeLayout)v.findViewById(R.id.rl_background);
TextView tv_title = (TextView)v.findViewById(R.id.tv_title);
tv_title.setText(f);
TextView tv_number = (TextView)v.findViewById(R.id.tv_number);
tv_number.setVisibility(View.GONE);
TextView tv_currentNumber = (TextView)v.findViewById(R.id.tv_current_number);
tv_currentNumber.setVisibility(View.GONE);
Button applyBtn = (Button)v.findViewById(R.id.applyBtn);
applyBtn.setTag(f);
if(recommendedInfo.containsKey(f)){
rl_background.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_gray));
applyBtn.setText("철회하기");
applyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String field = (String)v.getTag();
unrecommend(field);
}
});
}else{
rl_background.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
applyBtn.setText("추천하기");
applyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String field = (String)v.getTag();
recommend(field);
}
});
}
li_recommendField.addView(v);
}
}
private void unrecommend(String field){
String id = recommendedInfo.get(field);
progressDialog.show();
HashMap<String, String> map = new HashMap<String, String>();
map.put("service", "unrecommendUser");
map.put("id", id);
new ParsePHP(Information.MAIN_SERVER_ADDRESS, map){
@Override
protected void afterThreadFinish(String data) {
if("1".equals(data)){
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_SHOW_LOADING));
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_REFRESH_LIST));
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_SUCCESS_UNRECOMMEND));
}else{
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_ERROR));
}
}
}.start();
}
private void recommend(String field){
progressDialog.show();
HashMap<String, String> map = new HashMap<String, String>();
map.put("service", "recommendUser");
map.put("userId", getUserID(this));
map.put("recipientId", userId);
map.put("field", field);
new ParsePHP(Information.MAIN_SERVER_ADDRESS, map){
@Override
protected void afterThreadFinish(String data) {
if("1".equals(data)){
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_SHOW_LOADING));
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_REFRESH_LIST));
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_SUCCESS_RECOMMEND));
}else{
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_ERROR));
}
}
}.start();
}
private void getRecommendedList(){
HashMap<String, String> map = new HashMap<String, String>();
map.put("service", "getRecommendedList");
map.put("userId", getUserID(this));
map.put("recipientId", userId);
loading.show();
new ParsePHP(Information.MAIN_SERVER_ADDRESS, map) {
@Override
protected void afterThreadFinish(String data) {
try {
// PHP에서 받아온 JSON 데이터를 JSON오브젝트로 변환
JSONObject jObject = new JSONObject(data);
// results라는 key는 JSON배열로 되어있다.
JSONArray results = jObject.getJSONArray("result");
String countTemp = (String) jObject.get("num_result");
int count = Integer.parseInt(countTemp);
//recommendedList.clear();
recommendedInfo.clear();
for (int i = 0; i < count; ++i) {
JSONObject temp = results.getJSONObject(i);
//recommendedList.add((String) temp.get("field"));
recommendedInfo.put((String) temp.get("field"), (String) temp.get("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MAKE_LIST));
}
}.start();
}
private class MyHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MESSAGE_MAKE_LIST:
loading.hide();
makeList();
break;
case MSG_MESSAGE_SHOW_LOADING:
loading.show();
break;
case MSG_MESSAGE_REFRESH_LIST:
progressDialog.hide();
getRecommendedList();
break;
case MSG_MESSAGE_SUCCESS_RECOMMEND:
setResult(ProfileActivity.UPDATE_RECOMMEND_LIST);
new MaterialDialog.Builder(RecommendListActivity.this)
.title("성공")
.content("성공적으로 추천하였습니다.")
.positiveText("확인")
.show();
break;
case MSG_MESSAGE_SUCCESS_UNRECOMMEND:
setResult(ProfileActivity.UPDATE_RECOMMEND_LIST);
new MaterialDialog.Builder(RecommendListActivity.this)
.title("성공")
.content("성공적으로 철회하였습니다.")
.positiveText("확인")
.show();
break;
case MSG_MESSAGE_ERROR:
new MaterialDialog.Builder(RecommendListActivity.this)
.title("오류")
.content("잠시 후 다시시도해주세요.")
.positiveText("확인")
.show();
break;
default:
break;
}
}
}
@Override
public void onDestroy(){
super.onDestroy();
if(progressDialog != null){
progressDialog.dismiss();
}
}
}
| 33.765886 | 120 | 0.575079 |
522ca7a12702317c56ebbb1bdcbdb4f343526cc8 | 8,898 | package org.apereo.cas.qr.validation;
import org.apereo.cas.authentication.AuthenticationException;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.mock.MockTicketGrantingTicket;
import org.apereo.cas.qr.BaseQRAuthenticationTokenValidatorServiceTests;
import org.apereo.cas.qr.QRAuthenticationConstants;
import org.apereo.cas.qr.authentication.QRAuthenticationDeviceRepository;
import org.apereo.cas.ticket.InvalidTicketException;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.token.JwtBuilder;
import org.apereo.cas.util.DateTimeUtils;
import lombok.val;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.Clock;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link DefaultQRAuthenticationTokenValidatorServiceTests}.
*
* @author Misagh Moayyed
* @since 6.3.0
*/
@Tag("Authentication")
@SpringBootTest(classes = BaseQRAuthenticationTokenValidatorServiceTests.SharedTestConfiguration.class,
properties = "cas.authn.qr.json.location=file:${java.io.tmpdir}/cas-qr-devices.json")
public class DefaultQRAuthenticationTokenValidatorServiceTests {
@Autowired
@Qualifier("tokenTicketJwtBuilder")
private JwtBuilder jwtBuilder;
@Autowired
@Qualifier("ticketRegistry")
private TicketRegistry ticketRegistry;
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("qrAuthenticationTokenValidatorService")
private QRAuthenticationTokenValidatorService qrAuthenticationTokenValidatorService;
@Autowired
@Qualifier("qrAuthenticationDeviceRepository")
private QRAuthenticationDeviceRepository qrAuthenticationDeviceRepository;
@BeforeEach
public void beforeEach() {
qrAuthenticationDeviceRepository.removeAll();
}
@Test
public void verifyUnknownTicket() {
val payload = JwtBuilder.JwtRequest.builder()
.subject("casuser")
.jwtId("unknown-id")
.serviceAudience("https://example.com/normal/")
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(UUID.randomUUID().toString())
.build();
assertThrows(InvalidTicketException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
@Test
public void verifyExpiredJwt() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val payload = JwtBuilder.JwtRequest.builder()
.subject("casuser")
.jwtId(tgt.getId())
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).minusDays(1)))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(UUID.randomUUID().toString())
.build();
assertThrows(AuthenticationException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
@Test
public void verifyBadSubject() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val payload = JwtBuilder.JwtRequest.builder()
.subject("unknown")
.jwtId(tgt.getId())
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).plusDays(1)))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(UUID.randomUUID().toString())
.build();
assertThrows(AuthenticationException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
@Test
public void verifyBadIssuer() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val payload = JwtBuilder.JwtRequest.builder()
.subject(tgt.getAuthentication().getPrincipal().getId())
.jwtId(tgt.getId())
.issuer("unknown")
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).plusDays(1)))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(UUID.randomUUID().toString())
.build();
assertThrows(AuthenticationException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
@Test
public void verifyUnauhzDevice() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val deviceId = UUID.randomUUID().toString();
val payload = JwtBuilder.JwtRequest.builder()
.subject(tgt.getAuthentication().getPrincipal().getId())
.jwtId(tgt.getId())
.issuer(casProperties.getServer().getPrefix())
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).plusDays(1)))
.attributes(Map.of(QRAuthenticationConstants.QR_AUTHENTICATION_DEVICE_ID, List.of(deviceId)))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(deviceId)
.build();
assertThrows(AuthenticationException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
@Test
public void verifySuccess() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val deviceId = UUID.randomUUID().toString();
qrAuthenticationDeviceRepository.authorizeDeviceFor(deviceId, tgt.getAuthentication().getPrincipal().getId());
val payload = JwtBuilder.JwtRequest.builder()
.subject(tgt.getAuthentication().getPrincipal().getId())
.jwtId(tgt.getId())
.issuer(casProperties.getServer().getPrefix())
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).plusDays(1)))
.attributes(Map.of(QRAuthenticationConstants.QR_AUTHENTICATION_DEVICE_ID, List.of(deviceId)))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(deviceId)
.build();
val res = qrAuthenticationTokenValidatorService.validate(request);
assertNotNull(res.getAuthentication());
}
@Test
public void verifyBadDeviceId() {
val tgt = new MockTicketGrantingTicket("casuser");
ticketRegistry.addTicket(tgt);
val deviceId = UUID.randomUUID().toString();
qrAuthenticationDeviceRepository.authorizeDeviceFor(deviceId, tgt.getAuthentication().getPrincipal().getId());
val payload = JwtBuilder.JwtRequest.builder()
.subject(tgt.getAuthentication().getPrincipal().getId())
.jwtId(tgt.getId())
.issuer(casProperties.getServer().getPrefix())
.serviceAudience("https://example.com/normal/")
.validUntilDate(DateTimeUtils.dateOf(LocalDate.now(Clock.systemUTC()).plusDays(1)))
.attributes(Map.of(QRAuthenticationConstants.QR_AUTHENTICATION_DEVICE_ID, List.of("mismatch")))
.build();
val jwt = jwtBuilder.build(payload);
val request = QRAuthenticationTokenValidationRequest.builder()
.registeredService(Optional.empty())
.token(jwt)
.deviceId(deviceId)
.build();
assertThrows(AuthenticationException.class,
() -> qrAuthenticationTokenValidatorService.validate(request));
}
}
| 39.546667 | 118 | 0.67532 |
90672b74c1bebdc04caf7b98831496d27e34c5f5 | 1,527 | package com.ufc.br.model;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
public class Prato {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long codigo;
@NotBlank(message = "Campo nome obrigatorio")
private String nome;
@NotNull(message = "Campo time obrigatorio")
private BigDecimal preco;
@OneToMany(mappedBy = "prato", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<ItemSacola> itens;
public Long getCodigo() {
return codigo;
}
public void setCodigo(Long codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public Prato() {
}
public Prato(Long codigo, @NotBlank(message = "Campo nome obrigatorio") String nome,
@NotNull(message = "Campo time obrigatorio") BigDecimal preco) {
this.codigo = codigo;
this.nome = nome;
this.preco = preco;
}
}
| 23.136364 | 85 | 0.751801 |
c5862bd125d512509c66e5464dcf9a79e4cace58 | 11,978 | /*
* Copyright (c) 2016 CA. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.ca.mas.identity.group;
import android.net.Uri;
import androidx.annotation.Keep;
import android.text.TextUtils;
import android.util.Log;
import com.ca.mas.foundation.FoundationConsts;
import com.ca.mas.foundation.MAS;
import com.ca.mas.foundation.MASCallback;
import com.ca.mas.foundation.MASGroup;
import com.ca.mas.foundation.MASRequest;
import com.ca.mas.foundation.MASRequestBody;
import com.ca.mas.foundation.MASResponse;
import com.ca.mas.foundation.MASResponseBody;
import com.ca.mas.foundation.notify.Callback;
import com.ca.mas.identity.common.MASFilteredRequest;
import com.ca.mas.identity.util.IdentityConsts;
import com.ca.mas.identity.util.IdentityUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import static com.ca.mas.foundation.MAS.DEBUG;
import static com.ca.mas.foundation.MAS.TAG;
/**
* The <i>GroupIdentityManager</i> behaves as the controller between the MAS SDK and the
* {@link <a href="https://tools.ietf.org/html/rfc7643">SCIM</a>} service. The GroupIdentityManager performs the same type
* of operations as the {@link com.ca.mas.identity.user.MASUserRepository} does for users. A MASGroup can be an enterprise or an
* ad-hoc group. The difference is that an enterprise group cannot be created, updated, or deleted while and ad-hoc group can be created,
* updated, or delete by the group's {@link MASOwner}.
*/
@Keep
public class MASGroupRepositoryImpl implements MASGroupRepository {
@Override
public void getGroupById(String id, final MASCallback<MASGroup> callback) {
MASRequest masRequest = new MASRequest.MASRequestBuilder(Uri.parse(IdentityUtil.getGroupPath()
+ FoundationConsts.FSLASH + id))
.header(IdentityConsts.HEADER_KEY_ACCEPT, IdentityConsts.HEADER_VALUE_ACCEPT)
.header(IdentityConsts.HEADER_KEY_CONTENT_TYPE, IdentityConsts.HEADER_VALUE_CONTENT_TYPE)
.responseBody(MASResponseBody.jsonBody())
.get()
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
try {
Callback.onSuccess(callback, processGroupById(result.getBody().getContent()));
} catch (JSONException je) {
Callback.onError(callback, je);
}
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
}
@Override
public void getGroupsByFilter(final MASFilteredRequest filteredRequest, final MASCallback<List<MASGroup>> callback) {
Uri uri = filteredRequest.createUri(MAS.getContext());
MASRequest masRequest = new MASRequest.MASRequestBuilder(uri)
.header(IdentityConsts.HEADER_KEY_ACCEPT, IdentityConsts.HEADER_VALUE_ACCEPT)
.header(IdentityConsts.HEADER_KEY_CONTENT_TYPE, IdentityConsts.HEADER_VALUE_CONTENT_TYPE)
.responseBody(MASResponseBody.jsonBody())
.get()
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
try {
Callback.onSuccess(callback, parse(result.getBody().getContent()));
} catch (JSONException je) {
Callback.onError(callback, je);
}
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
}
private void createAdHocGroup(MASGroup group, final MASCallback<MASGroup> callback) {
try {
MASRequest masRequest = new MASRequest.MASRequestBuilder(Uri.parse(IdentityUtil.getGroupPath()))
.header(IdentityConsts.HEADER_KEY_ACCEPT, IdentityConsts.HEADER_VALUE_ACCEPT)
.header(IdentityConsts.HEADER_KEY_CONTENT_TYPE, IdentityConsts.HEADER_VALUE_CONTENT_TYPE)
.responseBody(MASResponseBody.jsonBody())
.post(MASRequestBody.jsonBody(group.getAsJSONObject()))
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
MASGroup group = MASGroup.newInstance();
try {
group.populate(result.getBody().getContent());
Callback.onSuccess(callback, group);
} catch (JSONException je) {
Callback.onError(callback, je);
}
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
} catch (JSONException e) {
Callback.onError(callback, e);
}
}
private void updateAdHocGroup(MASGroup group, MASCallback<MASGroup> callback) {
groupUpdate(group, callback);
}
@Override
public void delete(MASGroup group, final MASCallback<Void> callback) {
String url = IdentityUtil.getGroupPath() + IdentityConsts.FSLASH + group.getId();
MASRequest masRequest = new MASRequest.MASRequestBuilder(Uri.parse(url))
.header(IdentityConsts.HEADER_KEY_ACCEPT, IdentityConsts.HEADER_VALUE_ACCEPT)
.header(IdentityConsts.HEADER_KEY_CONTENT_TYPE, IdentityConsts.HEADER_VALUE_CONTENT_TYPE)
.responseBody(MASResponseBody.jsonBody())
.delete(null)
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
Callback.onSuccess(callback, null);
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
}
@Override
public void getGroupMetaData(final MASCallback<GroupAttributes> callback) {
String schemaPath = IdentityUtil.getSchemasPath() + FoundationConsts.FSLASH;
MASRequest masRequest = new MASRequest.MASRequestBuilder(Uri.parse(schemaPath
+ IdentityConsts.SCHEMA_GROUP))
.responseBody(MASResponseBody.jsonBody())
.get()
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
try {
Callback.onSuccess(callback, doPopulateAttributes(result.getBody().getContent()));
} catch (JSONException e) {
Callback.onError(callback, e);
}
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
}
@Override
public void save(MASGroup group, MASCallback<MASGroup> callback) {
if (group.getId() == null) {
createAdHocGroup(group, callback);
} else {
updateAdHocGroup(group, callback);
}
}
private GroupAttributes doPopulateAttributes(JSONObject jsonObject) throws JSONException {
String id = jsonObject.optString(IdentityConsts.KEY_ID);
if (TextUtils.isEmpty(id)) {
throw new IllegalArgumentException("The ID cannot be null!");
}
// -------- GROUP ATTRIBUTES ------------------------------
if (id.equals(IdentityConsts.SCHEMA_GROUP)) {
GroupAttributes groupAttributes = new GroupAttributes();
groupAttributes.populate(jsonObject);
return groupAttributes;
} else {
return null;
}
}
private void groupUpdate(final MASGroup group, final MASCallback<MASGroup> callback) {
try {
String updateUrl = IdentityUtil.getGroupPath() + FoundationConsts.FSLASH + group.getId();
MASRequest masRequest = new MASRequest.MASRequestBuilder(Uri.parse(updateUrl))
.header(IdentityConsts.HEADER_KEY_ACCEPT, IdentityConsts.HEADER_VALUE_ACCEPT)
.header(IdentityConsts.HEADER_KEY_CONTENT_TYPE, IdentityConsts.HEADER_VALUE_CONTENT_TYPE)
.responseBody(MASResponseBody.jsonBody())
.put(MASRequestBody.jsonBody(group.getAsJSONObject()))
.build();
MAS.invoke(masRequest, new MASCallback<MASResponse<JSONObject>>() {
@Override
public void onSuccess(MASResponse<JSONObject> result) {
try {
MASGroup updated = MASGroup.newInstance();
updated.populate(result.getBody().getContent());
Callback.onSuccess(callback, updated);
} catch (JSONException e) {
Callback.onError(callback, e);
}
}
@Override
public void onError(Throwable e) {
Callback.onError(callback, e);
}
});
} catch (JSONException e) {
Callback.onError(callback, e);
}
}
private MASGroup processGroupById(JSONObject jsonObject) throws JSONException {
if (DEBUG) Log.d(TAG,
String.format("Group raw JSON data: %s", jsonObject.toString(4)));
// should only be 1 user
MASGroup group = MASGroup.newInstance();
// get the array 'Resources'
if (jsonObject.has(IdentityConsts.KEY_RESOURCES)) {
JSONArray jsonArray = jsonObject.getJSONArray(IdentityConsts.KEY_RESOURCES);
// <i>setTotalResults</i> can be called repeatedly. Calling it with
// the same value that it is currently set does not alter the functionality.
int totalResults = jsonObject.optInt(IdentityConsts.KEY_TOTAL_RESULTS);
if (totalResults != 1) {
throw new IllegalStateException("Should not return more than 1 group");
}
// extract the object from the JSONArray - verified that there is only 1 by this point
JSONObject arrElem = jsonArray.getJSONObject(0);
group.populate(arrElem);
} else {
group.populate(jsonObject);
}
return group;
}
private List<MASGroup> parse(JSONObject jsonObject) throws JSONException {
List<MASGroup> result = new ArrayList<>();
// get the array 'Resources'
if (jsonObject.has(IdentityConsts.KEY_RESOURCES)) {
JSONArray jsonArray = jsonObject.getJSONArray(IdentityConsts.KEY_RESOURCES);
// <i>setTotalResults</i> can be called repeatedly. Calling it with
// the same value that it is currently set does not alter the functionality.
//int totalResults = jsonObject.optInt(IdentityConsts.KEY_TOTAL_RESULTS);
if (jsonArray.length() > 0) {
// iterate through the array, creating a user for each entry
for (int i = 0; i < jsonArray.length(); i++) {
MASGroup ident = MASGroup.newInstance();
JSONObject arrElem = jsonArray.getJSONObject(i);
ident.populate(arrElem);
result.add(ident);
}
}
}
return result;
}
}
| 41.020548 | 137 | 0.608282 |
395b1c8ca809cd5438ef98cbab924d5b357f7c75 | 1,481 | package uk.ac.ebi.atlas.model.resource;
import org.junit.Test;
import uk.ac.ebi.atlas.solr.bioentities.BioentityProperty;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class BioentityPropertyFileTest {
private BioentityPropertyFile testFile = new BioentityPropertyFile(null, null) {
@Override
public Stream<BioentityProperty> get() {
return null;
}
};
@Test
public void testCleanUpPropertyValue() {
assertThat(
testFile.cleanUpPropertyValue("BRCA1"),
is("BRCA1")
);
assertThat(
testFile.cleanUpPropertyValue("zinc finger"),
is("zinc finger")
);
assertThat(
testFile.cleanUpPropertyValue("words with space "),
is("words with space")
);
assertThat(
testFile.cleanUpPropertyValue(
"shoot apex {http://www.co-ode.org/patterns#createdBy=" +
"\\\"http://www.ebi.ac.uk/ontology/webulous#OPPL_pattern\\\"}"),
is("shoot apex")
);
assertThat(
testFile.cleanUpPropertyValue(
"Homeodomain-like/winged-helix DNA-binding family protein [Source:TAIR;Acc:AT1G17520]"),
is("Homeodomain-like/winged-helix DNA-binding family protein")
);
}
}
| 31.510638 | 112 | 0.578663 |
e0711509d2ed26d25d88f24511fbd8afb96cbdb7 | 1,704 | /*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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 io.joynr.messaging.channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.joynr.messaging.FailureAction;
import io.joynr.messaging.IMessagingStub;
import io.joynr.messaging.SuccessAction;
import io.joynr.messaging.http.HttpMessageSender;
import joynr.ImmutableMessage;
import joynr.system.RoutingTypes.ChannelAddress;
public class ChannelMessagingStub implements IMessagingStub {
private static final Logger LOG = LoggerFactory.getLogger(ChannelMessagingStub.class);
private ChannelAddress address;
private HttpMessageSender httpMessageSender;
public ChannelMessagingStub(ChannelAddress address, HttpMessageSender httpMessageSender) {
this.address = address;
this.httpMessageSender = httpMessageSender;
}
@Override
public void transmit(ImmutableMessage message, SuccessAction successAction, FailureAction failureAction) {
LOG.debug(">>> OUTGOING >>> {}", message);
httpMessageSender.sendMessage(address, message.getSerializedMessage(), successAction, failureAction);
}
}
| 35.5 | 110 | 0.757629 |
88a06c252412577ac65794e2c02b2a2a291d28fe | 1,625 | package com.lmn.Arbiter_Android.ProjectStructure;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import com.lmn.Arbiter_Android.R;
public class ProjectAlerts {
private static final String TAG = "ProjectAlerts";
public ProjectAlerts(){
}
public void alertProjectAlreadyExists(Activity activity){
Log.w(TAG, TAG + " alertProjectAlreadyExists");
createAlertDialog(activity, R.string.project_exists_title,
R.string.project_already_exists, R.drawable.icon, null, null);
}
public void alertCreateProjectFailed(Activity activity){
createAlertDialog(activity, R.string.project_creation_failed,
R.string.project_creation_failed_message, R.drawable.icon, null, null);
}
public void createAlertDialog(Activity activity, int title, int message,
int icon, final Runnable okCallback, final Runnable cancelCallback){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setIcon(activity.getResources().getDrawable(icon));
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(okCallback != null){
okCallback.run();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(cancelCallback != null){
cancelCallback.run();
}
}
});
builder.create().show();
}
}
| 28.017241 | 91 | 0.750154 |
d22ac2193a9c670e6a67f5bef5cd5bb973a29ea1 | 592 | package com.example.features.dashboard.view;
import android.view.View;
import com.example.tools.images.ImageLoader;
import com.example.util.other.ViewHolderFactory;
/**
* Assisted injections in dagger via factories.
*/
public class ShotViewHolderFactory implements ViewHolderFactory<ShotViewHolder> {
private final ImageLoader imageLoader;
public ShotViewHolderFactory(ImageLoader imageLoader) {
this.imageLoader = imageLoader;
}
@Override
public ShotViewHolder createViewHolder(View view) {
return new ShotViewHolder(view, imageLoader);
}
}
| 22.769231 | 81 | 0.758446 |
4ea176081fe29b5c1f59b95b8cbf91beca34a77f | 1,646 | /*
* Copyright 2013-2018 (c) MuleSoft, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.raml.jaxrs.generator.builders.extensions.resources;
import com.squareup.javapoet.MethodSpec;
import org.raml.jaxrs.generator.CurrentBuild;
import org.raml.jaxrs.generator.builders.extensions.ContextImpl;
import org.raml.jaxrs.generator.extension.resources.api.ResourceContext;
import org.raml.jaxrs.generator.ramltypes.GMethod;
import org.raml.jaxrs.generator.ramltypes.GRequest;
import org.raml.ramltopojo.RamlToPojo;
/**
* Created by Jean-Philippe Belanger on 1/29/17. Just potential zeroes and ones
*/
public class ResourceContextImpl extends ContextImpl implements ResourceContext {
public ResourceContextImpl(CurrentBuild build) {
super(build);
}
@Override
public MethodSpec.Builder onMethod(ResourceContext context, GMethod method, GRequest gRequest, MethodSpec.Builder methodSpec) {
return getBuildContext().withResourceListeners().onMethod(context, method, gRequest, methodSpec);
}
@Override
public RamlToPojo fetchRamlToPojoBuilder() {
return getBuild().fetchRamlToPojoBuilder();
}
}
| 35.782609 | 129 | 0.777643 |
f40868e0dc4661b1a45e25382820549138cd41b1 | 446 | package demo.boot.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* 启动类
*
* @author leishiguang
* @since v1.0
*/
@EnableWebMvc
@SpringBootApplication
public class BootWebApplication {
public static void main(String[] args) {
SpringApplication.run(BootWebApplication.class);
}
}
| 21.238095 | 70 | 0.784753 |
9b411a4d35a92948acfce00c0330fc1a8170c6b1 | 427 | package com.thebund1st.tiantong.web.webhooks;
import com.thebund1st.tiantong.commands.NotifyOnlinePaymentResultCommand;
/**
* Assembler that converts raw webhook request body to a {@link NotifyOnlinePaymentResultCommand}.
* The signature verification should also be covered here, if any.
*/
public interface NotifyOnlinePaymentResultCommandAssembler {
NotifyOnlinePaymentResultCommand from(String rawNotification);
}
| 32.846154 | 98 | 0.824356 |
bcb940fd687083654016907b5ba80563f33432f5 | 6,316 | package com.singularsys.jeptests.system;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.singularsys.jep.Jep;
import com.singularsys.jep.Operator;
import com.singularsys.jep.OperatorTable2;
import com.singularsys.jep.ParseException;
import com.singularsys.jep.EmptyOperatorTable.OperatorKey;
import com.singularsys.jep.configurableparser.ConfigurableParser;
import com.singularsys.jep.configurableparser.StandardConfigurableParser;
import com.singularsys.jep.parser.Node;
/**
* Tests for the configurable parser.
*/
public class CPTest extends JepTest {
@Override
@Before
public void setUp() {
this.jep = new Jep(new StandardConfigurableParser());
}
enum MyOps implements OperatorKey {
A,B,C,D,E,F,G,H,I,J,K
}
/**
* Tests the addOperator method
*
* @throws ParseException
*/
@Test
public void testAddOp() throws ParseException {
OperatorTable2 ot = (OperatorTable2) jep.getOperatorTable();
Operator preinc = new Operator("preinc", "++", null, Operator.PREFIX + Operator.UNARY);
Operator postinc = new Operator("postinc", "++", null, Operator.SUFFIX + Operator.UNARY);
Operator predec = new Operator("predec", "--", null, Operator.PREFIX + Operator.UNARY);
Operator postdec = new Operator("postdec", "--", null, Operator.SUFFIX + Operator.UNARY);
Operator bitcomp = new Operator("bitcomp", "~", null, Operator.PREFIX + Operator.UNARY);
Operator lshift = new Operator("<<", null, Operator.BINARY + Operator.LEFT);
Operator rshift = new Operator(">>", null, Operator.BINARY + Operator.LEFT);
Operator rshift0 = new Operator(">>>", null, Operator.BINARY + Operator.LEFT);
Operator bitand = new Operator("&", null, Operator.BINARY + Operator.LEFT);
Operator bitor = new Operator("|", null, Operator.BINARY + Operator.LEFT);
Operator bitxor = new Operator("^", null, Operator.BINARY + Operator.LEFT);
ot.addOperator(MyOps.A,preinc, ot.getUMinus());
ot.addOperator(MyOps.B,postinc, preinc);
ot.addOperator(MyOps.C,predec, preinc);
ot.addOperator(MyOps.D,postdec, preinc);
ot.addOperator(MyOps.E,bitcomp, ot.getNot());
ot.insertOperator(MyOps.F,lshift, ot.getLT());
ot.addOperator(MyOps.G,rshift, lshift);
ot.addOperator(MyOps.H,rshift0, lshift);
ot.appendOperator(MyOps.I,bitand, ot.getEQ());
ot.removeOperator(ot.getPower());
ot.appendOperator(MyOps.J,bitxor, bitand);
ot.appendOperator(MyOps.K,bitor, bitxor);
jep.reinitializeComponents();
Node n = jep.parse("x=1");
n = jep.parse("++x");
nodeTest(n, preinc);
n = jep.parse("x++");
nodeTest(n, postinc);
n = jep.parse("--x");
nodeTest(n, predec);
n = jep.parse("x--");
nodeTest(n, postdec);
n = jep.parse("-x");
nodeTest(n, ot.getUMinus());
}
@Test
public void testCPStrings() throws Exception
{
valueTest("'A\\bB\\fC\\nD\\rE\\tF'","A\bB\fC\nD\rE\tF");
valueTest("'A\\u0021B\\u00a3C'","A!B\u00a3C");
valueTest("'A\u0021B\\u00a3C'","A!B\u00a3C");
valueTest("'\7'","\u0007");
valueTest("'\07'","\u0007");
valueTest("'\007'","\u0007");
valueTest("'\7A'","\u0007A");
valueTest("'\07A'","\u0007A");
valueTest("'\007A'","\u0007A");
valueTest("A='1'","1");
valueTest("B='2'","2");
valueTest("(A=='1')&&(B=='2')",myTrue);
valueTest("\"A\\bB\\fC\\nD\\rE\\tF\"","A\bB\fC\nD\rE\tF");
valueTest("\"A\\u0021B\\u00a3C\"","A!B\u00a3C");
valueTest("\"A\u0021B\\u00a3C\"","A!B\u00a3C");
valueTest("\"\7\"","\u0007");
valueTest("\"\07\"","\u0007");
valueTest("\"\007\"","\u0007");
valueTest("\"\7A\"","\u0007A");
valueTest("\"\07A\"","\u0007A");
valueTest("\"\007A\"","\u0007A");
valueTest("A=\"1\"","1");
valueTest("B=\"2\"","2");
valueTest("(A==\"1\")&&(B==\"2\")",myTrue);
}
@Override
@Test
public void testEmptyEqn2() throws Exception
{
String s = "1;;2;\n;3;\n";
printTestHeader("Testing reading multiple with empty equations: "+s);
jep.initMultiParse(s);
ConfigurableParser cp = (ConfigurableParser) jep.getParser();
Node n1 = cp.continueParse();
Object o1 = jep.evaluate(n1);
this.myAssertEquals("1", 1.0,o1);
Node n2 = cp.continueParse();
Object o2 = jep.evaluate(n2);
this.myAssertEquals("2", 2.0,o2);
Node n3 = cp.continueParse();
Object o3 = jep.evaluate(n3);
this.myAssertEquals("3", 3.0,o3);
Node n4 = jep.continueParsing();
assertNull("Next parse should give a null result",n4);
}
@Test
public void testBug61() throws Exception
{
valueTest("a=2",2.0);
valueTest("b=3",3.0);
valueTest("c=4",4.0);
valueTest("d=5",5.0);
valueTest("(a+b+c)/d",(2.+3.+4.)/5.);
}
@Test
public void testMultiDimArrayAccess() throws Exception
{
printTestHeader("Testing multidim array access");
valueTestString("x=[[1,2],[3,4]]","[[1.0, 2.0], [3.0, 4.0]]");
valueTest("x[2][1]",3.0);
valueTest("x[2][1]=5",5.0);
valueTestString("x","[[1.0, 2.0], [5.0, 4.0]]");
valueTestString("x=[[1,2,3],[4,5,6],[7,8,9]]","[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]");
valueTest("x[2][3]=-1",-1.0);
valueTestString("x","[[1.0, 2.0, 3.0], [4.0, 5.0, -1.0], [7.0, 8.0, 9.0]]");
valueTestString("x=[[[1,2],[3,4]],[[5,6],[7,8]]]",
"[[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]");
valueTest("x[2][1][2]",6.0);
valueTest("x[2][1][2]=-1",-1.0);
valueTestString("x",
"[[[1.0, 2.0], [3.0, 4.0]], [[5.0, -1.0], [7.0, 8.0]]]");
}
@Test
public void testMultiDimArrayPrint() throws Exception
{
printTestHeader("Testing printing of multidim array printing");
String s1 = "x[2.0][1.0]";
Node n1 = jep.parse(s1);
String res = jep.toString(n1);
assertEquals(s1,res);
}
}
| 34.895028 | 109 | 0.564915 |
e2b8272730013ee4ed63bb134036cb1bffeddbfa | 6,643 | package cellularAutomata.reflection;
/*
* This is a 3rd part open source debugging tool which I have altered
* to suit my needs. This class is not used in the distributed version
* of this program.
*/
import java.io.*;
import java.net.URL;
import java.util.StringTokenizer;
import cellularAutomata.util.Debug;
/**
* <code>JWhich</code> is a utility that takes a Java class name and displays
* the absolute pathname of the class file that would be loaded first by the
* class loader, as prescribed by the class path.
* <p>
* <code>JWhich</code> also validates the class path and reports any
* non-existent or invalid class path entries.
* <p>
* Usage is similar to the UNIX <code>which</code> command.
* <p>
* Example uses:
* <p>
* <blockquote>To find the absolute pathname of <code>MyClass.class</code> not
* in a package:
*
* <pre>
*
*
* java JWhich MyClass
*
*
* </pre>
*
* To find the absolute pathname of <code>MyClass.class</code> in the
* <code>my.package</code> package:
*
* <pre>
*
*
* java JWhich my.package.MyClass
*
*
* </pre>
*
* </blockquote>
*
* @author <a href="mailto:[email protected]">Mike Clark </a>
* @author <a href="http://www.clarkware.com">Clarkware Consulting, Inc. </a>
*/
public class JWhich
{
private static String CLASSPATH;
/**
* Prints the absolute pathname of the class file containing the specified
* class name, as prescribed by the class path.
*
* @param className
* Name of the class.
*/
public static void which(String className)
{
URL classUrl = findClass(className);
if(classUrl == null)
{
System.out.println("\nClass '" + className + "' not found.");
}
else
{
System.out.println("\nClass '" + className + "' found in \n'"
+ classUrl.getFile() + "'");
}
validate();
printClasspath();
}
/**
* Prints the absolute pathname of the class file containing the specified
* class name, as prescribed by the class path.
*
* @param className
* Name of the class.
*/
public static String returnWhich(String className)
{
URL classUrl = findClass(className);
String answer = "";
if(classUrl == null)
{
answer = "\nClass '" + className + "' not found.";
}
else
{
answer = "\nClass '" + className + "' found in \n'"
+ classUrl.getFile() + "'";
}
return answer;
}
/**
* Returns the URL of the resource denoted by the specified class name, as
* prescribed by the class path.
*
* @param className
* Name of the class.
* @return Class URL, or null of the class was not found.
*/
public static URL findClass(final String className)
{
return JWhich.class.getResource(asResourceName(className));
}
protected static String asResourceName(String resource)
{
if(!resource.startsWith("/"))
{
resource = "/" + resource;
}
resource = resource.replace('.', '/');
resource = resource + ".class";
return resource;
}
/**
* Validates the class path and reports any non-existent or invalid class
* path entries.
* <p>
* Valid class path entries include directories, <code>.zip</code> files,
* and <code>.jar</code> files.
*/
public static void validate()
{
StringTokenizer tokenizer = new StringTokenizer(getClasspath(),
File.pathSeparator);
while(tokenizer.hasMoreTokens())
{
String element = tokenizer.nextToken();
File f = new File(element);
if(!f.exists())
{
System.out.println("\nClasspath element '" + element + "' "
+ "does not exist.");
}
else if((!f.isDirectory())
&& (!element.toLowerCase().endsWith(".jar"))
&& (!element.toLowerCase().endsWith(".zip")))
{
System.out.println("\nClasspath element '" + element + "' "
+ "is not a directory, .jar file, or .zip file.");
}
}
}
public static void printClasspath()
{
System.out.println("\nClasspath:");
StringTokenizer tokenizer = new StringTokenizer(getClasspath(),
File.pathSeparator);
while(tokenizer.hasMoreTokens())
{
System.out.println(tokenizer.nextToken());
}
}
public static void displayClasspath()
{
String answer = "\nClasspath:";
StringTokenizer tokenizer = new StringTokenizer(getClasspath(),
File.pathSeparator);
while(tokenizer.hasMoreTokens())
{
answer += "\n" + tokenizer.nextToken();
}
Debug.print(new JWhich(), answer);
}
public static void setClasspath(String classpath)
{
CLASSPATH = classpath;
}
protected static String getClasspath()
{
if(CLASSPATH == null)
{
setClasspath(System.getProperty("java.class.path"));
}
return CLASSPATH;
}
private static void instanceMain(String[] args)
{
if(args.length == 0)
{
printUsage();
}
for(int cmdIndex = 0; cmdIndex < args.length; cmdIndex++)
{
String cmd = args[cmdIndex];
if("-help".equals(cmd))
{
printUsage();
}
else
{
which(cmd);
}
}
}
private static void printUsage()
{
System.out.println("\nSyntax: java JWhich [options] className");
System.out.println("");
System.out.println("where options include:");
System.out.println("");
System.out.println("\t-help Prints usage information.");
System.out.println("");
System.out.println("Examples:");
System.out.println("\tjava JWhich MyClass");
System.out.println("\tjava JWhich my.package.MyClass");
System.exit(0);
}
public static void main(String args[])
{
JWhich.instanceMain(args);
}
}
| 25.949219 | 79 | 0.530784 |
cfb14922670b9b049e73920a1c878875472adfd4 | 2,295 | package com.sjl.bookmark.ui.base.extend;
import android.os.Bundle;
import android.view.View;
import com.sjl.bookmark.R;
import com.sjl.core.mvp.BaseActivity;
import androidx.annotation.Nullable;
import cn.feng.skin.manager.loader.SkinManager;
import cn.feng.skin.manager.statusbar.StatusBarUtil;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityBase;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityHelper;
/**
* 重写库中SwipeBackActivity,方便扩展
*
* @author Kelly
* @version 1.0.0
* @filename BaseSwipeBackActivity.java
* @time 2018/3/6 14:16
* @copyright(C) 2018 song
*/
public abstract class BaseSwipeBackActivity extends BaseActivity implements SwipeBackActivityBase {
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
Utils.convertActivityToTranslucent(this);
getSwipeBackLayout().scrollToFinishActivity();
}
/**
* 为滑动返回界面设置状态栏颜色
* 主要适配需要滑动关闭的页面,否则状态栏会出现透明颜色,很难看
*/
protected void setColorForSwipeBack() {
int color = SkinManager.getInstance().getColorPrimary();
int statusBarColor;
if (color != -1) {
statusBarColor = color;
} else {
statusBarColor = getResources().getColor(R.color.colorPrimary);
}
StatusBarUtil.setColorForSwipeBack(this, statusBarColor, 0);
}
}
| 27.321429 | 99 | 0.698039 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.