hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92462fb940d015f9f02d060649da70939142a56d | 3,603 | java | Java | simple-tests/src/test/java/com/cleverbuilder/cameldemos/transform/JsonToJaxbTest.java | samridhis/https---github.com-samridhis-camelexposerest | 3639d7d35abd1c2ec4d76a15ea9e8b03ab5c70fd | [
"Apache-2.0"
] | 58 | 2018-08-10T05:56:20.000Z | 2022-03-12T16:06:33.000Z | simple-tests/src/test/java/com/cleverbuilder/cameldemos/transform/JsonToJaxbTest.java | samridhis/https---github.com-samridhis-camelexposerest | 3639d7d35abd1c2ec4d76a15ea9e8b03ab5c70fd | [
"Apache-2.0"
] | 3 | 2019-07-02T09:58:31.000Z | 2022-02-24T10:28:49.000Z | simple-tests/src/test/java/com/cleverbuilder/cameldemos/transform/JsonToJaxbTest.java | samridhis/https---github.com-samridhis-camelexposerest | 3639d7d35abd1c2ec4d76a15ea9e8b03ab5c70fd | [
"Apache-2.0"
] | 131 | 2018-04-18T17:42:10.000Z | 2022-03-25T12:44:27.000Z | 31.330435 | 113 | 0.59617 | 1,003,681 | package com.cleverbuilder.cameldemos.transform;
import org.apache.camel.EndpointInject;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.model.dataformat.JsonDataFormat;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Reading in a JSON file and converting it to XML via JAXB classes,\
* using a custom TypeConverter in Camel (you could also do this using
* a Processor class)
* Requires: camel-jaxb
*/
public class JsonToJaxbTest extends CamelTestSupport {
@EndpointInject(uri = "mock:output")
MockEndpoint mockOutput;
@Test
public void transformJsonToJaxb() throws InterruptedException {
mockOutput.expectedMessageCount(1);
mockOutput.expectedBodiesReceived("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<album>\n" +
" <accolades>many</accolades>\n" +
" <artist>Cilla Black</artist>\n" +
" <rating>5.0</rating>\n" +
" <title>Surprise Surprise: The Very Best of Cilla Black, with additional remixes</title>\n" +
"</album>\n");
template.sendBody("direct:start",
new File("src/test/data/album.json"));
assertMockEndpointsSatisfied(5, TimeUnit.SECONDS);
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
JsonDataFormat json = new JsonDataFormat(JsonLibrary.Jackson);
JaxbDataFormat jaxb =
new JaxbDataFormat(JAXBContext.newInstance(Album.class));
from("direct:start")
.unmarshal(json)
.log("Body unmarshalled, it is now ${body}")
.to("log:mylogger?showAll=true")
.wireTap("mock:intermediate-step")
.convertBodyTo(Album.class)
.marshal(jaxb)
.log("Body marshalled, it is now ${body}")
.to("mock:output");
}
};
}
/**
* This would be your JAXB class, generated by CXF-XJC-Plugin, or similar.
* We're just writing an ad-hoc one here, for demo purposes.
*/
@XmlRootElement
public static class Album {
private String artist;
private String title;
private String rating;
private String accolades;
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getAccolades() {
return accolades;
}
public void setAccolades(String accolades) {
this.accolades = accolades;
}
}
}
|
924632586514cd8ef87f110f8ec2b434bc6ed228 | 1,509 | java | Java | 2016season/OldCode/Turtwig2016DumbArm.java | FRC1458/turtwig | d98969f2a496eae19a42546391772922208c9228 | [
"MIT"
] | null | null | null | 2016season/OldCode/Turtwig2016DumbArm.java | FRC1458/turtwig | d98969f2a496eae19a42546391772922208c9228 | [
"MIT"
] | null | null | null | 2016season/OldCode/Turtwig2016DumbArm.java | FRC1458/turtwig | d98969f2a496eae19a42546391772922208c9228 | [
"MIT"
] | null | null | null | 30.18 | 74 | 0.787939 | 1,003,682 | package org.usfirst.frc.team1458.robot;
import com.team1458.turtleshell2.implementations.movement.TurtleVictor888;
import com.team1458.turtleshell2.interfaces.input.TurtleAnalogInput;
import com.team1458.turtleshell2.interfaces.input.TurtleDigitalInput;
import com.team1458.turtleshell2.interfaces.movement.TurtleMotor;
import com.team1458.turtleshell2.util.types.MotorValue;
public class Turtwig2016DumbArm {
// Xbox axis, when thing pulled, arm moves?
private final TurtleMotor armRight = new TurtleVictor888(
TurtwigConstants.RIGHTINTAKEVICTORPORT);
private final TurtleMotor armLeft = new TurtleVictor888(
TurtwigConstants.LEFTINTAKEVICTORPORT);
private final TurtleMotor armIntake = new TurtleVictor888(
TurtwigConstants.SPININTAKEVICTORSPPORT);
private TurtleAnalogInput armPower;
private TurtleDigitalInput spinForward;
private TurtleDigitalInput spinBackward;
public void setXBoxJoystick(TurtleAnalogInput a) {
armPower = a;
}
public void setLeftXBoxButton(TurtleDigitalInput d) {
spinForward = d;
}
public void setRightXBoxButton(TurtleDigitalInput d) {
spinBackward = d;
}
public void teleUpdate() {
MotorValue armPowerness = new MotorValue(armPower.get());
armRight.set(armPowerness);
armLeft.set(armPowerness);
if (spinForward.get() == 1) {
armIntake.set(MotorValue.fullForward);
} else if (spinBackward.get() == 1) {
armIntake.set(MotorValue.fullBackward);
} else {
armIntake.set(MotorValue.zero);
}
}
public void autoUpdate() {
}
}
|
92463388b724a6d2f4644877e6a4cd7b79ef2225 | 4,169 | java | Java | lealone-db/src/main/java/org/lealone/db/util/IntIntHashMap.java | v64500/Lealone | 73e492b007178a6e2f7aa85eda742a59cd2476c1 | [
"Apache-2.0"
] | 1,483 | 2016-02-27T15:35:36.000Z | 2022-03-31T17:02:03.000Z | lealone-db/src/main/java/org/lealone/db/util/IntIntHashMap.java | fwnan/Lealone | a4c73838a9ae99a1c2a4064034a26fa6dbf34094 | [
"Apache-2.0"
] | 67 | 2016-03-09T04:52:46.000Z | 2022-03-28T03:13:11.000Z | lealone-db/src/main/java/org/lealone/db/util/IntIntHashMap.java | fwnan/Lealone | a4c73838a9ae99a1c2a4064034a26fa6dbf34094 | [
"Apache-2.0"
] | 297 | 2016-02-25T15:17:52.000Z | 2022-03-30T17:04:49.000Z | 27.427632 | 76 | 0.459583 | 1,003,683 | /*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.lealone.db.util;
import org.lealone.common.exceptions.DbException;
/**
* A hash map with int key and int values. There is a restriction: the
* value -1 (NOT_FOUND) cannot be stored in the map. 0 can be stored.
* An empty record has key=0 and value=0.
* A deleted record has key=0 and value=DELETED
*/
public class IntIntHashMap extends HashBase {
/**
* The value indicating that the entry has not been found.
*/
public static final int NOT_FOUND = -1;
private static final int DELETED = 1;
private int[] keys;
private int[] values;
private int zeroValue;
@Override
protected void reset(int newLevel) {
super.reset(newLevel);
keys = new int[len];
values = new int[len];
}
/**
* Store the given key-value pair. The value is overwritten or added.
*
* @param key the key
* @param value the value (-1 is not supported)
*/
public void put(int key, int value) {
if (key == 0) {
zeroKey = true;
zeroValue = value;
return;
}
checkSizePut();
int index = getIndex(key);
int plus = 1;
int deleted = -1;
do {
int k = keys[index];
if (k == 0) {
if (values[index] != DELETED) {
// found an empty record
if (deleted >= 0) {
index = deleted;
deletedCount--;
}
size++;
keys[index] = key;
values[index] = value;
return;
}
// found a deleted record
if (deleted < 0) {
deleted = index;
}
} else if (k == key) {
// update existing
values[index] = value;
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// no space
DbException.throwInternalError("hashmap is full");
}
/**
* Remove the key-value pair with the given key.
*
* @param key the key
*/
public void remove(int key) {
if (key == 0) {
zeroKey = false;
return;
}
checkSizeRemove();
int index = getIndex(key);
int plus = 1;
do {
int k = keys[index];
if (k == key) {
// found the record
keys[index] = 0;
values[index] = DELETED;
deletedCount++;
size--;
return;
} else if (k == 0 && values[index] == 0) {
// found an empty record
return;
}
index = (index + plus++) & mask;
} while (plus <= len);
// not found
}
@Override
protected void rehash(int newLevel) {
int[] oldKeys = keys;
int[] oldValues = values;
reset(newLevel);
for (int i = 0; i < oldKeys.length; i++) {
int k = oldKeys[i];
if (k != 0) {
put(k, oldValues[i]);
}
}
}
/**
* Get the value for the given key. This method returns NOT_FOUND if the
* entry has not been found.
*
* @param key the key
* @return the value or NOT_FOUND
*/
public int get(int key) {
if (key == 0) {
return zeroKey ? zeroValue : NOT_FOUND;
}
int index = getIndex(key);
int plus = 1;
do {
int k = keys[index];
if (k == 0 && values[index] == 0) {
// found an empty record
return NOT_FOUND;
} else if (k == key) {
// found it
return values[index];
}
index = (index + plus++) & mask;
} while (plus <= len);
return NOT_FOUND;
}
}
|
924634a87048e2553ee1f9aa408e082cdd4c3658 | 1,019 | java | Java | src/main/java/com/scaleton/dfinity/candid/annotations/Field.java | rdobrik/dfinity-agent | 1678d240e5bc3be16c601f5e1131320c39bfd0cd | [
"Apache-2.0"
] | 16 | 2021-08-20T06:48:00.000Z | 2022-03-08T08:07:18.000Z | src/main/java/com/scaleton/dfinity/candid/annotations/Field.java | langloisga/dfinity-agent | 1678d240e5bc3be16c601f5e1131320c39bfd0cd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/scaleton/dfinity/candid/annotations/Field.java | langloisga/dfinity-agent | 1678d240e5bc3be16c601f5e1131320c39bfd0cd | [
"Apache-2.0"
] | 5 | 2021-08-20T06:48:03.000Z | 2022-01-10T13:10:47.000Z | 29.970588 | 75 | 0.771344 | 1,003,684 | /*
* Copyright 2021 Exilor Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scaleton.dfinity.candid.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.scaleton.dfinity.candid.types.Type;
@Documented
@Retention(RUNTIME)
@Target(FIELD)
public @interface Field {
public Type value();
}
|
924634b8d068215bab97995ae1ed062ac16c32b5 | 13,809 | java | Java | polardbx-gms/src/main/java/com/alibaba/polardbx/gms/metadb/MetaDbConnectionProxy.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 480 | 2021-10-16T06:00:00.000Z | 2022-03-28T05:54:49.000Z | polardbx-gms/src/main/java/com/alibaba/polardbx/gms/metadb/MetaDbConnectionProxy.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 31 | 2021-10-20T02:59:55.000Z | 2022-03-29T03:38:33.000Z | polardbx-gms/src/main/java/com/alibaba/polardbx/gms/metadb/MetaDbConnectionProxy.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 96 | 2021-10-17T14:19:49.000Z | 2022-03-23T09:25:37.000Z | 27.618 | 119 | 0.691071 | 1,003,685 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.gms.metadb;
import com.alibaba.polardbx.common.jdbc.BatchInsertPolicy;
import com.alibaba.polardbx.common.jdbc.IConnection;
import com.alibaba.polardbx.common.jdbc.ITransactionPolicy;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* @author chenghui.lch
*/
public class MetaDbConnectionProxy implements IConnection {
private static final Logger log = LoggerFactory.getLogger(MetaDbConnectionProxy.class);
protected Connection conn = null;
private String encoding;
private String sqlMode;
private Map<String, Object> serverVariables = null;
private boolean stressTestValid = false;
private Statement currentStatement = null;
public MetaDbConnectionProxy() throws SQLException {
conn = createNewConnection(MetaDbDataSource.getInstance().getDataSource());
}
private Connection createNewConnection(DataSource metaDbDs) throws SQLException {
return metaDbDs.getConnection();
}
@Override
public void setEncoding(String encoding) throws SQLException {
this.encoding = encoding;
}
public Connection getConn() {
return conn;
}
@Override
public void abort(Executor executor) throws SQLException {
conn.abort(executor);
}
@Override
public void clearWarnings() throws SQLException {
conn.clearWarnings();
}
@Override
public void close() throws SQLException {
conn.close();
}
@Override
public void commit() throws SQLException {
conn.commit();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return conn.createArrayOf(typeName, elements);
}
@Override
public Blob createBlob() throws SQLException {
return conn.createBlob();
}
@Override
public Clob createClob() throws SQLException {
return conn.createClob();
}
@Override
public NClob createNClob() throws SQLException {
return conn.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return conn.createSQLXML();
}
@Override
public Statement createStatement() throws SQLException {
currentStatement = conn.createStatement();
return currentStatement;
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
currentStatement = conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
return currentStatement;
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
currentStatement = conn.createStatement(resultSetType, resultSetConcurrency);
return currentStatement;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return conn.createStruct(typeName, attributes);
}
@Override
public boolean getAutoCommit() throws SQLException {
return conn.getAutoCommit();
}
@Override
public String getCatalog() throws SQLException {
return conn.getCatalog();
}
@Override
public Properties getClientInfo() throws SQLException {
return conn.getClientInfo();
}
@Override
public String getClientInfo(String name) throws SQLException {
return conn.getClientInfo(name);
}
@Override
public int getHoldability() throws SQLException {
return conn.getHoldability();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return conn.getMetaData();
}
@Override
public int getNetworkTimeout() throws SQLException {
return 1000;
}
@Override
public String getSchema() throws SQLException {
return conn.getSchema();
}
@Override
public int getTransactionIsolation() throws SQLException {
return conn.getTransactionIsolation();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return conn.getTypeMap();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return conn.getWarnings();
}
@Override
public boolean isClosed() throws SQLException {
return conn.isClosed();
}
@Override
public boolean isReadOnly() throws SQLException {
return conn.isReadOnly();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return conn.isValid(timeout);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return conn.isWrapperFor(iface);
}
@Override
public String nativeSQL(String sql) throws SQLException {
return conn.nativeSQL(sql);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
currentStatement = conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
return (CallableStatement) currentStatement;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
currentStatement = conn.prepareCall(sql, resultSetType, resultSetConcurrency);
return (CallableStatement) currentStatement;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
currentStatement = conn.prepareCall(sql);
return (CallableStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
currentStatement = conn.prepareStatement(sql,
resultSetType,
resultSetConcurrency,
resultSetHoldability);
return (PreparedStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
currentStatement = conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
return (PreparedStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
currentStatement = conn.prepareStatement(sql, autoGeneratedKeys);
return (PreparedStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
currentStatement = conn.prepareStatement(sql, columnIndexes);
return (PreparedStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
currentStatement = conn.prepareStatement(sql, columnNames);
return (PreparedStatement) currentStatement;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
currentStatement = conn.prepareStatement(sql);
return (PreparedStatement) currentStatement;
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
conn.releaseSavepoint(savepoint);
}
@Override
public void rollback() throws SQLException {
conn.rollback();
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
conn.rollback(savepoint);
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
conn.setAutoCommit(autoCommit);
}
@Override
public void setCatalog(String catalog) throws SQLException {
conn.setCatalog(catalog);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
conn.setClientInfo(properties);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
conn.setClientInfo(name, value);
}
@Override
public void setHoldability(int holdability) throws SQLException {
conn.setHoldability(holdability);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
conn.setReadOnly(readOnly);
}
@Override
public Savepoint setSavepoint() throws SQLException {
return conn.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return conn.setSavepoint(name);
}
@Override
public void setSchema(String schema) throws SQLException {
conn.setSchema(schema);
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
conn.setTransactionIsolation(level);
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
conn.setTypeMap(map);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return conn.unwrap(iface);
}
@Override
public void kill() throws SQLException {
Statement stmt = currentStatement;
if (stmt != null && !stmt.isClosed()) {
stmt.cancel();
}
}
@Override
public long getLastInsertId() {
throw new UnsupportedOperationException();
}
@Override
public void setLastInsertId(long id) {
throw new UnsupportedOperationException();
}
@Override
public long getReturnedLastInsertId() {
throw new UnsupportedOperationException();
}
@Override
public void setReturnedLastInsertId(long id) {
throw new UnsupportedOperationException();
}
@Override
public List<Long> getGeneratedKeys() {
throw new UnsupportedOperationException();
}
@Override
public void setGeneratedKeys(List<Long> ids) {
throw new UnsupportedOperationException();
}
@Override
public ITransactionPolicy getTrxPolicy() {
throw new UnsupportedOperationException();
}
@Override
public void setTrxPolicy(ITransactionPolicy trxPolicy) {
throw new UnsupportedOperationException();
}
@Override
public BatchInsertPolicy getBatchInsertPolicy(Map<String, Object> extraCmds) {
throw new UnsupportedOperationException();
}
@Override
public void setBatchInsertPolicy(BatchInsertPolicy policy) {
throw new UnsupportedOperationException();
}
@Override
public String getEncoding() {
return this.encoding;
}
@Override
public void setSqlMode(String sqlMode) {
this.sqlMode = sqlMode;
}
@Override
public String getSqlMode() {
return this.sqlMode;
}
@Override
public void setStressTestValid(boolean stressTestValid) {
this.stressTestValid = stressTestValid;
}
@Override
public boolean isStressTestValid() {
return stressTestValid;
}
@Override
public Map<String, Object> getServerVariables() {
return this.serverVariables;
}
@Override
public void setServerVariables(Map<String, Object> serverVariables) throws SQLException {
}
@Override
public long getFoundRows() {
throw new UnsupportedOperationException();
}
@Override
public void setFoundRows(long foundRows) {
throw new UnsupportedOperationException();
}
@Override
public long getAffectedRows() {
throw new UnsupportedOperationException();
}
@Override
public void setAffectedRows(long affectedRows) {
throw new UnsupportedOperationException();
}
@Override
public String getUser() {
throw new UnsupportedOperationException();
}
@Override
public void setUser(String userName) {
throw new UnsupportedOperationException();
}
@Override
public void executeLater(String sql) throws SQLException {
try (Statement stmt = conn.createStatement()) {
stmt.execute(sql);
}
}
@Override
public void flushUnsent() throws SQLException {
// Nothing to flush
}
}
|
924635c9052755df6cd2c836fa82e4bc90fd1ee4 | 5,545 | java | Java | library/src/main/java/de/mrapp/android/tabswitcher/Animation.java | hardikbhalodia99/Web-Browser | 906c3171538df0e9cfe1ab27fafc3a874db03950 | [
"Apache-2.0"
] | 1,297 | 2017-04-22T22:25:55.000Z | 2022-03-28T01:33:28.000Z | library/src/main/java/de/mrapp/android/tabswitcher/Animation.java | hardikbhalodia99/Web-Browser | 906c3171538df0e9cfe1ab27fafc3a874db03950 | [
"Apache-2.0"
] | 34 | 2017-04-29T05:16:57.000Z | 2021-08-30T03:53:49.000Z | library/src/main/java/de/mrapp/android/tabswitcher/Animation.java | hardikbhalodia99/Web-Browser | 906c3171538df0e9cfe1ab27fafc3a874db03950 | [
"Apache-2.0"
] | 173 | 2017-04-23T02:38:40.000Z | 2022-03-19T23:55:19.000Z | 34.228395 | 100 | 0.624707 | 1,003,686 | /*
* Copyright 2016 - 2020 Michael Rapp
*
* 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.mrapp.android.tabswitcher;
import android.view.animation.Interpolator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.mrapp.util.Condition;
/**
* An animation, which can be used to add or remove tabs to/from a {@link TabSwitcher}.
*
* @author Michael Rapp
* @since 0.1.0
*/
public abstract class Animation {
/**
* An abstract base class for all builders, which allow to configure and create instances of the
* class {@link Animation}.
*
* @param <AnimationType>
* The type of the animations, which are created by the builder
* @param <BuilderType>
* The type of the builder
*/
protected static abstract class Builder<AnimationType, BuilderType> {
/**
* The duration of the animations, which are created by the builder.
*/
protected long duration;
/**
* The interpolator, which is used by the animations, which are created by the builder.
*/
protected Interpolator interpolator;
/**
* Returns a reference to the builder.
*
* @return A reference to the builder, casted to the generic type BuilderType. The reference
* may not be null
*/
@NonNull
@SuppressWarnings("unchecked")
protected final BuilderType self() {
return (BuilderType) this;
}
/**
* Creates a new builder, which allows to configure and create instances of the class {@link
* Animation}.
*/
public Builder() {
setDuration(-1);
setInterpolator(null);
}
/**
* Creates and returns the animation.
*
* @return The animation, which has been created, as an instance of the generic type
* AnimationType. The animation may not be null
*/
@NonNull
public abstract AnimationType create();
/**
* Sets the duration of the animations, which are created by the builder.
*
* @param duration
* The duration, which should be set, in milliseconds as a {@link Long} value or -1,
* if the default duration should be used
* @return The builder, this method has be called upon, as an instance of the generic type
* BuilderType. The builder may not be null
*/
@NonNull
public final BuilderType setDuration(final long duration) {
Condition.INSTANCE.ensureAtLeast(duration, -1, "The duration must be at least -1");
this.duration = duration;
return self();
}
/**
* Sets the interpolator, which should be used by the animations, which are created by the
* builder.
*
* @param interpolator
* The interpolator, which should be set, as an instance of the type {@link
* Interpolator} or null, if the default interpolator should be used
* @return The builder, this method has be called upon, as an instance of the generic type
* BuilderType. The builder may not be null
*/
@NonNull
public final BuilderType setInterpolator(@Nullable final Interpolator interpolator) {
this.interpolator = interpolator;
return self();
}
}
/**
* The duration of the animation in milliseconds.
*/
private final long duration;
/**
* The interpolator, which is used by the animation.
*/
private final Interpolator interpolator;
/**
* Creates a new animation.
*
* @param duration
* The duration of the animation in milliseconds as a {@link Long} value or -1, if the
* default duration should be used
* @param interpolator
* The interpolator, which should be used by the animation, as an instance of the type
* {@link Interpolator} or null, if the default interpolator should be used
*/
protected Animation(final long duration, @Nullable final Interpolator interpolator) {
Condition.INSTANCE.ensureAtLeast(duration, -1, "The duration must be at least -1");
this.duration = duration;
this.interpolator = interpolator;
}
/**
* Returns the duration of the animation.
*
* @return The duration of the animation in milliseconds as a {@link Long} value or -1, if the
* default duration is used
*/
public final long getDuration() {
return duration;
}
/**
* Returns the interpolator, which is used by the animation.
*
* @return The interpolator, which is used by the animation, as an instance of the type {@link
* Interpolator} or null, if the default interpolator is used
*/
@Nullable
public final Interpolator getInterpolator() {
return interpolator;
}
} |
924636cef67557928d3086660116fb75cec66858 | 2,082 | java | Java | src/no/geosoft/common/geometry/spline/BezierSpline.java | rabbagast/common | e55e9ffadaefaf2c58cc424ab4bc0b1a3bb4e985 | [
"Apache-2.0"
] | null | null | null | src/no/geosoft/common/geometry/spline/BezierSpline.java | rabbagast/common | e55e9ffadaefaf2c58cc424ab4bc0b1a3bb4e985 | [
"Apache-2.0"
] | null | null | null | src/no/geosoft/common/geometry/spline/BezierSpline.java | rabbagast/common | e55e9ffadaefaf2c58cc424ab4bc0b1a3bb4e985 | [
"Apache-2.0"
] | null | null | null | 22.695652 | 75 | 0.54933 | 1,003,687 | package no.geosoft.common.geometry.spline;
/**
* A Bezier spline object. Use the SplineFactory class to create
* splines of this type.
*
* @author <a href="mailto:[email protected]">Jacob Dreyer</a>
*/
class BezierSpline extends Spline
{
/**
* Construct a bezier spline. Package local; Use the SplineFactory
* to create splines of this type. The control points are used according
* to the definition of Bezier splines.
*
* @param controlPoints Control points of spline (x0,y0,z0,x1,y1,z1,...)
* @param nParts Number of parts in generated spline.
*/
BezierSpline (double controlPoints[], int nParts)
{
controlPoints_ = controlPoints;
nParts_ = nParts;
}
/**
* Generate this spline.
*
* @return Coordinates of the spline (x0,y0,z0,x1,y1,z1,...)
*/
double[] generate()
{
if (controlPoints_.length < 9) {
double[] copy = new double[controlPoints_.length];
System.arraycopy (controlPoints_, 0, copy, 0, controlPoints_.length);
return copy;
}
int n = controlPoints_.length / 3;
int length = (n - 3) * nParts_ + 1;
double spline[] = new double[length * 3];
p (0, 0, controlPoints_, spline, 0);
int index = 3;
for (int i = 0; i < n - 3; i += 3) {
for (int j = 1; j <= nParts_; j++) {
p (i, j / (double) nParts_, controlPoints_, spline, index);
index += 3;
}
}
return spline;
}
private void p (int i, double t, double cp[], double spline[], int index)
{
double x = 0.0;
double y = 0.0;
double z = 0.0;
int k = i;
for (int j = 0; j <= 3; j++) {
double b = blend (j, t);
x += b * cp[k++];
y += b * cp[k++];
z += b * cp[k++];
}
spline[index + 0] = x;
spline[index + 1] = y;
spline[index + 2] = z;
}
private double blend (int i, double t)
{
if (i == 0) return (1 - t) * (1 - t) * (1 - t);
else if (i == 1) return 3 * t * (1 - t) * (1 - t);
else if (i == 2) return 3 * t * t * (1 - t);
else return t * t * t;
}
}
|
924638dea56a0cc3ca036d63b81547c222ff8b80 | 1,648 | java | Java | src/main/java/com/ibm/ssi/controller/company/service/dto/IssuedCredentialDTO.java | admin-bn/company-controller | 920186bd20e775ba8ccf3431a5a163e0a63965d7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ibm/ssi/controller/company/service/dto/IssuedCredentialDTO.java | admin-bn/company-controller | 920186bd20e775ba8ccf3431a5a163e0a63965d7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ibm/ssi/controller/company/service/dto/IssuedCredentialDTO.java | admin-bn/company-controller | 920186bd20e775ba8ccf3431a5a163e0a63965d7 | [
"Apache-2.0"
] | null | null | null | 21.684211 | 88 | 0.70267 | 1,003,688 | /*
* Copyright 2021 Bundesreplublik Deutschland
*
* 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.ibm.ssi.controller.company.service.dto;
import com.ibm.ssi.controller.company.domain.IssuedCredential;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;
import java.util.Date;
public class IssuedCredentialDTO {
@Id
private String id;
@Field("issuance_date")
private Date issuanceDate;
public IssuedCredentialDTO(IssuedCredential issuedCredential) {
this.id = issuedCredential.getId();
this.issuanceDate = issuedCredential.getIssuanceDate();
}
public IssuedCredentialDTO() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Date getIssuanceDate() {
return issuanceDate;
}
public void setIssuanceDate(Date issuanceDate) {
this.issuanceDate = issuanceDate;
}
@Override
public String toString() {
return "IssuedCredentialDTO [id=" + id + ", issuanceDate=" + issuanceDate + "]";
}
}
|
92463991da4fe90d2b9ebb9de0af02d303939b74 | 44,553 | java | Java | java-psi-api/src/main/java/com/intellij/psi/LambdaUtil.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 5 | 2015-12-19T15:27:30.000Z | 2019-08-17T10:07:23.000Z | java-psi-api/src/main/java/com/intellij/psi/LambdaUtil.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 47 | 2015-02-28T12:45:13.000Z | 2021-12-15T15:42:34.000Z | java-psi-api/src/main/java/com/intellij/psi/LambdaUtil.java | consulo/consulo-java | e016b25321f49547a57e97132c013468c2a50316 | [
"Apache-2.0"
] | 2 | 2018-03-08T16:17:47.000Z | 2019-08-17T18:20:38.000Z | 31.823571 | 190 | 0.742913 | 1,003,689 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.psi;
import com.intellij.codeInsight.AnnotationTargetUtil;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.RecursionGuard;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.*;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import consulo.java.module.util.JavaClassNames;
import consulo.logging.Logger;
import org.jetbrains.annotations.Contract;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
/**
* User: anna
* Date: 7/17/12
*/
public class LambdaUtil
{
private static final boolean JDK8042508_BUG_FIXED = SystemProperties.getBooleanProperty("JDK8042508.bug.fixed", false);
public static final RecursionGuard ourParameterGuard = RecursionManager.createGuard("lambdaParameterGuard");
public static final ThreadLocal<Map<PsiElement, PsiType>> ourFunctionTypes = new ThreadLocal<Map<PsiElement, PsiType>>();
private static final Logger LOG = Logger.getInstance(LambdaUtil.class);
@javax.annotation.Nullable
public static PsiType getFunctionalInterfaceReturnType(PsiFunctionalExpression expr)
{
return getFunctionalInterfaceReturnType(expr.getFunctionalInterfaceType());
}
@Nullable
public static PsiType getFunctionalInterfaceReturnType(@Nullable PsiType functionalInterfaceType)
{
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiClass psiClass = resolveResult.getElement();
if(psiClass != null)
{
final MethodSignature methodSignature = getFunction(psiClass);
if(methodSignature != null)
{
final PsiType returnType = getReturnType(psiClass, methodSignature);
return resolveResult.getSubstitutor().substitute(returnType);
}
}
return null;
}
@Contract("null -> null")
@javax.annotation.Nullable
public static PsiMethod getFunctionalInterfaceMethod(@javax.annotation.Nullable PsiType functionalInterfaceType)
{
return getFunctionalInterfaceMethod(PsiUtil.resolveGenericsClassInType(functionalInterfaceType));
}
public static PsiMethod getFunctionalInterfaceMethod(@Nullable PsiElement element)
{
if(element instanceof PsiFunctionalExpression)
{
final PsiType samType = ((PsiFunctionalExpression) element).getFunctionalInterfaceType();
return getFunctionalInterfaceMethod(samType);
}
return null;
}
@Nullable
public static PsiMethod getFunctionalInterfaceMethod(@Nonnull PsiClassType.ClassResolveResult result)
{
return getFunctionalInterfaceMethod(result.getElement());
}
@Contract("null -> null")
@Nullable
public static PsiMethod getFunctionalInterfaceMethod(PsiClass aClass)
{
final MethodSignature methodSignature = getFunction(aClass);
if(methodSignature != null)
{
return getMethod(aClass, methodSignature);
}
return null;
}
public static PsiSubstitutor getSubstitutor(@Nonnull PsiMethod method, @Nonnull PsiClassType.ClassResolveResult resolveResult)
{
final PsiClass derivedClass = resolveResult.getElement();
LOG.assertTrue(derivedClass != null);
final PsiClass methodContainingClass = method.getContainingClass();
LOG.assertTrue(methodContainingClass != null);
PsiSubstitutor initialSubst = resolveResult.getSubstitutor();
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(methodContainingClass, derivedClass, PsiSubstitutor.EMPTY);
for(PsiTypeParameter param : superClassSubstitutor.getSubstitutionMap().keySet())
{
final PsiType substitute = superClassSubstitutor.substitute(param);
if(substitute != null)
{
initialSubst = initialSubst.put(param, initialSubst.substitute(substitute));
}
}
return initialSubst;
}
public static boolean isFunctionalType(PsiType type)
{
if(type instanceof PsiIntersectionType)
{
return extractFunctionalConjunct((PsiIntersectionType) type) != null;
}
return isFunctionalClass(PsiUtil.resolveGenericsClassInType(type).getElement());
}
@Contract("null -> false")
public static boolean isFunctionalClass(PsiClass aClass)
{
if(aClass != null)
{
if(aClass instanceof PsiTypeParameter)
{
return false;
}
return getFunction(aClass) != null;
}
return false;
}
@Contract("null -> false")
public static boolean isValidLambdaContext(@Nullable PsiElement context)
{
context = PsiUtil.skipParenthesizedExprUp(context);
if(isAssignmentOrInvocationContext(context) || context instanceof PsiTypeCastExpression)
{
return true;
}
if(context instanceof PsiConditionalExpression)
{
PsiElement parentContext = PsiUtil.skipParenthesizedExprUp(context.getParent());
if(isAssignmentOrInvocationContext(parentContext))
{
return true;
}
if(parentContext instanceof PsiConditionalExpression)
{
return isValidLambdaContext(parentContext);
}
}
return false;
}
@Contract("null -> false")
private static boolean isAssignmentOrInvocationContext(PsiElement context)
{
return isAssignmentContext(context) || isInvocationContext(context);
}
private static boolean isInvocationContext(@Nullable PsiElement context)
{
return context instanceof PsiExpressionList;
}
private static boolean isAssignmentContext(PsiElement context)
{
return context instanceof PsiLambdaExpression || context instanceof PsiReturnStatement || context instanceof PsiAssignmentExpression || context instanceof PsiVariable || context instanceof
PsiArrayInitializerExpression;
}
public static boolean isLambdaFullyInferred(PsiLambdaExpression expression, PsiType functionalInterfaceType)
{
final boolean hasParams = expression.getParameterList().getParametersCount() > 0;
if(hasParams || !PsiType.VOID.equals(getFunctionalInterfaceReturnType(functionalInterfaceType)))
{ //todo check that void lambdas without params check
return !dependsOnTypeParams(functionalInterfaceType, functionalInterfaceType, expression);
}
return true;
}
@Contract("null -> null")
@Nullable
public static MethodSignature getFunction(final PsiClass psiClass)
{
if(isPlainInterface(psiClass))
{
return CachedValuesManager.getCachedValue(psiClass, new CachedValueProvider<MethodSignature>()
{
@javax.annotation.Nullable
@Override
public Result<MethodSignature> compute()
{
return Result.create(calcFunction(psiClass), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
}
});
}
return null;
}
private static boolean isPlainInterface(PsiClass psiClass)
{
return psiClass != null && psiClass.isInterface() && !psiClass.isAnnotationType();
}
@Nullable
private static MethodSignature calcFunction(@Nonnull PsiClass psiClass)
{
if(hasManyOwnAbstractMethods(psiClass) || hasManyInheritedAbstractMethods(psiClass))
{
return null;
}
final List<HierarchicalMethodSignature> functions = findFunctionCandidates(psiClass);
return functions != null && functions.size() == 1 ? functions.get(0) : null;
}
private static boolean hasManyOwnAbstractMethods(@Nonnull PsiClass psiClass)
{
int abstractCount = 0;
for(PsiMethod method : psiClass.getMethods())
{
if(isDefinitelyAbstractInterfaceMethod(method) && ++abstractCount > 1)
{
return true;
}
}
return false;
}
private static boolean isDefinitelyAbstractInterfaceMethod(PsiMethod method)
{
return method.hasModifierProperty(PsiModifier.ABSTRACT) && !isPublicObjectMethod(method.getName());
}
private static boolean isPublicObjectMethod(String methodName)
{
return "equals".equals(methodName) || "hashCode".equals(methodName) || "toString".equals(methodName);
}
private static boolean hasManyInheritedAbstractMethods(@Nonnull PsiClass psiClass)
{
final Set<String> abstractNames = ContainerUtil.newHashSet();
final Set<String> defaultNames = ContainerUtil.newHashSet();
InheritanceUtil.processSupers(psiClass, true, new Processor<PsiClass>()
{
@Override
public boolean process(PsiClass psiClass)
{
for(PsiMethod method : psiClass.getMethods())
{
if(isDefinitelyAbstractInterfaceMethod(method))
{
abstractNames.add(method.getName());
}
else if(method.hasModifierProperty(PsiModifier.DEFAULT))
{
defaultNames.add(method.getName());
}
}
return true;
}
});
abstractNames.removeAll(defaultNames);
return abstractNames.size() > 1;
}
private static boolean overridesPublicObjectMethod(HierarchicalMethodSignature psiMethod)
{
final List<HierarchicalMethodSignature> signatures = psiMethod.getSuperSignatures();
if(signatures.isEmpty())
{
final PsiMethod method = psiMethod.getMethod();
final PsiClass containingClass = method.getContainingClass();
if(containingClass != null && JavaClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName()))
{
if(method.hasModifierProperty(PsiModifier.PUBLIC))
{
return true;
}
}
}
for(HierarchicalMethodSignature superMethod : signatures)
{
if(overridesPublicObjectMethod(superMethod))
{
return true;
}
}
return false;
}
private static MethodSignature getMethodSignature(PsiMethod method, PsiClass psiClass, PsiClass containingClass)
{
final MethodSignature methodSignature;
if(containingClass != null && containingClass != psiClass)
{
methodSignature = method.getSignature(TypeConversionUtil.getSuperClassSubstitutor(containingClass, psiClass, PsiSubstitutor.EMPTY));
}
else
{
methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
}
return methodSignature;
}
@Nullable
private static List<HierarchicalMethodSignature> hasSubsignature(List<HierarchicalMethodSignature> signatures)
{
for(HierarchicalMethodSignature signature : signatures)
{
boolean subsignature = true;
for(HierarchicalMethodSignature methodSignature : signatures)
{
if(!signature.equals(methodSignature) && !skipMethod(signature, methodSignature))
{
subsignature = false;
break;
}
}
if(subsignature)
{
return Collections.singletonList(signature);
}
}
return signatures;
}
private static boolean skipMethod(HierarchicalMethodSignature signature, HierarchicalMethodSignature methodSignature)
{
//not generic
if(methodSignature.getTypeParameters().length == 0)
{
return false;
}
//foreign class
return signature.getMethod().getContainingClass() != methodSignature.getMethod().getContainingClass();
}
@Contract("null -> null")
@Nullable
public static List<HierarchicalMethodSignature> findFunctionCandidates(@Nullable final PsiClass psiClass)
{
if(!isPlainInterface(psiClass))
{
return null;
}
final List<HierarchicalMethodSignature> methods = new ArrayList<HierarchicalMethodSignature>();
final Map<MethodSignature, Set<PsiMethod>> overrideEquivalents = PsiSuperMethodUtil.collectOverrideEquivalents(psiClass);
final Collection<HierarchicalMethodSignature> visibleSignatures = psiClass.getVisibleSignatures();
for(HierarchicalMethodSignature signature : visibleSignatures)
{
final PsiMethod psiMethod = signature.getMethod();
if(!psiMethod.hasModifierProperty(PsiModifier.ABSTRACT))
{
continue;
}
if(psiMethod.hasModifierProperty(PsiModifier.STATIC))
{
continue;
}
final Set<PsiMethod> equivalentMethods = overrideEquivalents.get(signature);
if(equivalentMethods != null && equivalentMethods.size() > 1)
{
boolean hasNonAbstractOverrideEquivalent = false;
for(PsiMethod method : equivalentMethods)
{
if(!method.hasModifierProperty(PsiModifier.ABSTRACT) && !MethodSignatureUtil.isSuperMethod(method, psiMethod))
{
hasNonAbstractOverrideEquivalent = true;
break;
}
}
if(hasNonAbstractOverrideEquivalent)
{
continue;
}
}
if(!overridesPublicObjectMethod(signature))
{
methods.add(signature);
}
}
return hasSubsignature(methods);
}
@Nullable
private static PsiType getReturnType(PsiClass psiClass, MethodSignature methodSignature)
{
final PsiMethod method = getMethod(psiClass, methodSignature);
if(method != null)
{
final PsiClass containingClass = method.getContainingClass();
if(containingClass == null)
{
return null;
}
return TypeConversionUtil.getSuperClassSubstitutor(containingClass, psiClass, PsiSubstitutor.EMPTY).substitute(method.getReturnType());
}
else
{
return null;
}
}
@Nullable
private static PsiMethod getMethod(PsiClass psiClass, MethodSignature methodSignature)
{
if(methodSignature instanceof MethodSignatureBackedByPsiMethod)
{
return ((MethodSignatureBackedByPsiMethod) methodSignature).getMethod();
}
final PsiMethod[] methodsByName = psiClass.findMethodsByName(methodSignature.getName(), true);
for(PsiMethod psiMethod : methodsByName)
{
if(MethodSignatureUtil.areSignaturesEqual(getMethodSignature(psiMethod, psiClass, psiMethod.getContainingClass()), methodSignature))
{
return psiMethod;
}
}
return null;
}
public static int getLambdaIdx(PsiExpressionList expressionList, final PsiElement element)
{
PsiExpression[] expressions = expressionList.getExpressions();
for(int i = 0; i < expressions.length; i++)
{
PsiExpression expression = expressions[i];
if(PsiTreeUtil.isAncestor(expression, element, false))
{
return i;
}
}
return -1;
}
public static boolean dependsOnTypeParams(PsiType type, PsiType functionalInterfaceType, PsiElement lambdaExpression, PsiTypeParameter... param2Check)
{
return depends(type, new TypeParamsChecker(lambdaExpression, PsiUtil.resolveClassInType(functionalInterfaceType)), param2Check);
}
public static boolean depends(PsiType type, TypeParamsChecker visitor, PsiTypeParameter... param2Check)
{
if(!visitor.startedInference())
{
return false;
}
final Boolean accept = type.accept(visitor);
if(param2Check.length > 0)
{
return visitor.used(param2Check);
}
return accept != null && accept.booleanValue();
}
@Nullable
public static PsiType getFunctionalInterfaceType(PsiElement expression, final boolean tryToSubstitute)
{
PsiElement parent = expression.getParent();
PsiElement element = expression;
while(parent instanceof PsiParenthesizedExpression || parent instanceof PsiConditionalExpression)
{
if(parent instanceof PsiConditionalExpression && ((PsiConditionalExpression) parent).getThenExpression() != element && ((PsiConditionalExpression) parent).getElseExpression() != element)
{
break;
}
element = parent;
parent = parent.getParent();
}
final Map<PsiElement, PsiType> map = ourFunctionTypes.get();
if(map != null)
{
final PsiType type = map.get(expression);
if(type != null)
{
return type;
}
}
if(parent instanceof PsiArrayInitializerExpression)
{
final PsiType psiType = ((PsiArrayInitializerExpression) parent).getType();
if(psiType instanceof PsiArrayType)
{
return ((PsiArrayType) psiType).getComponentType();
}
}
else if(parent instanceof PsiTypeCastExpression)
{
//ensure no capture is performed to target type of cast expression, from 15.16 Cast Expressions:
//Casts can be used to explicitly "tag" a lambda expression or a method reference expression with a particular target type.
//To provide an appropriate degree of flexibility, the target type may be a list of types denoting an intersection type,
// provided the intersection induces a functional interface (§9.8).
final PsiTypeElement castTypeElement = ((PsiTypeCastExpression) parent).getCastType();
final PsiType castType = castTypeElement != null ? castTypeElement.getType() : null;
if(castType instanceof PsiIntersectionType)
{
final PsiType conjunct = extractFunctionalConjunct((PsiIntersectionType) castType);
if(conjunct != null)
{
return conjunct;
}
}
return castType;
}
else if(parent instanceof PsiVariable)
{
return ((PsiVariable) parent).getType();
}
else if(parent instanceof PsiAssignmentExpression && expression instanceof PsiExpression && !PsiUtil.isOnAssignmentLeftHand((PsiExpression) expression))
{
final PsiExpression lExpression = ((PsiAssignmentExpression) parent).getLExpression();
return lExpression.getType();
}
else if(parent instanceof PsiExpressionList)
{
final PsiExpressionList expressionList = (PsiExpressionList) parent;
final int lambdaIdx = getLambdaIdx(expressionList, expression);
if(lambdaIdx > -1)
{
PsiElement gParent = expressionList.getParent();
if(gParent instanceof PsiAnonymousClass)
{
gParent = gParent.getParent();
}
if(gParent instanceof PsiCall)
{
final PsiCall contextCall = (PsiCall) gParent;
final MethodCandidateInfo.CurrentCandidateProperties properties = MethodCandidateInfo.getCurrentMethod(contextCall.getArgumentList());
if(properties != null && properties.isApplicabilityCheck())
{ //todo simplification
final PsiParameter[] parameters = properties.getMethod().getParameterList().getParameters();
final int finalLambdaIdx = adjustLambdaIdx(lambdaIdx, properties.getMethod(), parameters);
if(finalLambdaIdx < parameters.length)
{
return properties.getSubstitutor().substitute(getNormalizedType(parameters[finalLambdaIdx]));
}
}
final JavaResolveResult resolveResult = properties != null ? properties.getInfo() : contextCall.resolveMethodGenerics();
return getSubstitutedType(expression, tryToSubstitute, lambdaIdx, resolveResult);
}
}
}
else if(parent instanceof PsiReturnStatement)
{
return PsiTypesUtil.getMethodReturnType(parent);
}
else if(parent instanceof PsiLambdaExpression)
{
return getFunctionalInterfaceTypeByContainingLambda((PsiLambdaExpression) parent);
}
return null;
}
@Nullable
private static PsiType getSubstitutedType(PsiElement expression, boolean tryToSubstitute, int lambdaIdx, final JavaResolveResult resolveResult)
{
final PsiElement resolve = resolveResult.getElement();
if(resolve instanceof PsiMethod)
{
final PsiParameter[] parameters = ((PsiMethod) resolve).getParameterList().getParameters();
final int finalLambdaIdx = adjustLambdaIdx(lambdaIdx, (PsiMethod) resolve, parameters);
if(finalLambdaIdx < parameters.length)
{
if(!tryToSubstitute)
{
return getNormalizedType(parameters[finalLambdaIdx]);
}
return PsiResolveHelper.ourGraphGuard.doPreventingRecursion(expression, !MethodCandidateInfo.isOverloadCheck(), new Computable<PsiType>()
{
@Override
public PsiType compute()
{
final PsiType normalizedType = getNormalizedType(parameters[finalLambdaIdx]);
if(resolveResult instanceof MethodCandidateInfo && ((MethodCandidateInfo) resolveResult).isRawSubstitution())
{
return TypeConversionUtil.erasure(normalizedType);
}
else
{
return resolveResult.getSubstitutor().substitute(normalizedType);
}
}
});
}
}
return null;
}
public static boolean processParentOverloads(PsiFunctionalExpression functionalExpression, final Consumer<PsiType> overloadProcessor)
{
LOG.assertTrue(PsiTypesUtil.getExpectedTypeByParent(functionalExpression) == null);
PsiElement parent = functionalExpression.getParent();
PsiElement expr = functionalExpression;
while(parent instanceof PsiParenthesizedExpression || parent instanceof PsiConditionalExpression)
{
if(parent instanceof PsiConditionalExpression && ((PsiConditionalExpression) parent).getThenExpression() != expr && ((PsiConditionalExpression) parent).getElseExpression() != expr)
{
break;
}
expr = parent;
parent = parent.getParent();
}
if(parent instanceof PsiExpressionList)
{
final PsiExpressionList expressionList = (PsiExpressionList) parent;
final int lambdaIdx = getLambdaIdx(expressionList, functionalExpression);
if(lambdaIdx > -1)
{
PsiElement gParent = expressionList.getParent();
if(gParent instanceof PsiAnonymousClass)
{
gParent = gParent.getParent();
}
if(gParent instanceof PsiMethodCallExpression)
{
final Set<PsiType> types = new HashSet<PsiType>();
final JavaResolveResult[] results = ((PsiMethodCallExpression) gParent).getMethodExpression().multiResolve(true);
for(JavaResolveResult result : results)
{
final PsiType functionalExpressionType = getSubstitutedType(functionalExpression, true, lambdaIdx, result);
if(functionalExpressionType != null && types.add(functionalExpressionType))
{
overloadProcessor.consume(functionalExpressionType);
}
}
return true;
}
}
}
return false;
}
@Nullable
private static PsiType extractFunctionalConjunct(PsiIntersectionType type)
{
PsiType conjunct = null;
for(PsiType conjunctType : type.getConjuncts())
{
final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(conjunctType);
if(interfaceMethod != null)
{
if(conjunct != null && !conjunct.equals(conjunctType))
{
return null;
}
conjunct = conjunctType;
}
}
return conjunct;
}
private static PsiType getFunctionalInterfaceTypeByContainingLambda(@Nonnull PsiLambdaExpression parentLambda)
{
final PsiType parentInterfaceType = parentLambda.getFunctionalInterfaceType();
return parentInterfaceType != null ? getFunctionalInterfaceReturnType(parentInterfaceType) : null;
}
private static int adjustLambdaIdx(int lambdaIdx, PsiMethod resolve, PsiParameter[] parameters)
{
final int finalLambdaIdx;
if(resolve.isVarArgs() && lambdaIdx >= parameters.length)
{
finalLambdaIdx = parameters.length - 1;
}
else
{
finalLambdaIdx = lambdaIdx;
}
return finalLambdaIdx;
}
private static PsiType getNormalizedType(PsiParameter parameter)
{
final PsiType type = parameter.getType();
if(type instanceof PsiEllipsisType)
{
return ((PsiEllipsisType) type).getComponentType();
}
return type;
}
@Contract(value = "null -> false", pure = true)
public static boolean notInferredType(PsiType typeByExpression)
{
return typeByExpression instanceof PsiMethodReferenceType || typeByExpression instanceof PsiLambdaExpressionType || typeByExpression instanceof PsiLambdaParameterType;
}
public static boolean isLambdaReturnExpression(PsiElement element)
{
final PsiElement parent = element.getParent();
return parent instanceof PsiLambdaExpression || parent instanceof PsiReturnStatement && PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class, true, PsiMethod.class) != null;
}
public static PsiReturnStatement[] getReturnStatements(PsiLambdaExpression lambdaExpression)
{
final PsiElement body = lambdaExpression.getBody();
return body instanceof PsiCodeBlock ? PsiUtil.findReturnStatements((PsiCodeBlock) body) : PsiReturnStatement.EMPTY_ARRAY;
}
public static List<PsiExpression> getReturnExpressions(PsiLambdaExpression lambdaExpression)
{
final PsiElement body = lambdaExpression.getBody();
if(body instanceof PsiExpression)
{
//if (((PsiExpression)body).getType() != PsiType.VOID) return Collections.emptyList();
return Collections.singletonList((PsiExpression) body);
}
final List<PsiExpression> result = new ArrayList<PsiExpression>();
for(PsiReturnStatement returnStatement : getReturnStatements(lambdaExpression))
{
final PsiExpression returnValue = returnStatement.getReturnValue();
if(returnValue != null)
{
result.add(returnValue);
}
}
return result;
}
public static boolean isValidQualifier4InterfaceStaticMethodCall(@Nonnull PsiMethod method,
@Nonnull PsiReferenceExpression methodReferenceExpression,
@Nullable PsiElement scope,
@Nonnull LanguageLevel languageLevel)
{
return getInvalidQualifier4StaticInterfaceMethodMessage(method, methodReferenceExpression, scope, languageLevel) == null;
}
@Nullable
public static String getInvalidQualifier4StaticInterfaceMethodMessage(@Nonnull PsiMethod method,
@Nonnull PsiReferenceExpression methodReferenceExpression,
@Nullable PsiElement scope,
@Nonnull LanguageLevel languageLevel)
{
final PsiExpression qualifierExpression = methodReferenceExpression.getQualifierExpression();
final PsiClass containingClass = method.getContainingClass();
if(containingClass != null && containingClass.isInterface() && method.hasModifierProperty(PsiModifier.STATIC))
{
if(!languageLevel.isAtLeast(LanguageLevel.JDK_1_8))
{
return "Static interface method invocations are not supported at this language level";
}
if(qualifierExpression == null && (scope instanceof PsiImportStaticStatement || PsiTreeUtil.isAncestor(containingClass, methodReferenceExpression, true)))
{
return null;
}
if(qualifierExpression instanceof PsiReferenceExpression)
{
final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve();
if(resolve == containingClass)
{
return null;
}
if(resolve instanceof PsiTypeParameter)
{
final Set<PsiClass> classes = new HashSet<PsiClass>();
for(PsiClassType type : ((PsiTypeParameter) resolve).getExtendsListTypes())
{
final PsiClass aClass = type.resolve();
if(aClass != null)
{
classes.add(aClass);
}
}
if(classes.size() == 1 && classes.contains(containingClass))
{
return null;
}
}
}
return "Static method may be invoked on containing interface class only";
}
return null;
}
//JLS 14.8 Expression Statements
@Contract("null -> false")
public static boolean isExpressionStatementExpression(PsiElement body)
{
return body instanceof PsiAssignmentExpression || body instanceof PsiPrefixExpression && (((PsiPrefixExpression) body).getOperationTokenType() == JavaTokenType.PLUSPLUS || (
(PsiPrefixExpression) body).getOperationTokenType() == JavaTokenType.MINUSMINUS) || body instanceof PsiPostfixExpression || body instanceof PsiCallExpression || body instanceof
PsiReferenceExpression && !body.isPhysical();
}
public static PsiExpression extractSingleExpressionFromBody(PsiElement body)
{
PsiExpression expression = null;
if(body instanceof PsiExpression)
{
expression = (PsiExpression) body;
}
else if(body instanceof PsiCodeBlock)
{
final PsiStatement[] statements = ((PsiCodeBlock) body).getStatements();
if(statements.length == 1)
{
if(statements[0] instanceof PsiReturnStatement)
{
expression = ((PsiReturnStatement) statements[0]).getReturnValue();
}
else if(statements[0] instanceof PsiExpressionStatement)
{
expression = ((PsiExpressionStatement) statements[0]).getExpression();
}
else if(statements[0] instanceof PsiBlockStatement)
{
return extractSingleExpressionFromBody(((PsiBlockStatement) statements[0]).getCodeBlock());
}
}
}
else if(body instanceof PsiBlockStatement)
{
return extractSingleExpressionFromBody(((PsiBlockStatement) body).getCodeBlock());
}
else if(body instanceof PsiExpressionStatement)
{
expression = ((PsiExpressionStatement) body).getExpression();
}
return expression;
}
// http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.1
// A lambda expression or a method reference expression is potentially compatible with a type variable
// if the type variable is a type parameter of the candidate method.
public static boolean isPotentiallyCompatibleWithTypeParameter(PsiFunctionalExpression expression, PsiExpressionList argsList, PsiMethod method)
{
if(!JDK8042508_BUG_FIXED)
{
final PsiCallExpression callExpression = PsiTreeUtil.getParentOfType(argsList, PsiCallExpression.class);
if(callExpression == null || callExpression.getTypeArguments().length > 0)
{
return false;
}
}
final int lambdaIdx = getLambdaIdx(argsList, expression);
if(lambdaIdx >= 0)
{
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiParameter lambdaParameter = parameters[Math.min(lambdaIdx, parameters.length - 1)];
final PsiClass paramClass = PsiUtil.resolveClassInType(lambdaParameter.getType());
if(paramClass instanceof PsiTypeParameter && ((PsiTypeParameter) paramClass).getOwner() == method)
{
return true;
}
}
return false;
}
@Nonnull
public static Map<PsiElement, PsiType> getFunctionalTypeMap()
{
Map<PsiElement, PsiType> map = ourFunctionTypes.get();
if(map == null)
{
map = new HashMap<PsiElement, PsiType>();
ourFunctionTypes.set(map);
}
return map;
}
public static Map<PsiElement, String> checkReturnTypeCompatible(PsiLambdaExpression lambdaExpression, PsiType functionalInterfaceReturnType)
{
Map<PsiElement, String> errors = new LinkedHashMap<PsiElement, String>();
if(PsiType.VOID.equals(functionalInterfaceReturnType))
{
final PsiElement body = lambdaExpression.getBody();
if(body instanceof PsiCodeBlock)
{
for(PsiExpression expression : getReturnExpressions(lambdaExpression))
{
errors.put(expression, "Unexpected return value");
}
}
else if(body instanceof PsiExpression)
{
final PsiType type = ((PsiExpression) body).getType();
try
{
if(!PsiUtil.isStatement(JavaPsiFacade.getElementFactory(body.getProject()).createStatementFromText(body.getText(), body)))
{
if(PsiType.VOID.equals(type))
{
errors.put(body, "Lambda body must be a statement expression");
}
else
{
errors.put(body, "Bad return type in lambda expression: " + (type == PsiType.NULL || type == null ? "<null>" : type.getPresentableText()) + " cannot be converted to " +
"void");
}
}
}
catch(IncorrectOperationException ignore)
{
}
}
}
else if(functionalInterfaceReturnType != null)
{
final List<PsiExpression> returnExpressions = getReturnExpressions(lambdaExpression);
for(final PsiExpression expression : returnExpressions)
{
final PsiType expressionType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(expression, true, new Computable<PsiType>()
{
@Override
public PsiType compute()
{
return expression.getType();
}
});
if(expressionType != null && !functionalInterfaceReturnType.isAssignableFrom(expressionType))
{
errors.put(expression, "Bad return type in lambda expression: " + expressionType.getPresentableText() + " cannot be converted to " + functionalInterfaceReturnType
.getPresentableText());
}
}
final PsiReturnStatement[] returnStatements = getReturnStatements(lambdaExpression);
if(returnStatements.length > returnExpressions.size())
{
for(PsiReturnStatement statement : returnStatements)
{
final PsiExpression value = statement.getReturnValue();
if(value == null)
{
errors.put(statement, "Missing return value");
}
}
}
else if(returnExpressions.isEmpty() && !lambdaExpression.isVoidCompatible())
{
errors.put(lambdaExpression, "Missing return value");
}
}
return errors.isEmpty() ? null : errors;
}
@Nullable
public static PsiType getLambdaParameterFromType(PsiType functionalInterfaceType, int parameterIndex)
{
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod method = getFunctionalInterfaceMethod(functionalInterfaceType);
if(method != null)
{
final PsiParameter[] parameters = method.getParameterList().getParameters();
if(parameterIndex < parameters.length)
{
return getSubstitutor(method, resolveResult).substitute(parameters[parameterIndex].getType());
}
}
return null;
}
public static boolean isLambdaParameterCheck()
{
return !ourParameterGuard.currentStack().isEmpty();
}
@Nullable
public static PsiCall treeWalkUp(PsiElement context)
{
PsiCall top = null;
PsiElement parent = PsiTreeUtil.getParentOfType(context, PsiExpressionList.class, PsiLambdaExpression.class, PsiConditionalExpression.class, PsiCodeBlock.class, PsiCall.class);
while(true)
{
if(parent instanceof PsiCall)
{
break;
}
final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class);
if(parent instanceof PsiCodeBlock)
{
if(lambdaExpression == null)
{
break;
}
else
{
boolean inReturnExpressions = false;
for(PsiExpression expression : getReturnExpressions(lambdaExpression))
{
inReturnExpressions |= PsiTreeUtil.isAncestor(expression, context, false);
}
if(!inReturnExpressions)
{
break;
}
if(getFunctionalTypeMap().containsKey(lambdaExpression))
{
break;
}
}
}
if(parent instanceof PsiConditionalExpression && !PsiPolyExpressionUtil.isPolyExpression((PsiExpression) parent))
{
break;
}
if(parent instanceof PsiLambdaExpression && getFunctionalTypeMap().containsKey(parent))
{
break;
}
final PsiCall psiCall = PsiTreeUtil.getParentOfType(parent, PsiCall.class, false, PsiMember.class);
if(psiCall == null)
{
break;
}
final MethodCandidateInfo.CurrentCandidateProperties properties = MethodCandidateInfo.getCurrentMethod(psiCall.getArgumentList());
if(properties != null)
{
if(properties.isApplicabilityCheck() || lambdaExpression != null && lambdaExpression.hasFormalParameterTypes())
{
break;
}
}
top = psiCall;
if(top instanceof PsiExpression && PsiPolyExpressionUtil.isPolyExpression((PsiExpression) top))
{
parent = PsiTreeUtil.getParentOfType(parent.getParent(), PsiExpressionList.class, PsiLambdaExpression.class, PsiCodeBlock.class);
}
else
{
break;
}
}
if(top == null)
{
return null;
}
final PsiExpressionList argumentList = top.getArgumentList();
if(argumentList == null)
{
return null;
}
LOG.assertTrue(MethodCandidateInfo.getCurrentMethod(argumentList) == null);
return top;
}
public static PsiCall copyTopLevelCall(@Nonnull PsiCall call)
{
PsiCall copyCall = (PsiCall) call.copy();
if(call instanceof PsiEnumConstant)
{
PsiClass containingClass = ((PsiEnumConstant) call).getContainingClass();
if(containingClass == null)
{
return null;
}
String enumName = containingClass.getName();
if(enumName == null)
{
return null;
}
PsiMethod resolveMethod = call.resolveMethod();
if(resolveMethod == null)
{
return null;
}
PsiClass anEnum = JavaPsiFacade.getElementFactory(call.getProject()).createEnum(enumName);
anEnum.add(resolveMethod);
return (PsiCall) anEnum.add(copyCall);
}
return copyCall;
}
public static <T> T performWithSubstitutedParameterBounds(final PsiTypeParameter[] typeParameters, final PsiSubstitutor substitutor, final Producer<T> producer)
{
try
{
for(PsiTypeParameter parameter : typeParameters)
{
final PsiClassType[] types = parameter.getExtendsListTypes();
if(types.length > 0)
{
final List<PsiType> conjuncts = ContainerUtil.map(types, new Function<PsiClassType, PsiType>()
{
@Override
public PsiType fun(PsiClassType type)
{
return substitutor.substitute(type);
}
});
//don't glb to avoid flattening = Object&Interface would be preserved
//otherwise methods with different signatures could get same erasure
final PsiType upperBound = PsiIntersectionType.createIntersection(false, conjuncts.toArray(new PsiType[conjuncts.size()]));
getFunctionalTypeMap().put(parameter, upperBound);
}
}
return producer.produce();
}
finally
{
for(PsiTypeParameter parameter : typeParameters)
{
getFunctionalTypeMap().remove(parameter);
}
}
}
public static <T> T performWithLambdaTargetType(PsiLambdaExpression lambdaExpression, PsiType targetType, Producer<T> producer)
{
try
{
getFunctionalTypeMap().put(lambdaExpression, targetType);
return producer.produce();
}
finally
{
getFunctionalTypeMap().remove(lambdaExpression);
}
}
/**
* Generate lambda text for single argument expression lambda
*
* @param variable lambda sole argument
* @param expression lambda body (expression)
* @return lambda text
*/
public static String createLambda(@Nonnull PsiVariable variable, @Nonnull PsiExpression expression)
{
return variable.getName() + " -> " + expression.getText();
}
public static PsiElement copyWithExpectedType(PsiElement expression, PsiType type)
{
String canonicalText = type.getCanonicalText();
if(!PsiUtil.isLanguageLevel8OrHigher(expression))
{
final String arrayInitializer = "new " + canonicalText + "[]{0}";
PsiNewExpression newExpr = (PsiNewExpression) createExpressionFromText(arrayInitializer, expression);
final PsiArrayInitializerExpression initializer = newExpr.getArrayInitializer();
LOG.assertTrue(initializer != null);
return initializer.getInitializers()[0].replace(expression);
}
final String callableWithExpectedType = "(java.util.concurrent.Callable<" + canonicalText + ">)() -> x";
PsiTypeCastExpression typeCastExpr = (PsiTypeCastExpression) createExpressionFromText(callableWithExpectedType, expression);
PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) typeCastExpr.getOperand();
LOG.assertTrue(lambdaExpression != null);
PsiElement body = lambdaExpression.getBody();
LOG.assertTrue(body instanceof PsiExpression);
return body.replace(expression);
}
private static PsiExpression createExpressionFromText(String exprText, PsiElement context)
{
PsiExpression expr = JavaPsiFacade.getElementFactory(context.getProject())
.createExpressionFromText(exprText, context);
//ensure refs to inner classes are collapsed to avoid raw types (container type would be raw in qualified text)
return (PsiExpression) JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(expr);
}
public static
@Nullable
String createLambdaParameterListWithFormalTypes(PsiType functionalInterfaceType,
PsiLambdaExpression lambdaExpression,
boolean checkApplicability)
{
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final StringBuilder buf = new StringBuilder();
buf.append("(");
final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(functionalInterfaceType);
if(interfaceMethod == null)
{
return null;
}
final PsiParameter[] parameters = interfaceMethod.getParameterList().getParameters();
final PsiParameter[] lambdaParameters = lambdaExpression.getParameterList().getParameters();
if(parameters.length != lambdaParameters.length)
{
return null;
}
final PsiSubstitutor substitutor = getSubstitutor(interfaceMethod, resolveResult);
for(int i = 0; i < parameters.length; i++)
{
PsiParameter lambdaParameter = lambdaParameters[i];
PsiTypeElement origTypeElement = lambdaParameter.getTypeElement();
PsiType psiType;
if(origTypeElement != null && !origTypeElement.isInferredType())
{
psiType = origTypeElement.getType();
}
else
{
psiType = substitutor.substitute(parameters[i].getType());
if(!PsiTypesUtil.isDenotableType(psiType, lambdaExpression))
{
return null;
}
}
PsiAnnotation[] annotations = lambdaParameter.getAnnotations();
for(PsiAnnotation annotation : annotations)
{
if(AnnotationTargetUtil.isTypeAnnotation(annotation))
{
continue;
}
buf.append(annotation.getText()).append(' ');
}
buf.append(checkApplicability ? psiType.getPresentableText(true) : psiType.getCanonicalText(true))
.append(" ")
.append(lambdaParameter.getName());
if(i < parameters.length - 1)
{
buf.append(", ");
}
}
buf.append(")");
return buf.toString();
}
@Nullable
public static PsiParameterList specifyLambdaParameterTypes(PsiLambdaExpression lambdaExpression)
{
return specifyLambdaParameterTypes(lambdaExpression.getFunctionalInterfaceType(), lambdaExpression);
}
@Nullable
public static PsiParameterList specifyLambdaParameterTypes(PsiType functionalInterfaceType,
@Nonnull PsiLambdaExpression lambdaExpression)
{
String typedParamList = createLambdaParameterListWithFormalTypes(functionalInterfaceType, lambdaExpression, false);
if(typedParamList != null)
{
PsiParameterList paramListWithFormalTypes = JavaPsiFacade.getElementFactory(lambdaExpression.getProject())
.createMethodFromText("void foo" + typedParamList, lambdaExpression).getParameterList();
return (PsiParameterList) JavaCodeStyleManager.getInstance(lambdaExpression.getProject())
.shortenClassReferences(lambdaExpression.getParameterList().replace(paramListWithFormalTypes));
}
return null;
}
public static class TypeParamsChecker extends PsiTypeVisitor<Boolean>
{
private PsiMethod myMethod;
private final PsiClass myClass;
public final Set<PsiTypeParameter> myUsedTypeParams = new HashSet<PsiTypeParameter>();
public TypeParamsChecker(PsiElement expression, PsiClass aClass)
{
myClass = aClass;
PsiElement parent = expression != null ? expression.getParent() : null;
while(parent instanceof PsiParenthesizedExpression)
{
parent = parent.getParent();
}
if(parent instanceof PsiExpressionList)
{
final PsiElement gParent = parent.getParent();
if(gParent instanceof PsiCall)
{
final MethodCandidateInfo.CurrentCandidateProperties pair = MethodCandidateInfo.getCurrentMethod(parent);
myMethod = pair != null ? pair.getMethod() : null;
if(myMethod == null)
{
myMethod = ((PsiCall) gParent).resolveMethod();
}
if(myMethod != null && PsiTreeUtil.isAncestor(myMethod, expression, false))
{
myMethod = null;
}
}
}
}
public boolean startedInference()
{
return myMethod != null;
}
@Override
public Boolean visitClassType(PsiClassType classType)
{
boolean used = false;
for(PsiType paramType : classType.getParameters())
{
final Boolean paramAccepted = paramType.accept(this);
used |= paramAccepted != null && paramAccepted.booleanValue();
}
final PsiClass resolve = classType.resolve();
if(resolve instanceof PsiTypeParameter)
{
final PsiTypeParameter typeParameter = (PsiTypeParameter) resolve;
if(check(typeParameter))
{
myUsedTypeParams.add(typeParameter);
return true;
}
}
return used;
}
@Nullable
@Override
public Boolean visitWildcardType(PsiWildcardType wildcardType)
{
final PsiType bound = wildcardType.getBound();
if(bound != null)
{
return bound.accept(this);
}
return false;
}
@Nullable
@Override
public Boolean visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType)
{
return true;
}
@javax.annotation.Nullable
@Override
public Boolean visitLambdaExpressionType(PsiLambdaExpressionType lambdaExpressionType)
{
return true;
}
@Nullable
@Override
public Boolean visitArrayType(PsiArrayType arrayType)
{
return arrayType.getComponentType().accept(this);
}
@Override
public Boolean visitType(PsiType type)
{
return false;
}
private boolean check(PsiTypeParameter check)
{
final PsiTypeParameterListOwner owner = check.getOwner();
if(owner == myMethod || owner == myClass)
{
return true;
}
return false;
}
public boolean used(PsiTypeParameter... parameters)
{
for(PsiTypeParameter parameter : parameters)
{
if(myUsedTypeParams.contains(parameter))
{
return true;
}
}
return false;
}
}
}
|
92463a39e38b99897e44df8057337af61aeced65 | 1,959 | java | Java | src/main/java/gg/projecteden/nexus/features/menus/sabotage/tasks/LightsTask.java | ProjectEdenGG/Nexus | 8e463d6dd2f18cf2e33fd9ec00b51b613b02ff73 | [
"MIT"
] | 3 | 2021-05-07T18:19:28.000Z | 2022-01-05T17:25:38.000Z | src/main/java/gg/projecteden/nexus/features/menus/sabotage/tasks/LightsTask.java | Pugabyte/Nexus | 25744e8f010ecf1bf61cbee776d5c43ba3ece3d7 | [
"MIT"
] | 4 | 2021-03-12T23:08:31.000Z | 2021-04-24T18:37:23.000Z | src/main/java/gg/projecteden/nexus/features/menus/sabotage/tasks/LightsTask.java | ProjectEdenGG/Nexus | 8e463d6dd2f18cf2e33fd9ec00b51b613b02ff73 | [
"MIT"
] | null | null | null | 36.277778 | 178 | 0.751404 | 1,003,690 | package gg.projecteden.nexus.features.menus.sabotage.tasks;
import fr.minuskube.inv.ClickableItem;
import fr.minuskube.inv.SmartInventory;
import fr.minuskube.inv.content.InventoryContents;
import gg.projecteden.nexus.features.minigames.managers.PlayerManager;
import gg.projecteden.nexus.features.minigames.models.Match;
import gg.projecteden.nexus.features.minigames.models.matchdata.SabotageMatchData;
import gg.projecteden.nexus.features.minigames.models.mechanics.custom.sabotage.Task;
import gg.projecteden.nexus.features.minigames.models.mechanics.custom.sabotage.taskpartdata.LightsTaskPartData;
import gg.projecteden.nexus.utils.ItemBuilder;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.concurrent.atomic.AtomicInteger;
public class LightsTask extends AbstractTaskMenu {
@Getter
private final SmartInventory inventory = SmartInventory.builder()
.title("")
.size(3, 9)
.provider(this)
.build();
private final LightsTaskPartData data;
public LightsTask(Task task) {
super(task);
task.nextPart();
data = task.getData();
}
@Override
public void init(Player player, InventoryContents contents) {
AtomicInteger taskId = new AtomicInteger();
Match match = PlayerManager.get(player).getMatch();
SabotageMatchData matchData = match.getMatchData();
taskId.set(match.getTasks().repeat(1, 1, () -> {
if (matchData.getSabotage() == null)
match.getTasks().cancel(taskId.get());
contents.fill(ClickableItem.empty(new ItemBuilder(Material.BLACK_STAINED_GLASS).name(" ").build()));
int index = 0;
for (boolean swtch : data.getSwitches()) {
final int thisIndex = index;
contents.set(1, (index * 2) - 1, ClickableItem.from(new ItemBuilder(swtch ? Material.LIME_CONCRETE : Material.GREEN_TERRACOTTA).name(swtch ? "&aON" : "&2OFF").build(), $ -> {
if (data.toggle(thisIndex))
matchData.endSabotage();
}));
index += 1;
}
}));
}
}
|
92463b0323b4b31c796bd48129eb97dc6c0a5ee4 | 169 | java | Java | exodia/src/main/java/org/atanasov/exodia/service/MessageService.java | VasAtanasov/SoftUni-Java-Web-Basics-September-2019 | c5456fd987d559159a3ba3dc16da0875138defd1 | [
"MIT"
] | null | null | null | exodia/src/main/java/org/atanasov/exodia/service/MessageService.java | VasAtanasov/SoftUni-Java-Web-Basics-September-2019 | c5456fd987d559159a3ba3dc16da0875138defd1 | [
"MIT"
] | null | null | null | exodia/src/main/java/org/atanasov/exodia/service/MessageService.java | VasAtanasov/SoftUni-Java-Web-Basics-September-2019 | c5456fd987d559159a3ba3dc16da0875138defd1 | [
"MIT"
] | null | null | null | 16.9 | 53 | 0.757396 | 1,003,691 | package org.atanasov.exodia.service;
public interface MessageService {
void addMessage(String message);
void addMessage(String clientId, String message);
}
|
92463b03ab1321a15e9b6f019a0c8806aa5535a0 | 1,477 | java | Java | main/java/org/usfirst/frc/team4488/robot/app/paths/untested_paths/LeftCrossLineOwnScaleDiffSideSecondCubePartTwo.java | shockwave4488/FRC-2018-Public | a65ec6b219f29c28ed9cbb1098d22963bdf8e894 | [
"MIT"
] | null | null | null | main/java/org/usfirst/frc/team4488/robot/app/paths/untested_paths/LeftCrossLineOwnScaleDiffSideSecondCubePartTwo.java | shockwave4488/FRC-2018-Public | a65ec6b219f29c28ed9cbb1098d22963bdf8e894 | [
"MIT"
] | null | null | null | main/java/org/usfirst/frc/team4488/robot/app/paths/untested_paths/LeftCrossLineOwnScaleDiffSideSecondCubePartTwo.java | shockwave4488/FRC-2018-Public | a65ec6b219f29c28ed9cbb1098d22963bdf8e894 | [
"MIT"
] | 1 | 2019-10-31T22:06:39.000Z | 2019-10-31T22:06:39.000Z | 38.868421 | 201 | 0.741368 | 1,003,692 | package org.usfirst.frc.team4488.robot.app.paths.untested_paths;
import java.util.ArrayList;
import org.usfirst.frc.team4488.lib.util.app.control.Path;
import org.usfirst.frc.team4488.lib.util.app.math.RigidTransform2d;
import org.usfirst.frc.team4488.lib.util.app.math.Rotation2d;
import org.usfirst.frc.team4488.lib.util.app.math.Translation2d;
import org.usfirst.frc.team4488.robot.app.paths.PathBuilder;
import org.usfirst.frc.team4488.robot.app.paths.PathBuilder.Waypoint;
import org.usfirst.frc.team4488.robot.app.paths.PathContainer;
public class LeftCrossLineOwnScaleDiffSideSecondCubePartTwo implements PathContainer {
@Override
public Path buildPath() {
ArrayList<Waypoint> sWaypoints = new ArrayList<Waypoint>();
sWaypoints.add(new Waypoint(250, 40, 0, 0));
sWaypoints.add(new Waypoint(250, 90, 25, 30));
sWaypoints.add(new Waypoint(215, 90, 0, 30));
return PathBuilder.buildPathFromWaypoints(sWaypoints);
}
@Override
public RigidTransform2d getStartPose() {
return new RigidTransform2d(new Translation2d(250, 40), Rotation2d.fromDegrees(0.0));
}
@Override
public boolean isReversed() {
return false;
}
// WAYPOINT_DATA:
// [{"position":{"x":240,"y":40},"speed":0,"radius":0,"comment":""},{"position":{"x":240,"y":60},"speed":60,"radius":10,"comment":""},{"position":{"x":215,"y":80},"speed":60,"radius":0,"comment":""}]
// IS_REVERSED: false
// FILE_NAME: LeftCrossLineOwnScaleDiffSideSecondCubePartTwo
}
|
92463cf0b6dd0416e82abebfd530e3e6b6cd9dcb | 2,942 | java | Java | src/main/java/net/ugorji/oxygen/markup/indexing/MarkupIndexingParserBase.java | ugorji/java-markup | 938947a81c221360759e8e8a7fe10eaf15aaa426 | [
"MIT"
] | null | null | null | src/main/java/net/ugorji/oxygen/markup/indexing/MarkupIndexingParserBase.java | ugorji/java-markup | 938947a81c221360759e8e8a7fe10eaf15aaa426 | [
"MIT"
] | null | null | null | src/main/java/net/ugorji/oxygen/markup/indexing/MarkupIndexingParserBase.java | ugorji/java-markup | 938947a81c221360759e8e8a7fe10eaf15aaa426 | [
"MIT"
] | null | null | null | 30.329897 | 107 | 0.701224 | 1,003,693 | /* <<< COPYRIGHT START >>>
* Copyright 2006-Present OxygenSoftwareLibrary.com
* Licensed under the GNU Lesser General Public License.
* http://www.gnu.org/licenses/lgpl.html
*
* @author: Ugorji Nwoke
* <<< COPYRIGHT END >>>
*/
package net.ugorji.oxygen.markup.indexing;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import net.ugorji.oxygen.markup.MarkupLink;
import net.ugorji.oxygen.markup.MarkupParser;
import net.ugorji.oxygen.markup.MarkupParserBase;
import net.ugorji.oxygen.util.StringUtils;
public class MarkupIndexingParserBase extends MarkupParserBase {
// protected static Pattern pattern = Pattern.compile("[\\:\\-\\.\\{\\}\\(\\)]");
protected static Pattern pattern = Pattern.compile("[\\:\\{\\}\\(\\)]");
protected List tokenstrings = null;
protected HashSet hs = null;
protected MarkupParser mp;
public MarkupIndexingParserBase(MarkupParser mp0, List _tokenstrings, HashSet _hs)
throws Exception {
mp = mp0;
tokenstrings = _tokenstrings;
hs = _hs;
}
public MarkupParser getMarkupParser() {
return mp;
}
public void link(MarkupLink mlink, boolean doPrint) throws Exception {
if (tokenstrings == null) return;
tokenizeAndAdd(mlink.text);
tokenizeAndAdd(mlink.text2);
tokenstrings.add(mlink.urlpart);
}
public void word(String s, boolean isSlashSeperated, boolean doPrint) throws Exception {
if (tokenstrings == null) return;
String s2 = s;
// List ll = StringUtils.tokens(s2, ":-.", true, true);
List ll = StringUtils.tokens(s2, ":", true, true);
tokenstrings.addAll(ll);
}
public void do_emoticon(String s) {}
public void macro(String s, boolean hascontent) throws Exception {
tokenizeAndAdd(s);
}
public void comment(String s) throws Exception {
tokenizeAndAdd(s);
}
public void preformatted(String s) throws Exception {
tokenizeAndAdd(s);
}
public void escapedWord(String s) throws Exception {
tokenizeAndAdd(s);
}
private void tokenizeAndAdd(String s) throws Exception {
if (tokenstrings == null || StringUtils.isBlank(s)) return;
s = pattern.matcher(s).replaceAll(" ");
List ll = StringUtils.tokens(s, " ", true, true);
tokenstrings.addAll(ll);
}
}
/*
public void link(MarkupLink mlink, boolean doPrint) throws Exception {
if(tokenstrings == null) return;
if(!StringUtils.isBlank(mlink.text)) {
MarkupParser mp0 = mp.newMarkupParser(new StringReader(mlink.text));
MarkupIndexingParser wimap = new MarkupIndexingParser(mp0, rc, re, textSourceName, tokenstrings, hs);
wimap.markupToHTML();
}
if(!StringUtils.isBlank(mlink.text2)) {
MarkupParser mp0 = mp.newMarkupParser(new StringReader(mlink.text2));
MarkupIndexingParser wimap = new MarkupIndexingParser(mp0, rc, re, textSourceName, tokenstrings, hs);
wimap.markupToHTML();
}
tokenstrings.add(mlink.urlpart);
}
*/
|
92463de37c69090562ddb168fed8b752590c476f | 1,569 | java | Java | FeedbackRest/src/main/java/com/feedback/entities/FeedbackParticipant1.java | smadanu-git/FeedbackWebApp | f42bef57ad5567f2cafe37db01a7c6cfb628ba60 | [
"MIT"
] | null | null | null | FeedbackRest/src/main/java/com/feedback/entities/FeedbackParticipant1.java | smadanu-git/FeedbackWebApp | f42bef57ad5567f2cafe37db01a7c6cfb628ba60 | [
"MIT"
] | null | null | null | FeedbackRest/src/main/java/com/feedback/entities/FeedbackParticipant1.java | smadanu-git/FeedbackWebApp | f42bef57ad5567f2cafe37db01a7c6cfb628ba60 | [
"MIT"
] | null | null | null | 23.073529 | 69 | 0.779477 | 1,003,694 | package com.feedback.entities;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the feedback_participants database table.
*
*/
public class FeedbackParticipant1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private long id;
//bi-directional many-to-one association to Feedback
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="feedback_id")
private Feedback feedback;
//bi-directional many-to-one association to Participant
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="participant_id")
private Participant participant;
public FeedbackParticipant1() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Feedback getFeedback() {
return this.feedback;
}
public void setFeedback(Feedback feedback) {
this.feedback = feedback;
}
public Participant getParticipant() {
return this.participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
}
}
|
92463f53ac2bbdbd0ccb0cbb83367e3e44d3d877 | 16,937 | java | Java | rationals/src/test/java/prover/SubsumptionTest.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | rationals/src/test/java/prover/SubsumptionTest.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | rationals/src/test/java/prover/SubsumptionTest.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | 31.249077 | 98 | 0.601287 | 1,003,695 | package prover;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.WeakHashMap;
import org.junit.Test;
public class SubsumptionTest {
private Term random(Function[] predicates, Function[] functions, Term[] atoms, Random random) {
var depth = random.nextInt(5);
if (random.nextInt(3) == 0) {
var a = random(functions, atoms, depth, random);
var b = random(functions, atoms, depth, random);
switch (random.nextInt(5)) {
case 0:
case 1:
case 2:
return a.eq(b);
case 3:
return a.less(b);
case 4:
return a.lessEq(b);
}
}
var f = predicates[random.nextInt(predicates.length)];
var n = f.arity();
if (n > 0) {
var args = new Term[n];
for (var i = 0; i < args.length; i++) {
args[i] = random(functions, atoms, depth, random);
}
return f.call(args);
}
return f;
}
private Term random(Function[] functions, Term[] atoms, int depth, Random random) {
if (depth > 0) {
if (random.nextInt(10) == 0) {
var a = random(functions, atoms, depth - 1, random);
var b = random(functions, atoms, depth - 1, random);
switch (random.nextInt(3)) {
case 0:
return a.add(b);
case 1:
return a.subtract(b);
case 2:
return a.multiply(b);
}
}
var f = functions[random.nextInt(functions.length)];
var n = f.arity();
if (n > 0) {
var args = new Term[n];
for (var i = 0; i < args.length; i++) {
args[i] = random(functions, atoms, depth - 1, random);
}
return f.call(args);
}
return f;
}
return atoms[random.nextInt(atoms.length)];
}
private Clause randomClause(
Function[] predicates, Function[] functions, Term[] atoms, Random random) {
var n = 1 + random.nextInt(5);
var negative = new ArrayList<Term>(n);
for (var i = 0; i < n; i++) {
negative.add(random(predicates, functions, atoms, random));
}
n = 1 + random.nextInt(5);
var positive = new ArrayList<Term>(n);
for (var i = 0; i < n; i++) {
positive.add(random(predicates, functions, atoms, random));
}
return new ClauseInput(negative, positive, null, null);
}
private List<Clause> randomClauses(int n) {
// Predicates
var predicates = new ArrayList<Function>();
predicates.add(new Function(Type.BOOLEAN, "p"));
predicates.add(new Function(Type.of(Type.BOOLEAN, Type.INTEGER), "p1"));
predicates.add(new Function(Type.of(Type.BOOLEAN, Type.INTEGER, Type.INTEGER), "p2"));
predicates.add(new Function(Type.BOOLEAN, "q"));
predicates.add(new Function(Type.of(Type.BOOLEAN, Type.INTEGER), "q1"));
predicates.add(new Function(Type.of(Type.BOOLEAN, Type.INTEGER, Type.INTEGER), "q2"));
var predicates1 = predicates.toArray(new Function[0]);
// Functions
var functions = new ArrayList<Function>();
functions.add(new Function(Type.of(Type.INTEGER, Type.INTEGER), "a1"));
functions.add(new Function(Type.of(Type.INTEGER, Type.INTEGER, Type.INTEGER), "a2"));
functions.add(new Function(Type.of(Type.INTEGER, Type.INTEGER), "b1"));
functions.add(new Function(Type.of(Type.INTEGER, Type.INTEGER, Type.INTEGER), "b2"));
var funcs1 = functions.toArray(new Function[0]);
// Atoms
var atoms = new ArrayList<Term>();
atoms.add(Term.of(0));
atoms.add(Term.of(1));
atoms.add(new Variable(Type.INTEGER));
atoms.add(new Variable(Type.INTEGER));
atoms.add(new Variable(Type.INTEGER));
atoms.add(new Variable(Type.INTEGER));
atoms.add(new Function(Type.INTEGER, "a"));
atoms.add(new Function(Type.INTEGER, "b"));
var atoms1 = atoms.toArray(new Term[0]);
// Clauses
var random = new Random(0);
var r = new ArrayList<Clause>();
for (var i = 0; i < n; i++) {
var c = randomClause(predicates1, funcs1, atoms1, random);
r.add(c);
}
return r;
}
@Test
public void randomTest() {
// For a more thorough but slower test
// increase n to e.g. 10000
var clauses = randomClauses(300);
var subsumption = new Subsumption(clauses);
// Slow way
var clauses1 = new ArrayList<Clause>();
var subsumed1 = new WeakHashMap<Clause, Boolean>();
loop:
for (var d : clauses) {
for (var c : clauses1) {
if (subsumption.subsumes(c, d)) {
continue loop;
}
}
for (var c : clauses1) {
if (subsumption.subsumes(d, c)) {
subsumed1.put(c, true);
}
}
clauses1.add(d);
}
// Fast way
var clauses2 = new ArrayList<Clause>();
for (var d : clauses) {
if (!subsumption.add(d)) {
continue;
}
clauses2.add(d);
}
// Compare
assertEquals(clauses1, clauses2);
for (var i = 0; i < clauses1.size(); i++) {
assertEquals(subsumed1.containsKey(clauses1.get(i)), subsumption.subsumed(clauses2.get(i)));
}
}
@Test
public void subsumes() {
var a = new Function(Type.INTEGER, "a");
var a1 = new Function(Type.of(Type.INTEGER, Type.INTEGER), "a1");
var b = new Function(Type.INTEGER, "b");
var p = new Function(Type.BOOLEAN, "p");
var p1 = new Function(Type.of(Type.BOOLEAN, Type.INTEGER), "p1");
var p2 = new Function(Type.of(Type.BOOLEAN, Type.INTEGER, Type.INTEGER), "p2");
var q = new Function(Type.BOOLEAN, "q");
var q1 = new Function(Type.of(Type.BOOLEAN, Type.INTEGER), "q1");
var q2 = new Function(Type.of(Type.BOOLEAN, Type.INTEGER, Type.INTEGER), "q2");
var x = new Variable(Type.INTEGER);
var y = new Variable(Type.INTEGER);
var negative = new ArrayList<Term>();
var positive = new ArrayList<Term>();
Clause c, d;
var subsumption = new Subsumption(new ArrayList<>());
// false <= false
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
// false <= p
negative.clear();
positive.clear();
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p);
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p <= p
negative.clear();
positive.clear();
positive.add(p);
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p);
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
// !p <= !p
negative.clear();
negative.add(p);
positive.clear();
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
negative.add(p);
positive.clear();
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
// p <= p | p
negative.clear();
positive.clear();
positive.add(p);
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p);
positive.add(p);
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p !<= !p
negative.clear();
positive.clear();
positive.add(p);
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
negative.add(p);
positive.clear();
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertFalse(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p | q <= q | p
negative.clear();
positive.clear();
positive.add(p);
positive.add(q);
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(q);
positive.add(p);
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// p | q <= p | q | p
negative.clear();
positive.clear();
positive.add(p);
positive.add(q);
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p);
positive.add(q);
positive.add(p);
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(a) | p(b) | q(a) | q(b) | <= p(a) | q(a) | p(b) | q(b)
negative.clear();
positive.clear();
positive.add(p1.call(a));
positive.add(p1.call(b));
positive.add(q1.call(a));
positive.add(q1.call(b));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(a));
positive.add(q1.call(a));
positive.add(p1.call(b));
positive.add(q1.call(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// p(6,7) | p(4,5) <= q(6,7) | q(4,5) | p(0,1) | p(2,3) | p(4,4) | p(4,5) | p(6,6) | p(6,7)
negative.clear();
positive.clear();
positive.add(p2.call(Term.of(6), Term.of(7)));
positive.add(p2.call(Term.of(4), Term.of(5)));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(q2.call(Term.of(6), Term.of(7)));
positive.add(q2.call(Term.of(4), Term.of(5)));
positive.add(p2.call(Term.of(0), Term.of(1)));
positive.add(p2.call(Term.of(2), Term.of(3)));
positive.add(p2.call(Term.of(4), Term.of(4)));
positive.add(p2.call(Term.of(4), Term.of(5)));
positive.add(p2.call(Term.of(6), Term.of(6)));
positive.add(p2.call(Term.of(6), Term.of(7)));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(x,y) <= p(a,b)
negative.clear();
positive.clear();
positive.add(p2.call(x, y));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p2.call(a, b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(x,x) !<= p(a,b)
negative.clear();
positive.clear();
positive.add(p2.call(x, x));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p2.call(a, b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertFalse(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(x) <= p(y)
negative.clear();
positive.clear();
positive.add(p1.call(x));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(y));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// p(x) | p(a(x)) | p(a(a(x))) <= p(y) | p(a(y)) | p(a(a(y)))
negative.clear();
positive.clear();
positive.add(p1.call(x));
positive.add(p1.call(a1.call(x)));
positive.add(p1.call(a1.call(a1.call(x))));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(y));
positive.add(p1.call(a1.call(y)));
positive.add(p1.call(a1.call(a1.call(y))));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// p(x) | p(a) <= p(a) | p(b)
negative.clear();
positive.clear();
positive.add(p1.call(x));
positive.add(p1.call(a));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(a));
positive.add(p1.call(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(x) | p(a(x)) <= p(a(y)) | p(y)
negative.clear();
positive.clear();
positive.add(p1.call(x));
positive.add(p1.call(a1.call(x)));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(a1.call(y)));
positive.add(p1.call(y));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// p(x) | p(a(x)) | p(a(a(x))) <= p(a(a(y))) | p(a(y)) | p(y)
negative.clear();
positive.clear();
positive.add(p1.call(x));
positive.add(p1.call(a1.call(x)));
positive.add(p1.call(a1.call(a1.call(x))));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p1.call(a1.call(a1.call(y))));
positive.add(p1.call(a1.call(y)));
positive.add(p1.call(y));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertTrue(subsumption.subsumes(d, c));
// (a = x) <= (a = b)
negative.clear();
positive.clear();
positive.add(a.eq(x));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(a.eq(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// (x = a) <= (a = b)
negative.clear();
positive.clear();
positive.add(x.eq(a));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(a.eq(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// !p(y) | !p(x) | q(x) <= !p(a) | !p(b) | q(b)
negative.clear();
negative.add(p1.call(y));
negative.add(p1.call(x));
positive.clear();
positive.add(q1.call(x));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
negative.add(p1.call(a));
negative.add(p1.call(b));
positive.clear();
positive.add(q1.call(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// !p(x) | !p(y) | q(x) <= !p(a) | !p(b) | q(b)
negative.clear();
negative.add(p1.call(x));
negative.add(p1.call(y));
positive.clear();
positive.add(q1.call(x));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
negative.add(p1.call(a));
negative.add(p1.call(b));
positive.clear();
positive.add(q1.call(b));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertTrue(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// (x = a) | (1 = y) !<= (1 = a) | (x = 0)
negative.clear();
positive.clear();
positive.add(x.eq(a));
positive.add(Term.of(1).eq(y));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(Term.of(1).eq(a));
positive.add(x.eq(Term.of(0)));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertFalse(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
// p(x,a(x)) !<= p(a(y),a(y))
negative.clear();
positive.clear();
positive.add(p2.call(x, a1.call(x)));
c = new ClauseInput(negative, positive, null, null);
c.typeCheck();
negative.clear();
positive.clear();
positive.add(p2.call(a1.call(y), a1.call(y)));
d = new ClauseInput(negative, positive, null, null);
d.typeCheck();
assertFalse(subsumption.subsumes(c, d));
assertFalse(subsumption.subsumes(d, c));
}
}
|
924640289e8c1593fb2ad02181efe0a84f6d480e | 803 | java | Java | src/main/java/br/com/zupacademy/renato/casadocodigo/autor/AutorController.java | RenatoFOZupper/orange-talents-03-template-casa-do-codigo | 297ccaa3839f28bda691bdb8abc9dc098c68d388 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/renato/casadocodigo/autor/AutorController.java | RenatoFOZupper/orange-talents-03-template-casa-do-codigo | 297ccaa3839f28bda691bdb8abc9dc098c68d388 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/renato/casadocodigo/autor/AutorController.java | RenatoFOZupper/orange-talents-03-template-casa-do-codigo | 297ccaa3839f28bda691bdb8abc9dc098c68d388 | [
"Apache-2.0"
] | null | null | null | 27.689655 | 68 | 0.815691 | 1,003,696 | package br.com.zupacademy.renato.casadocodigo.autor;
import javax.transaction.Transactional;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/autores")
public class AutorController {
private AutorRepository autorRepository;
public AutorController(AutorRepository autorRepository) {
this.autorRepository = autorRepository;
}
@PostMapping
@Transactional
public String criaAutor(@RequestBody @Valid AutorRequest request) {
Autor autor = request.toModel();
autorRepository.save(autor);
return autor.toString();
}
}
|
9246411c84fa286c23508f4d14e0b7cdf7bd8523 | 1,892 | java | Java | APK/flappybirds/sources/org/andengine/opengl/b/e.java | F7YYY/IT178 | afdb9bd36d4ff237f8677d4475f8b911e6a0cda5 | [
"MIT"
] | 1 | 2020-12-16T20:02:40.000Z | 2020-12-16T20:02:40.000Z | APK/flappybirds/sources/org/andengine/opengl/b/e.java | F7YYY/IT178 | afdb9bd36d4ff237f8677d4475f8b911e6a0cda5 | [
"MIT"
] | null | null | null | APK/flappybirds/sources/org/andengine/opengl/b/e.java | F7YYY/IT178 | afdb9bd36d4ff237f8677d4475f8b911e6a0cda5 | [
"MIT"
] | null | null | null | 39.416667 | 662 | 0.67019 | 1,003,697 | package org.andengine.opengl.b;
import android.opengl.GLES20;
import org.andengine.opengl.d.a.c;
public class e extends g {
public static int a = -1;
public static int b = -1;
public static int c = -1;
public static int d = -1;
private static e e;
private e() {
super("uniform mat4 u_modelViewProjectionMatrix;\nattribute vec4 a_position;\nattribute vec2 a_textureCoordinates;\nvarying vec2 v_textureCoordinates;\nvoid main() {\n\tv_textureCoordinates = a_textureCoordinates;\n\tgl_Position = u_modelViewProjectionMatrix * a_position;\n}", "precision lowp float;\nuniform sampler2D u_texture_0;\nuniform sampler2D u_texture_1;\nuniform bool u_textureselect_texture_0;\nvarying mediump vec2 v_textureCoordinates;\nvoid main() {\n\tif(u_textureselect_texture_0) {\n\t\tgl_FragColor = texture2D(u_texture_0, v_textureCoordinates);\n\t} else {\n\t\tgl_FragColor = texture2D(u_texture_1, v_textureCoordinates);\n\t}\n}");
}
public static e a() {
if (e == null) {
e = new e();
}
return e;
}
/* access modifiers changed from: protected */
public void a(org.andengine.opengl.util.e eVar) {
GLES20.glBindAttribLocation(this.h, 0, "a_position");
GLES20.glBindAttribLocation(this.h, 3, "a_textureCoordinates");
super.a(eVar);
a = a("u_modelViewProjectionMatrix");
b = a("u_texture_0");
c = a("u_texture_1");
d = a("u_textureselect_texture_0");
}
public void a(org.andengine.opengl.util.e eVar, c cVar) {
GLES20.glDisableVertexAttribArray(1);
super.a(eVar, cVar);
GLES20.glUniformMatrix4fv(a, 1, false, eVar.p(), 0);
GLES20.glUniform1i(b, 0);
GLES20.glUniform1i(c, 1);
}
public void b(org.andengine.opengl.util.e eVar) {
GLES20.glEnableVertexAttribArray(1);
super.b(eVar);
}
}
|
92464162167fbd31b65c0dfc311ee000355ce102 | 5,515 | java | Java | bascomtask-core/src/main/java/com/ebay/bascomtask/core/TimeBox.java | eBay/bascomtask | 71daa09c8e9546fd8b57230f5e9587529804cda8 | [
"Apache-2.0"
] | 47 | 2018-05-21T16:17:06.000Z | 2022-03-20T16:51:51.000Z | bascomtask-core/src/main/java/com/ebay/bascomtask/core/TimeBox.java | eBay/bascomtask | 71daa09c8e9546fd8b57230f5e9587529804cda8 | [
"Apache-2.0"
] | 2 | 2019-05-05T05:56:02.000Z | 2021-04-24T15:49:09.000Z | bascomtask-core/src/main/java/com/ebay/bascomtask/core/TimeBox.java | eBay/bascomtask | 71daa09c8e9546fd8b57230f5e9587529804cda8 | [
"Apache-2.0"
] | 11 | 2018-09-07T16:01:35.000Z | 2022-02-05T00:53:41.000Z | 34.46875 | 133 | 0.57262 | 1,003,698 | /*-**********************************************************************
Copyright 2018 eBay Inc.
Author/Developer: Brendan McCarthy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
package com.ebay.bascomtask.core;
import com.ebay.bascomtask.exceptions.TimeoutExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Records user-requested timeout durations and detects when that timeout has been exceeded.
*
* @author Brendan McCarthy
*/
class TimeBox {
private static final Logger LOG = LoggerFactory.getLogger(TimeBox.class);
// Static instance used for no-timeout case (timeBudget==0) since there is no need to have a unique
// instance for values that will always be the same
static final TimeBox NO_TIMEOUT = new TimeBox(0);
// How many milliseconds before the timeout
final long timeBudget;
// When did the clock start, in milliseconds
final long start;
// Records threads to be interrupted, when the TimeoutStrategy in effect calls for interrupts
private List<Thread> activeThreeads = null;
/**
* A timeBudget of zero means no timeout check will later be made.
*
* @param timeBudget to (later) check for
*/
TimeBox(long timeBudget) {
this.timeBudget = timeBudget;
this.start = System.currentTimeMillis();
}
@Override
public String toString() {
if (timeBudget == 0) {
return "TimeBox(0)";
} else {
long left = (start + timeBudget) - System.currentTimeMillis();
String msg = isTimedOut() ? "EXCEEDED" : (left + "ms left");
return "TimeBox(" + start + "," + timeBudget + ',' + msg + ')';
}
}
private boolean isTimedOut() {
// Apply gt here rather than gte since in some spawnmodes we get to this point very quickly
return System.currentTimeMillis() > start + timeBudget;
}
void checkIfTimeoutExceeded(Binding<?> binding) {
if (timeBudget > 0 && isTimedOut()) {
String msg = "Timeout " + timeBudget + " exceeded before " + binding.getTaskPlusMethodName() + ", ceasing task creation";
LOG.debug("Throwing " + msg);
throw new TimeoutExceededException(msg);
}
}
void checkForInterruptsNeeded(Binding<?> binding) {
if (timeBudget > 0) {
if (binding.engine.getTimeoutStrategy() == TimeoutStrategy.INTERRUPT_AT_NEXT_OPPORTUNITY) {
if (isTimedOut()) {
interruptRegisteredThreads();
}
}
}
}
/**
* Interrupts any currently-registered thread.
*/
void interruptRegisteredThreads() {
synchronized (this) {
if (activeThreeads != null) {
int count = activeThreeads.size() - 1; // Exclude current thread
if (count > 0) {
String msg = " on timeout " + timeBudget + " exceeded";
for (Thread next : activeThreeads) {
if (next != Thread.currentThread()) {
LOG.debug("Interrupting " + next.getName() + msg);
next.interrupt();
}
}
}
}
}
}
/**
* Register current thread so that it may later be interrupted on timeout.
*
* @param orchestrator active
*/
void register(Orchestrator orchestrator) {
if (orchestrator.getTimeoutStrategy() != TimeoutStrategy.PREVENT_NEW) {
synchronized (this) {
if (activeThreeads == null) {
activeThreeads = new ArrayList<>();
}
activeThreeads.add(Thread.currentThread());
}
}
}
/**
* De-registers current thead and ensures monitoring thread, if present is notified if there are no
* more registered threads. This call must follow every {@link #register(Orchestrator)} call.
*/
synchronized void deregister() {
if (activeThreeads != null) {
activeThreeads.remove(Thread.currentThread());
if (activeThreeads.size() == 0) {
notify();
}
}
}
/**
* Sets up a monitoring thread if needed.
*
* @param orchestrator context
*/
void monitorIfNeeded(Orchestrator orchestrator) {
if (orchestrator.getTimeoutStrategy() == TimeoutStrategy.INTERRUPT_IMMEDIATELY) {
orchestrator.getExecutorService().execute(() -> {
synchronized (this) {
try {
wait(timeBudget);
interruptRegisteredThreads();
} catch (InterruptedException ignore) {
// do nothing
}
}
});
}
}
}
|
9246441c1b1cc5022a93f751d63bdefe6c432eaf | 2,469 | java | Java | src/org/example/source/org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java | suxingjie99/JavaSource | a7deb777dc3d11a522e2b03bc28598d906ec45f8 | [
"Apache-2.0"
] | null | null | null | src/org/example/source/org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java | suxingjie99/JavaSource | a7deb777dc3d11a522e2b03bc28598d906ec45f8 | [
"Apache-2.0"
] | null | null | null | src/org/example/source/org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java | suxingjie99/JavaSource | a7deb777dc3d11a522e2b03bc28598d906ec45f8 | [
"Apache-2.0"
] | null | null | null | 33.821918 | 179 | 0.707979 | 1,003,699 | package org.omg.DynamicAny.DynAnyFactoryPackage;
/**
* org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u231/13620/corba/src/share/classes/org/omg/DynamicAny/DynamicAny.idl
* Saturday, October 5, 2019 3:17:53 AM PDT
*/
abstract public class InconsistentTypeCodeHelper
{
private static String _id = "IDL:omg.org/DynamicAny/DynAnyFactory/InconsistentTypeCode:1.0";
public static void insert (org.omg.CORBA.Any a, org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper.id (), "InconsistentTypeCode", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode read (org.omg.CORBA.portable.InputStream istream)
{
org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode value = new org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode value)
{
// write the repository ID
ostream.write_string (id ());
}
}
|
92464471f30c78c6554da5e4d320e43c9aa43853 | 511 | java | Java | code/leetcode/DP_343.java | yuhaishenedc/codewar | 8c8e2f448326017b1677a3d330cb5be2797d9e27 | [
"MIT"
] | null | null | null | code/leetcode/DP_343.java | yuhaishenedc/codewar | 8c8e2f448326017b1677a3d330cb5be2797d9e27 | [
"MIT"
] | null | null | null | code/leetcode/DP_343.java | yuhaishenedc/codewar | 8c8e2f448326017b1677a3d330cb5be2797d9e27 | [
"MIT"
] | null | null | null | 23.227273 | 52 | 0.332681 | 1,003,700 | package leetcode;
public class DP_343 {
class Solution {
public int cuttingRope(int n) {
int[] dp=new int[n+1];
dp[1]=1;
dp[2]=1;
for(int i=3;i<=n;i++){
int max=-1;
for(int j=1;j<i;j++){
if(j*Math.max(i-j,dp[i-j])>max){
max=j*Math.max(i-j,dp[i-j]);
}
}
dp[i]=max;
}
return dp[n];
}
}
}
|
9246449b7aa6516860172e91eb25ae400a6c8d63 | 882 | java | Java | spectator-reg-tdigest/src/main/java/com/netflix/spectator/tdigest/TDigestMeter.java | dmuino/spectator | ae6897b4aec7cb77d08d2f6b9e178be4ed4d1841 | [
"Apache-2.0"
] | null | null | null | spectator-reg-tdigest/src/main/java/com/netflix/spectator/tdigest/TDigestMeter.java | dmuino/spectator | ae6897b4aec7cb77d08d2f6b9e178be4ed4d1841 | [
"Apache-2.0"
] | null | null | null | spectator-reg-tdigest/src/main/java/com/netflix/spectator/tdigest/TDigestMeter.java | dmuino/spectator | ae6897b4aec7cb77d08d2f6b9e178be4ed4d1841 | [
"Apache-2.0"
] | null | null | null | 32.666667 | 75 | 0.743764 | 1,003,701 | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spectator.tdigest;
import com.netflix.spectator.api.Meter;
/**
* Meter type for collecting a digest measurment.
*/
interface TDigestMeter extends Meter {
/** Returns the measurement for the last completed interval. */
TDigestMeasurement measureDigest();
}
|
924644b936c8dffed3d02fb7f279b423b90d7fc0 | 693 | java | Java | src/main/java/com/mongodb/kafka/connect/source/codec/JsonCodecProvider.java | koi8-r/mongo-kafka | 6c3c9830444569e23c07b87c6f738fc1920645d9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mongodb/kafka/connect/source/codec/JsonCodecProvider.java | koi8-r/mongo-kafka | 6c3c9830444569e23c07b87c6f738fc1920645d9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mongodb/kafka/connect/source/codec/JsonCodecProvider.java | koi8-r/mongo-kafka | 6c3c9830444569e23c07b87c6f738fc1920645d9 | [
"Apache-2.0"
] | null | null | null | 27.72 | 86 | 0.707071 | 1,003,702 | package com.mongodb.kafka.connect.source.codec ;
import org.bson.codecs.Codec ;
import org.bson.codecs.configuration.CodecProvider ;
import org.bson.codecs.configuration.CodecRegistry ;
import java.util.HashMap ;
import java.util.Map ;
import java.util.UUID ;
public class JsonCodecProvider implements CodecProvider {
private final Map<Class<?>, Codec<?>> codecs = new HashMap<Class<?>, Codec<?>>() ;
public JsonCodecProvider() {
codecs.put(UUID.class, new JsonUuidCodec(true)) ;
}
@Override
@SuppressWarnings("unchecked")
public <T> Codec<T> get(final Class<T> clazz, final CodecRegistry registry) {
return (Codec<T>) codecs.get(clazz) ;
}
}
|
924645535266abc6d74cdb4b670181e62ddcfe44 | 969 | java | Java | wildfly/cdi-config/src/main/java/org/wildfly/swarm/ts/wildfly/cdi/config/HelloServlet.java | mirostary/thorntail-test-suite | b04ba1ec4f3dc25f5128a3fea20fec94ee4f595e | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2019-09-16T14:02:42.000Z | 2020-08-12T13:01:34.000Z | wildfly/cdi-config/src/main/java/org/wildfly/swarm/ts/wildfly/cdi/config/HelloServlet.java | mirostary/thorntail-test-suite | b04ba1ec4f3dc25f5128a3fea20fec94ee4f595e | [
"ECL-2.0",
"Apache-2.0"
] | 58 | 2018-07-16T11:37:15.000Z | 2022-01-07T09:22:02.000Z | wildfly/cdi-config/src/main/java/org/wildfly/swarm/ts/wildfly/cdi/config/HelloServlet.java | mirostary/thorntail-test-suite | b04ba1ec4f3dc25f5128a3fea20fec94ee4f595e | [
"ECL-2.0",
"Apache-2.0"
] | 13 | 2018-06-05T11:28:52.000Z | 2020-08-12T12:34:20.000Z | 33.413793 | 129 | 0.772962 | 1,003,703 | package org.wildfly.swarm.ts.wildfly.cdi.config;
import org.wildfly.swarm.spi.api.config.ConfigKey;
import org.wildfly.swarm.spi.api.config.ConfigView;
import org.wildfly.swarm.spi.runtime.annotations.ConfigurationValue;
import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/")
public class HelloServlet extends HttpServlet {
@Inject
@ConfigurationValue("app.config")
private String appConfig;
@Inject
private ConfigView configView;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Value of app.config: " + appConfig);
resp.getWriter().println("ConfigView contains app.config: " + configView.hasKeyOrSubkeys(ConfigKey.parse("app.config")));
}
}
|
9246459d850830371cf05d4a9081e166de48aa71 | 2,307 | java | Java | geoportal/src/com/esri/gpt/catalog/search/ISearchSaveRepository.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 176 | 2015-01-08T19:00:40.000Z | 2022-03-23T10:17:30.000Z | geoportal/src/com/esri/gpt/catalog/search/ISearchSaveRepository.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 224 | 2015-01-05T16:17:21.000Z | 2021-08-30T22:39:28.000Z | geoportal/src/com/esri/gpt/catalog/search/ISearchSaveRepository.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 88 | 2015-01-15T11:47:05.000Z | 2022-03-10T02:06:46.000Z | 27.795181 | 80 | 0.720416 | 1,003,704 | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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 com.esri.gpt.catalog.search;
import com.esri.gpt.framework.security.principal.User;
/**
* The Interface ISearchHibernation. Represents a repository
* where the search criteria will be kept for each user who
* wants to save a search for a later time.
*/
public interface ISearchSaveRepository {
// methods =====================================================================
/**
* Saves the criteria onto the repository.
*
* @param savedCriteria the criteria
*
* @throws SearchException the search exception
*/
public void save(SavedSearchCriteria savedCriteria)throws SearchException;
/**
* Returns the original search criteria from the repository.
* @param id id of the search
* @param user user
* @return search criteria
* @throws SearchException the search exception
*/
public SearchCriteria getSearchCriteria(Object id, User user)
throws SearchException;
/**
* Delete.
*
* @param id the id of the search to be deleted
* @param user the user user associated with action
*
* @throws SearchException the search exception
*/
public void delete(Object id, User user)
throws SearchException;
/**
* Gets the saved list.
*
* @param user the user
*
* @return the saved list
*
* @throws SearchException the search exception
*/
public SavedSearchCriterias getSavedList(User user)throws SearchException;
/**
* Save.
*
* @param name the name
* @param restCriteria the rest criteria
* @param user the user
* @throws SearchException the search exception
*/
public void save(String name, String restCriteria, User user)
throws SearchException;
}
|
924645b9666ad9cba8fb23f05a244a487af8e7f0 | 2,068 | java | Java | src/test/java/com/google/maps/internal/UrlSignerTest.java | ljfabiano3/googlemaps | 3160ddedc546a7c0602483b7612dffa7153b883e | [
"Apache-2.0"
] | 2 | 2021-09-07T12:09:06.000Z | 2021-09-10T16:15:24.000Z | src/test/java/com/google/maps/internal/UrlSignerTest.java | ljfabiano3/googlemaps | 3160ddedc546a7c0602483b7612dffa7153b883e | [
"Apache-2.0"
] | 1 | 2021-06-04T00:14:04.000Z | 2021-06-04T00:14:04.000Z | src/test/java/com/google/maps/internal/UrlSignerTest.java | ljfabiano3/googlemaps | 3160ddedc546a7c0602483b7612dffa7153b883e | [
"Apache-2.0"
] | null | null | null | 34.163934 | 91 | 0.703935 | 1,003,705 | /*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.google.maps.internal;
import static org.junit.Assert.assertEquals;
import com.google.maps.SmallTests;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import okio.ByteString;
/**
* Test case for {@link UrlSigner}.
*/
@Category(SmallTests.class)
public class UrlSignerTest {
// From http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
// HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog")
// = 0xax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b
private static final String MESSAGE = "The quick brown fox jumps over the lazy dog";
private static final String SIGNING_KEY = ByteString.of("key".getBytes())
.base64().replace('+', '-').replace('/', '_');
private static final String SIGNATURE = ByteString.of(
hexStringToByteArray("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b")).base64()
.replace('+', '-').replace('/', '_');
@Test
public void testUrlSigner() throws Exception {
UrlSigner urlSigner = new UrlSigner(SIGNING_KEY);
assertEquals(SIGNATURE, urlSigner.getSignature(MESSAGE));
}
// Helper code from http://stackoverflow.com/questions/140131/
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
|
92464693ec125a5280ed2562ceb42d3fda6fa899 | 5,311 | java | Java | frontend/src/test/java/org/abs_models/frontend/mtvl/ChocoSolverExperiment.java | oab/abstools | 6f245ec8d684efb0977049d075e853a4b4d7d8dc | [
"BSD-3-Clause"
] | 38 | 2015-04-23T09:08:06.000Z | 2022-03-18T19:26:34.000Z | frontend/src/test/java/org/abs_models/frontend/mtvl/ChocoSolverExperiment.java | oab/abstools | 6f245ec8d684efb0977049d075e853a4b4d7d8dc | [
"BSD-3-Clause"
] | 271 | 2015-07-30T19:04:52.000Z | 2022-03-28T09:05:50.000Z | frontend/src/test/java/org/abs_models/frontend/mtvl/ChocoSolverExperiment.java | oab/abstools | 6f245ec8d684efb0977049d075e853a4b4d7d8dc | [
"BSD-3-Clause"
] | 33 | 2015-04-23T09:08:09.000Z | 2022-01-26T08:11:55.000Z | 34.044872 | 139 | 0.597251 | 1,003,706 | /*
* Copyright (c) 2009-2011, The HATS Consortium. All rights reserved.
* This file is licensed under the terms of the Modified BSD License.
*/
package org.abs_models.frontend.mtvl;
import java.text.MessageFormat;
import choco.Choco;
import choco.cp.model.CPModel;
import choco.cp.solver.CPSolver;
import choco.kernel.common.logging.ChocoLogging;
import choco.kernel.common.logging.Verbosity;
import choco.kernel.model.constraints.Constraint;
import choco.kernel.model.variables.integer.IntegerVariable;
public class ChocoSolverExperiment {
@SuppressWarnings("unused")
public static void main(final String[] args) throws Exception {
CPModel m = new CPModel();
boolean verbose = false;
if (!verbose) ChocoLogging.setVerbosity(Verbosity.OFF);
IntegerVariable i1 = Choco.makeIntVar("i1",-10,100); //m.addVariable(i1);
IntegerVariable i2 = Choco.makeIntVar("i2",-10,100); //m.addVariable(i2);
IntegerVariable i3 = Choco.makeIntVar("i3",-10,100); //m.addVariable(i3);
IntegerVariable i4 = Choco.makeIntVar("i4",-10,100); //m.addVariable(i4);
IntegerVariable b1 = Choco.makeBooleanVar("b1"); //m.addVariable(b1);
IntegerVariable b2 = Choco.makeBooleanVar("b2"); //m.addVariable(b2);
IntegerVariable b3 = Choco.makeBooleanVar("b3"); //m.addVariable(b3);
IntegerVariable b4 = Choco.makeBooleanVar("b4"); //m.addVariable(b4);
IntegerVariable b5 = Choco.makeBooleanVar("b5"); //m.addVariable(b5);
m.addConstraint(
// Choco.and(Choco.eq(i1, 1), Choco.TRUE)
// Choco.or(Choco.eq(b1,1),Choco.eq(b2,1)) // b1 && b2
// Choco.and( Choco.lt(i1, i2) , Choco.lt(i2, 7) )
Choco.or(Choco.eq(i1,-3), Choco.eq(i1,5))
// Choco.and(Choco.and(b1),Choco.TRUE)
// Choco.ifOnlyIf( Choco.and( Choco.leq(i3, 9), Choco.eq(i1, Choco.mult(10, Choco.abs(i2))) ), Choco.TRUE )
);
// Build the solver
CPSolver s = new CPSolver();
if (verbose)
System.out.println("####" + s.getConfiguration().stringPropertyNames());
// print the problem
if (verbose)
System.out.println(m.pretty());
// Read the model
s.read(m);
// Solve the model
// s.solve();
// s.setObjective(s.getVar(i1))
Boolean solved = //s.solve(); //
s.maximize(s.getVar(i1), true);
if (solved) {
System.out.println("i1: "+s.getVar(i1).getVal());
// System.out.println("i2: "+s.getVar(i2).getVal());
}
else {
System.out.println("no sol...");
}
try {
// s.getVar(b1).setVal(1);
//// s.getVar(b2).setVal(0);
//// s.getVar(b3).setVal(1);
// System.out.println("$$$ check sol: "+s.checkSolution()+" $$$");
// System.out.println("$$$ b1: "+s.getVar(b1).isInstantiated()+" $$$");
// System.out.println("$$$ b2: "+s.getVar(b2).isInstantiated()+" $$$");
}
catch (Exception e1) {
// Catch-all
System.err.println("$$$ Failed to check solution... $$$");
// e1.printStackTrace();
}
if (verbose)
System.out.println(s.pretty());
}
public static void othermain(final String[] args) throws Exception {
// Constant declaration
int n = 3; // Order of the magic square
int magicSum = n * (n * n + 1) / 2; // Magic sum
// Build the model
CPModel m = new CPModel();
// Creation of an array of variables
IntegerVariable[][] var = new IntegerVariable[n][n];
// For each variable, we define its name and the boundaries of its domain.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
var[i][j] = Choco.makeIntVar("var_" + i + "_" + j, 1, n * n);
// Associate the variable to the model.
m.addVariable(var[i][j]);
}
}
// All cells of the matrix must be different
for (int i = 0; i < n * n; i++) {
for (int j = i + 1; j < n * n; j++) {
Constraint c = (Choco.neq(var[i / n][i % n], var[j / n][j % n])); m.addConstraint(c);
}
}
// All rows must be equal to the magic sum
for (int i = 0; i < n; i++) {
m.addConstraint(Choco.eq(Choco.sum(var[i]), magicSum));
}
IntegerVariable[][] varCol = new IntegerVariable[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { // Copy of var in the column order
varCol[i][j] = var[j][i];
}
// Each column?s sum is equal to the magic sum
m.addConstraint(Choco.eq(Choco.sum(varCol[i]), magicSum));
}
IntegerVariable[] varDiag1 = new IntegerVariable[n]; IntegerVariable[] varDiag2 = new IntegerVariable[n]; for (int i = 0; i < n; i++) {
varDiag1[i] = var[i][i]; // Copy of var in varDiag1
varDiag2[i] = var[(n - 1) - i][i]; // Copy of var in varDiag2
}
// Every diagonal?s sum has to be equal to the magic sum
m.addConstraint(Choco.eq(Choco.sum(varDiag1), magicSum)); m.addConstraint(Choco.eq(Choco.sum(varDiag2), magicSum));
// Build the solver
CPSolver s = new CPSolver();
// print the problem
System.out.println(m.pretty());
// Read the model
s.read(m);
// Solve the model
s.solve();
// Print the solution
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(MessageFormat.format("{0} ", s.getVar(var[i][j]).getVal()));
}
System.out.println();
}
}
}
|
92464711bad1cd76f6bfb634e694b745e11bcfce | 1,051 | java | Java | projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/routing_policy/communities/CommunityNotTest.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 763 | 2017-02-21T20:35:50.000Z | 2022-03-29T09:27:14.000Z | projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/routing_policy/communities/CommunityNotTest.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 7,675 | 2017-01-18T08:04:59.000Z | 2022-03-31T21:29:36.000Z | projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/routing_policy/communities/CommunityNotTest.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 194 | 2017-05-03T14:58:10.000Z | 2022-03-30T20:56:44.000Z | 30.028571 | 95 | 0.758325 | 1,003,707 | package org.batfish.datamodel.routing_policy.communities;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.google.common.testing.EqualsTester;
import org.apache.commons.lang3.SerializationUtils;
import org.batfish.common.util.BatfishObjectMapper;
import org.junit.Test;
/** Test of {@link CommunityNot}. */
public final class CommunityNotTest {
private static final CommunityNot EXPR = new CommunityNot(AllStandardCommunities.instance());
@Test
public void testJacksonSerialization() {
assertThat(BatfishObjectMapper.clone(EXPR, CommunityNot.class), equalTo(EXPR));
}
@Test
public void testJavaSerialization() {
assertThat(SerializationUtils.clone(EXPR), equalTo(EXPR));
}
@Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(EXPR, EXPR, new CommunityNot(AllStandardCommunities.instance()))
.addEqualityGroup(new CommunityNot(AllExtendedCommunities.instance()))
.addEqualityGroup(new Object())
.testEquals();
}
}
|
9246471ef11fc309ac3b504e1aa4c8b12e0ed4b4 | 286 | java | Java | chapter_006/src/main/java/ru/job4j/cinemaservice/persistent/HallRepository.java | MedoevRuslan/job4j | 20af579f030b63a89c9d1cfdda15f36540bba0e2 | [
"Apache-2.0"
] | null | null | null | chapter_006/src/main/java/ru/job4j/cinemaservice/persistent/HallRepository.java | MedoevRuslan/job4j | 20af579f030b63a89c9d1cfdda15f36540bba0e2 | [
"Apache-2.0"
] | null | null | null | chapter_006/src/main/java/ru/job4j/cinemaservice/persistent/HallRepository.java | MedoevRuslan/job4j | 20af579f030b63a89c9d1cfdda15f36540bba0e2 | [
"Apache-2.0"
] | null | null | null | 22 | 64 | 0.800699 | 1,003,708 | package ru.job4j.cinemaservice.persistent;
import ru.job4j.cinemaservice.model.Hall;
import ru.job4j.cinemaservice.model.Seat;
import java.util.ArrayList;
import java.util.HashMap;
public interface HallRepository {
HashMap<Integer, ArrayList<Seat>> getSeatsByHall(Hall hall);
}
|
9246476d04588152612e891fe6007e8928ad0141 | 3,542 | java | Java | src/main/java/it/poliba/sisinflab/LODRec/graphkernel/graphEmbedding/Tokenizer.java | sisinflab/lodreclib | 0b933be46b14d74c5313536b055c772d6f1a9d19 | [
"MIT"
] | 19 | 2016-04-02T14:18:22.000Z | 2022-03-29T18:24:18.000Z | src/main/java/it/poliba/sisinflab/LODRec/graphkernel/graphEmbedding/Tokenizer.java | sisinflab/lodreclib | 0b933be46b14d74c5313536b055c772d6f1a9d19 | [
"MIT"
] | null | null | null | src/main/java/it/poliba/sisinflab/LODRec/graphkernel/graphEmbedding/Tokenizer.java | sisinflab/lodreclib | 0b933be46b14d74c5313536b055c772d6f1a9d19 | [
"MIT"
] | 5 | 2016-01-26T03:01:44.000Z | 2020-01-28T09:46:04.000Z | 25.120567 | 112 | 0.643139 | 1,003,709 | package it.poliba.sisinflab.LODRec.graphkernel.graphEmbedding;
import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import it.poliba.sisinflab.LODRec.fileManager.ItemFileManager;
import it.poliba.sisinflab.LODRec.itemManager.ItemTree;
import it.poliba.sisinflab.LODRec.utils.MemoryMonitor;
import it.poliba.sisinflab.LODRec.utils.PropertyFileReader;
import it.poliba.sisinflab.LODRec.utils.TextFileUtils;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class Tokenizer {
private String items_file;
private TIntObjectHashMap<String> props_index; // property index
private TIntObjectHashMap<String> metadata_index; // metadata index
private static Logger logger = LogManager.getLogger(Tokenizer.class.getName());
public Tokenizer(){
// load config file
Map<String, String> prop = null;
try {
prop = PropertyFileReader.loadProperties("config.properties");
this.items_file = prop.get("itemsFile");
loadPropsIndex();
loadMetadataIndex();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
prop.clear();
}
private void loadPropsIndex(){
props_index = new TIntObjectHashMap<String>();
TextFileUtils.loadIndex("props_index", props_index);
}
private void loadMetadataIndex(){
metadata_index = new TIntObjectHashMap<String>();
TextFileUtils.loadIndex("metadata_index", metadata_index);
}
private void tokenize(){
try{
BufferedWriter br = new BufferedWriter(new FileWriter("metadata_string_1"));
ItemFileManager itemReader = new ItemFileManager(items_file, ItemFileManager.READ);
ArrayList<String> items_id = new ArrayList<String>(itemReader.getKeysIndex());
THashMap<String, TIntIntHashMap> branches = null;
ItemTree item = null;
StringBuffer str = null;
for(String item_id : items_id){
item = itemReader.read(item_id);
branches = item.getBranches();
logger.info("Convert " + item_id);
str = new StringBuffer();
str.append(item_id + "\t");
for(String s : branches.keySet()){
String prop = "";
String[] prop_vals = s.split("-");
if(prop_vals.length==1){
for(String ss: prop_vals){
String[] p = props_index.get(Integer.parseInt(ss)).split("/");
prop += p[p.length-1] + "--";
}
for(int f : branches.get(s).keys()){
String[] lbl = metadata_index.get(f).split("/");
str.append(prop + lbl[lbl.length-1].replaceAll("[{'.,;:/}]", "_") + ":" + branches.get(s).get(f) + " ");
}
}
}
br.append(str);
br.newLine();
}
br.flush();
br.close();
itemReader.close();
}
catch(Exception e){
e.printStackTrace();
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Tokenizer ss = new Tokenizer();
long start = System.currentTimeMillis();
ss.tokenize();
long stop = System.currentTimeMillis();
logger.info("Conversion terminated in [sec]: "
+ ((stop - start) / 1000));
MemoryMonitor.stats();
}
}
|
924647bd11df90099fcb2a3775bea77d9fcf36be | 1,271 | java | Java | exam-be/src/main/java/com/vintrace/exam/ServiceRunner.java | ponspeter/vintraceExam | 9e4e20e1c40f91dc5b869e28178d91a3853f900c | [
"MIT"
] | null | null | null | exam-be/src/main/java/com/vintrace/exam/ServiceRunner.java | ponspeter/vintraceExam | 9e4e20e1c40f91dc5b869e28178d91a3853f900c | [
"MIT"
] | null | null | null | exam-be/src/main/java/com/vintrace/exam/ServiceRunner.java | ponspeter/vintraceExam | 9e4e20e1c40f91dc5b869e28178d91a3853f900c | [
"MIT"
] | null | null | null | 33.447368 | 98 | 0.829268 | 1,003,710 | package com.vintrace.exam;
import com.vintrace.exam.config.Initializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import javax.faces.webapp.FacesServlet;
@SpringBootApplication
public class ServiceRunner extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ServiceRunner.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(new Class[] { ServiceRunner.class, Initializer.class});
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf");
return servletRegistrationBean;
}
@Bean
public com.sun.faces.config.ConfigureListener mojarraConfigureListener() {
return new com.sun.faces.config.ConfigureListener();
}
}
|
924647cd743235458e0d910d7637c38486aab067 | 4,632 | java | Java | legacy/clouditor-engine-core/src/test/java/io/clouditor/assurance/CertificationTest.java | clouditor/clouditor | 58a7e43fd70e6177654de6dccd26b5c8f11962dc | [
"Apache-2.0"
] | 49 | 2019-05-13T09:21:48.000Z | 2022-02-12T12:18:24.000Z | clouditor-engine-core/src/test/java/io/clouditor/assurance/CertificationTest.java | kedbirhan/clouditor | 631302858654d07b9e35f7f97c4de234429e5fd4 | [
"Apache-2.0"
] | 504 | 2019-05-26T12:04:16.000Z | 2022-03-31T13:18:35.000Z | clouditor-engine-core/src/test/java/io/clouditor/assurance/CertificationTest.java | kedbirhan/clouditor | 631302858654d07b9e35f7f97c4de234429e5fd4 | [
"Apache-2.0"
] | 15 | 2019-05-27T22:02:35.000Z | 2022-03-30T08:21:00.000Z | 34.827068 | 86 | 0.644214 | 1,003,711 | /*
* Copyright 2016-2019 Fraunhofer AISEC
*
* 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.
*
* $$\ $$\ $$\ $$\
* $$ | $$ |\__| $$ |
* $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\
* $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\
* $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__|
* $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ |
* \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ |
* \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
*
* This file is part of Clouditor Community Edition.
*/
package io.clouditor.assurance;
import io.clouditor.AbstractEngineUnitTest;
import io.clouditor.assurance.ccl.AssetType;
import io.clouditor.assurance.ccl.CCLDeserializer;
import io.clouditor.discovery.Asset;
import io.clouditor.discovery.AssetProperties;
import io.clouditor.discovery.DiscoveryResult;
import io.clouditor.discovery.DiscoveryService;
import io.clouditor.discovery.Scan;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
class CertificationTest extends AbstractEngineUnitTest {
@Test
void testEvaluate() {
// build a simple rule
var rule = new Rule();
rule.addCondition(new CCLDeserializer().parse("MockAsset has property == true"));
var ruleService = this.engine.getService(RuleService.class);
ruleService.getRules().put("MockAsset", Set.of(rule));
// put some assets into our asset service
// TODO: inject service into test
var discoveryService = this.engine.getService(DiscoveryService.class);
var certificationService = this.engine.getService(CertificationService.class);
var properties = new AssetProperties();
properties.put("property", true);
final String assetTypeID = "id";
final AssetType assetType = new AssetType();
assetType.setValue(assetTypeID);
var asset = new Asset("MockAsset", "id", "name", properties);
var discovery = new DiscoveryResult(assetType.getValue());
discovery.setDiscoveredAssets(Map.of(asset.getId(), asset));
// pipe it through the discovery pipeline
discoveryService.submit(new Scan(), discovery);
Certification cert = new Certification();
cert.setId("some-cert");
var control = new Control();
control.setAutomated(true);
control.setControlId("good-control-id");
control.setRules(List.of(rule));
certificationService.startMonitoring(control);
control.evaluate(this.engine.getServiceLocator());
var results = control.getResults();
/*cert.setControls(Arrays.asList(goodControl, controlWithWarnings));
this.engine.modifyCertification(cert);
assertEquals(Fulfillment.GOOD, goodControl.getFulfilled());
assertEquals(Fulfillment.WARNING, controlWithWarnings.getFulfilled());
var assets = this.engine.getNonCompliantAssets("some-cert", "warning-control-id");
assertEquals(1, assets.size());
var detail = (ResultDetail) assets.values().toArray()[0];
assertNotNull(detail);*/
}
/*@Test
void testEqual() {
var cert = new Certification();
var control = new Control();
control.setAutomated(true);
control.setDomain(new Domain("Some Domain"));
control.setObjectives(
Collections.singletonList(new Objective(URI.create("test"), "true", "1")));
cert.setControls(Arrays.asList(control, new Control()));
// compare with self
assertEquals(cert, cert);
// compare with null
assertNotEquals(cert, null);
var other = new Certification();
var otherControl = new Control();
otherControl.setDomain(new Domain("Some Other Domain"));
otherControl.setObjectives(
Collections.singletonList(new Objective(URI.create("test"), "true", "1")));
other.setControls(Collections.singletonList(otherControl));
// compare with other
assertNotEquals(cert, other);
// compare with wrong class
assertNotEquals(cert, new Object());
}*/
}
|
924648293fa45a8fd297b916cc597487cb81b7e6 | 2,598 | java | Java | chest/base-utils/jdk/src/main/java/net/community/chest/dom/impl/StandaloneDOMImplementation.java | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | 1 | 2020-08-12T07:40:11.000Z | 2020-08-12T07:40:11.000Z | chest/base-utils/jdk/src/main/java/net/community/chest/dom/impl/StandaloneDOMImplementation.java | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | null | null | null | chest/base-utils/jdk/src/main/java/net/community/chest/dom/impl/StandaloneDOMImplementation.java | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | null | null | null | 27.638298 | 120 | 0.653965 | 1,003,712 | /*
*
*/
package net.community.chest.dom.impl;
import java.util.Comparator;
import java.util.TreeMap;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
/**
* <P>Copyright 2008 as per GPLv2</P>
*
* @author Lyor G.
* @since Feb 12, 2009 10:52:05 AM
*/
public class StandaloneDOMImplementation extends TreeMap<String,Object> implements DOMImplementation {
/**
*
*/
private static final long serialVersionUID = -834060221307514669L;
public StandaloneDOMImplementation (Comparator<? super String> c)
{
super(c);
}
public StandaloneDOMImplementation ()
{
this(String.CASE_INSENSITIVE_ORDER);
}
public StandaloneDOMImplementation (StandaloneDOMImplementation impl)
{
this();
if ((impl != null) && (impl.size() > 0))
putAll(impl);
}
/*
* @see org.w3c.dom.DOMImplementation#createDocument(java.lang.String, java.lang.String, org.w3c.dom.DocumentType)
*/
@Override
public Document createDocument (String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException
{
final StandaloneDocumentImpl doc=new StandaloneDocumentImpl();
doc.setBaseURI(namespaceURI);
doc.setNodeName(qualifiedName);
doc.setDoctype(doctype);
return doc;
}
/*
* @see org.w3c.dom.DOMImplementation#createDocumentType(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public DocumentType createDocumentType (String qualifiedName, String publicId, String systemId) throws DOMException
{
return null;
}
protected String getFeatureKey (String feature, String version)
{
return feature + "[" + version + "]";
}
public Object putFeature (String feature, String version, Object val)
{
final String k=getFeatureKey(feature, version);
if (null == val)
return remove(k);
else
return put(k, val);
}
/*
* @see org.w3c.dom.DOMImplementation#getFeature(java.lang.String, java.lang.String)
*/
@Override
public Object getFeature (String feature, String version)
{
final String k=getFeatureKey(feature, version);
return get(k);
}
/*
* @see org.w3c.dom.DOMImplementation#hasFeature(java.lang.String, java.lang.String)
*/
@Override
public boolean hasFeature (String feature, String version)
{
return (getFeature(feature, version) != null);
}
}
|
924648381f03da0a4a4ee2802260ec13b3173a0d | 1,071 | java | Java | app/src/main/java/audio/sxshi/com/audiostudy/thread/ThreadPoolFactory.java | AbnormalExit/AudioStudy | 902d7a6f5af3853175169859274c7633aff83d29 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/audio/sxshi/com/audiostudy/thread/ThreadPoolFactory.java | AbnormalExit/AudioStudy | 902d7a6f5af3853175169859274c7633aff83d29 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/audio/sxshi/com/audiostudy/thread/ThreadPoolFactory.java | AbnormalExit/AudioStudy | 902d7a6f5af3853175169859274c7633aff83d29 | [
"Apache-2.0"
] | null | null | null | 24.906977 | 105 | 0.564893 | 1,003,713 | package audio.sxshi.com.audiostudy.thread;
/**
* @author sxshi
*/
public class ThreadPoolFactory {
private static final String TAG = "ThreadPoolFactory";
static ThreadPoolProxy mRecordlPool;
static ThreadPoolProxy mPlayPool;
/**
* 得到一个录制线程队列
*
* @return
*/
public static ThreadPoolProxy getRecordPool() {
if (mRecordlPool == null) {
synchronized (ThreadPoolFactory.class) {
if (mRecordlPool == null) {
mRecordlPool = new ThreadPoolProxy(CustomThreadPoolExecutor.newThreadPoolExecutor());
}
}
}
return mRecordlPool;
}
/**
* 得到一个播放线程池
* @return
*/
public static ThreadPoolProxy getPlayPool() {
if (mPlayPool == null) {
synchronized (ThreadPoolFactory.class) {
if (mPlayPool == null) {
mPlayPool = new ThreadPoolProxy(CustomThreadPoolExecutor.newThreadPoolExecutor());
}
}
}
return mPlayPool;
}
}
|
924648b4da45cb27def84efd04aca0f4734d2a5c | 987 | java | Java | netty/src/main/java/com/kuroha/netty/netty/server/codec/handler/OrderServerProcessHandler.java | kurohayan/dataStructureAndAlgorithm | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | null | null | null | netty/src/main/java/com/kuroha/netty/netty/server/codec/handler/OrderServerProcessHandler.java | kurohayan/dataStructureAndAlgorithm | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | 2 | 2020-08-07T10:24:54.000Z | 2021-12-31T07:37:20.000Z | netty/src/main/java/com/kuroha/netty/netty/server/codec/handler/OrderServerProcessHandler.java | kurohayan/kuroha-study | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | null | null | null | 39.48 | 108 | 0.794326 | 1,003,714 | package com.kuroha.netty.netty.server.codec.handler;
import com.kuroha.netty.netty.common.Operation;
import com.kuroha.netty.netty.common.OperationResult;
import com.kuroha.netty.netty.common.RequestMessage;
import com.kuroha.netty.netty.common.ResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @author Chenyudeng
*/
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, RequestMessage requestMessage) throws Exception {
Operation operation = requestMessage.getMessageBody();
OperationResult operationResult = operation.execute();
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.setMessageHeader(requestMessage.getMessageHeader());
responseMessage.setMessageBody(operationResult);
ctx.writeAndFlush(requestMessage);
}
}
|
924648cbde22666f5ba245a7136cea40c2a05b69 | 1,367 | java | Java | src/main/java/com/codeberry/tadlib/nn/model/layer/ReluLayer.java | pingng/tadlib | bbfcad4e52af40adaa9e736444763fd02e0e995c | [
"MIT"
] | 3 | 2021-07-25T17:19:06.000Z | 2022-01-07T02:59:47.000Z | src/main/java/com/codeberry/tadlib/nn/model/layer/ReluLayer.java | pingng/tadlib | bbfcad4e52af40adaa9e736444763fd02e0e995c | [
"MIT"
] | null | null | null | src/main/java/com/codeberry/tadlib/nn/model/layer/ReluLayer.java | pingng/tadlib | bbfcad4e52af40adaa9e736444763fd02e0e995c | [
"MIT"
] | null | null | null | 26.288462 | 107 | 0.686174 | 1,003,715 | package com.codeberry.tadlib.nn.model.layer;
import com.codeberry.tadlib.array.Shape;
import com.codeberry.tadlib.nn.model.Model;
import com.codeberry.tadlib.nn.model.Model.IterationInfo;
import com.codeberry.tadlib.tensor.Tensor;
import java.util.Random;
import static com.codeberry.tadlib.nn.model.layer.Layer.ForwardResult.result;
import static com.codeberry.tadlib.tensor.Ops.*;
public class ReluLayer implements Layer {
private final double leakyScale;
private final Shape outputShape;
public ReluLayer(Shape inputShape, Builder params) {
this.leakyScale = params.leakyScale;
outputShape = inputShape;
}
@Override
public ForwardResult forward(Random rnd, Tensor inputs, RunMode runMode, IterationInfo iterationInfo) {
return result(leakyRelu(inputs, leakyScale));
}
@Override
public Shape getOutputShape() {
return outputShape;
}
public static class Builder implements LayerBuilder {
double leakyScale;
@Override
public Layer build(Random rnd, Shape inputShape) {
return new ReluLayer(inputShape, this);
}
public static Builder relu() {
return new Builder();
}
public Builder leakyScale(double leakyScale) {
this.leakyScale = leakyScale;
return this;
}
}
}
|
924649c01a9888bfdfeeb14d7c6f30b4f7f848e6 | 3,648 | java | Java | service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 157 | 2015-04-16T17:39:08.000Z | 2022-01-18T14:07:48.000Z | service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 567 | 2015-03-04T17:44:25.000Z | 2021-02-23T22:59:43.000Z | service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 133 | 2015-03-04T19:11:33.000Z | 2020-12-02T14:32:18.000Z | 38 | 120 | 0.702303 | 1,003,716 | /**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.service.http.proxy;
import static java.lang.String.format;
import java.util.Collection;
import java.util.Properties;
import javax.annotation.Resource;
import org.kaazing.gateway.resource.address.uri.URIUtils;
import org.kaazing.gateway.service.ServiceContext;
import org.kaazing.gateway.service.proxy.AbstractProxyService;
import org.kaazing.gateway.util.feature.EarlyAccessFeatures;
/**
* Http proxy service
*/
public class HttpProxyService extends AbstractProxyService<HttpProxyServiceHandler> {
private static final String TRAILING_SLASH_ERROR = "The accept URI is '%s' and the connect URI is '%s'. "
+ "One has a trailing slash and one doesn't. Both URIs either need to include a trailing slash or omit it.";
private Properties configuration;
@Override
public String getType() {
return "http.proxy";
}
@Override
public void init(ServiceContext serviceContext) throws Exception {
EarlyAccessFeatures.HTTP_PROXY_SERVICE.assertEnabled(configuration, serviceContext.getLogger());
super.init(serviceContext);
Collection<String> connectURIs = serviceContext.getConnects();
if (connectURIs == null || connectURIs.isEmpty()) {
throw new IllegalArgumentException("Missing required element: <connect>");
}
checkForTrailingSlashes(serviceContext);
HttpProxyServiceHandler handler = getHandler();
handler.setConnectURIs(connectURIs);
handler.init();
}
@Resource(name = "configuration")
public void setConfiguration(Properties configuration) {
this.configuration = configuration;
}
private void checkForTrailingSlashes(ServiceContext serviceContext) {
Collection<String> acceptURIs = serviceContext.getAccepts();
Collection<String> connectURIs = serviceContext.getConnects();
assert acceptURIs.size() == 1;
assert connectURIs.size() == 1;
String acceptURI = acceptURIs.iterator().next();
String connectURI = connectURIs.iterator().next();
String acceptPath = URIUtils.getPath(acceptURI);
String connectPath = URIUtils.getPath(connectURI);
boolean acceptPathIsSlash = acceptPath.endsWith("/");
boolean connectPathIsSlash = connectPath.endsWith("/");
if (!acceptPathIsSlash) {
String msg = String.format("The path %s of accept URI %s for service %s needs to end with /",
acceptPath, acceptURI, serviceContext.getServiceName());
throw new IllegalArgumentException(msg);
}
if (!connectPathIsSlash) {
String msg = String.format("The path %s of connect URI %s for service %s needs to end with /",
connectPath, connectURI, serviceContext.getServiceName());
throw new IllegalArgumentException(msg);
}
}
@Override
protected HttpProxyServiceHandler createHandler() {
return new HttpProxyServiceHandler();
}
}
|
92464b0435c47fd27b424241b684bc413a412252 | 5,923 | java | Java | fossil/src/main/java/hudson/plugins/fossil/FossilChangeLogEntry.java | rjperrella/jenkins-fossil-adapter | 81688de3047858a51822c4f51a37cf4bd94c175a | [
"MIT"
] | 7 | 2017-11-25T10:25:36.000Z | 2021-10-17T11:37:11.000Z | fossil/src/main/java/hudson/plugins/fossil/FossilChangeLogEntry.java | rjperrella/jenkins-fossil-adapter | 81688de3047858a51822c4f51a37cf4bd94c175a | [
"MIT"
] | 1 | 2020-05-18T17:11:02.000Z | 2020-07-03T13:33:34.000Z | fossil/src/main/java/hudson/plugins/fossil/FossilChangeLogEntry.java | rjperrella/jenkins-fossil-adapter | 81688de3047858a51822c4f51a37cf4bd94c175a | [
"MIT"
] | 3 | 2015-06-19T09:54:58.000Z | 2020-07-26T02:32:35.000Z | 23.318898 | 95 | 0.576735 | 1,003,717 |
package hudson.plugins.fossil;
import static hudson.Util.fixEmpty;
import hudson.model.User;
import hudson.scm.ChangeLogSet;
import hudson.tasks.Mailer;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;
import org.kohsuke.stapler.export.Exported;
/**
* Represents a "change log" which is a bunch of file changes, tags, and the author who did it.
*
* https://wiki.jenkins-ci.org/display/JENKINS/Change+log
*
* <p>
* The object should be treated like an immutable object.
* </p>
*
* @author Trond Norbye (Bazaar version)
* @author Ron Perrella
*/
public class FossilChangeLogEntry extends ChangeLogSet.Entry {
private String author;
private String authorEmail;
private String revid;
private List<String> tags = new ArrayList<String>();
private String date;
private String msg;
private boolean isMerge = false;
private List<FossilAffectedFile> affectedFiles = new ArrayList<FossilAffectedFile>();
/**
* Create an empty Fossil Change Log object
*/
FossilChangeLogEntry()
{
author = "";
authorEmail = "";
revid = "";
date = "";
msg = "";
}
/**
* Get the Checkin (aka Commit) message.
*
* This is a mandatory part of the change log architecture.
*
* @return the checkin message
*/
@Exported
public String getMsg() {
return msg;
}
/**
* Gets the user who made this change.
*
* This is a mandatory part of the Change Log Architecture
*
* @return the author of the checkin (aka commit)
*/
@Exported
public User getAuthor() {
User user = User.get(author, false);
if (user == null) {
user = User.get(author, true);
// set email address for user
if (fixEmpty(authorEmail) != null) {
try {
user.addProperty(new Mailer.UserProperty(authorEmail));
} catch (IOException e) {
// ignore error
}
}
}
return user;
}
/**
* @return the checkin (aka commit) of the change log
*/
@Exported
public String getCommitId() {
return revid;
}
/**
* @return a list of tags for this checkin (aka commit) for this change log
*/
@Exported
public List<String> getTags() {
return tags;
}
/**
* @return the date in string form for the checkin (aka commit) for this change log
*/
@Exported
public String getDate() {
return date;
}
/**
* @return the timestamp associated with the date for this change log.
*/
@Exported
public long getTimeStamp()
{
Calendar cal = new GregorianCalendar();
try
{
DateFormat df = new SimpleDateFormat();
cal.setTime( df.parse(date) );
return getTimeStamp();
}catch(ParseException e)
{
return (-1);
}
}
/**
* @return whether or not this change log is a merge
*/
@Exported
public boolean isMerge() {
return this.isMerge;
}
/**
* This is mandatory part of the Change Log Architecture.
*
* @return a collection of affected file paths
*/
@Override
public Collection<String> getAffectedPaths() {
return new AbstractList<String>() {
public String get(int index) {
return affectedFiles.get(index).getPath();
}
public int size() {
return affectedFiles.size();
}
};
}
/**
* @return a collection of affectedFiles for this change log
*/
@Override
public Collection<FossilAffectedFile> getAffectedFiles() {
return affectedFiles;
}
/**
* Associate a parent change log set for this change log.
*
* @param parent
*/
@Override
protected void setParent(ChangeLogSet parent) {
super.setParent(parent);
}
/**
* Set the commit message.
*
* @param msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* Set the author field
* @param author the author responsible for this checkin (aka commit)
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Set the author Email field (if available) May be empty string.
*
* @param authorEmail
*/
public void setAuthorEmail(String authorEmail) {
this.authorEmail = authorEmail;
}
/**
* Set the Reviid (checkin aka commit) for this change log.
*
* @param revid
*/
public void setRevid(String revid) {
this.revid = revid;
}
/**
* Set the list of Tags for this change log.
*
* @param tags
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
* Set the date that corresponds to the checkin (aka commit) for this change log.
*
* @param date
*/
public void setDate(String date) {
this.date = date;
}
/**
* set whether or not this was a merge.
*
* @param isMerge
*/
public void setMerge(boolean isMerge) {
this.isMerge = isMerge;
}
/**
* Add another affected file to the change log.
*
* @param affectedFile the affected file for the change log.
*/
public void addAffectedFile(FossilAffectedFile affectedFile) {
affectedFile.setChangeSet(this);
this.affectedFiles.add(affectedFile);
}
} |
92464c1488aa25cb7bdb8ac5abaf6643414a9469 | 827 | java | Java | part05-Part05_09.HealthStation/src/main/java/Main.java | originalzacsoftware/helsinki-java-programming-mooc-2021 | dad8286868e75aa42522b6d82bc399b10a3e924e | [
"MIT"
] | 2 | 2021-01-05T14:49:59.000Z | 2021-01-05T15:36:45.000Z | part05/famous-malayan-tiger-640048-part05-Part05_09.HealthStation-7514210/src/main/main/java/Main.java | bexxmodd/Java-Programming | 6d7490a920992e246b1d6915a1f0141c620325a8 | [
"MIT"
] | null | null | null | part05/famous-malayan-tiger-640048-part05-Part05_09.HealthStation-7514210/src/main/main/java/Main.java | bexxmodd/Java-Programming | 6d7490a920992e246b1d6915a1f0141c620325a8 | [
"MIT"
] | 1 | 2021-12-02T14:45:13.000Z | 2021-12-02T14:45:13.000Z | 31.807692 | 84 | 0.665054 | 1,003,718 |
public class Main {
public static void main(String[] args) {
// write experimental code here to check how your program functions
HealthStation childrensHospital = new HealthStation();
Person ethan = new Person("Ethan", 1, 110, 7);
Person peter = new Person("Peter", 33, 176, 85);
System.out.println("weighings performed: " + childrensHospital.weighings());
childrensHospital.weigh(ethan);
childrensHospital.weigh(peter);
System.out.println("weighings performed: " + childrensHospital.weighings());
childrensHospital.weigh(ethan);
childrensHospital.weigh(ethan);
childrensHospital.weigh(ethan);
childrensHospital.weigh(ethan);
System.out.println("weighings performed: " + childrensHospital.weighings());
}
}
|
92464d6afcf04a3cc85db319346bdb4b5a346a31 | 10,831 | java | Java | modules/global/src/com/haulmont/cuba/core/global/ValueLoadContext.java | tausendschoen/cuba | e4342d4e840b54b85ff3851e76c2c01b7987b33a | [
"Apache-2.0"
] | 1,337 | 2016-03-24T09:32:00.000Z | 2022-03-31T16:46:59.000Z | modules/global/src/com/haulmont/cuba/core/global/ValueLoadContext.java | tausendschoen/cuba | e4342d4e840b54b85ff3851e76c2c01b7987b33a | [
"Apache-2.0"
] | 2,911 | 2016-04-28T14:36:19.000Z | 2022-03-22T06:09:57.000Z | modules/global/src/com/haulmont/cuba/core/global/ValueLoadContext.java | tausendschoen/cuba | e4342d4e840b54b85ff3851e76c2c01b7987b33a | [
"Apache-2.0"
] | 271 | 2016-04-15T03:29:20.000Z | 2022-03-27T01:05:43.000Z | 30.169916 | 130 | 0.60253 | 1,003,719 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.core.global;
import com.haulmont.bali.util.StringHelper;
import com.haulmont.cuba.core.global.queryconditions.Condition;
import javax.annotation.Nullable;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.*;
/**
* Class that defines parameters for loading values from the database via {@link DataManager#loadValues(ValueLoadContext)}.
* <p>Typical usage:
* <pre>
* ValueLoadContext context = ValueLoadContext.create()
* .setQuery(ValueLoadContext.createQuery("select e.id, e.name from sample$Customer e where e.grade = :grade")
* .setParameter("grade", 1))
* .addProperty("id")
* .addProperty("name");
* </pre>
*/
public class ValueLoadContext implements DataLoadContext, Serializable {
protected String storeName = Stores.MAIN;
protected Query query;
protected boolean softDeletion = true;
protected String idName;
protected List<String> properties = new ArrayList<>();
protected boolean authorizationRequired;
protected boolean joinTransaction;
/**
* Creates an instance of ValueLoadContext
*/
public static ValueLoadContext create() {
return new ValueLoadContext();
}
/**
* Creates an instance of ValueLoadContext query
*/
public static Query createQuery(String queryString) {
return new Query(queryString);
}
/**
* @param queryString JPQL query string. Only named parameters are supported.
* @return query definition object
*/
@Override
public Query setQueryString(String queryString) {
query = new Query(queryString);
return query;
}
/**
* @return data store name if set by {@link #setStoreName(String)}
*/
public String getStoreName() {
return storeName;
}
/**
* Sets a data store name if it is different from the main database.
* @return this instance for chaining
*/
public ValueLoadContext setStoreName(String storeName) {
this.storeName = storeName;
return this;
}
/**
* Sets query instance
* @return this instance for chaining
*/
public ValueLoadContext setQuery(Query query) {
this.query = query;
return this;
}
/**
* @return query instance
*/
public Query getQuery() {
return query;
}
/**
* @param softDeletion whether to use soft deletion when loading entities
*/
public ValueLoadContext setSoftDeletion(boolean softDeletion) {
this.softDeletion = softDeletion;
return this;
}
/**
* @return whether to use soft deletion when loading entities
*/
public boolean isSoftDeletion() {
return softDeletion;
}
/**
* @return name of property that represents an identifier of the returned KeyValueEntity, if set by {@link #setIdName(String)}
*/
public String getIdName() {
return idName;
}
/**
* Sets name of the property that represents an identifier of the returned KeyValueEntity.
*/
public void setIdName(String idName) {
this.idName = idName;
}
/**
* Adds a key of a returned key-value pair. The sequence of adding properties must conform to the sequence of
* result fields in the query "select" clause.
* <p>For example, if the query is <code>select e.id, e.name from sample$Customer</code>
* and you executed <code>context.addProperty("customerId").addProperty("customerName")</code>, the returned KeyValueEntity
* will contain customer identifiers in "customerId" property and names in "customerName" property.
* @return this instance for chaining
*/
public ValueLoadContext addProperty(String name) {
properties.add(name);
return this;
}
/**
* The same as invoking {@link #addProperty(String)} multiple times.
* @return this instance for chaining
*/
public ValueLoadContext setProperties(List<String> properties) {
this.properties.clear();
this.properties.addAll(properties);
return this;
}
/**
* @return the list of properties added by {@link #addProperty(String)}
*/
public List<String> getProperties() {
return properties;
}
public boolean isAuthorizationRequired() {
return authorizationRequired;
}
public ValueLoadContext setAuthorizationRequired(boolean authorizationRequired) {
this.authorizationRequired = authorizationRequired;
return this;
}
public boolean isJoinTransaction() {
return joinTransaction;
}
public ValueLoadContext setJoinTransaction(boolean joinTransaction) {
this.joinTransaction = joinTransaction;
return this;
}
@Override
public String toString() {
return String.format("ValuesContext{query=%s, softDeletion=%s, keys=%s}", query, softDeletion, properties);
}
/**
* Class that defines a query to be executed for loading values.
*/
public static class Query implements DataLoadContextQuery, Serializable {
private String queryString;
private int firstResult;
private int maxResults;
private Map<String, Object> parameters = new HashMap<>();
private String[] noConversionParams;
private Condition condition;
private Sort sort;
/**
* @param queryString JPQL query string. Only named parameters are supported.
*/
public Query(String queryString) {
this.queryString = queryString;
}
/**
* @return JPQL query string
*/
public String getQueryString() {
return queryString;
}
/**
* @param queryString JPQL query string. Only named parameters are supported.
*/
public void setQueryString(String queryString) {
this.queryString = queryString;
}
/**
* Set value for a query parameter.
* @param name parameter name
* @param value parameter value
* @return this query instance for chaining
*/
public Query setParameter(String name, Object value) {
parameters.put(name, value);
return this;
}
/**
* Set value for a query parameter.
* @param name parameter name
* @param value parameter value
* @param implicitConversions whether to do parameter value conversions, e.g. convert an entity to its ID
* @return this query instance for chaining
*/
public Query setParameter(String name, Object value, boolean implicitConversions) {
parameters.put(name, value);
if (!implicitConversions) {
// this is a rare case, so let's save some memory by using an array instead of a list
if (noConversionParams == null)
noConversionParams = new String[0];
noConversionParams = new String[noConversionParams.length + 1];
noConversionParams[noConversionParams.length - 1] = name;
}
return this;
}
/**
* Set value for a parameter of java.util.Date type.
* @param name parameter name
* @param value date value
* @param temporalType temporal type
* @return this query instance for chaining
*/
public Query setParameter(String name, Date value, TemporalType temporalType) {
parameters.put(name, new TemporalValue(value, temporalType));
return this;
}
/**
* @return editable map of the query parameters
*/
public Map<String, Object> getParameters() {
return parameters;
}
/**
* @param parameters map of the query parameters
*/
public Query setParameters(Map<String, Object> parameters) {
this.parameters.putAll(parameters);
return this;
}
/**
* @param firstResult results offset
* @return this query instance for chaining
*/
public Query setFirstResult(int firstResult) {
this.firstResult = firstResult;
return this;
}
/**
* @param maxResults results limit
* @return this query instance for chaining
*/
public Query setMaxResults(int maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* @return root query condition
*/
public Condition getCondition() {
return condition;
}
/**
* @param condition root query condition
* @return this query instance for chaining
*/
public Query setCondition(Condition condition) {
this.condition = condition;
return this;
}
/**
* @return query sort
*/
public Sort getSort() {
return sort;
}
/**
* @param sort query sort
* @return this query instance for chaining
*/
public Query setSort(Sort sort) {
this.sort = sort;
return this;
}
/**
* @return results offset
*/
public int getFirstResult() {
return firstResult;
}
/**
* @return results limit
*/
public int getMaxResults() {
return maxResults;
}
@Nullable
public String[] getNoConversionParams() {
return noConversionParams;
}
@Override
public String toString() {
String stringResult = "Query{" +
"queryString='" + queryString + '\'' +
", condition=" + condition +
", sort=" + sort +
", firstResult=" + firstResult +
", maxResults=" + maxResults +
"}";
return StringHelper.removeExtraSpaces(stringResult.replace('\n', ' '));
}
}
}
|
92464de0a6dbaa698635f712eefb043ce3fbbe34 | 2,469 | java | Java | src/java/platform/com.ibm.streams.platform/src/main/java/com/ibm/streams/instance/sam/applicationModel/ApplicationModelFactory.java | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 10 | 2021-02-19T20:19:24.000Z | 2021-09-16T05:11:50.000Z | src/java/platform/com.ibm.streams.platform/src/main/java/com/ibm/streams/instance/sam/applicationModel/ApplicationModelFactory.java | xguerin/openstreams | 7000370b81a7f8778db283b2ba9f9ead984b7439 | [
"Apache-2.0"
] | 7 | 2021-02-20T01:17:12.000Z | 2021-06-08T14:56:34.000Z | src/java/platform/com.ibm.streams.platform/src/main/java/com/ibm/streams/instance/sam/applicationModel/ApplicationModelFactory.java | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 4 | 2021-02-19T18:43:10.000Z | 2022-02-23T14:18:16.000Z | 41.847458 | 100 | 0.758607 | 1,003,720 | /*
* Copyright 2021 IBM 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 com.ibm.streams.instance.sam.applicationModel;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class ApplicationModelFactory {
private static JAXBContext jc4000;
private static JAXBContext jc4200;
public static synchronized com.ibm.streams.platform.services.v4000.ApplicationType
createV4000ApplicationModel(InputStream iStream) throws JAXBException {
if (jc4000 == null) {
jc4000 = JAXBContext.newInstance(com.ibm.streams.platform.services.v4000.ObjectFactory.class);
}
Unmarshaller um = jc4000.createUnmarshaller();
JAXBElement<com.ibm.streams.platform.services.v4000.ApplicationSetType> jbe =
(JAXBElement<com.ibm.streams.platform.services.v4000.ApplicationSetType>)
um.unmarshal(iStream);
com.ibm.streams.platform.services.v4000.ApplicationSetType app = jbe.getValue();
com.ibm.streams.platform.services.v4000.ApplicationType adlModel = app.getApplication().get(0);
return adlModel;
}
public static synchronized com.ibm.streams.platform.services.v4200.ApplicationType
createV4200ApplicationModel(InputStream iStream) throws JAXBException {
if (jc4200 == null) {
jc4200 = JAXBContext.newInstance(com.ibm.streams.platform.services.v4200.ObjectFactory.class);
}
Unmarshaller um = jc4200.createUnmarshaller();
JAXBElement<com.ibm.streams.platform.services.v4200.ApplicationSetType> jbe =
(JAXBElement<com.ibm.streams.platform.services.v4200.ApplicationSetType>)
um.unmarshal(iStream);
com.ibm.streams.platform.services.v4200.ApplicationSetType app = jbe.getValue();
com.ibm.streams.platform.services.v4200.ApplicationType adlModel =
app.getSplApplication().get(0);
return adlModel;
}
}
|
92464de10c6b4d646db38debdb5a3a082d62d51b | 9,364 | java | Java | src/java/com/google/feedserver/tools/FeedServerClientAclTool.java | Type-of-iframe/google-feedserver | 620de22e23bb7bc50cd155e53e92cbd4a0bd41ff | [
"Apache-2.0"
] | 1 | 2016-04-19T11:12:05.000Z | 2016-04-19T11:12:05.000Z | src/java/com/google/feedserver/tools/FeedServerClientAclTool.java | Type-of-iframe/google-feedserver | 620de22e23bb7bc50cd155e53e92cbd4a0bd41ff | [
"Apache-2.0"
] | 1 | 2016-03-30T22:33:46.000Z | 2016-03-30T22:33:46.000Z | src/java/com/google/feedserver/tools/FeedServerClientAclTool.java | Type-of-iframe/google-feedserver | 620de22e23bb7bc50cd155e53e92cbd4a0bd41ff | [
"Apache-2.0"
] | null | null | null | 38.182927 | 99 | 0.672416 | 1,003,721 | /*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.feedserver.tools;
import com.google.feedserver.client.FeedServerClient;
import com.google.feedserver.resource.Acl;
import com.google.feedserver.resource.AuthorizedEntity;
import com.google.feedserver.resource.ResourceInfo;
import com.google.feedserver.util.CommonsCliHelper;
import com.google.feedserver.util.FeedServerClientException;
import com.google.gdata.util.AuthenticationException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* FeedServer client tool for setting ACLs.
*
* -url <aclFeedUrl> -resource <feedUrl|feedUrl/entryName> -op setAcl
* -acl (<crud><+|-><principal:...>,)*
*
* Special principals are:
* For per domain resources:
* DOMAIN_USERS: any user in the domain
* DOMAIN_ADMIN: any administrator in the domain
* *: anyone
* For per user resources:
* DOMAIN_INDIVIDUAL: any user in the domain
* ANY_INDIVIDUAL: any user him/herself
* *: anyone
*
* Example:
* -url http://feedserver-enterprise.googleusercontent.com/a/example.com/g/acl - resource Contact
* -op setAcl -acl [email protected]:[email protected],r+DOMAIN_USERS,
* [email protected]:[email protected]
*/
public class FeedServerClientAclTool extends FeedServerClientTool {
public static final String OPERATION_SET_ACL = "setAcl";
public static String resource_FLAG = null;
public static String resource_HELP = "resource name whose ACL to change " +
"(e.g. Contact or Contact/john.doe";
public static String acl_FLAG = null;
public static String acl_HELP = "Access control list";
public static final void main(String[] args) {
new FeedServerClientAclTool().run(args);
}
@Override
protected void processRequest(CommonsCliHelper cliHelper) throws FeedServerClientException,
MalformedURLException, IOException, AuthenticationException {
if (resource_FLAG == null) {
printError("resource missing (please use flag '-resource')");
} else if (OPERATION_SET_ACL.equals(op_FLAG)) {
getUserCredentials();
List<Acl> existingAcls = getAcl(resource_FLAG);
if (existingAcls.size() > 1) {
printError("More than 1 ACL per resource not supported by this client tool");
} else {
setAcl(url_FLAG, resource_FLAG, existingAcls, acl_FLAG);
}
} else {
super.processRequest(cliHelper);
}
}
/**
* Gets all the ACLs of a resource.
* @param resourceName Name of resource
* @return List of ACLs for the resource
* @throws MalformedURLException
* @throws FeedServerClientException
*/
protected List<Acl> getAcl(String resourceName) throws MalformedURLException,
FeedServerClientException {
FeedServerClient<Acl> feedServerClient = new FeedServerClient<Acl>(
this.feedServerClient.getService(), Acl.class);
String aclFeedUrl = url_FLAG + "?bq=[resourceRule=" + resourceName + "]";
List<Acl> aclIds = feedServerClient.getEntities(new URL(aclFeedUrl));
List<Acl> acls = new ArrayList<Acl>(aclIds.size());
for (Acl aclId: aclIds) {
URL aclEntryUrl = new URL(url_FLAG + '/' + aclId.getName());
acls.add(feedServerClient.getEntity(aclEntryUrl));
}
return acls;
}
/**
* Sets ACLs of a resource.
* @param url URL of resource to set ACLs
* @param resource Resource to set ACLs for
* @param acls Existing ACLs to change
* @param aclDef ACL change definitions (<crud><+|-><principal:...>,)*
* @throws MalformedURLException
* @throws FeedServerClientException
* @throws UnsupportedEncodingException
*/
protected void setAcl(String url, String resource, List<Acl> acls, String aclDef)
throws MalformedURLException, FeedServerClientException, UnsupportedEncodingException {
String[] authorizedEntitiesDefs = aclDef.split(",");
for (String authorizedEntitiesDef: authorizedEntitiesDefs) {
String modifier = authorizedEntitiesDef.indexOf('+') > 0 ? "\\+" : "-";
String[] opEntities = authorizedEntitiesDef.split(modifier);
if (opEntities.length != 2) {
continue;
}
String[] entities = opEntities[1].split(":");
for (int i = 0; i < opEntities[0].length(); i++) {
char op = opEntities[0].charAt(i);
for (String entity: entities) {
if ("\\+".equals(modifier)) {
addAcl(acls, op, entity);
} else {
removeAcl(acls, op, entity);
}
}
}
}
FeedServerClient<Acl> feedServerClient = new FeedServerClient<Acl>(
this.feedServerClient.getService(), Acl.class);
for (Acl acl: acls) {
if (acl.getAuthorizedEntities().length == 0) {
delete(url + "/" + URLEncoder.encode(resource, "UTF-8"));
} else {
if (acl.getName() == null) {
acl.setName(resource);
acl.setResourceInfo(new ResourceInfo(resource, ResourceInfo.RESOURCE_TYPE_FEED));
feedServerClient.insertEntity(new URL(url), acl);
} else {
feedServerClient.updateEntity(new URL(url), acl);
}
}
}
}
/**
* Adds a principal for an operation to ACLs.
* @param existingAcls ACLs to add to
* @param op Operation of interest
* @param principalToAdd Principal of interest
*/
protected void addAcl(List<Acl> existingAcls, char op, String principalToAdd) {
removeAcl(existingAcls, op, principalToAdd);
Acl firstAcl = (existingAcls.size() > 0) ? existingAcls.get(0) : new Acl();
if (existingAcls.size() == 0) {
existingAcls.add(firstAcl);
}
boolean opFound = false;
if (firstAcl.getAuthorizedEntities() != null) {
for (AuthorizedEntity authorizedEntity: firstAcl.getAuthorizedEntities()) {
if (authorizedEntity.getOperation().charAt(0) == op) {
opFound = true;
String[] currentPrincipals = authorizedEntity.getEntities();
if (currentPrincipals == null) {
authorizedEntity.setEntities(new String[]{principalToAdd});
} else {
String[] updatedPrincipals = new String[currentPrincipals.length + 1];
for (int i = 0; i < currentPrincipals.length; i++) {
updatedPrincipals[i] = currentPrincipals[i];
}
updatedPrincipals[currentPrincipals.length] = principalToAdd;
authorizedEntity.setEntities(updatedPrincipals);
}
}
}
}
if (!opFound) {
int currentLength = firstAcl.getAuthorizedEntities().length;
AuthorizedEntity[] updatedAuthorizedEntities =
new AuthorizedEntity[currentLength + 1];
for (int i = 0; i < currentLength; i++) {
updatedAuthorizedEntities[i] = firstAcl.getAuthorizedEntities()[i];
}
AuthorizedEntity authorizedEntity = new AuthorizedEntity();
authorizedEntity.setOperation(authorizedEntity.lookupOperation(op));
authorizedEntity.setEntities(new String[]{principalToAdd});
updatedAuthorizedEntities[currentLength] = authorizedEntity;
firstAcl.setAuthorizedEntities(updatedAuthorizedEntities);
}
}
/**
* Removes a principal for an operation from ACLs.
* @param existingAcls ACLs to remove from
* @param op Operation of interest
* @param principalToRemove Principal of interest
*/
protected void removeAcl(List<Acl> existingAcls, char op, String principalToRemove) {
for (Acl existingAcl: existingAcls) {
if (existingAcl.getAuthorizedEntities() != null) {
List<AuthorizedEntity> updatedAuthorizedEntities = new ArrayList<AuthorizedEntity>();
for (AuthorizedEntity authorizedEntity: existingAcl.getAuthorizedEntities()) {
if (authorizedEntity.getOperation().charAt(0) == op) {
List<String> updatedPrincipals = new ArrayList<String>();
if (authorizedEntity.getEntities() != null) {
for (String principal: authorizedEntity.getEntities()) {
if (!principal.equals(principalToRemove)) {
updatedPrincipals.add(principal);
}
}
if (updatedPrincipals.size() != 0) {
authorizedEntity.setEntities(
updatedPrincipals.toArray(new String[updatedPrincipals.size()]));
updatedAuthorizedEntities.add(authorizedEntity);
}
}
} else {
// not operation of interest
updatedAuthorizedEntities.add(authorizedEntity);
}
}
existingAcl.setAuthorizedEntities(updatedAuthorizedEntities.toArray(
new AuthorizedEntity[updatedAuthorizedEntities.size()]));
}
}
}
}
|
92464ecb7baa2f6bb16b905784739359af1bc691 | 11,945 | java | Java | src/test/java/seedu/address/model/ModelManagerTest.java | AY1920S1-CS2103T-W12-3/main | f87107dcd36d45b5db493b7ab71eea483a0020c6 | [
"MIT"
] | 1 | 2019-09-06T12:25:03.000Z | 2019-09-06T12:25:03.000Z | src/test/java/seedu/address/model/ModelManagerTest.java | AY1920S1-CS2103T-W12-3/main | f87107dcd36d45b5db493b7ab71eea483a0020c6 | [
"MIT"
] | 166 | 2019-09-17T16:35:13.000Z | 2019-11-21T04:44:48.000Z | src/test/java/seedu/address/model/ModelManagerTest.java | AY1920S1-CS2103T-W12-3/main | f87107dcd36d45b5db493b7ab71eea483a0020c6 | [
"MIT"
] | 5 | 2019-09-06T12:39:33.000Z | 2019-09-18T03:26:23.000Z | 37.681388 | 109 | 0.720887 | 1,003,722 | package seedu.address.model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.Assert.assertThrows;
import static seedu.address.testutil.TypicalTransactions.ALICE;
import static seedu.address.testutil.TypicalTransactions.BENSON;
import static seedu.address.testutil.TypicalTransactions.getTypicalTransactions;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.Test;
import seedu.address.commons.core.GuiSettings;
import seedu.address.model.category.Category;
import seedu.address.model.person.Name;
import seedu.address.model.person.Person;
import seedu.address.model.projection.Projection;
import seedu.address.model.transaction.Amount;
import seedu.address.model.transaction.BankAccountOperation;
import seedu.address.model.transaction.Budget;
import seedu.address.model.transaction.Description;
import seedu.address.model.transaction.LedgerOperation;
import seedu.address.model.transaction.LendMoney;
import seedu.address.model.transaction.TransactionPredicate;
import seedu.address.model.transaction.UniqueBudgetList;
import seedu.address.model.util.Date;
import seedu.address.testutil.BankOperationBuilder;
import seedu.address.testutil.UserStateBuilder;
public class ModelManagerTest {
private ModelManager modelManager = new ModelManager();
@Test
public void constructor() {
assertEquals(new UserPrefs(), modelManager.getUserPrefs());
assertEquals(new GuiSettings(), modelManager.getGuiSettings());
assertEquals(new VersionedUserState(new UserState()), modelManager.getUserState());
assertEquals(new BankAccount(), new BankAccount(modelManager.getBankAccount()));
}
@Test
public void setUserState() {
UserState userState = new UserState();
VersionedUserState versionedUserState = new VersionedUserState(userState);
BankAccountOperation op = new BankOperationBuilder()
.withDescription("milk")
.withAmount("69")
.withDate("19112019")
.withCategories("Uncategorised")
.build();
versionedUserState.add(op);
modelManager.setUserState(versionedUserState);
VersionedUserState expectedVersionedUserState = new VersionedUserState(new UserState());
expectedVersionedUserState.add(op);
VersionedUserState actualVersionedUserState = (VersionedUserState) modelManager.getUserState();
assertEquals(expectedVersionedUserState, actualVersionedUserState);
}
@Test
public void setUserPrefs_nullUserPrefs_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.setUserPrefs(null));
}
@Test
public void setUserPrefs_validUserPrefs_copiesUserPrefs() {
UserPrefs userPrefs = new UserPrefs();
userPrefs.setUserStateFilePath(Paths.get("bank/account/file/path"));
userPrefs.setGuiSettings(new GuiSettings(1, 2, 3, 4));
modelManager.setUserPrefs(userPrefs);
assertEquals(userPrefs, modelManager.getUserPrefs());
// Modifying userPrefs should not modify modelManager's userPrefs
UserPrefs oldUserPrefs = new UserPrefs(userPrefs);
userPrefs.setUserStateFilePath(Paths.get("new/bank/account/file/path"));
assertEquals(oldUserPrefs, modelManager.getUserPrefs());
}
@Test
public void setGuiSettings_nullGuiSettings_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.setGuiSettings(null));
}
@Test
public void setGuiSettings_validGuiSettings_setsGuiSettings() {
GuiSettings guiSettings = new GuiSettings(1, 2, 3, 4);
modelManager.setGuiSettings(guiSettings);
assertEquals(guiSettings, modelManager.getGuiSettings());
}
@Test
public void setBankAccountFilePath_nullPath_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.setUserStateFilePath(null));
}
@Test
public void setBankAccountFilePath_validPath_setsBankAccountFilePath() {
Path path = Paths.get("bank/account/file/path");
modelManager.setUserStateFilePath(path);
assertEquals(path, modelManager.getUserStateFilePath());
}
@Test
public void hasTransaction_nullTransaction_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.has((BankAccountOperation) null));
}
@Test
public void hasTransaction_transactionNotInBankAccount_returnsFalse() {
assertFalse(modelManager.has(ALICE));
}
@Test
public void hasTransaction_transactionInBankAccount_returnsTrue() {
modelManager.add(ALICE);
assertTrue(modelManager.has(ALICE));
}
@Test
public void hasBudget_nullBudget_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.has((Budget) null));
}
@Test
public void hasBudget_budgetNotInBankAccount_returnsFalse() {
Budget falseBudget = new Budget(new Amount(700), new Date("19112019"));
assertFalse(modelManager.has(falseBudget));
}
@Test
public void hasBudget_budgetInBankAccount_returnsTrue() {
Budget budget = new Budget(new Amount(700), new Date("19112019"));
modelManager.add(budget);
assertTrue(modelManager.has(budget));
}
@Test
public void hasLedgerOperation_nullLedgerOperation_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.has((LedgerOperation) null));
}
@Test
public void hasLedgerOperation_ledgerOperationNotInUserState_returnsFalse() {
LedgerOperation falseLedger = new LendMoney(
new Person(new Name("John")), new Amount(700),
new Date("19112019"), new Description("loanshark"));
assertFalse(modelManager.has(falseLedger));
}
@Test
public void hasLedgerOperation_ledgerOperationInUserState_returnsTrue() {
LedgerOperation ledger = new LendMoney(
new Person(new Name("John")), new Amount(700),
new Date("19112019"), new Description("loanshark"));
modelManager.add(ledger);
assertTrue(modelManager.has(ledger));
}
@Test
public void hasProjection_nullProjection_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> modelManager.has((Projection) null));
}
@Test
public void hasProjection_projectionNotInUserState_returnsFalse() {
Model falseModel = new ModelManager();
falseModel.setTransactions(getTypicalTransactions());
Projection projection = new Projection(falseModel.getFilteredTransactionList(), new Date("19112019"),
new UniqueBudgetList().asUnmodifiableObservableList());
assertFalse(modelManager.has(projection));
}
@Test
public void hasProjection_projectionInUserState_returnsTrue() {
Model stubModel = new ModelManager();
stubModel.setTransactions(getTypicalTransactions());
Projection projection = new Projection(stubModel.getFilteredTransactionList(), new Date("19112019"),
new UniqueBudgetList().asUnmodifiableObservableList());
modelManager.add(projection);
assertTrue(modelManager.has(projection));
}
@Test
public void deleteTransaction_transactionInBankAccount_returnsTrue() {
modelManager.add(ALICE);
assertTrue(modelManager.has(ALICE));
modelManager.delete(ALICE);
assertFalse(modelManager.has(ALICE));
}
@Test
public void deleteBudget_budgetInBankAccount_returnsTrue() {
Budget budget = new Budget(new Amount(700), new Date("19112019"));
modelManager.add(budget);
assertTrue(modelManager.has(budget));
modelManager.delete(budget);
assertFalse(modelManager.has(budget));
}
@Test
public void deleteProjection_projectionInUserState_returnsTrue() {
Model stubModel = new ModelManager();
stubModel.setTransactions(getTypicalTransactions());
Projection projection = new Projection(stubModel.getFilteredTransactionList(), new Date("19112019"),
new UniqueBudgetList().asUnmodifiableObservableList());
modelManager.add(projection);
assertTrue(modelManager.has(projection));
modelManager.delete(projection);
assertFalse(modelManager.has(projection));
}
@Test
public void getFilteredTransactionList_modifyList_throwsUnsupportedOperationException() {
assertThrows(UnsupportedOperationException.class, () -> modelManager
.getFilteredTransactionList().remove(0));
}
@Test
public void getFilteredBudgetList_modifyList_throwsUnsupportedOperationException() {
assertThrows(UnsupportedOperationException.class, () -> modelManager
.getFilteredBudgetList().remove(0));
}
@Test
public void getFilteredLedgerOperationsList_modifyList_throwsUnsupportedOperationException() {
assertThrows(UnsupportedOperationException.class, () -> modelManager
.getFilteredLedgerOperationsList().remove(0));
}
@Test
public void getFilteredProjectionList_modifyList_throwsUnsupportedOperationException() {
assertThrows(UnsupportedOperationException.class, () -> modelManager
.getFilteredProjectionsList().remove(0));
}
@Test
public void canUndo_noUndo_returnsFalse() {
assertFalse(modelManager.canUndoUserState());
}
@Test
public void canUndo_gotUndo_returnsFalse() {
modelManager.commitUserState();
assertTrue(modelManager.canUndoUserState());
}
@Test
public void canRedo_noRedo_returnsFalse() {
assertFalse(modelManager.canRedoUserState());
}
@Test
public void canRedo_gotRedo_returnsFalse() {
modelManager.commitUserState();
modelManager.undoUserState();
assertTrue(modelManager.canRedoUserState());
}
@Test
public void equals() {
UserState userState = new UserStateBuilder().withTransaction(ALICE).withTransaction(BENSON).build();
UserState differentUserState = new UserState();
UserPrefs userPrefs = new UserPrefs();
// same values -> returns true
modelManager = new ModelManager(userState, userPrefs);
ModelManager modelManagerCopy = new ModelManager(userState, userPrefs);
assertTrue(modelManager.equals(modelManagerCopy));
// same object -> returns true
assertTrue(modelManager.equals(modelManager));
// null -> returns false
assertFalse(modelManager.equals(null));
// different types -> returns false
assertFalse(modelManager.equals(5));
// different bankAccount -> returns false
assertFalse(modelManager.equals(new ModelManager(differentUserState, userPrefs)));
// different filteredList -> returns false
Optional<Set<Category>> categories = Optional.of(ALICE
.getCategories());
modelManager.updateFilteredTransactionList(new TransactionPredicate(categories,
Optional.empty(), Optional.empty(), Optional.empty()));
assertFalse(modelManager.equals(new ModelManager(userState, userPrefs)));
// resets modelManager to initial state for upcoming tests
modelManager.updateFilteredTransactionList(Model.PREDICATE_SHOW_ALL_TRANSACTIONS);
// different userPrefs -> returns false
UserPrefs differentUserPrefs = new UserPrefs();
differentUserPrefs.setUserStateFilePath(Paths.get("differentFilePath"));
assertFalse(modelManager.equals(new ModelManager(userState, differentUserPrefs)));
}
}
|
9246512f0b238bdae85acda3dd9a6f6477ef685d | 1,343 | java | Java | tardigrade/src/main/java/com/tardigrade/resources/impl/Channel.java | dgsolucoesmobile/Coup-Acessibility | a1f2a700f4fef3d726822b150e1cec713a3538ec | [
"Apache-2.0"
] | 2 | 2017-12-15T05:48:41.000Z | 2021-03-16T00:56:41.000Z | tardigrade/src/main/java/com/tardigrade/resources/impl/Channel.java | dgsolucoesmobile/Coup-Acessibility | a1f2a700f4fef3d726822b150e1cec713a3538ec | [
"Apache-2.0"
] | null | null | null | tardigrade/src/main/java/com/tardigrade/resources/impl/Channel.java | dgsolucoesmobile/Coup-Acessibility | a1f2a700f4fef3d726822b150e1cec713a3538ec | [
"Apache-2.0"
] | 1 | 2017-12-15T05:48:55.000Z | 2017-12-15T05:48:55.000Z | 20.661538 | 87 | 0.708116 | 1,003,723 | package com.tardigrade.resources.impl;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import com.tardigrade.comunication.IChannel;
import com.tardigrade.comunication.IPack;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Channel implements IChannel {
private String name;
private InetAddress host;
private int port;
private Socket channel;
public Channel(String name, InetAddress host, int port) {
this.name = name;
this.host = host;
this.port = port;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getAddress() {
if(host != null) {
return this.host.toString();
}
return null;
}
@SuppressLint("NewApi")
@Override
public void sendPack(IPack pack) {
new Send().execute(pack);
}
@Override
public int getPort() {
return port;
}
@SuppressLint("NewApi")
private class Send extends AsyncTask<IPack, Void, Void> {
@Override
protected Void doInBackground(IPack... params) {
try {
channel = new Socket(host, port);
ObjectOutputStream outToServer = new ObjectOutputStream(channel.getOutputStream());
outToServer.writeObject(params[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
|
924651b13806f7c9382aa2dec7d5bce6bad8dc72 | 2,046 | java | Java | src/test/java/simplehttp/matchers/UrlMatcherTest.java | simple-http/simple-http | 1f7d4c95a7f5a53c166a9b5221c6890fb7678f12 | [
"Apache-2.0"
] | 4 | 2018-07-01T10:47:39.000Z | 2021-05-04T00:27:36.000Z | src/test/java/simplehttp/matchers/UrlMatcherTest.java | simple-http/simple-http | 1f7d4c95a7f5a53c166a9b5221c6890fb7678f12 | [
"Apache-2.0"
] | 14 | 2018-06-19T08:20:02.000Z | 2019-07-03T07:37:14.000Z | src/test/java/simplehttp/matchers/UrlMatcherTest.java | simple-http/simple-http | 1f7d4c95a7f5a53c166a9b5221c6890fb7678f12 | [
"Apache-2.0"
] | 3 | 2019-03-21T09:11:33.000Z | 2021-07-19T14:42:29.000Z | 31 | 73 | 0.705279 | 1,003,724 | /*
* Copyright (c) 2011-2019, simple-http committers
*
* 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 simplehttp.matchers;
import org.hamcrest.StringDescription;
import org.junit.Test;
import java.net.URL;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static simplehttp.Url.url;
import static simplehttp.matchers.UrlMatcher.containsPath;
public class UrlMatcherTest {
private URL url = url("http://baddotrobot.com:80/blog/archives/");
@Test
public void exampleUsage() {
assertThat(url, containsPath("blog/archives"));
assertThat(url, containsPath("baddotrobot"));
assertThat(url, containsPath("80"));
}
@Test
public void matches() {
assertThat(containsPath("blog/archives").matches(url), is(true));
}
@Test
public void doesNotMatch() {
assertThat(containsPath("blog/2012/01").matches(url), is(false));
}
@Test
public void description() {
StringDescription description = new StringDescription();
containsPath("blog/archives").describeTo(description);
assertThat(description.toString(), allOf(
containsString("a URL containing the text"),
containsString("blog/archives"))
);
}
}
|
924652d75c16af8ecb5a298f1511165e1de2d6ba | 875 | java | Java | src/main/java/dingbinthuAt163com/opensource/freedom/es/demo/EsAdminApiDemo.java | apollo008/ElasticsearchEfficientBuilder | 3e2fc8f3f12a8dfc24a61ab7f2695e247097d686 | [
"Apache-2.0"
] | 6 | 2018-07-17T03:22:02.000Z | 2021-05-19T07:02:38.000Z | src/main/java/dingbinthuAt163com/opensource/freedom/es/demo/EsAdminApiDemo.java | apollo008/ElasticsearchEfficientBuilder | 3e2fc8f3f12a8dfc24a61ab7f2695e247097d686 | [
"Apache-2.0"
] | null | null | null | src/main/java/dingbinthuAt163com/opensource/freedom/es/demo/EsAdminApiDemo.java | apollo008/ElasticsearchEfficientBuilder | 3e2fc8f3f12a8dfc24a61ab7f2695e247097d686 | [
"Apache-2.0"
] | null | null | null | 30.206897 | 79 | 0.667808 | 1,003,725 | package dingbinthuAt163com.opensource.freedom.es.demo;
import dingbinthuAt163com.opensource.freedom.es.util.ExceptionUtil;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*@author DingBin, [email protected]
*@create 2017-07-08, 23:32
*/
public class EsAdminApiDemo {
private static Logger LOG = LoggerFactory.getLogger(EsAdminApiDemo.class);
public static void main(String[] args) {
try {
TransportClient client = EsClient.getClient();
AdminClient adminClient = client.admin();
// Refresh your indices
adminClient.indices().prepareRefresh().get();
}
catch (Exception ex) {
LOG.error(ExceptionUtil.getTrace(ex));
}
}
}
|
9246533d6de1b53860ea6aefe2b89fbdf7de7581 | 5,848 | java | Java | runescape-client/src/main/java/Skeleton.java | guthix/runelite | f622b7d822c8a4064f55cca5ab7e4e3b6ce3d1b3 | [
"BSD-2-Clause"
] | 1 | 2022-03-04T07:31:25.000Z | 2022-03-04T07:31:25.000Z | runescape-client/src/main/java/Skeleton.java | guthix/runelite | f622b7d822c8a4064f55cca5ab7e4e3b6ce3d1b3 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/Skeleton.java | guthix/runelite | f622b7d822c8a4064f55cca5ab7e4e3b6ce3d1b3 | [
"BSD-2-Clause"
] | null | null | null | 34.809524 | 288 | 0.636799 | 1,003,726 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ej")
@Implements("Skeleton")
public class Skeleton extends Node {
@ObfuscatedName("he")
@ObfuscatedGetter(
intValue = -502356211
)
@Export("cameraPitch")
static int cameraPitch;
@ObfuscatedName("h")
@ObfuscatedGetter(
intValue = 1773427771
)
@Export("id")
int id;
@ObfuscatedName("v")
@ObfuscatedGetter(
intValue = -1481451601
)
@Export("count")
int count;
@ObfuscatedName("x")
@Export("transformTypes")
int[] transformTypes;
@ObfuscatedName("w")
@Export("labels")
int[][] labels;
Skeleton(int var1, byte[] var2) {
this.id = var1; // L: 13
Buffer var3 = new Buffer(var2); // L: 14
this.count = var3.readUnsignedByte(); // L: 15
this.transformTypes = new int[this.count]; // L: 16
this.labels = new int[this.count][]; // L: 17
int var4;
for (var4 = 0; var4 < this.count; ++var4) { // L: 18
this.transformTypes[var4] = var3.readUnsignedByte();
}
for (var4 = 0; var4 < this.count; ++var4) { // L: 19
this.labels[var4] = new int[var3.readUnsignedByte()];
}
for (var4 = 0; var4 < this.count; ++var4) { // L: 20
for (int var5 = 0; var5 < this.labels[var4].length; ++var5) { // L: 21
this.labels[var4][var5] = var3.readUnsignedByte();
}
}
} // L: 23
@ObfuscatedName("f")
@ObfuscatedSignature(
descriptor = "(Ljava/lang/String;B)V",
garbageValue = "-5"
)
static final void method3155(String var0) {
PacketBufferNode var1 = ItemContainer.getPacketBufferNode(ClientPacket.IGNORELIST_ADD, Client.packetWriter.isaacCipher); // L: 194
var1.packetBuffer.writeByte(FloorDecoration.stringCp1252NullTerminatedByteSize(var0)); // L: 195
var1.packetBuffer.writeStringCp1252NullTerminated(var0); // L: 196
Client.packetWriter.addNode(var1); // L: 197
} // L: 198
@ObfuscatedName("ha")
@ObfuscatedSignature(
descriptor = "(ZI)V",
garbageValue = "-1484457450"
)
@Export("addNpcsToScene")
static final void addNpcsToScene(boolean var0) {
for (int var1 = 0; var1 < Client.npcCount; ++var1) { // L: 4752
NPC var2 = Client.npcs[Client.npcIndices[var1]]; // L: 4753
if (var2 != null && var2.isVisible() && var2.definition.isVisible == var0 && var2.definition.transformIsVisible()) { // L: 4754
int var3 = var2.x >> 7; // L: 4755
int var4 = var2.y >> 7; // L: 4756
if (var3 >= 0 && var3 < 104 && var4 >= 0 && var4 < 104) { // L: 4757
if (var2.field941 == 1 && (var2.x & 127) == 64 && (var2.y & 127) == 64) { // L: 4758
if (Client.tileLastDrawnActor[var3][var4] == Client.viewportDrawCount) { // L: 4759
continue;
}
Client.tileLastDrawnActor[var3][var4] = Client.viewportDrawCount; // L: 4760
}
long var5 = NPC.calculateTag(0, 0, 1, !var2.definition.isInteractable, Client.npcIndices[var1]); // L: 4762
var2.playerCycle = Client.cycle; // L: 4763
ArchiveLoader.scene.drawEntity(GameObject.Client_plane, var2.x, var2.y, SecureRandomFuture.getTileHeight(var2.field941 * 64 - 64 + var2.x, var2.field941 * 64 - 64 + var2.y, GameObject.Client_plane), var2.field941 * 64 - 64 + 60, var2, var2.rotation, var5, var2.isWalking); // L: 4764
}
}
}
} // L: 4768
@ObfuscatedName("ke")
@ObfuscatedSignature(
descriptor = "([Lhe;II)V",
garbageValue = "-1212206355"
)
@Export("drawModelComponents")
static final void drawModelComponents(Widget[] var0, int var1) {
for (int var2 = 0; var2 < var0.length; ++var2) { // L: 10596
Widget var3 = var0[var2]; // L: 10597
if (var3 != null && var3.parentId == var1 && (!var3.isIf3 || !DevicePcmPlayerProvider.isComponentHidden(var3))) { // L: 10598 10599 10600
if (var3.type == 0) { // L: 10601
if (!var3.isIf3 && DevicePcmPlayerProvider.isComponentHidden(var3) && var3 != EnumComposition.mousedOverWidgetIf1) { // L: 10602
continue;
}
drawModelComponents(var0, var3.id); // L: 10603
if (var3.children != null) { // L: 10604
drawModelComponents(var3.children, var3.id);
}
InterfaceParent var4 = (InterfaceParent)Client.interfaceParents.get((long)var3.id); // L: 10605
if (var4 != null) { // L: 10606
NPCComposition.method4759(var4.group);
}
}
if (var3.type == 6) { // L: 10608
int var5;
if (var3.sequenceId != -1 || var3.sequenceId2 != -1) { // L: 10609
boolean var7 = class8.runCs1(var3); // L: 10610
if (var7) { // L: 10612
var5 = var3.sequenceId2;
} else {
var5 = var3.sequenceId; // L: 10613
}
if (var5 != -1) { // L: 10614
SequenceDefinition var6 = ParamComposition.SequenceDefinition_get(var5); // L: 10615
for (var3.modelFrameCycle += Client.field850; var3.modelFrameCycle > var6.frameLengths[var3.modelFrame]; CollisionMap.invalidateWidget(var3)) { // L: 10616 10617 10624
var3.modelFrameCycle -= var6.frameLengths[var3.modelFrame]; // L: 10618
++var3.modelFrame; // L: 10619
if (var3.modelFrame >= var6.frameIds.length) { // L: 10620
var3.modelFrame -= var6.frameCount; // L: 10621
if (var3.modelFrame < 0 || var3.modelFrame >= var6.frameIds.length) { // L: 10622
var3.modelFrame = 0;
}
}
}
}
}
if (var3.field2642 != 0 && !var3.isIf3) { // L: 10628
int var8 = var3.field2642 >> 16; // L: 10629
var5 = var3.field2642 << 16 >> 16; // L: 10630
var8 *= Client.field850; // L: 10631
var5 *= Client.field850; // L: 10632
var3.modelAngleX = var8 + var3.modelAngleX & 2047; // L: 10633
var3.modelAngleY = var5 + var3.modelAngleY & 2047; // L: 10634
CollisionMap.invalidateWidget(var3); // L: 10635
}
}
}
}
} // L: 10639
}
|
924653d125281df1f136c4e71c6071c5e2cd7d05 | 4,938 | java | Java | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/PrivateKeyParser.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | 1 | 2021-11-22T11:59:46.000Z | 2021-11-22T11:59:46.000Z | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/PrivateKeyParser.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | null | null | null | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/PrivateKeyParser.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | 1 | 2020-12-07T00:42:04.000Z | 2020-12-07T00:42:04.000Z | 32.92 | 108 | 0.722762 | 1,003,727 | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
/**
* Parser for PKCS private key files in PEM format.
*
* @author Scott Frederick
* @author Phillip Webb
*/
final class PrivateKeyParser {
private static final String PKCS1_HEADER = "-+BEGIN\\s+RSA\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+";
private static final String PKCS1_FOOTER = "-+END\\s+RSA\\s+PRIVATE\\s+KEY[^-]*-+";
private static final String PKCS8_FOOTER = "-+END\\s+PRIVATE\\s+KEY[^-]*-+";
private static final String PKCS8_HEADER = "-+BEGIN\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+";
private static final String BASE64_TEXT = "([a-z0-9+/=\\r\\n]+)";
private static final Pattern PKCS1_PATTERN = Pattern.compile(PKCS1_HEADER + BASE64_TEXT + PKCS1_FOOTER,
Pattern.CASE_INSENSITIVE);
private static final Pattern PKCS8_KEY_PATTERN = Pattern.compile(PKCS8_HEADER + BASE64_TEXT + PKCS8_FOOTER,
Pattern.CASE_INSENSITIVE);
private PrivateKeyParser() {
}
/**
* Load a private key from the specified resource.
* @param resource the private key to parse
* @return the parsed private key
*/
static PrivateKey parse(String resource) {
try {
String text = readText(resource);
Matcher matcher = PKCS1_PATTERN.matcher(text);
if (matcher.find()) {
return parsePkcs1(decodeBase64(matcher.group(1)));
}
matcher = PKCS8_KEY_PATTERN.matcher(text);
if (matcher.find()) {
return parsePkcs8(decodeBase64(matcher.group(1)));
}
throw new IllegalStateException("Unrecognized private key format in " + resource);
}
catch (GeneralSecurityException | IOException ex) {
throw new IllegalStateException("Error loading private key file " + resource, ex);
}
}
private static PrivateKey parsePkcs1(byte[] privateKeyBytes) throws GeneralSecurityException {
byte[] pkcs8Bytes = convertPkcs1ToPkcs8(privateKeyBytes);
return parsePkcs8(pkcs8Bytes);
}
private static byte[] convertPkcs1ToPkcs8(byte[] pkcs1) {
try {
ByteArrayOutputStream result = new ByteArrayOutputStream();
int pkcs1Length = pkcs1.length;
int totalLength = pkcs1Length + 22;
// Sequence + total length
result.write(bytes(0x30, 0x82));
result.write((totalLength >> 8) & 0xff);
result.write(totalLength & 0xff);
// Integer (0)
result.write(bytes(0x02, 0x01, 0x00));
// Sequence: 1.2.840.113549.1.1.1, NULL
result.write(
bytes(0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00));
// Octet string + length
result.write(bytes(0x04, 0x82));
result.write((pkcs1Length >> 8) & 0xff);
result.write(pkcs1Length & 0xff);
// PKCS1
result.write(pkcs1);
return result.toByteArray();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
private static byte[] bytes(int... elements) {
byte[] result = new byte[elements.length];
for (int i = 0; i < elements.length; i++) {
result[i] = (byte) elements[i];
}
return result;
}
private static PrivateKey parsePkcs8(byte[] privateKeyBytes) throws GeneralSecurityException {
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
}
catch (InvalidKeySpecException ex) {
throw new IllegalArgumentException("Unexpected key format", ex);
}
}
private static String readText(String resource) throws IOException {
URL url = ResourceUtils.getURL(resource);
try (Reader reader = new InputStreamReader(url.openStream())) {
return FileCopyUtils.copyToString(reader);
}
}
private static byte[] decodeBase64(String content) {
byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes();
return Base64Utils.decode(contentBytes);
}
}
|
924653fec1189eb59d8fa0e7b47aa838af6b1a2e | 2,923 | java | Java | pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/auth/ClearTextFunctionTokenAuthProviderTest.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 9,156 | 2018-09-23T14:10:46.000Z | 2022-03-31T07:17:16.000Z | pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/auth/ClearTextFunctionTokenAuthProviderTest.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 10,453 | 2018-09-22T00:31:02.000Z | 2022-03-31T20:02:09.000Z | pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/auth/ClearTextFunctionTokenAuthProviderTest.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 2,730 | 2018-09-25T05:46:22.000Z | 2022-03-31T06:48:59.000Z | 44.969231 | 163 | 0.735546 | 1,003,728 | /**
* 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.pulsar.functions.auth;
import org.apache.pulsar.broker.authentication.AuthenticationDataSource;
import org.apache.pulsar.client.impl.auth.AuthenticationToken;
import org.apache.pulsar.functions.instance.AuthenticationConfig;
import org.apache.pulsar.functions.proto.Function;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Optional;
public class ClearTextFunctionTokenAuthProviderTest {
@Test
public void testClearTextAuth() throws Exception {
ClearTextFunctionTokenAuthProvider clearTextFunctionTokenAuthProvider = new ClearTextFunctionTokenAuthProvider();
Function.FunctionDetails funcDetails = Function.FunctionDetails.newBuilder().setTenant("test-tenant").setNamespace("test-ns").setName("test-func").build();
Optional<FunctionAuthData> functionAuthData = clearTextFunctionTokenAuthProvider.cacheAuthData(funcDetails, new AuthenticationDataSource() {
@Override
public boolean hasDataFromCommand() {
return true;
}
@Override
public String getCommandData() {
return "test-token";
}
});
Assert.assertTrue(functionAuthData.isPresent());
Assert.assertEquals(functionAuthData.get().getData(), "test-token".getBytes());
AuthenticationConfig authenticationConfig = AuthenticationConfig.builder().build();
clearTextFunctionTokenAuthProvider.configureAuthenticationConfig(authenticationConfig, functionAuthData);
Assert.assertEquals(authenticationConfig.getClientAuthenticationPlugin(), AuthenticationToken.class.getName());
Assert.assertEquals(authenticationConfig.getClientAuthenticationParameters(), "token:test-token");
AuthenticationToken authenticationToken = new AuthenticationToken();
authenticationToken.configure(authenticationConfig.getClientAuthenticationParameters());
Assert.assertEquals(authenticationToken.getAuthData().getCommandData(), "test-token");
}
}
|
924654d2663a35982ae2b4f611e1036fbfc8b589 | 1,470 | java | Java | classes/cc/eguid/livepush/dao/HandlerDaoImpl.java | eguid/livePush_Demo | 977504434ab1cff5ad310db24c819e77eb2a4ce8 | [
"Apache-2.0"
] | 22 | 2017-05-29T17:51:39.000Z | 2020-03-27T07:16:39.000Z | classes/cc/eguid/livepush/dao/HandlerDaoImpl.java | eguid/livePush_Demo | 977504434ab1cff5ad310db24c819e77eb2a4ce8 | [
"Apache-2.0"
] | null | null | null | classes/cc/eguid/livepush/dao/HandlerDaoImpl.java | eguid/livePush_Demo | 977504434ab1cff5ad310db24c819e77eb2a4ce8 | [
"Apache-2.0"
] | 15 | 2016-12-19T04:38:30.000Z | 2021-04-30T06:23:25.000Z | 19.864865 | 150 | 0.617007 | 1,003,729 | /**
* 文件名:HandlerDaoImpl.java 描述:命令行执行处理器缓存的简单实现 修改人:eguid 修改时间:2016年6月27日 修改内容:
*/
package cc.eguid.livepush.dao;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 处理器的缓存简单实现
* @author eguid
* @version 2016年6月27日
* @see HandlerDaoImpl
* @since jdk1.7
*/
public class HandlerDaoImpl implements HandlerDao
{
/**
* 存放process
*/
private static ConcurrentMap<String, ConcurrentMap<String, Object>> handlerMap = new ConcurrentHashMap<String, ConcurrentMap<String, Object>>(20);
@Override
public ConcurrentMap<String,Object> get(String pushId)
{
if(handlerMap.containsKey(pushId))
{
return handlerMap.get(pushId);
}
return null;
}
@Override
public ConcurrentMap<String, ConcurrentMap<String, Object>> getAll()
{
return handlerMap;
}
@Override
public void delete(String pushId)
{
if (pushId != null)
{
handlerMap.remove(pushId);
}
}
@Override
public void set(String key, ConcurrentMap<String, Object> map)
{
if (key != null)
{
handlerMap.put(key, map);
}
}
@Override
public boolean isHave(String pushId)
{
return handlerMap.containsKey(pushId);
}
@Override
public Set<String> getAllAppName()
{
return handlerMap.keySet();
}
}
|
924655e1d78e4bd0a53c75abbbe29b1f564b07ff | 3,524 | java | Java | src/main/java/com/infinities/skyport/websockify/client/WebSocketClientHandler.java | infinitiessoft/skyport-websockify | 640611f54f5fb95571ef30be9fe9467bc96c87be | [
"Apache-2.0"
] | 1 | 2017-05-12T12:45:03.000Z | 2017-05-12T12:45:03.000Z | src/main/java/com/infinities/skyport/websockify/client/WebSocketClientHandler.java | infinitiessoft/skyport-websockify | 640611f54f5fb95571ef30be9fe9467bc96c87be | [
"Apache-2.0"
] | null | null | null | src/main/java/com/infinities/skyport/websockify/client/WebSocketClientHandler.java | infinitiessoft/skyport-websockify | 640611f54f5fb95571ef30be9fe9467bc96c87be | [
"Apache-2.0"
] | null | null | null | 41.952381 | 95 | 0.744892 | 1,003,730 | /*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package com.infinities.skyport.websockify.client;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.jboss.netty.util.CharsetUtil;
public class WebSocketClientHandler extends SimpleChannelUpstreamHandler {
private final WebSocketClientHandshaker handshaker;
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("WebSocket Client disconnected!");
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Channel ch = ctx.getChannel();
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ch, (HttpResponse) e.getMessage());
System.out.println("WebSocket Client connected!");
return;
}
if (e.getMessage() instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e.getMessage();
throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content="
+ response.getContent().toString(CharsetUtil.UTF_8) + ')');
}
WebSocketFrame frame = (WebSocketFrame) e.getMessage();
if (frame instanceof TextWebSocketFrame) {
TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
System.out.println("WebSocket Client received message: " + textFrame.getText());
} else if (frame instanceof PongWebSocketFrame) {
System.out.println("WebSocket Client received pong");
} else if (frame instanceof CloseWebSocketFrame) {
System.out.println("WebSocket Client received closing");
ch.close();
} else if (frame instanceof PingWebSocketFrame) {
System.out.println("WebSocket Client received ping, response with pong");
ch.write(new PongWebSocketFrame(frame.getBinaryData()));
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
final Throwable t = e.getCause();
t.printStackTrace();
e.getChannel().close();
}
}
|
92465612e5de99f0620ade4eac8f04af6848c26e | 976 | java | Java | src/fitaview/automaton/nondeterminism/RandomChoice.java | ref-humbold/FITA-View | a64cc4e125c6753917c191adcbf9b220f548d97d | [
"MIT"
] | 4 | 2017-10-31T14:15:48.000Z | 2021-11-13T00:28:29.000Z | src/fitaview/automaton/nondeterminism/RandomChoice.java | ref-humbold/FITA-View | a64cc4e125c6753917c191adcbf9b220f548d97d | [
"MIT"
] | null | null | null | src/fitaview/automaton/nondeterminism/RandomChoice.java | ref-humbold/FITA-View | a64cc4e125c6753917c191adcbf9b220f548d97d | [
"MIT"
] | null | null | null | 23.804878 | 67 | 0.641393 | 1,003,731 | package fitaview.automaton.nondeterminism;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import fitaview.automaton.Variable;
public class RandomChoice<K, R>
implements StateChoice<K, R>
{
private final Random random = new Random();
@Override
public StateChoiceMode getMode()
{
return StateChoiceMode.RANDOM;
}
/**
* Non-deterministically choosing variable values.
* @param key transition key in node.
* @param states set of possible state variable values
* @return variable value chosen randomly
*/
@Override
public R chooseState(Variable var, K key, Collection<R> states)
{
if(states.size() == 1)
return states.iterator().next();
int index = random.nextInt(states.size());
Iterator<R> iterator = states.iterator();
for(int i = 1; i < index; ++i)
iterator.next();
return iterator.next();
}
}
|
924656566bf0aad99916b831bcebccb30fb31de6 | 4,730 | java | Java | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/injection/KeyedDialogProvider.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | null | null | null | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/injection/KeyedDialogProvider.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 61 | 2015-01-04T01:14:08.000Z | 2017-04-14T22:46:37.000Z | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/injection/KeyedDialogProvider.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 4 | 2017-03-22T03:11:43.000Z | 2020-01-10T07:08:50.000Z | 36.666667 | 119 | 0.676321 | 1,003,732 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.injection;
import com.dmdirc.addons.ui_swing.dialogs.StandardDialog;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;
import static com.dmdirc.addons.ui_swing.SwingPreconditions.checkOnEDT;
/**
* Provider for {@link StandardDialog} based windows that correspond to some key.
* <p>
* This provider will cache instances that are created until the windows are closed. Once a window
* has been closed, the next call to {@link #get} or {@link #displayOrRequestFocus} will result
* in a new instance being created.
* <p>
* Dialogs with different keys may be open simultaneously, and are treated independently.
*
* @param <K> The type of key that dialogs are associated with.
* @param <T> The type of dialog that will be managed.
*/
public abstract class KeyedDialogProvider<K, T extends StandardDialog> {
/** The existing instances being displayed, if any. */
private final Map<K, T> instances = new HashMap<>();
/**
* Gets an instance of the dialog provided by this class.
* <p>
* If there is an existing instance with the same key that hasn't been closed, it will be
* returned. Otherwise a new instance will be created and returned. New instances will not be
* automatically be displayed to the user - use {@link #displayOrRequestFocus(java.lang.Object)}
* to do so.
* <p>
* This method <em>must</em> be called on the Event Despatch Thread.
*
* @param key The key associated with the dialog to get.
*
* @return An instance of the dialog.
*/
public T get(final K key) {
checkOnEDT();
if (!instances.containsKey(key)) {
final T instance = getInstance(key);
instance.addWindowListener(new Listener(key));
instances.put(key, instance);
}
return instances.get(key);
}
/**
* Disposes of the dialog associated with the given key, if it exists.
* <p>
* This method <em>must</em> be called on the Event Despatch Thread.
*
* @param key The key associated with the dialog to close.
*/
public void dispose(final K key) {
checkOnEDT();
if (instances.containsKey(key)) {
instances.get(key).dispose();
}
}
/**
* Ensures the dialog is visible to the user.
* <p>
* If no dialog currently exists with the same key, a new one will be created and displayed to
* the user. If a dialog existed prior to this method being invoked, it will request focus to
* bring it to the user's attention.
* <p>
* This method <em>must</em> be called on the Event Despatch Thread.
*
* @param key The key associated with the dialog to display.
*/
public void displayOrRequestFocus(final K key) {
checkOnEDT();
get(key).displayOrRequestFocus();
}
/**
* Returns a new instance of the dialog with the specified key.
*
* @param key The key to create a new dialog for.
*
* @return A new instance of this provider's dialog.
*/
protected abstract T getInstance(final K key);
/**
* Listens to window closed events to remove the cached instance of the dialog.
*/
private class Listener extends WindowAdapter {
private final K key;
Listener(final K key) {
this.key = key;
}
@Override
public void windowClosed(final WindowEvent e) {
super.windowClosed(e);
instances.remove(key);
}
}
}
|
924656ba212334b193931c7698aafeebf32457a2 | 2,020 | java | Java | querydsl-jpa/src/test/java/com/querydsl/jpa/domain/sql/SFoo.java | cpugputpu/querydsl | 6ed90d6779325e3308031c3c719c457a12d81797 | [
"Apache-2.0"
] | 3,579 | 2015-01-01T18:13:48.000Z | 2022-03-31T18:28:45.000Z | querydsl-jpa/src/test/java/com/querydsl/jpa/domain/sql/SFoo.java | cpugputpu/querydsl | 6ed90d6779325e3308031c3c719c457a12d81797 | [
"Apache-2.0"
] | 1,828 | 2015-01-04T10:52:58.000Z | 2022-03-31T14:45:10.000Z | querydsl-jpa/src/test/java/com/querydsl/jpa/domain/sql/SFoo.java | cpugputpu/querydsl | 6ed90d6779325e3308031c3c719c457a12d81797 | [
"Apache-2.0"
] | 867 | 2015-01-07T21:46:24.000Z | 2022-03-29T12:56:31.000Z | 32.063492 | 112 | 0.707426 | 1,003,733 | package com.querydsl.jpa.domain.sql;
import static com.querydsl.core.types.PathMetadataFactory.forVariable;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.dsl.DatePath;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.StringPath;
import com.querydsl.sql.ColumnMetadata;
/**
* SFoo is a Querydsl query type for SFoo
*/
@Generated("com.querydsl.sql.codegen.MetaDataSerializer")
public class SFoo extends com.querydsl.sql.RelationalPathBase<SFoo> {
private static final long serialVersionUID = -1389443894;
public static final SFoo foo_ = new SFoo("foo_");
public final StringPath bar = createString("bar");
public final NumberPath<Integer> id = createNumber("id", Integer.class);
public final DatePath<java.sql.Date> startDate = createDate("startDate", java.sql.Date.class);
public final com.querydsl.sql.PrimaryKey<SFoo> primary = createPrimaryKey(id);
public final com.querydsl.sql.ForeignKey<SFooNames> _fkb6129a8f94e297f8 = createInvForeignKey(id, "foo_id");
public SFoo(String variable) {
super(SFoo.class, forVariable(variable), "", "foo_");
addMetadata();
}
public SFoo(String variable, String schema, String table) {
super(SFoo.class, forVariable(variable), schema, table);
addMetadata();
}
public SFoo(Path<? extends SFoo> path) {
super(path.getType(), path.getMetadata(), "", "foo_");
addMetadata();
}
public SFoo(PathMetadata metadata) {
super(SFoo.class, metadata, "", "foo_");
addMetadata();
}
public void addMetadata() {
addMetadata(bar, ColumnMetadata.named("bar").withIndex(2).ofType(12).withSize(255));
addMetadata(id, ColumnMetadata.named("id").withIndex(1).ofType(4).withSize(10).notNull());
addMetadata(startDate, ColumnMetadata.named("startDate").withIndex(3).ofType(91).withSize(10));
}
}
|
924656d17d135378721fea96644cd9eea4588212 | 3,747 | java | Java | switcher/src/main/java/com/networknt/switcher/LocalSwitcherService.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 3,383 | 2017-05-07T07:43:27.000Z | 2022-03-26T10:11:27.000Z | switcher/src/main/java/com/networknt/switcher/LocalSwitcherService.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 857 | 2017-05-05T18:29:15.000Z | 2022-03-30T22:08:27.000Z | switcher/src/main/java/com/networknt/switcher/LocalSwitcherService.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 596 | 2017-05-08T13:43:35.000Z | 2022-03-26T10:11:11.000Z | 32.025641 | 107 | 0.647985 | 1,003,734 | /*
* Copyright 2009-2016 Weibo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.switcher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Local switcher service implementation
*
* @author maijunsheng
*
*/
public class LocalSwitcherService implements SwitcherService {
private static ConcurrentMap<String, Switcher> switchers = new ConcurrentHashMap<>();
final private Map<String, List<SwitcherListener>> listenerMap = new ConcurrentHashMap();
@Override
public Switcher getSwitcher(String name) {
return switchers.get(name);
}
@Override
public List<Switcher> getAllSwitchers() {
return new ArrayList<>(switchers.values());
}
private void putSwitcher(Switcher switcher) {
if (switcher == null) {
throw new IllegalArgumentException("LocalSwitcherService addSwitcher Error: switcher is null");
}
switchers.put(switcher.getName(), switcher);
}
@Override
public void initSwitcher(String switcherName, boolean initialValue) {
setValue(switcherName, initialValue);
}
@Override
public boolean isOpen(String switcherName) {
Switcher switcher = switchers.get(switcherName);
return switcher != null && switcher.isOn();
}
@Override
public boolean isOpen(String switcherName, boolean defaultValue) {
Switcher switcher = switchers.get(switcherName);
if (switcher == null) {
switchers.putIfAbsent(switcherName, new Switcher(switcherName, defaultValue));
switcher = switchers.get(switcherName);
}
return switcher.isOn();
}
@Override
public void setValue(String switcherName, boolean value) {
putSwitcher(new Switcher(switcherName, value));
List<SwitcherListener> listeners = listenerMap.get(switcherName);
if(listeners != null) {
for (SwitcherListener listener : listeners) {
listener.onValueChanged(switcherName, value);
}
}
}
@Override
public void registerListener(String switcherName, SwitcherListener listener) {
synchronized (listenerMap) {
if (listenerMap.get(switcherName) == null) {
List listeners = Collections.synchronizedList(new ArrayList());
listenerMap.put(switcherName, listeners);
listeners.add(listener);
} else {
List listeners = listenerMap.get(switcherName);
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
}
}
@Override
public void unRegisterListener(String switcherName, SwitcherListener listener) {
synchronized (listenerMap) {
if (listener == null) {
listenerMap.remove(switcherName);
} else {
List<SwitcherListener> listeners = listenerMap.get(switcherName);
listeners.remove(listener);
}
}
}
}
|
924657e909f1ebc9fe48711d8fb86f72042b5a55 | 1,710 | java | Java | languages/languageDesign/behavior/languages/behavior/generator/source_gen/jetbrains/mps/lang/behavior/generator/template/util/MethodNameHelper.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/languageDesign/behavior/languages/behavior/generator/source_gen/jetbrains/mps/lang/behavior/generator/template/util/MethodNameHelper.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/languageDesign/behavior/languages/behavior/generator/source_gen/jetbrains/mps/lang/behavior/generator/template/util/MethodNameHelper.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 33.529412 | 164 | 0.784211 | 1,003,735 | package jetbrains.mps.lang.behavior.generator.template.util;
/*Generated by MPS */
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.core.aspects.behaviour.SMethodTrimmedId;
import jetbrains.mps.baseLanguage.behavior.BaseMethodDeclaration__BehaviorDescriptor;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
/**
* TODO need to be moved to the behavior of the ConceptBehavior after MPS project rebuilt
*/
public final class MethodNameHelper {
private final SNode myMethodDecl;
public MethodNameHelper(@NotNull SNode methodDecl) {
myMethodDecl = methodDecl;
}
@NotNull
public String getGeneratedString() {
return getGeneratedName() + "_id" + getGeneratedId();
}
@NotNull
public String getGeneratedName() {
return SPropertyOperations.getString(getBaseMethod(), PROPS.name$MnvL);
}
@NotNull
public String getGeneratedId() {
SNode baseMethod = getBaseMethod();
return SMethodTrimmedId.toText(baseMethod.getNodeId());
}
private SNode getBaseMethod() {
SNode baseMethod = myMethodDecl;
if (BaseMethodDeclaration__BehaviorDescriptor.getBaseMethod_id4mmymf_0z7l.invoke(myMethodDecl) != null) {
baseMethod = BaseMethodDeclaration__BehaviorDescriptor.getBaseMethod_id4mmymf_0z7l.invoke(myMethodDecl);
}
return baseMethod;
}
private static final class PROPS {
/*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
}
}
|
9246586f4afd0f4039fe66ed14831173fae761e9 | 5,373 | java | Java | SPACEXIFA/src/com/spring/service/impl/InsframeworkServiceImpl.java | 12345asdf555/XIAN | 53fac722b4433b0300bfb3a6d718bf6796da0b21 | [
"MIT"
] | null | null | null | SPACEXIFA/src/com/spring/service/impl/InsframeworkServiceImpl.java | 12345asdf555/XIAN | 53fac722b4433b0300bfb3a6d718bf6796da0b21 | [
"MIT"
] | null | null | null | SPACEXIFA/src/com/spring/service/impl/InsframeworkServiceImpl.java | 12345asdf555/XIAN | 53fac722b4433b0300bfb3a6d718bf6796da0b21 | [
"MIT"
] | null | null | null | 24.534247 | 100 | 0.757491 | 1,003,736 | package com.spring.service.impl;
import java.math.BigInteger;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.spring.dao.InsframeworkMapper;
import com.spring.dao.WeldingMachineMapper;
import com.spring.dao.WeldingMaintenanceMapper;
import com.spring.dto.WeldDto;
import com.spring.model.Insframework;
import com.spring.model.MyUser;
import com.spring.model.WeldingMachine;
import com.spring.model.WeldingMaintenance;
import com.spring.page.Page;
import com.spring.service.InsframeworkService;
import com.spring.util.IsnullUtil;
@Service
@Transactional
public class InsframeworkServiceImpl implements InsframeworkService {
@Autowired
private InsframeworkMapper im;
@Autowired
private WeldingMachineMapper wmm;
@Autowired
private WeldingMaintenanceMapper wm;
@Override
public List<Insframework> getInsframeworkAll(Page page,BigInteger parent, String str,WeldDto dto) {
PageHelper.startPage(page.getPageIndex(),page.getPageSize());
return im.getInsframeworkAll(parent,str,dto);
}
@Override
public void addInsframework(Insframework ins) {
im.addInsframework(ins);
}
@Override
public void editInsframework(Insframework ins) {
im.editInsframework(ins);
}
@Override
public void deleteInsframework(BigInteger id) {
//删除维修记录
List<WeldingMachine> weldingmachine = wmm.getWeldingMachineByInsf(id);
for(WeldingMachine welding:weldingmachine){
List<WeldingMaintenance> list = wm.getMaintainByWeldingMachinId(welding.getId());
for(WeldingMaintenance w:list){
WeldingMaintenance m = wm.getWeldingMaintenanceById(w.getId());
wm.deleteMaintenanceRecord(m.getMaintenance().getId());
wm.deleteWeldingMaintenance(m.getId());
}
}
//删除焊机
wmm.deleteByInsf(id);
//删除项目
im.deleteInsframework(id);
}
@Override
public List<Insframework> getInsframework(String str) {
return im.getInsframeworkAll(null,str,null);
}
@Override
public int getInsframeworkNameCount(String name) {
return im.getInsframeworkNameCount(name);
}
@Override
public String getInsframeworkById(BigInteger id) {
return im.getInsframeworkById(id);
}
@Override
public Insframework getInsfAllById(BigInteger id) {
return im.getInsfAllById(id);
}
@Override
public List<Insframework> getConmpany() {
return im.getConmpany();
}
@Override
public List<Insframework> getCause(BigInteger id) {
return im.getCause(id);
}
@Override
public List<Insframework> getWeldingMachineInsf(BigInteger parent) {
return im.getInsframework(parent);
}
@Override
public Insframework getParent(BigInteger id) {
return im.getParent(id);
}
@Override
public void showParent(HttpServletRequest request,String parentid) {
IsnullUtil iutil = new IsnullUtil();
if(iutil.isNull(parentid)){
StringBuffer sb = new StringBuffer();
boolean flag = true;
Insframework ins = getParent(new BigInteger(parentid));
while(flag){
if(ins!=null){
sb.insert(0, ins.getName()+"-");
ins = getParent(ins.getId());
}else if(ins==null){
flag = false;
}
}
String name = getInsframeworkById(new BigInteger(parentid));
sb.append(name);
request.setAttribute("str", sb);
}
}
@Override
public List<Insframework> getInsByType(int type,BigInteger parent) {
return im.getInsByType(type,parent);
}
@Override
public int getUserInsfType(BigInteger uid) {
return im.getUserInsfType(uid);
}
@Override
public BigInteger getUserInsfId(BigInteger uid) {
return im.getUserInsfId(uid);
}
@Override
public Insframework getBloc() {
return im.getBloc();
}
@Override
public int getTypeById(BigInteger id) {
return im.getTypeById(id);
}
@Override
public BigInteger getParentById(BigInteger id) {
return im.getParentById(id);
}
@Override
public List<Insframework> getInsIdByParent(BigInteger parent,int type) {
return im.getInsIdByParent(parent,type);
}
@Override
public List<Insframework> getInsByUserid(BigInteger uid) {
return im.getInsByUserid(uid);
}
@Override
public Insframework getInsById(BigInteger id) {
return im.getInsById(id);
}
@Override
public List<Insframework> getInsAll(int type) {
return im.getInsAll(type);
}
@Override
public List<Insframework> getUserInsAll(String str) {
return im.getUserInsAll(str);
}
@Override
public List<Insframework> getOperateArea(String str, int type) {
return im.getOperateArea(str, type);
}
@Override
public BigInteger getUserInsframework() {
try{
//获取用户id
MyUser myuser = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long uid = myuser.getId();
List<Insframework> insframework = im.getInsByUserid(BigInteger.valueOf(uid));
return insframework.get(0).getId();
}catch(Exception e){
return null;
}
}
@Override
public List<Insframework> getConmpany(BigInteger value1) {
// TODO Auto-generated method stub
return im.getConmpany1(String.valueOf(value1));
}
@Override
public List<Insframework> getCause(BigInteger id, BigInteger value2) {
// TODO Auto-generated method stub
return im.getCause1(id, value2);
}
}
|
924658c00639adad33a2bd0622f76ead6f2b527d | 2,122 | java | Java | src/main/java/com/google_melange/Dataset/Question.java | rsharnag/QuestionAnswerGSOC | 2aab590e0395101dbddeb682291d31f67182312f | [
"MIT"
] | 1 | 2015-04-05T20:24:43.000Z | 2015-04-05T20:24:43.000Z | src/main/java/com/google_melange/Dataset/Question.java | rsharnag/QuestionAnswerGSOC | 2aab590e0395101dbddeb682291d31f67182312f | [
"MIT"
] | null | null | null | src/main/java/com/google_melange/Dataset/Question.java | rsharnag/QuestionAnswerGSOC | 2aab590e0395101dbddeb682291d31f67182312f | [
"MIT"
] | null | null | null | 19.831776 | 73 | 0.681433 | 1,003,737 | /**
*
*/
package com.google_melange.Dataset;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
/**
* @author Rahul Sharnagat
*
*/
public class Question {
List<QuestionInstance> questionList = new ArrayList<QuestionInstance>();
List<KeyWords> keywords = new ArrayList<KeyWords>();
private int id;
private boolean onlydbo;
String answerType;
boolean aggregation;
@XmlElement
String query;
public String getId() {
return id+"";
}
@XmlAttribute
public void setId(String id) {
this.id = Integer.parseInt(id.trim());
}
public String isOnlydbo() {
return onlydbo+"";
}
@XmlAttribute
public void setOnlydbo(String onlydbo) {
this.onlydbo = Boolean.parseBoolean(onlydbo.trim());
}
public String getAnswerType() {
return answerType+"";
}
@XmlAttribute(name="answertype")
public void setAnswerType(String answerType) {
this.answerType = answerType.trim();
}
public String getAggregation() {
return aggregation+"";
}
@XmlAttribute
public void setAggregation(String aggregation) {
this.aggregation = Boolean.parseBoolean(aggregation.trim());
}
public List<QuestionInstance> getQuestionList() {
return questionList;
}
@XmlElement(name="string")
public void setQuestionList(List<QuestionInstance> questionList) {
this.questionList = questionList;
}
public List<KeyWords> getKeywords() {
return keywords;
}
@XmlElement(name="keywords")
public void setKeywords(List<KeyWords> keywords) {
this.keywords = keywords;
}
@Override
public String toString() {
String out= "";
if(questionList==null || questionList.size()==0) {
out="no elements loaded";
}else {
for (QuestionInstance q : questionList) {
out+=" "+q.lang+"-"+q.question;
}
}
out+="\n";
if(keywords==null || keywords.size()==0) {
out="no elements loaded";
}else {
for (KeyWords q : keywords) {
out+=" "+q.lang+"-"+q.keyword;
}
}
out+="\n";
out+=id+"-"+onlydbo+"-"+answerType+"-"+aggregation+"\n";
out+="\n";
out+=query;
return out;
}
}
|
924658d0e56450a17c0c6048feef4b4eae8ad77e | 959 | java | Java | src/main/java/com/github/angleshq/angles/basetest/testng/AnglesTestngBaseTest.java | cosminoance/angles-java-client | a7aad38b133e673dd1f57c26b5bd44ed4da0867b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/angleshq/angles/basetest/testng/AnglesTestngBaseTest.java | cosminoance/angles-java-client | a7aad38b133e673dd1f57c26b5bd44ed4da0867b | [
"Apache-2.0"
] | 9 | 2021-03-28T14:44:43.000Z | 2021-12-18T18:37:13.000Z | src/main/java/com/github/angleshq/angles/basetest/testng/AnglesTestngBaseTest.java | cosminoance/angles-java-client | a7aad38b133e673dd1f57c26b5bd44ed4da0867b | [
"Apache-2.0"
] | 2 | 2021-03-17T11:41:10.000Z | 2021-04-21T09:15:19.000Z | 33.068966 | 72 | 0.749739 | 1,003,738 | package com.github.angleshq.angles.basetest.testng;
import com.github.angleshq.angles.assertion.testng.AnglesTestngAssert;
import com.github.angleshq.angles.basetest.AbstractAnglesTestCase;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.lang.reflect.Method;
public class AnglesTestngBaseTest extends AbstractAnglesTestCase {
protected AnglesTestngAssert doAssert = new AnglesTestngAssert();
/**
* Starts a test run within Angles. Override to customise test name.
* @param method
*/
@BeforeMethod(alwaysRun = true)
public void anglesBeforeMethod(Method method) {
String suiteName = method.getDeclaringClass().getSimpleName();
String methodName = method.getName();
anglesReporter.startTest(suiteName, methodName);
}
@AfterMethod(alwaysRun = true)
public void anglesAfterMethod(Method method) {
anglesReporter.saveTest();
}
} |
92465986fb9c46877d55ff4e43a84d97929cd594 | 1,730 | java | Java | src/test/java/TC002/TC002.java | filipeferreira86/DesafioTec | 1e7eb79c1c69b0b7a8d131d867b10ebe2bc22d7d | [
"Apache-2.0"
] | 1 | 2018-10-08T01:33:30.000Z | 2018-10-08T01:33:30.000Z | src/test/java/TC002/TC002.java | filipeferreira86/DesafioTec | 1e7eb79c1c69b0b7a8d131d867b10ebe2bc22d7d | [
"Apache-2.0"
] | null | null | null | src/test/java/TC002/TC002.java | filipeferreira86/DesafioTec | 1e7eb79c1c69b0b7a8d131d867b10ebe2bc22d7d | [
"Apache-2.0"
] | null | null | null | 24.366197 | 104 | 0.695954 | 1,003,739 | package TC002;
import org.junit.validator.ValidateWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import func.Campos;
import func.PrtScr;
public class TC002 {
WebDriver driver;
Campos campos;
int prtnu = 1;
String caso = "TC002";
PrtScr prt;
@DataProvider(name = "userLogin")
public Object[][] createData1() {
return new Object[][] {
{ "Demouser" , "abc123" },
{ "demouser_", "xyz" },
{ "demouser" , "nananana"},
{ "Demouser" , "abc123" }
};
}
@BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "C:/Users/Filipe/Documents/webdriver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://automation-sandbox.herokuapp.com/");
campos = new Campos(driver);
prtnu = prt.capturar(driver, caso+"/print", prtnu);
prtnu++;
}
@Test(dataProvider = "userLogin")
public void f(String u, String p) {
prtnu = campos.preencherCampos(u, p, prtnu, caso);
String vAlerta = null;
try {
WebElement alerta = driver.findElement(By.cssSelector(".alert"));
alerta.isDisplayed();
vAlerta = alerta.getText();
} catch (Exception e) {
Assert.assertTrue(false);
}
if(vAlerta!=null) {
String msg = "Wrong Username or Password";
Assert.assertEquals(vAlerta, msg,
caso + " - Mensagem incorreta sendo ");
}
}
@AfterClass
public void afterClass() {
driver.quit();
}
}
|
924659d41848dcf1d24c6039f7d3fd1aa6e4d022 | 869 | java | Java | wms-integration/src/main/java/com/lsh/wms/integration/model/OrderResponse.java | weiandedidi/work_sys | d2c6358ebef524d93104ad8e003395176a8ac599 | [
"Apache-2.0"
] | null | null | null | wms-integration/src/main/java/com/lsh/wms/integration/model/OrderResponse.java | weiandedidi/work_sys | d2c6358ebef524d93104ad8e003395176a8ac599 | [
"Apache-2.0"
] | null | null | null | wms-integration/src/main/java/com/lsh/wms/integration/model/OrderResponse.java | weiandedidi/work_sys | d2c6358ebef524d93104ad8e003395176a8ac599 | [
"Apache-2.0"
] | null | null | null | 18.891304 | 54 | 0.64557 | 1,003,740 | package com.lsh.wms.integration.model;
import java.io.Serializable;
public class OrderResponse implements Serializable {
private String code;
private String gatewayToken;//gatewayToken
private boolean succcess;
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getGatewayToken() {
return gatewayToken;
}
public void setGatewayToken(String gatewayToken) {
this.gatewayToken = gatewayToken;
}
public boolean isSucccess() {
return succcess;
}
public void setSucccess(boolean succcess) {
this.succcess = succcess;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
} |
92465b22b1661a5252890190c2a4d889b69377a6 | 2,221 | java | Java | tool/src/java/org/sakaiproject/sms/tool/beans/SmsSiteConfigActionBean.java | cilt-uct/sms | dfe29606fa196b8027135a2790cd15680c729029 | [
"ECL-2.0"
] | 1 | 2018-01-19T15:46:30.000Z | 2018-01-19T15:46:30.000Z | tool/src/java/org/sakaiproject/sms/tool/beans/SmsSiteConfigActionBean.java | cilt-uct/sms | dfe29606fa196b8027135a2790cd15680c729029 | [
"ECL-2.0"
] | 5 | 2018-01-22T16:32:43.000Z | 2019-08-12T12:40:08.000Z | tool/src/java/org/sakaiproject/sms/tool/beans/SmsSiteConfigActionBean.java | cilt-uct/sms | dfe29606fa196b8027135a2790cd15680c729029 | [
"ECL-2.0"
] | 1 | 2017-11-13T06:09:07.000Z | 2017-11-13T06:09:07.000Z | 30.424658 | 84 | 0.716344 | 1,003,741 | /***********************************************************************************
* SMSConfigActionBean.java
* Copyright (c) 2008 Sakai Project/Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.sms.tool.beans;
import org.sakaiproject.sms.logic.SmsConfigLogic;
import org.sakaiproject.sms.logic.external.ExternalLogic;
import org.sakaiproject.sms.model.SmsConfig;
import org.sakaiproject.sms.tool.otp.SmsConfigLocator;
import org.springframework.util.Assert;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SmsSiteConfigActionBean {
private SmsConfigLocator smsConfigLocator;
private SmsConfigLogic smsConfigLogic;
private ExternalLogic externalLogic;
public void setSmsConfigLocator(SmsConfigLocator smsConfigLocator) {
this.smsConfigLocator = smsConfigLocator;
}
public void setSmsConfigLogic(SmsConfigLogic smsConfigLogic) {
this.smsConfigLogic = smsConfigLogic;
}
public void setExternalLogic(ExternalLogic externalLogic) {
this.externalLogic = externalLogic;
}
public void init() {
Assert.notNull(smsConfigLocator);
Assert.notNull(smsConfigLogic);
Assert.notNull(externalLogic);
}
public String save() {
final SmsConfig smsConfig = (SmsConfig) smsConfigLocator
.locateBean(externalLogic.getCurrentSiteId());
// TODO: find out if this should be the case
// if(smsConfig.getSmsEnabled().equals(Boolean.FALSE))
// smsConfig.setNotificationEmail("");
if (log.isInfoEnabled()) {
log.info("Persisting smsConfig");
}
smsConfigLogic.persistSmsConfig(smsConfig);
return ActionResults.SUCCESS;
}
}
|
92465e3e4313e5e0a5f527c1bcc168c5f11e6a42 | 7,605 | java | Java | src/main/java/io/xdag/crypto/ECKeyPair.java | q424492629/xdagj-master | 38715c361a00c0bba0f9284eb54c17b40b43cc71 | [
"MIT"
] | 92 | 2020-07-22T12:32:54.000Z | 2022-03-15T13:35:56.000Z | src/main/java/io/xdag/crypto/ECKeyPair.java | q424492629/xdagj-master | 38715c361a00c0bba0f9284eb54c17b40b43cc71 | [
"MIT"
] | 46 | 2021-02-20T18:07:03.000Z | 2022-03-18T11:04:16.000Z | src/main/java/io/xdag/crypto/ECKeyPair.java | q424492629/xdagj-master | 38715c361a00c0bba0f9284eb54c17b40b43cc71 | [
"MIT"
] | 50 | 2020-07-22T12:33:00.000Z | 2022-03-12T11:05:35.000Z | 36.917476 | 117 | 0.682183 | 1,003,742 | /*
* The MIT License (MIT)
*
* Copyright (c) 2020-2030 The XdagJ Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.xdag.crypto;
import io.xdag.utils.BytesUtils;
import io.xdag.utils.Numeric;
import java.math.BigInteger;
import java.security.KeyPair;
import java.util.Arrays;
import java.util.Objects;
import org.bitcoin.NativeSecp256k1;
import org.bitcoin.NativeSecp256k1Util;
import org.bitcoin.Secp256k1Context;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.HMacDSAKCalculator;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
public class ECKeyPair {
private final BigInteger privateKey;
/**
* 非压缩+去前缀0x04
**/
private final BigInteger publicKey;
public ECKeyPair(BigInteger privateKey, BigInteger publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
}
/**
* <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
*
* <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
* larger than 520 bytes.</p>
*
* @param data Hash of the data to verify.
* @param signature ASN.1 encoded signature.
* @param pub The public key bytes to use.
*/
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
if (Secp256k1Context.isEnabled()) {
try {
return NativeSecp256k1.verify(data, signature.encodeToDER(), pub);
} catch (NativeSecp256k1Util.AssertFailException e) {
throw new RuntimeException("Caught AssertFailException inside secp256k1", e);
}
}
ECDSASigner signer = new ECDSASigner();
ECPublicKeyParameters params = new ECPublicKeyParameters(Sign.CURVE.getCurve().decodePoint(pub), Sign.CURVE);
signer.init(false, params);
try {
return signer.verifySignature(data, signature.r, signature.s);
} catch (NullPointerException e) {
// Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those signatures
// are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
throw new RuntimeException("Caught NPE inside bouncy castle", e);
}
}
public static ECKeyPair create(KeyPair keyPair) {
BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();
BigInteger privateKeyValue = privateKey.getD();
// Ethereum does not use encoded public keys like bitcoin - see
// https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
// Additionally, as the first bit is a constant prefix (0x04) we ignore this value
byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
BigInteger publicKeyValue =
new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));
return new ECKeyPair(privateKeyValue, publicKeyValue);
}
public static ECKeyPair create(BigInteger privateKey) {
return new ECKeyPair(privateKey, Sign.publicKeyFromPrivate(privateKey));
}
public static ECKeyPair create(byte[] privateKey) {
return create(Numeric.toBigInt(privateKey));
}
public BigInteger getPrivateKey() {
return privateKey;
}
public BigInteger getPublicKey() {
return publicKey;
}
/**
* Sign a hash with the private key of this key pair.
*
* @param transactionHash the hash to sign
* @return An {@link ECDSASignature} of the hash
*/
public ECDSASignature sign(byte[] transactionHash) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(transactionHash);
return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
/**
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
*
* @param hash Hash of the data to verify.
* @param signature ASN.1 encoded signature.
*/
public boolean verify(byte[] hash, byte[] signature) {
return ECKeyPair.verify(hash, ECDSASignature.decodeFromDER(signature),
Sign.publicKeyBytesFromPrivate(this.privateKey, false));
}
/**
* Verifies the given R/S pair (signature) against a hash using the public key.
*/
public boolean verify(byte[] hash, ECDSASignature signature) {
return ECKeyPair.verify(hash, signature, Sign.publicKeyBytesFromPrivate(this.privateKey, false));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ECKeyPair ecKeyPair = (ECKeyPair) o;
if (!Objects.equals(privateKey, ecKeyPair.privateKey)) {
return false;
}
return Objects.equals(publicKey, ecKeyPair.publicKey);
}
@Override
public int hashCode() {
int result = privateKey != null ? privateKey.hashCode() : 0;
result = 31 * result + (publicKey != null ? publicKey.hashCode() : 0);
return result;
}
/**
* ECKey 存储公钥类型为 非压缩+去前缀(0x04)
* 验证签名的时候需要获得压缩公钥
* 添加compressPubKey方法,将非压缩公钥解析成压缩公钥
*/
public byte[] getCompressPubKeyBytes() {
byte pubKeyYPrefix;
// pubkey 是奇数公钥
if (publicKey.testBit(0)) {
pubKeyYPrefix = 0x03;
} else {
pubKeyYPrefix = 0x02;
}
return BytesUtils.merge(pubKeyYPrefix, BytesUtils.subArray(Numeric.toBytesPadded(publicKey, 64), 0, 32));
}
/**
* ECKey 存储公钥类型为 压缩+前缀(0x04)
* 验证签名的时候需要获得压缩公钥
* 添加compressPubKey方法,将非压缩公钥解析成压缩公钥
*/
public byte[] getPubKeyBytes() {
byte pubKeyYPrefix = 0x04;
return BytesUtils.merge(pubKeyYPrefix, BytesUtils.subArray(Numeric.toBytesPadded(publicKey, 64), 0, 64));
}
}
|
92465e519715b24d49aa95d2c3114d75b45a471d | 723 | java | Java | src/main/java/sonar/calculator/mod/CalculatorSmelting.java | SonarSonic/Calculator | c796f1dc24e937f95cb5d8573f485b66e87164b4 | [
"MIT"
] | 65 | 2015-05-31T11:58:40.000Z | 2022-01-12T14:22:35.000Z | src/main/java/sonar/calculator/mod/CalculatorSmelting.java | SonarSonic/Calculator | c796f1dc24e937f95cb5d8573f485b66e87164b4 | [
"MIT"
] | 375 | 2015-06-13T11:20:55.000Z | 2021-08-04T03:22:37.000Z | src/main/java/sonar/calculator/mod/CalculatorSmelting.java | SonarSonic/Calculator | c796f1dc24e937f95cb5d8573f485b66e87164b4 | [
"MIT"
] | 60 | 2015-05-18T04:39:48.000Z | 2021-03-03T14:47:39.000Z | 32.863636 | 78 | 0.77455 | 1,003,743 | package sonar.calculator.mod;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.IFuelHandler;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CalculatorSmelting extends Calculator {
public static void addSmeltingRecipes() {
addSmelting(enrichedGold, new ItemStack(enrichedgold_ingot), 0.8F);
addSmelting(broccoli, new ItemStack(cookedBroccoli), 0.2F);
//addSmelting(firediamond, new ItemStack(electricDiamond), 1.0F);
}
public static void addSmelting(Item input, ItemStack output, float xp) {
if (input != null && output != null && CalculatorConfig.isEnabled(output)) {
GameRegistry.addSmelting(input, output, xp);
}
}
}
|
92465e6894675cb31347407b630031e507af8d7e | 2,511 | java | Java | src/main/java/nl/coenvl/sam/constraints/Constraint.java | coenvl/jSAM | 5e094519f8a3bb0184deafc3eb30fcfbc84b56a2 | [
"Apache-2.0"
] | 1 | 2020-09-15T23:50:57.000Z | 2020-09-15T23:50:57.000Z | src/main/java/nl/coenvl/sam/constraints/Constraint.java | coenvl/jSAM | 5e094519f8a3bb0184deafc3eb30fcfbc84b56a2 | [
"Apache-2.0"
] | 1 | 2021-03-04T10:30:35.000Z | 2021-03-04T10:30:35.000Z | src/main/java/nl/coenvl/sam/constraints/Constraint.java | coenvl/jSAM | 5e094519f8a3bb0184deafc3eb30fcfbc84b56a2 | [
"Apache-2.0"
] | 1 | 2016-12-06T11:19:18.000Z | 2016-12-06T11:19:18.000Z | 33.039474 | 120 | 0.660693 | 1,003,744 | /**
* File Constraint.java
*
* This file is part of the jSAM project.
*
* Copyright 2016 TNO
*
* 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 nl.coenvl.sam.constraints;
import java.util.Set;
import java.util.UUID;
import nl.coenvl.sam.variables.AssignmentMap;
import nl.coenvl.sam.variables.Variable;
/**
* Constraint
*
* @author leeuwencjv
* @version 0.1
* @since 26 feb. 2016
*/
public interface Constraint<T extends Variable<V>, V> {
/**
* Return a set of ids of the variables that are involved in this constraint
*
* @return
*/
public Set<UUID> getVariableIds();
/**
* Returns the costs for any involved variable. May be the same for all involved variables, or may be different.
*
* @param targetVariable
* The variable for which to return the current cost
* @return A double indicating the cost of this constraint
*/
public double getCost(T targetVariable);
/**
* Returns the costs for any involved variable assuming the involved variables are set to the values as provided
* instead of taking the actual current values.
*
* @param variable
* The variable for which to return the current cost
* @param valueMap
* The a Map of key value pairs, in which the keys are the ids of the involved variables (or a superset
* thereof), and the values are the corresponding variable values.
* @return A double indicating the cost of this constraint in the case that the variables are set as in the values
* Map.
*/
public double getCostIf(T variable, AssignmentMap<V> valueMap);
/**
* This function is to be used only from OUTSIDE of the simulation. It does not increase the CompareCounter, and it
* sums the costs of all involved variables.
*
* @return
*/
public double getExternalCost();
}
|
92465e767b9f6230593f1a0c6bb1ab4411d5aa69 | 2,687 | java | Java | src/java/beans/psdi/webclient/beans/common/ModifyDeleteWorkLogBean.java | shoukaiseki/sksweb | ca0afc7ac8ab5c9670c0b8d5ad79a23702f7c339 | [
"MIT"
] | null | null | null | src/java/beans/psdi/webclient/beans/common/ModifyDeleteWorkLogBean.java | shoukaiseki/sksweb | ca0afc7ac8ab5c9670c0b8d5ad79a23702f7c339 | [
"MIT"
] | null | null | null | src/java/beans/psdi/webclient/beans/common/ModifyDeleteWorkLogBean.java | shoukaiseki/sksweb | ca0afc7ac8ab5c9670c0b8d5ad79a23702f7c339 | [
"MIT"
] | null | null | null | 29.855556 | 76 | 0.47339 | 1,003,745 | /* */ package psdi.webclient.beans.common;
/* */
/* */ import java.rmi.RemoteException;
/* */ import psdi.app.ticket.WorkLogSetRemote;
/* */ import psdi.util.MXException;
/* */ import psdi.webclient.system.beans.DataBean;
/* */
/* */ public class ModifyDeleteWorkLogBean extends DataBean
/* */ {
/* */ public void initialize()
/* */ throws MXException, RemoteException
/* */ {
/* 37 */ super.initialize();
/* 38 */ WorkLogSetRemote workLogSet = (WorkLogSetRemote)getMboSet();
/* 39 */ workLogSet.setActionModify(true);
/* */ }
/* */
/* */ public int execute()
/* */ throws MXException, RemoteException
/* */ {
/* 45 */ WorkLogSetRemote workLogSet = (WorkLogSetRemote)getMboSet();
/* 46 */ workLogSet.setActionModify(false);
/* */ try {
/* 48 */ super.execute();
/* */ }
/* */ catch (MXException e)
/* */ {
/* 52 */ workLogSet.setActionModify(true);
/* 53 */ throw e;
/* */ }
/* */
/* 56 */ return 1;
/* */ }
/* */
/* */ public int filterrows()
/* */ throws MXException
/* */ {
/* 65 */ super.filterrows();
/* */ try
/* */ {
/* 68 */ WorkLogSetRemote workLogSet = (WorkLogSetRemote)getMboSet();
/* 69 */ workLogSet.setActionModify(true);
/* */ }
/* */ catch (RemoteException e)
/* */ {
/* 74 */ e.printStackTrace();
/* */ }
/* */
/* 77 */ return 1;
/* */ }
/* */
/* */ public int sortcolumn()
/* */ throws MXException
/* */ {
/* 86 */ super.sortcolumn();
/* */ try
/* */ {
/* 89 */ WorkLogSetRemote workLogSet = (WorkLogSetRemote)getMboSet();
/* 90 */ workLogSet.setActionModify(true);
/* */ }
/* */ catch (RemoteException e)
/* */ {
/* 95 */ e.printStackTrace();
/* */ }
/* */
/* 98 */ return 1;
/* */ }
/* */
/* */ public int clearfilter()
/* */ throws MXException
/* */ {
/* 106 */ super.clearfilter();
/* */ try
/* */ {
/* 109 */ WorkLogSetRemote workLogSet = (WorkLogSetRemote)getMboSet();
/* 110 */ workLogSet.setActionModify(true);
/* */ }
/* */ catch (RemoteException e)
/* */ {
/* 115 */ e.printStackTrace();
/* */ }
/* */
/* 118 */ return 1;
/* */ }
/* */ }
/* Location: D:\maxapp\MAXIMO.ear\maximouiweb.war\WEB-INF\classes\
* Qualified Name: psdi.webclient.beans.common.ModifyDeleteWorkLogBean
* JD-Core Version: 0.6.0
*/ |
92465e8b8952112b8f5b2a419285b58507913753 | 832 | java | Java | bali-auth-server/src/main/java/com/github/bali/auth/domain/vo/WebUserRegister.java | pettyferlove/bali-framework | 89f7512daee7f7fab9e4abca3386431ea99355ed | [
"Apache-2.0"
] | null | null | null | bali-auth-server/src/main/java/com/github/bali/auth/domain/vo/WebUserRegister.java | pettyferlove/bali-framework | 89f7512daee7f7fab9e4abca3386431ea99355ed | [
"Apache-2.0"
] | null | null | null | bali-auth-server/src/main/java/com/github/bali/auth/domain/vo/WebUserRegister.java | pettyferlove/bali-framework | 89f7512daee7f7fab9e4abca3386431ea99355ed | [
"Apache-2.0"
] | null | null | null | 25.212121 | 69 | 0.789663 | 1,003,746 | package com.github.bali.auth.domain.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.github.bali.core.framework.domain.vo.IVO;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Petty
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class WebUserRegister implements IVO {
private static final long serialVersionUID = 999821014362807723L;
@ApiModelProperty(value = "用户登录名")
private String loginId;
@ApiModelProperty(value = "账号密码")
private String password;
@ApiModelProperty(value = "重复密码")
private String repeatPassword;
}
|
92465ebafdf84a050bc783a76f95a1b83ceb972a | 1,218 | java | Java | src/main/java/moulinette/element/geometry/Point.java | Rosalien/PivotMetadata_snot | 8f7ce35dfe8583b823f727b6d7a43925e1126968 | [
"MIT"
] | null | null | null | src/main/java/moulinette/element/geometry/Point.java | Rosalien/PivotMetadata_snot | 8f7ce35dfe8583b823f727b6d7a43925e1126968 | [
"MIT"
] | 2 | 2020-06-09T13:22:33.000Z | 2021-12-09T22:24:36.000Z | src/main/java/moulinette/element/geometry/Point.java | Rosalien/PivotMetadata_snot | 8f7ce35dfe8583b823f727b6d7a43925e1126968 | [
"MIT"
] | null | null | null | 26.478261 | 106 | 0.609195 | 1,003,747 | package moulinette.element.geometry;
import java.util.LinkedList;
import java.util.List;
import moulinette.element.Enum.EnumGeoJSONTypes;
/**
*
* @author coussotc
*/
public class Point extends GeometryGeoJSON {
private double[] coordinates;
private final String type = EnumGeoJSONTypes.POINT.toString();
public Point(double longitude, double latitude) {
this.coordinates = new double[2];
this.coordinates[0] = longitude;
this.coordinates[1] = latitude;
}
public Point(double longitude, double latitude, double altitude) {
this.coordinates = new double[3];
this.coordinates[0] = longitude;
this.coordinates[1] = latitude;
this.coordinates[2] = altitude;
}
public Point(Position position) {
this.coordinates = position.getPosition();
}
public Point(List<Double> l) {
this.coordinates = new double[2];
this.coordinates[0] = l.get(0);
this.coordinates[1] = l.get(1);
}
@Override
public String toString() {
return "Point{" + "coordinates=[" + coordinates[0]+","+ coordinates[1] + "], type=" + type + '}';
}
}
|
92465f204506eef9e30a8426015cbf1ec7077a5a | 2,306 | java | Java | otsstreamreader/src/test/java/com/alibaba/datax/plugin/reader/otsstreamreader/internal/common/ShardInfoForTest.java | huaxuechensu/DataXC | f663f5c52061b0fe7ed141184d90a7a2b59fc7ea | [
"Apache-2.0"
] | 9 | 2016-10-12T01:23:29.000Z | 2020-11-05T03:06:09.000Z | otsstreamreader/src/test/java/com/alibaba/datax/plugin/reader/otsstreamreader/internal/common/ShardInfoForTest.java | huaxuechensu/DataXC | f663f5c52061b0fe7ed141184d90a7a2b59fc7ea | [
"Apache-2.0"
] | null | null | null | otsstreamreader/src/test/java/com/alibaba/datax/plugin/reader/otsstreamreader/internal/common/ShardInfoForTest.java | huaxuechensu/DataXC | f663f5c52061b0fe7ed141184d90a7a2b59fc7ea | [
"Apache-2.0"
] | 9 | 2016-11-09T09:19:46.000Z | 2021-02-25T01:43:30.000Z | 25.622222 | 146 | 0.660885 | 1,003,748 | package com.alibaba.datax.plugin.reader.otsstreamreader.internal.common;
public class ShardInfoForTest {
private String shardId;
private String parentId;
private String parentSiblingId;
private long startTime;
private long endTime;
private int rowNum;
/**
* siblingId只是为了方便使用MockOTS创建split后两个shard,
* 第一个shard的siblingId为第二个shard,第二个shard的siblingId为null。
*/
private String siblingId;
public ShardInfoForTest(String shardId, long startTime, long endTime, int rowNum) {
this(shardId, null, null, startTime, endTime, rowNum);
}
public ShardInfoForTest(String shardId, String parentId, String parentSiblingId, long startTime, long endTime, int rowNum) {
this(shardId, parentId, parentSiblingId, null, startTime, endTime, rowNum);
}
public ShardInfoForTest(String shardId, String parentId, String parentSiblingId, String siblingId, long startTime, long endTime, int rowNum) {
this.shardId = shardId;
this.parentId = parentId;
this.parentSiblingId = parentSiblingId;
this.siblingId = siblingId;
this.startTime = startTime;
this.endTime = endTime;
this.rowNum = rowNum;
}
public String getShardId() {
return shardId;
}
public void setShardId(String shardId) {
this.shardId = shardId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSiblingId() {
return parentSiblingId;
}
public void setParentSiblingId(String parentSiblingId) {
this.parentSiblingId = parentSiblingId;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getSiblingId() {
return siblingId;
}
public void setSiblingId(String siblingId) {
this.siblingId = siblingId;
}
} |
92465f815f32cb6e8e3fcc89bd3a240f2629c942 | 1,924 | java | Java | exercise-eureka/src/main/java/com/zyp/springcloud/exercise/eureka/ExerciseEurekaApplication.java | zhgyapeng/springcloud-exercise | e1ff73adf4f264238391236fbfa49c22a3b703d4 | [
"Apache-2.0"
] | null | null | null | exercise-eureka/src/main/java/com/zyp/springcloud/exercise/eureka/ExerciseEurekaApplication.java | zhgyapeng/springcloud-exercise | e1ff73adf4f264238391236fbfa49c22a3b703d4 | [
"Apache-2.0"
] | null | null | null | exercise-eureka/src/main/java/com/zyp/springcloud/exercise/eureka/ExerciseEurekaApplication.java | zhgyapeng/springcloud-exercise | e1ff73adf4f264238391236fbfa49c22a3b703d4 | [
"Apache-2.0"
] | null | null | null | 39.265306 | 88 | 0.794179 | 1,003,749 | package com.zyp.springcloud.exercise.eureka;
import com.google.common.base.Preconditions;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableZuulProxy
@EnableFeignClients
public class ExerciseEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(ExerciseEurekaApplication.class, args);
}
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/")
@HystrixCommand(fallbackMethod = "failHandle", commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE")
})
public String home() {
ServiceInstance instance = loadBalancerClient.choose("stores");
System.out.println(instance.getHost() + ":" + instance.getPort());
Preconditions.checkArgument(false, "Fail Message.");
return "Hello World.";
}
public String failHandle() {
return "Fails";
}
} |
92466118d93ea567bddbb3d3bab5aca0f0bfbeb6 | 1,048 | java | Java | src/main/java/com/alipay/api/domain/AlipayUserDtbankQrcodedataQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/domain/AlipayUserDtbankQrcodedataQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/domain/AlipayUserDtbankQrcodedataQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 18.714286 | 73 | 0.683206 | 1,003,750 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 数字分行银行码明细数据查询
*
* @author auto create
* @since 1.0, 2021-07-07 19:16:45
*/
public class AlipayUserDtbankQrcodedataQueryModel extends AlipayObject {
private static final long serialVersionUID = 3132483294721628161L;
/**
* 查询的数据日期
*/
@ApiField("data_date")
private String dataDate;
/**
* 二维码Id
*/
@ApiField("qrcode_id")
private String qrcodeId;
/**
* 二维码外部ID
*/
@ApiField("qrcode_out_id")
private String qrcodeOutId;
public String getDataDate() {
return this.dataDate;
}
public void setDataDate(String dataDate) {
this.dataDate = dataDate;
}
public String getQrcodeId() {
return this.qrcodeId;
}
public void setQrcodeId(String qrcodeId) {
this.qrcodeId = qrcodeId;
}
public String getQrcodeOutId() {
return this.qrcodeOutId;
}
public void setQrcodeOutId(String qrcodeOutId) {
this.qrcodeOutId = qrcodeOutId;
}
}
|
924661bc28ae31f93d5cf3861e10efa63d63583f | 767 | java | Java | src/main/java/com/oilfoot/senshi/items/katana/kazeshiniKatana.java | oilfoot/Minecraft-Senshi-Mod | 2903b618d2faebcd4186d64b568331f020b4a9b2 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/oilfoot/senshi/items/katana/kazeshiniKatana.java | oilfoot/Minecraft-Senshi-Mod | 2903b618d2faebcd4186d64b568331f020b4a9b2 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/oilfoot/senshi/items/katana/kazeshiniKatana.java | oilfoot/Minecraft-Senshi-Mod | 2903b618d2faebcd4186d64b568331f020b4a9b2 | [
"CC0-1.0"
] | null | null | null | 30.68 | 113 | 0.78618 | 1,003,751 | package com.oilfoot.senshi.items.katana;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.item.SwordItem;
import net.minecraft.item.ToolMaterial;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.world.World;
import java.util.List;
public class kazeshiniKatana extends SwordItem {
public kazeshiniKatana(ToolMaterial toolMaterial, int attackDamage, float attackSpeed, Settings settings) {
super(toolMaterial, attackDamage, attackSpeed, settings);
}
public void appendTooltip(ItemStack itemStack, World world, List<Text> list, TooltipContext tooltipContext) {
list.add(new TranslatableText("text.senshi.kazenshiText"));
}
}
|
924661f6656a41e7091ea7c3641dcc8182cde63f | 460 | java | Java | Abstract/src/demo1/App.java | Alok255/Core-Java-Code-Practice | d72f5cf770f2759b795b37b5989932f767154b23 | [
"Apache-2.0"
] | null | null | null | Abstract/src/demo1/App.java | Alok255/Core-Java-Code-Practice | d72f5cf770f2759b795b37b5989932f767154b23 | [
"Apache-2.0"
] | null | null | null | Abstract/src/demo1/App.java | Alok255/Core-Java-Code-Practice | d72f5cf770f2759b795b37b5989932f767154b23 | [
"Apache-2.0"
] | null | null | null | 13.142857 | 44 | 0.645652 | 1,003,752 | package demo1;
abstract class Bike{
public Bike() {
System.out.println("Hello Create Class!");
}
public void start(){
System.out.println("Bike Start!");
}
abstract void stop();
}
class Machine extends Bike{
@Override
void stop() {
System.out.println("Hello Stop!");
}
}
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
Bike bike=new Machine();
bike.start();
bike.stop();
}
}
|
924663b52a870accadcedbab4fd304eec2e73fc7 | 5,314 | java | Java | src/test/java/jooq/generated/entities/static_/tables/records/RouteRecord.java | BERNMOBIL/vibe-share | 3a9a7251dab0ac623a9f2e159648a8a9025eb70a | [
"MIT"
] | null | null | null | src/test/java/jooq/generated/entities/static_/tables/records/RouteRecord.java | BERNMOBIL/vibe-share | 3a9a7251dab0ac623a9f2e159648a8a9025eb70a | [
"MIT"
] | null | null | null | src/test/java/jooq/generated/entities/static_/tables/records/RouteRecord.java | BERNMOBIL/vibe-share | 3a9a7251dab0ac623a9f2e159648a8a9025eb70a | [
"MIT"
] | null | null | null | 20.128788 | 123 | 0.497554 | 1,003,753 | /*
* This file is generated by jOOQ.
*/
package jooq.generated.entities.static_.tables.records;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.UUID;
import javax.annotation.Generated;
import jooq.generated.entities.static_.tables.Route;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record4;
import org.jooq.Row4;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.9.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RouteRecord extends UpdatableRecordImpl<RouteRecord> implements Record4<UUID, BigDecimal, String, Timestamp> {
private static final long serialVersionUID = 407111323;
/**
* Setter for <code>public.route.id</code>.
*/
public RouteRecord setId(UUID value) {
set(0, value);
return this;
}
/**
* Getter for <code>public.route.id</code>.
*/
public UUID getId() {
return (UUID) get(0);
}
/**
* Setter for <code>public.route.type</code>.
*/
public RouteRecord setType(BigDecimal value) {
set(1, value);
return this;
}
/**
* Getter for <code>public.route.type</code>.
*/
public BigDecimal getType() {
return (BigDecimal) get(1);
}
/**
* Setter for <code>public.route.line</code>.
*/
public RouteRecord setLine(String value) {
set(2, value);
return this;
}
/**
* Getter for <code>public.route.line</code>.
*/
public String getLine() {
return (String) get(2);
}
/**
* Setter for <code>public.route.update</code>.
*/
public RouteRecord setUpdate(Timestamp value) {
set(3, value);
return this;
}
/**
* Getter for <code>public.route.update</code>.
*/
public Timestamp getUpdate() {
return (Timestamp) get(3);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<UUID> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row4<UUID, BigDecimal, String, Timestamp> fieldsRow() {
return (Row4) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row4<UUID, BigDecimal, String, Timestamp> valuesRow() {
return (Row4) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<UUID> field1() {
return Route.ROUTE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<BigDecimal> field2() {
return Route.ROUTE.TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return Route.ROUTE.LINE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field4() {
return Route.ROUTE.UPDATE;
}
/**
* {@inheritDoc}
*/
@Override
public UUID value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal value2() {
return getType();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getLine();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value4() {
return getUpdate();
}
/**
* {@inheritDoc}
*/
@Override
public RouteRecord value1(UUID value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public RouteRecord value2(BigDecimal value) {
setType(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public RouteRecord value3(String value) {
setLine(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public RouteRecord value4(Timestamp value) {
setUpdate(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public RouteRecord values(UUID value1, BigDecimal value2, String value3, Timestamp value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached RouteRecord
*/
public RouteRecord() {
super(Route.ROUTE);
}
/**
* Create a detached, initialised RouteRecord
*/
public RouteRecord(UUID id, BigDecimal type, String line, Timestamp update) {
super(Route.ROUTE);
set(0, id);
set(1, type);
set(2, line);
set(3, update);
}
}
|
924663d09c993ea049813377c90b5bec32bd0f74 | 842 | java | Java | luckily_cheng/zhubao/src/com/dao/CartDao.java | gaoxizhe/bishe | 18d802233671afff46336b4beed0e8441883afae | [
"Apache-2.0"
] | null | null | null | luckily_cheng/zhubao/src/com/dao/CartDao.java | gaoxizhe/bishe | 18d802233671afff46336b4beed0e8441883afae | [
"Apache-2.0"
] | null | null | null | luckily_cheng/zhubao/src/com/dao/CartDao.java | gaoxizhe/bishe | 18d802233671afff46336b4beed0e8441883afae | [
"Apache-2.0"
] | null | null | null | 35.083333 | 72 | 0.712589 | 1,003,754 | package com.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository("cartDao")
@Mapper
public interface CartDao {
//1.5.8 用户管理
//“用户管理”模块牵涉到删除用户时,要考虑到用户关联的购车、关注的商品、订单,如果存在关联就不能直接删除用户。
public List<Map<String, Object>> selectCart(Integer id);
//1.6.9 关注商品
//登录成功的用户可以在商品详情页面中单击”关注”按钮关注该商品,
// 此时请求路径为cart/focus?id=
public int focus(Map<String, Object> map);
public List<Map<String, Object>> isFocus(Map<String, Object> map);
//1.6.10 购物车
public List<Map<String, Object>> isPutCart(Map<String, Object> map);
public int putCart (Map<String, Object> map);
public int updateCart (Map<String, Object> map);
public int deleteAgoods (Map<String, Object> map);
public int clear(Integer id);
} |
92466573a41d3acba3f0782968ca913dbc50be71 | 324 | java | Java | listings/src/main/java/com/okta/developer/listings/ListingsApplication.java | oktadev/okta-spring-security-test-example | e4458bb723e1c45bf1252f07195c3dc5458501da | [
"Apache-2.0"
] | 3 | 2021-05-04T02:30:03.000Z | 2022-03-08T15:54:42.000Z | listings/src/main/java/com/okta/developer/listings/ListingsApplication.java | oktadeveloper/okta-spring-security-test-example | e4458bb723e1c45bf1252f07195c3dc5458501da | [
"Apache-2.0"
] | null | null | null | listings/src/main/java/com/okta/developer/listings/ListingsApplication.java | oktadeveloper/okta-spring-security-test-example | e4458bb723e1c45bf1252f07195c3dc5458501da | [
"Apache-2.0"
] | 1 | 2021-05-04T02:30:04.000Z | 2021-05-04T02:30:04.000Z | 23.142857 | 68 | 0.824074 | 1,003,755 | package com.okta.developer.listings;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ListingsApplication {
public static void main(String[] args) {
SpringApplication.run(ListingsApplication.class, args);
}
}
|
9246662595317552daf7be19976a6558174435ff | 1,414 | java | Java | igc-adapter/src/main/java/org/odpi/egeria/connectors/ibm/igc/repositoryconnector/mapping/relationships/TermISATypeOFRelationshipMapper.java | cryptox31/egeria-connector-ibm-information-server | 82dd25149d4259b66dbfef7510e1cac6c82fc0de | [
"Apache-2.0"
] | 14 | 2019-08-16T03:43:35.000Z | 2022-02-17T09:54:27.000Z | igc-adapter/src/main/java/org/odpi/egeria/connectors/ibm/igc/repositoryconnector/mapping/relationships/TermISATypeOFRelationshipMapper.java | cryptox31/egeria-connector-ibm-information-server | 82dd25149d4259b66dbfef7510e1cac6c82fc0de | [
"Apache-2.0"
] | 260 | 2019-08-12T12:39:09.000Z | 2022-03-31T18:07:37.000Z | igc-adapter/src/main/java/org/odpi/egeria/connectors/ibm/igc/repositoryconnector/mapping/relationships/TermISATypeOFRelationshipMapper.java | cryptox31/egeria-connector-ibm-information-server | 82dd25149d4259b66dbfef7510e1cac6c82fc0de | [
"Apache-2.0"
] | 16 | 2019-08-14T20:25:32.000Z | 2022-03-22T11:40:42.000Z | 38.216216 | 127 | 0.705799 | 1,003,756 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.egeria.connectors.ibm.igc.repositoryconnector.mapping.relationships;
import org.odpi.egeria.connectors.ibm.igc.clientlibrary.IGCVersionEnum;
import org.odpi.egeria.connectors.ibm.igc.repositoryconnector.mapping.attributes.TermRelationshipStatusMapper;
/**
* Singleton to map the OMRS "TermISATypeOFRelationship" relationship for IGC "term" assets.
*/
public class TermISATypeOFRelationshipMapper extends RelationshipMapping {
private static class Singleton {
private static final TermISATypeOFRelationshipMapper INSTANCE = new TermISATypeOFRelationshipMapper();
}
public static TermISATypeOFRelationshipMapper getInstance(IGCVersionEnum version) {
return Singleton.INSTANCE;
}
protected TermISATypeOFRelationshipMapper() {
super(
"term",
"term",
"has_types",
"is_a_type_of",
"TermISATypeOFRelationship",
"supertypes",
"subtypes"
);
addLiteralPropertyMapping("description", null);
addLiteralPropertyMapping("status", TermRelationshipStatusMapper.getInstance(null).getEnumMappingByIgcValue("Active"));
addLiteralPropertyMapping("steward", null);
addLiteralPropertyMapping("source", null);
}
}
|
924667582dffbed21fbfbd94884996d42b3eb643 | 1,637 | java | Java | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriter.java | aleksandarsajdovski/jenkins2-course-spring-boot | 6dcf7b1ee4dde2b8f5ceba58d2240a9130dded6e | [
"Apache-2.0"
] | 90 | 2016-09-04T09:17:09.000Z | 2021-01-25T03:50:54.000Z | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriter.java | glowyao/spring-boot | 2a22afdba7a646b972ea8c7b47b2df96048877c7 | [
"Apache-2.0"
] | 225 | 2021-03-10T01:27:30.000Z | 2021-09-15T01:03:46.000Z | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriter.java | glowyao/spring-boot | 2a22afdba7a646b972ea8c7b47b2df96048877c7 | [
"Apache-2.0"
] | 1,574 | 2016-08-30T04:09:26.000Z | 2022-03-24T08:14:58.000Z | 30.314815 | 88 | 0.754429 | 1,003,757 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.metrics.writer;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.messaging.MessageChannel;
/**
* A {@link MetricWriter} that publishes the metric updates on a {@link MessageChannel}.
* The messages have the writer input ({@link Delta} or {@link Metric}) as payload, and
* carry an additional header "metricName" with the name of the metric in it.
*
* @author Dave Syer
* @see MetricWriterMessageHandler
*/
public class MessageChannelMetricWriter implements MetricWriter {
private final MessageChannel channel;
public MessageChannelMetricWriter(MessageChannel channel) {
this.channel = channel;
}
@Override
public void increment(Delta<?> delta) {
this.channel.send(MetricMessage.forIncrement(delta));
}
@Override
public void set(Metric<?> value) {
this.channel.send(MetricMessage.forSet(value));
}
@Override
public void reset(String metricName) {
this.channel.send(MetricMessage.forReset(metricName));
}
}
|
924668d76b6bce8b5046350ccbbfc0289778eb58 | 1,109 | java | Java | selene-device-zigbee/src/main/java/moonstone/selene/device/xbee/zcl/domain/ha/events/commands/ApplianceEventsAndAlertClusterCommands.java | konexios/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 3 | 2019-12-24T05:28:11.000Z | 2021-05-02T21:20:16.000Z | selene-device-zigbee/src/main/java/moonstone/selene/device/xbee/zcl/domain/ha/events/commands/ApplianceEventsAndAlertClusterCommands.java | arrow-acs/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 4 | 2019-11-20T17:10:45.000Z | 2020-06-18T15:09:12.000Z | selene-device-zigbee/src/main/java/moonstone/selene/device/xbee/zcl/domain/ha/events/commands/ApplianceEventsAndAlertClusterCommands.java | arrow-acs/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 1 | 2021-05-02T21:20:30.000Z | 2021-05-02T21:20:30.000Z | 38.241379 | 115 | 0.811542 | 1,003,758 | package moonstone.selene.device.xbee.zcl.domain.ha.events.commands;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import moonstone.selene.device.xbee.zcl.ClusterSpecificCommand;
public class ApplianceEventsAndAlertClusterCommands {
public static final int GET_ALERTS_RESPONSE_COMMAND_ID = 0x00;
public static final int ALERTS_NOTIFICATION_COMMAND_ID = 0x01;
public static final int EVENTS_NOTIFICATION_COMMAND_ID = 0x02;
public static final int GET_ALERTS_COMMAND_ID = 0x00;
public static final Map<Integer, ImmutablePair<String, Class<? extends ClusterSpecificCommand<?>>>> ALL_RECEIVED =
new LinkedHashMap<>();
public static final Map<Integer, String> ALL_GENERATED = new LinkedHashMap<>();
static {
ALL_GENERATED.put(GET_ALERTS_RESPONSE_COMMAND_ID, "Get Alerts Response");
ALL_GENERATED.put(ALERTS_NOTIFICATION_COMMAND_ID, "Alerts Notification");
ALL_GENERATED.put(EVENTS_NOTIFICATION_COMMAND_ID, "Events Notification");
ALL_RECEIVED.put(GET_ALERTS_COMMAND_ID, new ImmutablePair<>("Get Alerts", GetAlerts.class));
}
}
|
9246692896411aa629bd01f60ff6da761ebc6819 | 1,195 | java | Java | shared/src/main/java/me/neznamy/tab/shared/features/UpdateChecker.java | CoasterFreakDE/TAB | 1466b24409bb96e7d7da585a099c28f21d96b897 | [
"Apache-2.0"
] | 431 | 2019-07-24T23:01:53.000Z | 2022-03-30T17:37:35.000Z | shared/src/main/java/me/neznamy/tab/shared/features/UpdateChecker.java | CoasterFreakDE/TAB | 1466b24409bb96e7d7da585a099c28f21d96b897 | [
"Apache-2.0"
] | 491 | 2019-07-25T09:10:40.000Z | 2022-03-31T21:59:34.000Z | shared/src/main/java/me/neznamy/tab/shared/features/UpdateChecker.java | CoasterFreakDE/TAB | 1466b24409bb96e7d7da585a099c28f21d96b897 | [
"Apache-2.0"
] | 322 | 2019-08-11T20:18:37.000Z | 2022-03-30T19:14:21.000Z | 34.142857 | 137 | 0.697908 | 1,003,760 | package me.neznamy.tab.shared.features;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import me.neznamy.tab.shared.TAB;
/**
* Update checker
*/
public class UpdateChecker {
//separate field to prevent false flag on pre releases
private String currentRelease = "2.9.2";
public UpdateChecker(TAB tab) {
new Thread(() -> {
try {
HttpURLConnection con = (HttpURLConnection) new URL("https://api.spigotmc.org/legacy/update.php?resource=57806").openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String versionString = br.readLine();
br.close();
con.disconnect();
if (!versionString.equals(currentRelease)) {
tab.getPlatform().sendConsoleMessage("&a[TAB] Version " + versionString + " is out! Your version: " + tab.getPluginVersion(), true);
tab.getPlatform().sendConsoleMessage("&a[TAB] Get the update at https://www.spigotmc.org/resources/57806/", true);
}
} catch (Exception e) {
tab.debug("&cFailed to check for updates (" + e.getClass().getSimpleName() + ": " + e.getMessage() + ")");
}
}).start();
}
} |
92466a5a077a2c1d8e63a3200f7ca2401498f3dd | 624 | java | Java | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/Application.java | liwen666/flink | a068f72f9093c566a79bc7ceaadd9722033d4ecc | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/Application.java | liwen666/flink | a068f72f9093c566a79bc7ceaadd9722033d4ecc | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/Application.java | liwen666/flink | a068f72f9093c566a79bc7ceaadd9722033d4ecc | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | 22.285714 | 78 | 0.738782 | 1,003,761 | package org.apache.flink.runtime.webmonitor;
import org.apache.flink.runtime.entrypoint.StandaloneSessionClusterEntrypoint;
import org.apache.flink.runtime.taskexecutor.TaskManagerRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* 描述.
* </p>
*
* @since 2020/10/23 17:39.
*/
public class Application {
private static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
StandaloneSessionClusterEntrypoint.main(args);
try {
TaskManagerRunner.main(args);
} catch (Exception e) {
log.error("TaskManagerRunner error:{}", e);
}
}
}
|
92466afc844c76e3ac790e1fb210eec1f7112e4d | 1,150 | java | Java | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CollateralDeliveryMethod1Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 40 | 2020-10-13T13:44:59.000Z | 2022-03-30T13:58:32.000Z | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CollateralDeliveryMethod1Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 25 | 2020-10-04T23:46:22.000Z | 2022-03-30T12:31:03.000Z | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CollateralDeliveryMethod1Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 22 | 2020-12-22T14:50:22.000Z | 2022-03-30T13:19:10.000Z | 20.535714 | 95 | 0.642609 | 1,003,762 |
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CollateralDeliveryMethod1Code.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CollateralDeliveryMethod1Code">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="SICA"/>
* <enumeration value="SIUR"/>
* <enumeration value="TTCA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CollateralDeliveryMethod1Code")
@XmlEnum
public enum CollateralDeliveryMethod1Code {
/**
* Securities interest collateral arrangement.
*
*/
SICA,
/**
* Securities interest with the right of use.
*
*/
SIUR,
/**
* Title transfer collateral arrangement.
*
*/
TTCA;
public String value() {
return name();
}
public static CollateralDeliveryMethod1Code fromValue(String v) {
return valueOf(v);
}
}
|
92466d7ecfe4ef9df551f4d0ba5b3565ddcd49c2 | 16,222 | java | Java | engine/src/test/java/org/camunda/bpm/engine/test/api/runtime/migration/batch/BatchMigrationHistoryTest.java | matthiasblaesing/camunda-bpm-platform | 1b2d4b9087d07788bc75736d0470ac1ee5ba1cca | [
"Apache-2.0"
] | 1 | 2019-04-23T11:35:12.000Z | 2019-04-23T11:35:12.000Z | engine/src/test/java/org/camunda/bpm/engine/test/api/runtime/migration/batch/BatchMigrationHistoryTest.java | matthiasblaesing/camunda-bpm-platform | 1b2d4b9087d07788bc75736d0470ac1ee5ba1cca | [
"Apache-2.0"
] | null | null | null | engine/src/test/java/org/camunda/bpm/engine/test/api/runtime/migration/batch/BatchMigrationHistoryTest.java | matthiasblaesing/camunda-bpm-platform | 1b2d4b9087d07788bc75736d0470ac1ee5ba1cca | [
"Apache-2.0"
] | null | null | null | 36.699095 | 95 | 0.761667 | 1,003,763 | /*
* Copyright © 2013-2019 camunda services GmbH and various authors ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.runtime.migration.batch;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.batch.history.HistoricBatch;
import org.camunda.bpm.engine.history.HistoricJobLog;
import org.camunda.bpm.engine.impl.batch.BatchMonitorJobHandler;
import org.camunda.bpm.engine.impl.batch.BatchSeedJobHandler;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.api.runtime.migration.MigrationTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL)
public class BatchMigrationHistoryTest {
protected static final Date START_DATE = new Date(1457326800000L);
protected ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
protected MigrationTestRule migrationRule = new MigrationTestRule(engineRule);
protected BatchMigrationHelper helper = new BatchMigrationHelper(engineRule, migrationRule);
protected ProcessEngineConfigurationImpl configuration;
protected RuntimeService runtimeService;
protected ManagementService managementService;
protected HistoryService historyService;
protected ProcessDefinition sourceProcessDefinition;
protected ProcessDefinition targetProcessDefinition;
protected boolean defaultEnsureJobDueDateSet;
@Parameterized.Parameter(0)
public boolean ensureJobDueDateSet;
@Parameterized.Parameter(1)
public Date currentTime;
@Parameterized.Parameters(name = "Job DueDate is set: {0}")
public static Collection<Object[]> scenarios() throws ParseException {
return Arrays.asList(new Object[][] {
{ false, null },
{ true, START_DATE }
});
}
@Rule
public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(migrationRule);
@Before
public void initServices() {
runtimeService = engineRule.getRuntimeService();
managementService = engineRule.getManagementService();
historyService = engineRule.getHistoryService();
}
@Before
public void setupConfiguration() {
configuration = engineRule.getProcessEngineConfiguration();
defaultEnsureJobDueDateSet = configuration.isEnsureJobDueDateNotNull();
configuration.setEnsureJobDueDateNotNull(ensureJobDueDateSet);
}
@Before
public void setClock() {
ClockUtil.setCurrentTime(START_DATE);
}
@After
public void resetClock() {
ClockUtil.reset();
}
@After
public void removeBatches() {
helper.removeAllRunningAndHistoricBatches();
}
@After
public void resetConfiguration() {
configuration.setEnsureJobDueDateNotNull(defaultEnsureJobDueDateSet);
}
@Test
public void testHistoricBatchCreation() {
// when
Batch batch = helper.migrateProcessInstancesAsync(10);
// then a historic batch was created
HistoricBatch historicBatch = helper.getHistoricBatch(batch);
assertNotNull(historicBatch);
assertEquals(batch.getId(), historicBatch.getId());
assertEquals(batch.getType(), historicBatch.getType());
assertEquals(batch.getTotalJobs(), historicBatch.getTotalJobs());
assertEquals(batch.getBatchJobsPerSeed(), historicBatch.getBatchJobsPerSeed());
assertEquals(batch.getInvocationsPerBatchJob(), historicBatch.getInvocationsPerBatchJob());
assertEquals(batch.getSeedJobDefinitionId(), historicBatch.getSeedJobDefinitionId());
assertEquals(batch.getMonitorJobDefinitionId(), historicBatch.getMonitorJobDefinitionId());
assertEquals(batch.getBatchJobDefinitionId(), historicBatch.getBatchJobDefinitionId());
assertEquals(START_DATE, historicBatch.getStartTime());
assertNull(historicBatch.getEndTime());
}
@Test
public void testHistoricBatchCompletion() {
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
helper.executeJobs(batch);
Date endDate = helper.addSecondsToClock(12);
// when
helper.executeMonitorJob(batch);
// then the historic batch has an end time set
HistoricBatch historicBatch = helper.getHistoricBatch(batch);
assertNotNull(historicBatch);
assertEquals(endDate, historicBatch.getEndTime());
}
@Test
public void testHistoricSeedJobLog() {
// when
Batch batch = helper.migrateProcessInstancesAsync(1);
// then a historic job log exists for the seed job
HistoricJobLog jobLog = helper.getHistoricSeedJobLog(batch).get(0);
assertNotNull(jobLog);
assertTrue(jobLog.isCreationLog());
assertEquals(batch.getSeedJobDefinitionId(), jobLog.getJobDefinitionId());
assertEquals(BatchSeedJobHandler.TYPE, jobLog.getJobDefinitionType());
assertEquals(batch.getId(), jobLog.getJobDefinitionConfiguration());
assertEquals(START_DATE, jobLog.getTimestamp());
assertNull(jobLog.getDeploymentId());
assertNull(jobLog.getProcessDefinitionId());
assertNull(jobLog.getExecutionId());
assertEquals(currentTime, jobLog.getJobDueDate());
// when the seed job is executed
Date executionDate = helper.addSecondsToClock(12);
helper.executeSeedJob(batch);
// then a new historic job log exists for the seed job
jobLog = helper.getHistoricSeedJobLog(batch).get(1);
assertNotNull(jobLog);
assertTrue(jobLog.isSuccessLog());
assertEquals(batch.getSeedJobDefinitionId(), jobLog.getJobDefinitionId());
assertEquals(BatchSeedJobHandler.TYPE, jobLog.getJobDefinitionType());
assertEquals(batch.getId(), jobLog.getJobDefinitionConfiguration());
assertEquals(executionDate, jobLog.getTimestamp());
assertNull(jobLog.getDeploymentId());
assertNull(jobLog.getProcessDefinitionId());
assertNull(jobLog.getExecutionId());
assertEquals(currentTime, jobLog.getJobDueDate());
}
@Test
public void testHistoricMonitorJobLog() {
Batch batch = helper.migrateProcessInstancesAsync(1);
// when the seed job is executed
helper.executeSeedJob(batch);
Job monitorJob = helper.getMonitorJob(batch);
List<HistoricJobLog> jobLogs = helper.getHistoricMonitorJobLog(batch, monitorJob);
assertEquals(1, jobLogs.size());
// then a creation historic job log exists for the monitor job without due date
HistoricJobLog jobLog = jobLogs.get(0);
assertCommonMonitorJobLogProperties(batch, jobLog);
assertTrue(jobLog.isCreationLog());
assertEquals(START_DATE, jobLog.getTimestamp());
assertEquals(currentTime, jobLog.getJobDueDate());
// when the monitor job is executed
Date executionDate = helper.addSecondsToClock(15);
Date monitorJobDueDate = helper.addSeconds(executionDate, 30);
helper.executeMonitorJob(batch);
jobLogs = helper.getHistoricMonitorJobLog(batch, monitorJob);
assertEquals(2, jobLogs.size());
// then a success job log was created for the last monitor job
jobLog = jobLogs.get(1);
assertCommonMonitorJobLogProperties(batch, jobLog);
assertTrue(jobLog.isSuccessLog());
assertEquals(executionDate, jobLog.getTimestamp());
assertEquals(currentTime, jobLog.getJobDueDate());
// and a creation job log for the new monitor job was created with due date
monitorJob = helper.getMonitorJob(batch);
jobLogs = helper.getHistoricMonitorJobLog(batch, monitorJob);
assertEquals(1, jobLogs.size());
jobLog = jobLogs.get(0);
assertCommonMonitorJobLogProperties(batch, jobLog);
assertTrue(jobLog.isCreationLog());
assertEquals(executionDate, jobLog.getTimestamp());
assertEquals(monitorJobDueDate, jobLog.getJobDueDate());
// when the migration and monitor jobs are executed
executionDate = helper.addSecondsToClock(15);
helper.executeJobs(batch);
helper.executeMonitorJob(batch);
jobLogs = helper.getHistoricMonitorJobLog(batch, monitorJob);
assertEquals(2, jobLogs.size());
// then a success job log was created for the last monitor job
jobLog = jobLogs.get(1);
assertCommonMonitorJobLogProperties(batch, jobLog);
assertTrue(jobLog.isSuccessLog());
assertEquals(executionDate, jobLog.getTimestamp());
assertEquals(monitorJobDueDate, jobLog.getJobDueDate());
}
@Test
public void testHistoricBatchJobLog() {
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
String sourceDeploymentId = helper.getSourceProcessDefinition().getDeploymentId();
// when
Date executionDate = helper.addSecondsToClock(12);
helper.executeJobs(batch);
// then a historic job log exists for the batch job
HistoricJobLog jobLog = helper.getHistoricBatchJobLog(batch).get(0);
assertNotNull(jobLog);
assertTrue(jobLog.isCreationLog());
assertEquals(batch.getBatchJobDefinitionId(), jobLog.getJobDefinitionId());
assertEquals(Batch.TYPE_PROCESS_INSTANCE_MIGRATION, jobLog.getJobDefinitionType());
assertEquals(batch.getId(), jobLog.getJobDefinitionConfiguration());
assertEquals(START_DATE, jobLog.getTimestamp());
assertEquals(sourceDeploymentId, jobLog.getDeploymentId());
assertNull(jobLog.getProcessDefinitionId());
assertNull(jobLog.getExecutionId());
assertEquals(currentTime, jobLog.getJobDueDate());
jobLog = helper.getHistoricBatchJobLog(batch).get(1);
assertNotNull(jobLog);
assertTrue(jobLog.isSuccessLog());
assertEquals(batch.getBatchJobDefinitionId(), jobLog.getJobDefinitionId());
assertEquals(Batch.TYPE_PROCESS_INSTANCE_MIGRATION, jobLog.getJobDefinitionType());
assertEquals(batch.getId(), jobLog.getJobDefinitionConfiguration());
assertEquals(executionDate, jobLog.getTimestamp());
assertEquals(sourceDeploymentId, jobLog.getDeploymentId());
assertNull(jobLog.getProcessDefinitionId());
assertNull(jobLog.getExecutionId());
assertEquals(currentTime, jobLog.getJobDueDate());
}
@Test
public void testHistoricBatchForBatchDeletion() {
Batch batch = helper.migrateProcessInstancesAsync(1);
// when
Date deletionDate = helper.addSecondsToClock(12);
managementService.deleteBatch(batch.getId(), false);
// then the end time was set for the historic batch
HistoricBatch historicBatch = helper.getHistoricBatch(batch);
assertNotNull(historicBatch);
assertEquals(deletionDate, historicBatch.getEndTime());
}
@Test
public void testHistoricSeedJobLogForBatchDeletion() {
Batch batch = helper.migrateProcessInstancesAsync(1);
// when
Date deletionDate = helper.addSecondsToClock(12);
managementService.deleteBatch(batch.getId(), false);
// then a deletion historic job log was added
HistoricJobLog jobLog = helper.getHistoricSeedJobLog(batch).get(1);
assertNotNull(jobLog);
assertTrue(jobLog.isDeletionLog());
assertEquals(deletionDate, jobLog.getTimestamp());
}
@Test
public void testHistoricMonitorJobLogForBatchDeletion() {
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
// when
Date deletionDate = helper.addSecondsToClock(12);
managementService.deleteBatch(batch.getId(), false);
// then a deletion historic job log was added
HistoricJobLog jobLog = helper.getHistoricMonitorJobLog(batch).get(1);
assertNotNull(jobLog);
assertTrue(jobLog.isDeletionLog());
assertEquals(deletionDate, jobLog.getTimestamp());
}
@Test
public void testHistoricBatchJobLogForBatchDeletion() {
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
// when
Date deletionDate = helper.addSecondsToClock(12);
managementService.deleteBatch(batch.getId(), false);
// then a deletion historic job log was added
HistoricJobLog jobLog = helper.getHistoricBatchJobLog(batch).get(1);
assertNotNull(jobLog);
assertTrue(jobLog.isDeletionLog());
assertEquals(deletionDate, jobLog.getTimestamp());
}
@Test
public void testDeleteHistoricBatch() {
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
helper.executeJobs(batch);
helper.executeMonitorJob(batch);
// when
HistoricBatch historicBatch = helper.getHistoricBatch(batch);
historyService.deleteHistoricBatch(historicBatch.getId());
// then the historic batch was removed and all job logs
assertNull(helper.getHistoricBatch(batch));
assertTrue(helper.getHistoricSeedJobLog(batch).isEmpty());
assertTrue(helper.getHistoricMonitorJobLog(batch).isEmpty());
assertTrue(helper.getHistoricBatchJobLog(batch).isEmpty());
}
@Test
public void testHistoricSeedJobIncidentDeletion() {
// given
Batch batch = helper.migrateProcessInstancesAsync(1);
Job seedJob = helper.getSeedJob(batch);
managementService.setJobRetries(seedJob.getId(), 0);
managementService.deleteBatch(batch.getId(), false);
// when
historyService.deleteHistoricBatch(batch.getId());
// then the historic incident was deleted
long historicIncidents = historyService.createHistoricIncidentQuery().count();
assertEquals(0, historicIncidents);
}
@Test
public void testHistoricMonitorJobIncidentDeletion() {
// given
Batch batch = helper.migrateProcessInstancesAsync(1);
helper.executeSeedJob(batch);
Job monitorJob = helper.getMonitorJob(batch);
managementService.setJobRetries(monitorJob.getId(), 0);
managementService.deleteBatch(batch.getId(), false);
// when
historyService.deleteHistoricBatch(batch.getId());
// then the historic incident was deleted
long historicIncidents = historyService.createHistoricIncidentQuery().count();
assertEquals(0, historicIncidents);
}
@Test
public void testHistoricBatchJobLogIncidentDeletion() {
// given
Batch batch = helper.migrateProcessInstancesAsync(3);
helper.executeSeedJob(batch);
helper.failExecutionJobs(batch, 3);
managementService.deleteBatch(batch.getId(), false);
// when
historyService.deleteHistoricBatch(batch.getId());
// then the historic incident was deleted
long historicIncidents = historyService.createHistoricIncidentQuery().count();
assertEquals(0, historicIncidents);
}
protected void assertCommonMonitorJobLogProperties(Batch batch, HistoricJobLog jobLog) {
assertNotNull(jobLog);
assertEquals(batch.getMonitorJobDefinitionId(), jobLog.getJobDefinitionId());
assertEquals(BatchMonitorJobHandler.TYPE, jobLog.getJobDefinitionType());
assertEquals(batch.getId(), jobLog.getJobDefinitionConfiguration());
assertNull(jobLog.getDeploymentId());
assertNull(jobLog.getProcessDefinitionId());
assertNull(jobLog.getExecutionId());
}
}
|
92466e7bd66a7e766d1eb4dd96ac628c5d9e9339 | 2,345 | java | Java | app/src/main/java/com/jjump/java/HomeFragment.java | ar-child-english-edu-service-jumping/JJUMP | 820cdcb51d7c37b8b42ae0434a4fcb257aadd0d3 | [
"MIT"
] | null | null | null | app/src/main/java/com/jjump/java/HomeFragment.java | ar-child-english-edu-service-jumping/JJUMP | 820cdcb51d7c37b8b42ae0434a4fcb257aadd0d3 | [
"MIT"
] | null | null | null | app/src/main/java/com/jjump/java/HomeFragment.java | ar-child-english-edu-service-jumping/JJUMP | 820cdcb51d7c37b8b42ae0434a4fcb257aadd0d3 | [
"MIT"
] | null | null | null | 35.530303 | 100 | 0.698934 | 1,003,764 | package com.jjump.java;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.jjump.R;
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false);
//camera button
ImageButton cameraBtn = rootView.findViewById(R.id.btn_camera);
cameraBtn.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
Intent intent=new Intent(getActivity(),CameraXLivePreviewActivity.class);
startActivity(intent);
}
});
// 나무 성장 애니메이션 gif
ImageView ic_tree1 = rootView.findViewById(R.id.ic_tree1);
ImageView ic_tree2 = rootView.findViewById(R.id.ic_tree2);
ImageView ic_tree3 = rootView.findViewById(R.id.ic_tree3);
ic_tree1.setVisibility(View.INVISIBLE);
ic_tree2.setVisibility(View.INVISIBLE);
ic_tree3.setVisibility(View.INVISIBLE);
// Glide 이용하여 gif 띄우기
GlideDrawableImageViewTarget gif_tree1 = new GlideDrawableImageViewTarget(ic_tree1);
GlideDrawableImageViewTarget gif_tree2 = new GlideDrawableImageViewTarget(ic_tree2);
GlideDrawableImageViewTarget gif_tree3 = new GlideDrawableImageViewTarget(ic_tree3);
// 데모에서 처음엔 나무 2단계, 퀴즈 한번 보고 오면 나무 3단계로
if(HomeActivity.quiz_taken_int == 1){
Glide.with(getActivity()).load(R.drawable.gif_tree3).into(gif_tree3);
ic_tree3.setVisibility(View.VISIBLE);
} else{
Glide.with(getActivity()).load(R.drawable.gif_tree2).into(gif_tree2);
ic_tree2.setVisibility(View.VISIBLE);
}
return rootView;
}
} |
92466ece57e203692b46e76c5652a56256ed3d50 | 589 | java | Java | src/main/java/com/peng/service/UserService.java | 412940226/ssms | bcf0a2a322ddf022cdeb8c61bd3adf81b04b4660 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/peng/service/UserService.java | 412940226/ssms | bcf0a2a322ddf022cdeb8c61bd3adf81b04b4660 | [
"Apache-2.0"
] | 5 | 2020-05-15T21:33:36.000Z | 2021-12-09T21:23:09.000Z | src/main/java/com/peng/service/UserService.java | 412940226/ssms | bcf0a2a322ddf022cdeb8c61bd3adf81b04b4660 | [
"Apache-2.0"
] | 1 | 2019-12-01T15:08:05.000Z | 2019-12-01T15:08:05.000Z | 25.608696 | 63 | 0.78438 | 1,003,765 | package com.peng.service;
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.peng.entity.User;
@Service
public interface UserService {
public User queryUserByName(String username);
public Set<String> queryRolesByUserName(String username);
public User findById(long id);
public void deleteUser(long id);
public List<User> list();
public Set<String> listRoles(Long userid);
public int save(User user);
public int update(User user);
public int remove(Long id);
public Set<String> queryPermissionByUserName(String username);
}
|
92466f66f2d30e5e3aba8b9435833231277acac1 | 3,417 | java | Java | src/main/java/org/orecruncher/dsurround/registry/item/SimpleArmorItemData.java | VoltoREv/DynamicSurroundings | d61057e9788eccc7e0632240e379bc41aedfdbb7 | [
"MIT"
] | 125 | 2016-12-06T06:04:18.000Z | 2022-03-21T00:47:23.000Z | src/main/java/org/orecruncher/dsurround/registry/item/SimpleArmorItemData.java | VoltoREv/DynamicSurroundings | d61057e9788eccc7e0632240e379bc41aedfdbb7 | [
"MIT"
] | 762 | 2016-12-05T22:11:58.000Z | 2022-03-27T16:27:52.000Z | src/main/java/org/orecruncher/dsurround/registry/item/SimpleArmorItemData.java | VoltoREv/DynamicSurroundings | d61057e9788eccc7e0632240e379bc41aedfdbb7 | [
"MIT"
] | 78 | 2016-12-11T09:44:31.000Z | 2022-03-27T16:44:55.000Z | 40.2 | 92 | 0.785484 | 1,003,766 | /* This file is part of Dynamic Surroundings, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.orecruncher.dsurround.registry.item;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.orecruncher.dsurround.ModInfo;
import org.orecruncher.dsurround.registry.RegistryDataEvent;
import org.orecruncher.dsurround.registry.RegistryManager;
import org.orecruncher.dsurround.registry.acoustics.AcousticRegistry;
import org.orecruncher.dsurround.registry.acoustics.IAcoustic;
import org.orecruncher.dsurround.registry.footstep.FootstepsRegistry;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
@EventBusSubscriber(modid = ModInfo.MOD_ID, value = Side.CLIENT)
public class SimpleArmorItemData extends SimpleItemData implements IArmorItemData {
private static final Map<ItemClass, IAcoustic> ARMOR = new Reference2ObjectOpenHashMap<>();
private static final Map<ItemClass, IAcoustic> FOOT = new Reference2ObjectOpenHashMap<>();
@SubscribeEvent
public static void registryReload(@Nonnull final RegistryDataEvent.Reload event) {
if (event.reg instanceof FootstepsRegistry) {
ARMOR.clear();
FOOT.clear();
final AcousticRegistry reg = RegistryManager.ACOUSTICS;
ARMOR.put(ItemClass.LEATHER, reg.getAcoustic("armor_light"));
ARMOR.put(ItemClass.CHAIN, reg.getAcoustic("armor_medium"));
ARMOR.put(ItemClass.CRYSTAL, reg.getAcoustic("armor_crystal"));
ARMOR.put(ItemClass.PLATE, reg.getAcoustic("armor_heavy"));
FOOT.put(ItemClass.LEATHER, reg.getAcoustic("armor_light"));
FOOT.put(ItemClass.CHAIN, reg.getAcoustic("medium_foot"));
FOOT.put(ItemClass.CRYSTAL, reg.getAcoustic("crystal_foot"));
FOOT.put(ItemClass.PLATE, reg.getAcoustic("heavy_foot"));
}
}
public SimpleArmorItemData(@Nonnull final ItemClass ic) {
super(ic);
}
@Override
@Nullable
public IAcoustic getArmorSound(@Nonnull final ItemStack stack) {
return ARMOR.get(this.itemClass);
}
@Override
@Nullable
public IAcoustic getFootArmorSound(@Nonnull final ItemStack stack) {
return FOOT.get(this.itemClass);
}
}
|
92466fd83e358f4adfcc9eb28bc12c1e8c08ead5 | 7,313 | java | Java | test/java/some/one/contract/ContractTestHelper.java | somedotone/IdentityVerification | 78731afcc5ed85ad3f5c034ada0e03e52c68c00d | [
"MIT"
] | 1 | 2019-01-28T16:47:50.000Z | 2019-01-28T16:47:50.000Z | test/java/some/one/contract/ContractTestHelper.java | somedotone/identity-verification | 78731afcc5ed85ad3f5c034ada0e03e52c68c00d | [
"MIT"
] | null | null | null | test/java/some/one/contract/ContractTestHelper.java | somedotone/identity-verification | 78731afcc5ed85ad3f5c034ada0e03e52c68c00d | [
"MIT"
] | null | null | null | 47.797386 | 202 | 0.693696 | 1,003,767 | package some.one.contract;
import nxt.BlockchainTest;
import nxt.addons.JO;
import nxt.blockchain.Chain;
import nxt.blockchain.ChainTransactionId;
import nxt.blockchain.ChildChain;
import nxt.http.APICall;
import nxt.http.callers.GetBlockCall;
import nxt.http.callers.GetBlockchainStatusCall;
import nxt.http.callers.GetExecutedTransactionsCall;
import nxt.http.responses.BlockResponse;
import nxt.http.responses.TransactionResponse;
import nxt.tools.ContractManager;
import nxt.util.Convert;
import nxt.util.Logger;
import org.junit.Assert;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Random;
import static nxt.blockchain.ChildChain.IGNIS;
class ContractTestHelper {
static String bobPaysContract(String message, Chain chain) {
return bobPaysContract(message, chain, true ,100);
}
static String bobPaysContract(String message, Chain chain, int amount) {
return bobPaysContract(message, chain, true ,amount);
}
static String bobPaysContract(String message, Chain chain, boolean encryptMessage, int amount) {
return payContract(message, chain, encryptMessage, BlockchainTest.BOB.getSecretPhrase(), BlockchainTest.ALICE.getRsAccount(), false, amount);
}
static String payContract(String message, Chain chain, boolean encryptMessage, String secretPhrase, String recipient) {
return payContract(message, chain, encryptMessage, secretPhrase, recipient, false, 100);
}
static String payContract(String message, Chain chain, boolean encryptMessage, String secretPhrase, String recipient, boolean addHashedSecret, int amount) {
APICall.Builder builder = new APICall.Builder("sendMoney").
secretPhrase(secretPhrase).
param("chain", chain.getId()).
param("recipient", recipient).
param("amountNQT", amount * chain.ONE_COIN);
if (message != null) {
if (encryptMessage) {
builder.param("encryptedMessageIsPrunable", "true").param("messageToEncrypt", message);
} else {
builder.param("messageIsPrunable", "true").param("message", message);
}
}
if (addHashedSecret) {
builder.param("phased", true);
builder.param("phasingFinishHeight", BlockResponse.create(GetBlockCall.create().call()).getHeight() + 201);
builder.param("phasingQuorum", 1);
builder.param("phasingVotingModel", 5);
builder.param("phasingHashedSecret", "ad531905859e62ee0b5ef2cc916cef3949b11d9b8817a8e4d7ac04f44c79e704");
builder.param("phasingHashedSecretAlgorithm", 2);
}
builder.feeNQT(IGNIS.ONE_COIN);
APICall apiCall = builder.build();
JO response = new JO(apiCall.invoke());
Logger.logDebugMessage("sendMoney: " + response);
BlockchainTest.generateBlock();
return (String)response.get("fullHash");
}
static String messageTriggerContract(String message) {
return messageTriggerContract(message, BlockchainTest.BOB.getSecretPhrase());
}
static String messageTriggerContract(String message, String secretPhrase) {
APICall apiCall = new APICall.Builder("sendMessage").
secretPhrase(secretPhrase).
param("chain", ChildChain.IGNIS.getId()).
param("recipient", BlockchainTest.ALICE.getRsAccount()).
param("messageIsPrunable", "true").
param("message", message).
feeNQT(IGNIS.ONE_COIN).
build();
JO response = new JO(apiCall.invoke());
Logger.logDebugMessage("sendMessage: " + response);
BlockchainTest.generateBlock();
return (String)response.get("fullHash");
}
static String deployContract(Class contractClass) {
return deployContract(contractClass, null);
}
static String deployContract(Class contractClass, JO setupParams) {
return deployContract(contractClass, setupParams, true);
}
static String deployContract(Class contractClass, JO setupParams, boolean isGenerateBlock) {
String contractName = contractClass.getSimpleName();
deployContract(contractName, contractClass.getPackage().getName(), setupParams, isGenerateBlock);
return contractName;
}
static void deployContract(String contractName, String packageName, JO setupParams) {
deployContract(contractName, packageName, setupParams, true);
}
static void deployContract(String contractName, String packageName, JO setupParams, boolean isGenerateBlock) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
ContractManager contractManager = new ContractManager();
contractManager.init(contractName);
ContractManager.ContractData contractData = contractManager.uploadImpl(contractName, packageName);
if (contractData.getResponse().isExist("errorCode")) {
JO response = contractData.getResponse();
Assert.fail(String.format("Failed to deploy contract, reason: %s: %s",response.get("errorCode"), response.get("errorDescription")));
}
Logger.logInfoMessage("tagged data hash: " + Convert.toHexString(contractData.getTaggedDataHash()));
JO contractReferenceTransaction = contractManager.reference(contractData, contractData.getResponse().parseHexString("fullHash"), setupParams);
if (contractReferenceTransaction.isExist("errorCode")) {
Assert.fail("Failed to set contract property");
}
if (isGenerateBlock) {
BlockchainTest.generateBlock();
}
return null;
});
}
@SuppressWarnings("SameParameterValue")
static void testChildTransaction(int chainId, int type, int subType, long amount, long fee, long sender, List<Long> recipients) {
JO getBlockchainStatusCall = GetBlockchainStatusCall.create().call();
ChainTransactionId contractResultTransactionId = null;
List<TransactionResponse> childTransactions = GetExecutedTransactionsCall.create(IGNIS.getId()).type(0).subtype(0).height(getBlockchainStatusCall.getInt("numberOfBlocks") - 1).getTransactions();
for (TransactionResponse childTransaction : childTransactions) {
Assert.assertEquals(chainId, childTransaction.getChainId());
Assert.assertEquals(type, childTransaction.getTransactionType().getType());
Assert.assertEquals(subType, childTransaction.getTransactionType().getSubtype());
Assert.assertEquals(amount, childTransaction.getAmount());
Assert.assertEquals(fee, childTransaction.getFee());
Assert.assertEquals(sender, childTransaction.getSenderId());
Assert.assertTrue(recipients.contains(childTransaction.getRecipientId()));
contractResultTransactionId = new ChainTransactionId(childTransaction.getChainId(), childTransaction.getFullHash());
}
Assert.assertNotNull(contractResultTransactionId);
}
static String getRandomSeed(int seed) {
return Convert.toHexString(Convert.longToBytes(new Random(seed).nextLong()));
}
}
|
92467024344588114bd046dec5a76c7f9bb9bed2 | 6,832 | java | Java | src/main/java/org/laxture/yaatask/YaaTask.java | hank-cp/YaaTask4j | 061454edb40e7661c9d5dab0cb8c320fd100e4d4 | [
"Apache-2.0"
] | 1 | 2021-12-23T18:38:45.000Z | 2021-12-23T18:38:45.000Z | src/main/java/org/laxture/yaatask/YaaTask.java | hank-cp/yaaTask4j | 061454edb40e7661c9d5dab0cb8c320fd100e4d4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/laxture/yaatask/YaaTask.java | hank-cp/yaaTask4j | 061454edb40e7661c9d5dab0cb8c320fd100e4d4 | [
"Apache-2.0"
] | null | null | null | 33.655172 | 102 | 0.592799 | 1,003,768 | /*
* Copyright (C) 2021-present 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.laxture.yaatask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.laxture.yaatask.TaskListener.TaskCancelledListener;
import org.laxture.yaatask.TaskListener.TaskFailedListener;
import org.laxture.yaatask.TaskListener.TaskFinishedListener;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author <a href="https://github.com/hank-cp">Hank CP</a>
*/
@Slf4j
public abstract class YaaTask<Result> {
// state
public enum State {
NotStart, Pending, Running, Finished, Cancelled, Failed
}
volatile State mState = State.NotStart;
public State getState() { return mState; }
public void setState(State state) { mState = state; }
private Result mResult;
// thread control
final AtomicBoolean mCancelled = new AtomicBoolean();
final AtomicBoolean mTaskInvoked = new AtomicBoolean();
// listeners
private final Set<TaskFinishedListener<Result>> mFinishedListeners = new HashSet<>();
private final Set<TaskCancelledListener<Result>> mCancelledListeners = new HashSet<>();
private final Set<TaskFailedListener<Result>> mFailedListeners = new HashSet<>();
// error code
private TaskException mException;
public TaskException getErrorDetails() { return mException; }
public void setErrorDetails(TaskException exception) { mException = exception; }
private String mId = UUID.randomUUID().toString();
public String getId() { return mId; }
public void setId(String id) { mId = id; }
private Object mTag;
public Object getTag() { return mTag; }
public void setTag(Object tag) { mTag = tag; }
//*************************************************************************
// These method need to be override in sub class
//*************************************************************************
public abstract Result run();
public boolean cancel() {
mCancelled.set(true);
return true;
}
public void setResult(Result result) {
mResult = result;
}
public Result getResult() {
return mResult;
}
public long getWaitingTime() {
return 0L;
}
public long getUsedTime() {
return 0L;
}
//*************************************************************************
// Public/Protected Method
//*************************************************************************
public YaaTask<Result> addFinishedListener(TaskFinishedListener<Result> listener) {
mFinishedListeners.add(listener);
return this;
}
public YaaTask<Result> addCancelledListener(TaskCancelledListener<Result> listener) {
mCancelledListeners.add(listener);
return this;
}
public YaaTask<Result> addFailedListener(TaskFailedListener<Result> listener) {
mFailedListeners.add(listener);
return this;
}
public void cloneTaskListeners(YaaTask<Result> task) {
mFinishedListeners.addAll(task.mFinishedListeners);
mCancelledListeners.addAll(task.mCancelledListeners);
mFailedListeners.addAll(task.mFailedListeners);
}
public void removeAllTaskListeners() {
mFinishedListeners.clear();
mCancelledListeners.clear();
mFailedListeners.clear();
}
public final boolean isCancelled() {
return mCancelled.get();
}
//*************************************************************************
// Internal Implementation
//*************************************************************************
/**
* If cancel, try to call cancel callback
*/
void postResultIfNotInvoked(Result result) {
if (!mTaskInvoked.get()) {
postResult(result);
}
}
/**
* This method must be called somewhere to trigger TaskListener callback.
*/
protected Result postResult(Result result) {
finish(result, getErrorDetails());
return result;
}
private void finish(Result result, TaskException exception) {
if (isCancelled()) {
if (log.isDebugEnabled()) {
log.debug(String.format("%s%s is cancelled in %d ms.", getClass().getSimpleName(),
StringUtils.isEmpty(mId) ? "" : " " + mId, getUsedTime()));
}
onTaskCancelled(result);
setState(State.Cancelled);
} else if (mException != null) {
log.warn(String.format("%s%s quit by error %s in %d ms.", getClass().getSimpleName(),
StringUtils.isEmpty(mId) ? "" : " " + mId, mException.getErrorCode(), getUsedTime()));
onTaskFailed(result, mException);
setState(State.Failed);
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("%s%s is completed in %dms.", getClass().getSimpleName(),
StringUtils.isEmpty(mId) ? "" : " " + mId, getUsedTime()));
}
onTaskFinished(result);
setState(State.Finished);
}
}
//*************************************************************************
// TaskCallback
//
// These methods will be delegated to UI thread, make sure they are only used
// to update UI.
//*************************************************************************
public void onTaskFinished(final Result returnObj) {
if (mFinishedListeners.size() == 0) return;
for (final TaskFinishedListener<Result> callback : mFinishedListeners) {
callback.onTaskFinished(returnObj);
}
}
public void onTaskCancelled(final Result result) {
if (mCancelledListeners.size() == 0) return;
for (final TaskCancelledListener<Result> callback : mCancelledListeners) {
callback.onTaskCancelled(result);
}
}
public void onTaskFailed(final Result result, final TaskException ex) {
if (mFailedListeners.size() == 0) return;
for (final TaskFailedListener<Result> callback : mFailedListeners) {
callback.onTaskFailed(result, ex);
}
}
}
|
924670863ebc79a259864dd969b35b811a58995d | 1,474 | java | Java | Viterbi/src/prob/Grid.java | benplus1/Path-Finding-AI | d892505b43f73b394add13fc76b470537ac257ba | [
"MIT"
] | 2 | 2017-09-28T14:49:54.000Z | 2017-09-29T20:49:59.000Z | Viterbi/src/prob/Grid.java | benplus1/Path-Finding-AI | d892505b43f73b394add13fc76b470537ac257ba | [
"MIT"
] | null | null | null | Viterbi/src/prob/Grid.java | benplus1/Path-Finding-AI | d892505b43f73b394add13fc76b470537ac257ba | [
"MIT"
] | null | null | null | 19.918919 | 59 | 0.464722 | 1,003,769 | package prob;
import java.util.*;
public class Grid {
Vertex[][] grid;
int ySize;
int xSize;
int numBlocked = 0;
public String actions = "";
public String observations = "";
ArrayList<Coordinate> path = new ArrayList<Coordinate>();
public Grid(int x, int y) {
grid = new Vertex[y][x];
ySize = y;
xSize = x;
Random generator = new Random();
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
int decider = generator.nextInt(10);
grid[i][j] = new Vertex();
if (decider <= 4) {
grid[i][j].type = 'N';
}
else if (decider <= 6) {
grid[i][j].type = 'H';
}
else if (decider <= 8) {
grid[i][j].type = 'T';
}
else {
grid[i][j].type = 'B';
numBlocked++;
}
grid[i][j].prob = 0;
}
}
}
public Grid() {
grid = new Vertex[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
grid[i][j] = new Vertex();
}
}
ySize = 3;
xSize = 3;
grid[0][0].type = 'H';
grid[0][1].type = 'H';
grid[0][2].type = 'T';
grid[1][0].type = 'N';
grid[1][1].type = 'N';
grid[1][2].type = 'N';
grid[2][0].type = 'N';
grid[2][1].type = 'B';
grid[2][2].type = 'H';
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
grid[i][j].prob = 0;
}
}
actions = "RRDD";
observations = "NNHH";
numBlocked = 1;
}
public void initializeGroundTruths() {
}
}
|
924670997e52f11a87a98477e7b2390b1092359f | 656 | java | Java | src/main/java/mekanism/common/inventory/container/tile/FluidTankContainer.java | Alexandrea/Mekanism | 73bd8b1b649e49e544e2f7e0925093af8ca822d1 | [
"MIT"
] | null | null | null | src/main/java/mekanism/common/inventory/container/tile/FluidTankContainer.java | Alexandrea/Mekanism | 73bd8b1b649e49e544e2f7e0925093af8ca822d1 | [
"MIT"
] | null | null | null | src/main/java/mekanism/common/inventory/container/tile/FluidTankContainer.java | Alexandrea/Mekanism | 73bd8b1b649e49e544e2f7e0925093af8ca822d1 | [
"MIT"
] | null | null | null | 38.588235 | 86 | 0.79878 | 1,003,770 | package mekanism.common.inventory.container.tile;
import mekanism.common.registries.MekanismContainerTypes;
import mekanism.common.tile.TileEntityFluidTank;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.PacketBuffer;
public class FluidTankContainer extends MekanismTileContainer<TileEntityFluidTank> {
public FluidTankContainer(int id, PlayerInventory inv, TileEntityFluidTank tile) {
super(MekanismContainerTypes.FLUID_TANK, id, inv, tile);
}
public FluidTankContainer(int id, PlayerInventory inv, PacketBuffer buf) {
this(id, inv, getTileFromBuf(buf, TileEntityFluidTank.class));
}
} |
924670ebdb5d2fbe77bb4d314ef112bd7c38d8b5 | 1,848 | java | Java | src/test/java/de/mpicbg/scf/labelhandling/ConstraintLabelMapTest.java | lguerard/BioImageAnalysisToolbox | f6f408a22a40ce559a1d889990bbba20608b96ad | [
"BSD-3-Clause"
] | 2 | 2019-08-20T18:53:28.000Z | 2020-09-24T08:03:50.000Z | src/test/java/de/mpicbg/scf/labelhandling/ConstraintLabelMapTest.java | lguerard/BioImageAnalysisToolbox | f6f408a22a40ce559a1d889990bbba20608b96ad | [
"BSD-3-Clause"
] | 1 | 2020-02-12T23:45:05.000Z | 2020-04-25T08:10:11.000Z | src/test/java/de/mpicbg/scf/labelhandling/ConstraintLabelMapTest.java | lguerard/BioImageAnalysisToolbox | f6f408a22a40ce559a1d889990bbba20608b96ad | [
"BSD-3-Clause"
] | 1 | 2021-11-24T10:44:24.000Z | 2021-11-24T10:44:24.000Z | 33.6 | 110 | 0.770563 | 1,003,771 | package de.mpicbg.scf.labelhandling;
import static org.junit.Assert.assertTrue;
import de.mpicbg.scf.labelhandling.data.Feature;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import net.imglib2.type.logic.BitType;
import org.junit.Test;
import de.mpicbg.scf.imgtools.ui.DebugHelper;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.integer.ByteType;
public class ConstraintLabelMapTest {
@Test
public void testLabelAnalyserAndConstraint() {
ArrayList<RandomAccessibleInterval<BitType>> regions = new ArrayList<RandomAccessibleInterval<BitType>> ();
regions.add(TestUtilities.getTestBinaryImage("0001110000"));
regions.add(TestUtilities.getTestBinaryImage("0001111000"));
regions.add(TestUtilities.getTestBinaryImage("0001100000"));
Feature[] featureList = {Feature.AREA};
OpsLabelAnalyser<ByteType, BitType> la = new OpsLabelAnalyser<ByteType, BitType>(regions, featureList);
double[] area = la.getFeatures(Feature.AREA);
DebugHelper.print(this, Arrays.toString(area));
assertTrue("measured size 0 is ok", area[0] == 3);
assertTrue("measured size 1 is ok", area[1] == 4);
assertTrue("measured size 2 is ok", area[2] == 2);
// setup Constrainter
ConstraintLabelMap<ByteType, BitType> clm = new ConstraintLabelMap<ByteType, BitType>(regions);
// configure filtering / constrainting
clm.addConstraint(Feature.AREA, 3, Double.MAX_VALUE);
// get filtered label map
ArrayList<RandomAccessibleInterval<BitType>> constraintedLabelMap = clm.getResult();
DebugHelper.print(this, "" + constraintedLabelMap.size());
assertTrue("number of remaining objects is ok", constraintedLabelMap.size() == 2);
}
public static void main(final String... args) throws IOException {
new ConstraintLabelMapTest().testLabelAnalyserAndConstraint();
}
}
|
92467270765d32a907033def1e699d8c4e406ceb | 1,139 | java | Java | optimizer/outdated/LambdaExample.java | cs335-optimizer-developers/schedule-optimizer | a49c5f2d6d247327b3cfd3ce0d62f53b729eb4ea | [
"MIT"
] | 3 | 2019-02-09T16:54:48.000Z | 2020-01-30T21:44:49.000Z | optimizer/outdated/LambdaExample.java | cs335-optimizer-developers/schedule-optimizer | a49c5f2d6d247327b3cfd3ce0d62f53b729eb4ea | [
"MIT"
] | 2 | 2019-02-02T18:14:53.000Z | 2019-02-28T16:10:20.000Z | optimizer/outdated/LambdaExample.java | cs335-optimizer-developers/schedule-optimizer | a49c5f2d6d247327b3cfd3ce0d62f53b729eb4ea | [
"MIT"
] | null | null | null | 22.333333 | 70 | 0.653205 | 1,003,772 | package display;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LambdaExample {
private static Button b1;
private static Button b2;
/*
* Demonstration of using lambda function to shorten ActionListener
* writing, as well as some basic Swing display functionality. Let me
* know if any of it doesn't make sense.
*/
public static void main(String[] args) {
Frame f = new Frame();
Label label = new Label("Display");
final TextField text = new TextField(20);
exampleA();
exampleB();
Panel p = new Panel(new GridLayout(6, 6));
p.add(label);
p.add(text);
p.add(label);
p.add(text);
p.add(b1);
p.add(b2);
f.add(p);
f.setVisible(true);
f.pack();
}
private static void exampleA() {
b1 = new Button("Test");
b1.addActionListener(e -> {
System.out.println("Button 1 pressed");
});
}
private static void exampleB() {
b2 = new Button("Test2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button 2 pressed");
}
});
}
}
|
92467284c2477f8fadfc5c32d86231f324dab4fa | 4,441 | java | Java | src/test/java/io/novaordis/events/processing/output/MockOutputFormat.java | NovaOrdis/events-processing | 0d5f87d0eb3e6e2754095041779f0eae8ee987f9 | [
"Apache-2.0"
] | null | null | null | src/test/java/io/novaordis/events/processing/output/MockOutputFormat.java | NovaOrdis/events-processing | 0d5f87d0eb3e6e2754095041779f0eae8ee987f9 | [
"Apache-2.0"
] | null | null | null | src/test/java/io/novaordis/events/processing/output/MockOutputFormat.java | NovaOrdis/events-processing | 0d5f87d0eb3e6e2754095041779f0eae8ee987f9 | [
"Apache-2.0"
] | null | null | null | 26.610778 | 120 | 0.465122 | 1,003,773 | /*
* Copyright (c) 2017 Nova Ordis LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.novaordis.events.processing.output;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.novaordis.events.api.event.Event;
import io.novaordis.events.api.event.Property;
import io.novaordis.events.api.event.TimedEvent;
/**
* @author Ovidiu Feodorov <[email protected]>
* @since 8/3/17
*/
public class MockOutputFormat implements OutputFormat {
// Constants -------------------------------------------------------------------------------------------------------
// Static ----------------------------------------------------------------------------------------------------------
// Attributes ------------------------------------------------------------------------------------------------------
// list because we need to preserve order
private List<String> matchingProperties;
private DateFormat timestampFormat;
private boolean isProvidingHeader;
private boolean leadWitTimestamp;
// Constructors ----------------------------------------------------------------------------------------------------
public MockOutputFormat() {
this.matchingProperties = new ArrayList<>();
this.isProvidingHeader = true;
this.leadWitTimestamp = true; // default behavior
}
// OutputFormat implementation -------------------------------------------------------------------------------------
@Override
public String formatHeader(Event e) {
if (!isProvidingHeader) {
return null;
}
String s = "";
for(Iterator<String> pi = matchingProperties.iterator(); pi.hasNext(); ) {
s += pi.next();
if (pi.hasNext()) {
s += getSeparator();
}
}
return s;
}
@Override
public String format(Event e) {
String s = "";
if (leadWitTimestamp && e instanceof TimedEvent) {
Long t = ((TimedEvent)e).getTime();
s += timestampFormat.format(t);
}
List<Object> values = new ArrayList<>();
for(String propertyName: matchingProperties) {
Property p = e.getProperty(propertyName);
if (p != null) {
values.add(p.getValue());
}
}
if (!s.isEmpty() && !values.isEmpty()) {
s += getSeparator();
}
for(Iterator<Object> i = values.iterator(); i.hasNext(); ) {
s += i.next();
if (i.hasNext()) {
s += getSeparator();
}
}
s += "\n";
return s;
}
@Override
public String getSeparator() {
return " ";
}
@Override
public DateFormat getTimestampFormat() {
return timestampFormat;
}
@Override
public void setTimestampFormat(DateFormat f) {
this.timestampFormat = f;
}
// Public ----------------------------------------------------------------------------------------------------------
public void addMatchingProperty(String propertyName) {
matchingProperties.add(propertyName);
}
public void setProvidingHeader(boolean b) {
this.isProvidingHeader = b;
}
public void setLeadWitTimestamp(boolean b) {
this.leadWitTimestamp = b;
}
// Package protected -----------------------------------------------------------------------------------------------
// Protected -------------------------------------------------------------------------------------------------------
// Private ---------------------------------------------------------------------------------------------------------
// Inner classes ---------------------------------------------------------------------------------------------------
}
|
924673bf8ee9d228a1aaffd274da740551a39e45 | 747 | java | Java | src/stats/OSBService.java | mockmotor/StatsWS | 0cd8d428a3887177dab47ec9fb60397f1dd74c20 | [
"MIT"
] | null | null | null | src/stats/OSBService.java | mockmotor/StatsWS | 0cd8d428a3887177dab47ec9fb60397f1dd74c20 | [
"MIT"
] | null | null | null | src/stats/OSBService.java | mockmotor/StatsWS | 0cd8d428a3887177dab47ec9fb60397f1dd74c20 | [
"MIT"
] | null | null | null | 16.977273 | 66 | 0.725569 | 1,003,774 | package stats;
import java.util.ArrayList;
import java.util.List;
public class OSBService {
private String name;
private String serviceType;
private List <OSBResource> resource;
public OSBService() {
}
public OSBService(String name, ArrayList<OSBResource> resource) {
this.name=name;
this.resource = resource;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public List<OSBResource> getOSBResources() {
return resource;
}
public void setOSBResource(List<OSBResource> resource) {
this.resource = resource;
}
}
|
924673e9c8805ef46d2b99109d35453d423f4e5d | 3,545 | java | Java | appstatus-spring-boot-demo/src/main/java/net/sf/appstatus/boot/demo/Application.java | appstatus/appstatus-spring-boot-starter | 18f5dd4ce4dccd2c6c121d0a65baea6f76c58671 | [
"Apache-2.0"
] | 7 | 2017-11-13T11:21:31.000Z | 2017-11-28T07:40:06.000Z | appstatus-spring-boot-demo/src/main/java/net/sf/appstatus/boot/demo/Application.java | appstatus/appstatus-spring-boot-starter | 18f5dd4ce4dccd2c6c121d0a65baea6f76c58671 | [
"Apache-2.0"
] | null | null | null | appstatus-spring-boot-demo/src/main/java/net/sf/appstatus/boot/demo/Application.java | appstatus/appstatus-spring-boot-starter | 18f5dd4ce4dccd2c6c121d0a65baea6f76c58671 | [
"Apache-2.0"
] | null | null | null | 35.09901 | 101 | 0.577151 | 1,003,775 | /*
* AppStatus SpringBoot Starter 11.11.2017
* Copyright (C) 2017 Capgemini and Contributors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package net.sf.appstatus.boot.demo;
import org.hsqldb.util.DatabaseManagerSwing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
/**
* AppStatusSpringBootDemo launcher.
*
* @author Franck Stephanovitch
*
*/
@ComponentScan
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
/** Active or not hsqldb explorer */
private static final boolean DEBUG_DB = false;
/*
* (non-Javadoc)
*
* @see
* org.springframework.boot.web.support.SpringBootServletInitializer#configure(
* org.springframework.boot.builder.SpringApplicationBuilder)
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
/**
* Application jar launcher.
*
* @param args
*/
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
runDatabaseManager();
}
/**
* Configure spring boot application.
*
* @param builder
* application builder
* @return SpringApplicationBuilder application builder
*/
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
welcome();
return builder.sources(Application.class)
.bannerMode(Banner.Mode.OFF);
}
/**
* Run hsqldb explorer.
*/
private static void runDatabaseManager() {
if (DEBUG_DB) {
System.setProperty("java.awt.headless", "false");
DatabaseManagerSwing.main(new String[] { "--url", "jdbc:hsqldb:mem:dbtest", "-noexit" });
}
}
/**
* Log start.
*/
private static void welcome() {
LOG.info("Starting application ...\n\n" //
+ " █████╗ ██████╗ ██████╗ ███████╗████████╗ █████╗ ████████╗██╗ ██╗███████╗\n" //
+ "██╔══██╗██╔══██╗██╔══██╗██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██║ ██║██╔════╝\n" //
+ "███████║██████╔╝██████╔╝███████╗ ██║ ███████║ ██║ ██║ ██║███████╗\n" //
+ "██╔══██║██╔═══╝ ██╔═══╝ ╚════██║ ██║ ██╔══██║ ██║ ██║ ██║╚════██║\n" //
+ "██║ ██║██║ ██║ ███████║ ██║ ██║ ██║ ██║ ╚██████╔╝███████║\n" //
+ "╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝\n");
}
}
|
92467405b34eed19a35394db7223f3de60a03f86 | 1,234 | java | Java | src/main/java/org/dataone/bookkeeper/resources/BaseResource.java | csjx/bookkeeper | 8da3eccf97ca6642ca8af9891cd8737178368a3b | [
"Apache-2.0"
] | 1 | 2020-02-03T20:56:19.000Z | 2020-02-03T20:56:19.000Z | src/main/java/org/dataone/bookkeeper/resources/BaseResource.java | csjx/bookkeeper | 8da3eccf97ca6642ca8af9891cd8737178368a3b | [
"Apache-2.0"
] | 61 | 2020-01-21T23:57:40.000Z | 2022-02-18T05:48:09.000Z | src/main/java/org/dataone/bookkeeper/resources/BaseResource.java | csjx/bookkeeper | 8da3eccf97ca6642ca8af9891cd8737178368a3b | [
"Apache-2.0"
] | 1 | 2020-05-15T23:40:25.000Z | 2020-05-15T23:40:25.000Z | 31.641026 | 77 | 0.73906 | 1,003,776 | /*
* This work was created by participants in the DataONE project, and is
* jointly copyrighted by participating institutions in DataONE. For
* more information on DataONE, see our web site at http://dataone.org.
*
* Copyright 2019
*
* 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.dataone.bookkeeper.resources;
import javax.validation.Validation;
import javax.validation.Validator;
/**
* A base resource class providing functionality across resource classes
*/
class BaseResource {
/* The product validator */
static Validator validator;
/* Create a static validator for resources */
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
}
|
924675021184bed7231d0f56a57ae77b2de3a40f | 27,596 | java | Java | dspace-api/src/main/java/org/dspace/layout/script/service/impl/CrisLayoutToolValidatorImpl.java | 4Science/DSpace | db563250ec4669dd8c7fdff7322baccff2bedc81 | [
"BSD-3-Clause"
] | 35 | 2016-09-27T14:34:43.000Z | 2021-12-15T11:20:31.000Z | dspace-api/src/main/java/org/dspace/layout/script/service/impl/CrisLayoutToolValidatorImpl.java | 4Science/DSpace | db563250ec4669dd8c7fdff7322baccff2bedc81 | [
"BSD-3-Clause"
] | 110 | 2016-09-15T13:49:39.000Z | 2022-02-01T07:00:17.000Z | dspace-api/src/main/java/org/dspace/layout/script/service/impl/CrisLayoutToolValidatorImpl.java | 4Science/DSpace | db563250ec4669dd8c7fdff7322baccff2bedc81 | [
"BSD-3-Clause"
] | 81 | 2016-11-28T12:52:20.000Z | 2022-03-07T16:12:20.000Z | 43.186228 | 120 | 0.659661 | 1,003,777 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.layout.script.service.impl;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.dspace.util.WorkbookUtils.getCellIndexFromHeaderName;
import static org.dspace.util.WorkbookUtils.getCellValue;
import static org.dspace.util.WorkbookUtils.getColumnWithoutHeader;
import static org.dspace.util.WorkbookUtils.getNotEmptyRowsSkippingHeader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.MetadataFieldService;
import org.dspace.core.Context;
import org.dspace.core.ReloadableEntity;
import org.dspace.core.exception.SQLRuntimeException;
import org.dspace.layout.CrisLayoutBoxTypes;
import org.dspace.layout.script.service.CrisLayoutToolValidationResult;
import org.dspace.layout.script.service.CrisLayoutToolValidator;
import org.dspace.util.WorkbookUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Implementation of {@link CrisLayoutToolValidator}.
*
* @author Luca Giamminonni (luca.giamminonni at 4science.it)
*
*/
public class CrisLayoutToolValidatorImpl implements CrisLayoutToolValidator {
@Autowired
private EntityTypeService entityTypeService;
@Autowired
private MetadataFieldService metadataFieldService;
@Override
public CrisLayoutToolValidationResult validate(Context context, Workbook workbook) {
List<String> allEntityTypes = getAllEntityTypes(context);
List<String> allMetadataFields = getAllMetadataFields(context);
CrisLayoutToolValidationResult result = new CrisLayoutToolValidationResult();
validateTabSheet(workbook, result, allEntityTypes);
validateBoxSheet(workbook, result, allEntityTypes);
validateTab2BoxSheet(workbook, result);
validateBox2MetadataSheet(allMetadataFields, workbook, result);
validateMetadataGroupsSheet(allMetadataFields, workbook, result);
validateBox2MetricsSheet(workbook, result);
validateBoxPolicySheet(allMetadataFields, workbook, result);
validateTabPolicySheet(allMetadataFields, workbook, result);
return result;
}
private void validateTabSheet(Workbook workbook, CrisLayoutToolValidationResult result, List<String> entityTypes) {
Sheet tabSheet = workbook.getSheet(TAB_SHEET);
if (tabSheet == null) {
result.addError("The " + TAB_SHEET + " sheet is missing");
return;
}
int entityTypeColumn = getCellIndexFromHeaderName(tabSheet, ENTITY_COLUMN);
if (entityTypeColumn != -1) {
validateEntityTypes(result, tabSheet, entityTypeColumn, entityTypes);
} else {
result.addError("The sheet " + TAB_SHEET + " has no " + ENTITY_COLUMN + " column");
}
validateBooleanColumns(tabSheet, result, LEADING_COLUMN);
validateIntegerColumns(tabSheet, result, PRIORITY_COLUMN);
validateSecurityColumns(tabSheet, result, SECURITY_COLUMN);
int shortnameColumn = getCellIndexFromHeaderName(tabSheet, SHORTNAME_COLUMN);
if (shortnameColumn == -1) {
result.addError("The sheet " + TAB_SHEET + " has no " + SHORTNAME_COLUMN + " column");
}
if (getCellIndexFromHeaderName(tabSheet, LABEL_COLUMN) == -1) {
result.addError("The sheet " + TAB_SHEET + " has no " + LABEL_COLUMN + " column");
}
if (entityTypeColumn != -1 && shortnameColumn != -1) {
validatePresenceInTab2BoxSheet(result, tabSheet, TAB_COLUMN, entityTypeColumn, shortnameColumn);
}
}
private void validateBoxSheet(Workbook workbook, CrisLayoutToolValidationResult result, List<String> entityTypes) {
Sheet boxSheet = workbook.getSheet(BOX_SHEET);
if (boxSheet == null) {
result.addError("The " + BOX_SHEET + " sheet is missing");
return;
}
int typeColumn = getCellIndexFromHeaderName(boxSheet, TYPE_COLUMN);
if (typeColumn != -1) {
validateBoxTypes(result, boxSheet, typeColumn);
} else {
result.addError("The sheet " + BOX_SHEET + " has no " + TYPE_COLUMN + " column");
}
int entityTypeColumn = getCellIndexFromHeaderName(boxSheet, ENTITY_COLUMN);
if (entityTypeColumn != -1) {
validateEntityTypes(result, boxSheet, entityTypeColumn, entityTypes);
} else {
result.addError("The sheet " + BOX_SHEET + " has no " + ENTITY_COLUMN + " column");
}
validateBooleanColumns(boxSheet, result, COLLAPSED_COLUMN, CONTAINER_COLUMN, MINOR_COLUMN);
validateSecurityColumns(boxSheet, result, SECURITY_COLUMN);
int shortnameColumn = getCellIndexFromHeaderName(boxSheet, SHORTNAME_COLUMN);
if (shortnameColumn == -1) {
result.addError("The sheet " + BOX_SHEET + " has no " + SHORTNAME_COLUMN + " column");
}
if (entityTypeColumn != -1 && shortnameColumn != -1) {
validatePresenceInTab2BoxSheet(result, boxSheet, BOXES_COLUMN, entityTypeColumn, shortnameColumn);
}
}
private void validateTab2BoxSheet(Workbook workbook, CrisLayoutToolValidationResult result) {
Sheet tab2boxSheet = workbook.getSheet(TAB2BOX_SHEET);
if (tab2boxSheet == null) {
result.addError("The " + TAB2BOX_SHEET + " sheet is missing");
return;
}
validateColumnsPresence(tab2boxSheet, result, ENTITY_COLUMN, TAB_COLUMN, BOXES_COLUMN);
validateTab2BoxRowsReferences(tab2boxSheet, result);
validateRowStyleColumn(tab2boxSheet, TAB_COLUMN, result);
}
private void validateBox2MetadataSheet(List<String> allMetadataFields,
Workbook workbook, CrisLayoutToolValidationResult result) {
Sheet box2metadataSheet = workbook.getSheet(BOX2METADATA_SHEET);
if (box2metadataSheet == null) {
result.addError("The " + BOX2METADATA_SHEET + " sheet is missing");
return;
}
validateIntegerColumns(box2metadataSheet, result, ROW_COLUMN, CELL_COLUMN);
validateBooleanColumns(box2metadataSheet, result, LABEL_AS_HEADING_COLUMN, VALUES_INLINE_COLUMN);
validateColumnsPresence(box2metadataSheet, result, BUNDLE_COLUMN, VALUE_COLUMN);
validateRowStyleColumn(box2metadataSheet, BOX_COLUMN, result);
int fieldTypeColumn = getCellIndexFromHeaderName(box2metadataSheet, FIELD_TYPE_COLUMN);
if (fieldTypeColumn == -1) {
result.addError("The sheet " + BOX2METADATA_SHEET + " has no " + FIELD_TYPE_COLUMN + " column");
} else {
validateBox2MetadataFieldTypes(box2metadataSheet, result, fieldTypeColumn);
}
int metadataColumn = getCellIndexFromHeaderName(box2metadataSheet, METADATA_COLUMN);
if (metadataColumn == -1) {
result.addError("The sheet " + BOX2METADATA_SHEET + " has no " + METADATA_COLUMN + " column");
} else {
validateMetadataFields(allMetadataFields, box2metadataSheet, metadataColumn, result);
}
int entityTypeColumn = getCellIndexFromHeaderName(box2metadataSheet, ENTITY_COLUMN);
if (entityTypeColumn == -1) {
result.addError("The sheet " + BOX2METADATA_SHEET + " has no " + ENTITY_COLUMN + " column");
}
int boxColumn = getCellIndexFromHeaderName(box2metadataSheet, BOX_COLUMN);
if (boxColumn == -1) {
result.addError("The sheet " + BOX2METADATA_SHEET + " has no " + BOX_COLUMN + " column");
}
if (entityTypeColumn != -1 && boxColumn != -1) {
validatePresenceInBoxSheet(result, box2metadataSheet, entityTypeColumn, boxColumn);
}
}
private void validateMetadataGroupsSheet(List<String> allMetadataFields,
Workbook workbook, CrisLayoutToolValidationResult result) {
Sheet metadataGroupsSheet = workbook.getSheet(METADATAGROUPS_SHEET);
if (metadataGroupsSheet == null) {
result.addError("The " + METADATAGROUPS_SHEET + " sheet is missing");
return;
}
validateColumnsPresence(metadataGroupsSheet, result, ENTITY_COLUMN);
int metadataColumn = getCellIndexFromHeaderName(metadataGroupsSheet, METADATA_COLUMN);
if (metadataColumn == -1) {
result.addError("The sheet " + METADATAGROUPS_SHEET + " has no " + METADATA_COLUMN + " column");
} else {
validateMetadataFields(allMetadataFields, metadataGroupsSheet, metadataColumn, result);
}
int parentColumn = getCellIndexFromHeaderName(metadataGroupsSheet, PARENT_COLUMN);
if (parentColumn == -1) {
result.addError("The sheet " + METADATAGROUPS_SHEET + " has no " + PARENT_COLUMN + " column");
} else {
validateMetadataFields(allMetadataFields, metadataGroupsSheet, parentColumn, result);
}
}
private void validateBox2MetricsSheet(Workbook workbook, CrisLayoutToolValidationResult result) {
Sheet box2MetricsSheet = workbook.getSheet(BOX2METRICS_SHEET);
if (box2MetricsSheet == null) {
result.addError("The " + BOX2METRICS_SHEET + " sheet is missing");
return;
}
validateColumnsPresence(box2MetricsSheet, result, ENTITY_COLUMN, BOX_COLUMN, METRIC_TYPE_COLUMN);
}
private void validateBoxPolicySheet(List<String> allMetadataFields, Workbook workbook,
CrisLayoutToolValidationResult result) {
validatePolicySheet(allMetadataFields, workbook, result, BOX_POLICY_SHEET);
}
private void validateTabPolicySheet(List<String> allMetadataFields, Workbook workbook,
CrisLayoutToolValidationResult result) {
validatePolicySheet(allMetadataFields, workbook, result, TAB_POLICY_SHEET);
}
private void validatePolicySheet(List<String> allMetadataFields, Workbook workbook,
CrisLayoutToolValidationResult result, String policySheetName) {
Sheet policySheet = workbook.getSheet(policySheetName);
if (policySheet == null) {
result.addError("The " + policySheetName + " sheet is missing");
return;
}
int metadataColumn = getCellIndexFromHeaderName(policySheet, METADATA_COLUMN);
if (metadataColumn == -1) {
result.addError("The sheet " + policySheetName + " has no " + METADATA_COLUMN + " column");
} else {
validateMetadataFields(allMetadataFields, policySheet, metadataColumn, result);
}
validateColumnsPresence(policySheet, result, ENTITY_COLUMN, SHORTNAME_COLUMN);
}
private void validateBox2MetadataFieldTypes(Sheet sheet, CrisLayoutToolValidationResult result, int typeColumn) {
int bundleColumn = getCellIndexFromHeaderName(sheet, BUNDLE_COLUMN);
int valueColumn = getCellIndexFromHeaderName(sheet, VALUE_COLUMN);
for (Row row : getNotEmptyRowsSkippingHeader(sheet)) {
String fieldType = getCellValue(row, typeColumn);
validateFieldType(row, result, bundleColumn, valueColumn, fieldType);
}
}
private void validateFieldType(Row row, CrisLayoutToolValidationResult result, int bundleColumn,
int valueColumn, String fieldType) {
String sheetName = row.getSheet().getSheetName();
int rowNum = row.getRowNum();
if (StringUtils.isBlank(fieldType)) {
result.addError("The " + sheetName + " contains an empty field type at row " + rowNum);
return;
}
if (!ALLOWED_FIELD_TYPES.contains(fieldType)) {
result.addError("The " + sheetName + " contains an unknown field type " + fieldType + " at row " + rowNum);
return;
}
if (METADATA_TYPE.equals(fieldType) && bundleColumn != -1 && valueColumn != -1) {
String bundle = getCellValue(row, bundleColumn);
String value = getCellValue(row, valueColumn);
if (StringUtils.isNotBlank(bundle) || StringUtils.isNotBlank(value)) {
result.addError("The " + sheetName + " contains a " + METADATA_TYPE + " field " + fieldType +
" with " + BUNDLE_COLUMN + " or " + VALUE_COLUMN + " set at row " + rowNum);
}
}
if (BITSTREAM_TYPE.equals(fieldType) && bundleColumn != -1) {
String bundle = getCellValue(row, bundleColumn);
if (StringUtils.isBlank(bundle)) {
result.addError("The " + sheetName + " contains a " + BITSTREAM_TYPE + " field "
+ " without " + BUNDLE_COLUMN + " at row " + rowNum);
}
}
}
private void validateMetadataFields(List<String> allMetadataFields, Sheet sheet,
int metadataColumn, CrisLayoutToolValidationResult result) {
for (Cell cell : getColumnWithoutHeader(sheet, metadataColumn)) {
String metadataField = WorkbookUtils.getCellValue(cell);
if (StringUtils.isNotBlank(metadataField) && !allMetadataFields.contains(metadataField)) {
result.addError("The " + sheet.getSheetName() + " contains an unknown metadata field " + metadataField
+ " at row " + cell.getRowIndex());
}
}
}
private void validatePresenceInBoxSheet(CrisLayoutToolValidationResult result, Sheet sheet,
int entityTypeColumn, int nameColumn) {
for (Row row : getNotEmptyRowsSkippingHeader(sheet)) {
String entityType = getCellValue(row, entityTypeColumn);
String name = getCellValue(row, nameColumn);
if (isNotPresentOnSheet(sheet.getWorkbook(), BOX_SHEET, entityType, name)) {
result.addError("The box with name " + name +
" and entity type " + entityType + " in the row "
+ row.getRowNum() + " of sheet " + sheet.getSheetName()
+ " is not present in the " + BOX_SHEET + " sheet");
}
}
}
private void validateTab2BoxRowsReferences(Sheet tab2boxSheet, CrisLayoutToolValidationResult result) {
int entityTypeColumn = getCellIndexFromHeaderName(tab2boxSheet, ENTITY_COLUMN);
int tabColumn = getCellIndexFromHeaderName(tab2boxSheet, TAB_COLUMN);
int boxesColumn = getCellIndexFromHeaderName(tab2boxSheet, BOXES_COLUMN);
if (entityTypeColumn != -1 && tabColumn != -1 && boxesColumn != -1) {
getNotEmptyRowsSkippingHeader(tab2boxSheet)
.forEach(row -> validateTab2BoxRowReferences(row, result, entityTypeColumn, tabColumn, boxesColumn));
}
}
private void validatePresenceInTab2BoxSheet(CrisLayoutToolValidationResult result, Sheet sheet, String columnName,
int entityTypeColumn, int shortnameColumn) {
Sheet tab2boxSheet = sheet.getWorkbook().getSheet(TAB2BOX_SHEET);
if (tab2boxSheet == null) {
return;
}
for (Row row : getNotEmptyRowsSkippingHeader(sheet)) {
String entityType = getCellValue(row, entityTypeColumn);
String shortname = getCellValue(row, shortnameColumn);
if (isNotPresentOnTab2Box(tab2boxSheet, columnName, entityType, shortname)) {
result.addWarning("The " + sheet.getSheetName() + " with name " + shortname +
" and entity type " + entityType + " in the row "
+ row.getRowNum() + " of sheet " + sheet.getSheetName()
+ " is not present in the " + TAB2BOX_SHEET + " sheet");
}
}
}
private void validateTab2BoxRowReferences(Row row, CrisLayoutToolValidationResult result,
int entityTypeColumn, int tabColumn, int boxesColumn) {
Sheet tab2boxSheet = row.getSheet();
String entityType = getCellValue(row, entityTypeColumn);
String tab = getCellValue(row, tabColumn);
String[] boxes = splitByCommaAndTrim(getCellValue(row, boxesColumn));
if (isNotPresentOnSheet(tab2boxSheet.getWorkbook(), TAB_SHEET, entityType, tab)) {
result.addError("The Tab with name " + tab + " and entity type " + entityType + " in the row " +
row.getRowNum() + " of sheet " + tab2boxSheet.getSheetName() + " is not present in the " + TAB_SHEET
+ " sheet");
}
for (String box : boxes) {
if (isNotPresentOnSheet(tab2boxSheet.getWorkbook(), BOX_SHEET, entityType, box)) {
result.addError("The Box with name " + box + " and entity type " + entityType + " in the row " +
row.getRowNum() + " of sheet " + tab2boxSheet.getSheetName() + " is not present in the " + BOX_SHEET
+ " sheet");
}
}
}
private void validateRowStyleColumn(Sheet sheet, String containerColumnName,
CrisLayoutToolValidationResult result) {
int rowStyleColumn = getCellIndexFromHeaderName(sheet, ROW_STYLE_COLUMN);
if (rowStyleColumn == -1) {
result.addError("The sheet " + sheet.getSheetName() + " has no " + ROW_STYLE_COLUMN + " column");
return;
}
int rowColumn = getCellIndexFromHeaderName(sheet, ROW_COLUMN);
if (rowColumn == -1) {
return;
}
int entityTypeColumn = getCellIndexFromHeaderName(sheet, ENTITY_COLUMN);
int containerColumn = getCellIndexFromHeaderName(sheet, containerColumnName);
if (entityTypeColumn == -1 || containerColumn == -1) {
return;
}
List<Integer> detectedRowWithConflicts = new ArrayList<Integer>();
for (Row row : getNotEmptyRowsSkippingHeader(sheet)) {
if (detectedRowWithConflicts.contains(row.getRowNum())) {
continue;
}
String style = getCellValue(row, rowStyleColumn);
if (StringUtils.isBlank(style)) {
continue;
}
String entityType = getCellValue(row, entityTypeColumn);
String container = getCellValue(row, containerColumn);
String rowCount = getCellValue(row, rowColumn);
List<Integer> sameRowsWithDifferentStyle = findSameRowsWithDifferentStyle(sheet,
entityType, container, containerColumn, rowCount, style, row.getRowNum());
if (CollectionUtils.isNotEmpty(sameRowsWithDifferentStyle)) {
detectedRowWithConflicts.addAll(sameRowsWithDifferentStyle);
result.addError("Row style conflict between rows " + row.getRowNum() + " and rows "
+ sameRowsWithDifferentStyle.toString() + " of sheet " + sheet.getSheetName());
}
}
}
private List<Integer> findSameRowsWithDifferentStyle(Sheet sheet, String entity,
String container, int containerColumn, String row, String style, int excelRowNum) {
int rowStyleColumn = getCellIndexFromHeaderName(sheet, ROW_STYLE_COLUMN);
int entityTypeColumn = getCellIndexFromHeaderName(sheet, ENTITY_COLUMN);
int rowColumn = getCellIndexFromHeaderName(sheet, ROW_COLUMN);
return getNotEmptyRowsSkippingHeader(sheet).stream()
.filter(sheetRow -> excelRowNum != sheetRow.getRowNum())
.filter(sheetRow -> row.equals(getCellValue(sheetRow, rowColumn)))
.filter(sheetRow -> container.equals(getCellValue(sheetRow, containerColumn)))
.filter(sheetRow -> entity.equals(getCellValue(sheetRow, entityTypeColumn)))
.filter(sheetRow -> hasDifferentStyle(sheetRow, rowStyleColumn, style))
.map(Row::getRowNum)
.collect(Collectors.toList());
}
private boolean hasDifferentStyle(Row row, int rowStyleColumn, String style) {
String cellValue = getCellValue(row, rowStyleColumn);
return isNotBlank(cellValue) && !style.trim().equals(cellValue.trim());
}
private boolean isNotPresentOnSheet(Workbook workbook, String sheetName, String entityType, String shortname) {
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
// Return false to avoid many validation error if the sheet is missing
return false;
}
int entityTypeColumn = getCellIndexFromHeaderName(sheet, ENTITY_COLUMN);
int shortnameColumn = getCellIndexFromHeaderName(sheet, SHORTNAME_COLUMN);
if (entityTypeColumn == -1 || shortnameColumn == -1) {
// Return false to avoid many validation error if one of the two columns is missing
return false;
}
return getNotEmptyRowsSkippingHeader(sheet).stream()
.noneMatch(row -> sameEntityTypeAndName(row, entityTypeColumn, entityType, shortnameColumn, shortname));
}
private boolean isNotPresentOnTab2Box(Sheet tab2boxSheet, String columnName, String entityType, String shortname) {
int entityTypeColumn = getCellIndexFromHeaderName(tab2boxSheet, ENTITY_COLUMN);
int nameColumn = getCellIndexFromHeaderName(tab2boxSheet, columnName);
if (entityTypeColumn == -1 || nameColumn == -1) {
// Return false to avoid many validation error if one of the two columns is
// missing
return false;
}
return getNotEmptyRowsSkippingHeader(tab2boxSheet).stream()
.noneMatch(row -> sameEntityTypeAndName(row, entityTypeColumn, entityType, nameColumn, shortname));
}
private boolean sameEntityTypeAndName(Row row, int entityTypeColumn, String entityType,
int nameColumn, String name) {
String[] namesOnColumn = splitByCommaAndTrim(getCellValue(row, nameColumn));
return entityType.equals(getCellValue(row, entityTypeColumn)) && ArrayUtils.contains(namesOnColumn, name);
}
private void validateEntityTypes(CrisLayoutToolValidationResult result, Sheet sheet,
int entityColumn, List<String> allEntityTypes) {
for (Cell entityTypeCell : getColumnWithoutHeader(sheet, entityColumn)) {
String entityType = WorkbookUtils.getCellValue(entityTypeCell);
if (!allEntityTypes.contains(entityType)) {
result.addError("The " + sheet.getSheetName() + " contains an unknown entity type '" + entityType
+ "' at row " + entityTypeCell.getRowIndex());
}
}
}
private void validateBoxTypes(CrisLayoutToolValidationResult result, Sheet sheet, int typeColumn) {
for (Cell typeCell : getColumnWithoutHeader(sheet, typeColumn)) {
String type = WorkbookUtils.getCellValue(typeCell);
if (StringUtils.isNotBlank(type) && !EnumUtils.isValidEnum(CrisLayoutBoxTypes.class, type)) {
result.addError("The sheet " + sheet.getSheetName() + " contains an invalid type " + type
+ " at row " + typeCell.getRowIndex());
}
}
}
private void validateColumnsPresence(Sheet sheet, CrisLayoutToolValidationResult result, String... columns) {
for (String column : columns) {
if (getCellIndexFromHeaderName(sheet, column) == -1) {
result.addError("The sheet " + sheet.getSheetName() + " has no " + column + " column");
}
}
}
private void validateBooleanColumns(Sheet sheet, CrisLayoutToolValidationResult result, String... columnNames) {
for (String columnName : columnNames) {
validateColumn(sheet, columnName, (value) -> isNotBoolean(value), result,
ALLOWED_BOOLEAN_VALUES.toString());
}
}
private void validateIntegerColumns(Sheet sheet, CrisLayoutToolValidationResult result, String... columnNames) {
for (String columnName : columnNames) {
validateColumn(sheet, columnName, (value) -> isNotInteger(value), result, "integer values");
}
}
private void validateSecurityColumns(Sheet sheet, CrisLayoutToolValidationResult result, String... columnNames) {
for (String columnName : columnNames) {
validateColumn(sheet, columnName, (value) -> !ALLOWED_SECURITY_VALUES.contains(value), result,
ALLOWED_SECURITY_VALUES.toString());
}
}
private void validateColumn(Sheet sheet, String columnName, Predicate<String> predicate,
CrisLayoutToolValidationResult result, String allowedValues) {
int rowColumn = getCellIndexFromHeaderName(sheet, columnName);
if (rowColumn == -1) {
result.addError("The sheet " + sheet.getSheetName() + " has no " + columnName + " column");
return;
}
for (Row row : getNotEmptyRowsSkippingHeader(sheet)) {
String rowValue = getCellValue(row, rowColumn);
if (StringUtils.isBlank(rowValue)) {
result.addError("The " + columnName + " value specified on the row " + row.getRowNum() + " of sheet "
+ sheet.getSheetName() + " is empty. Allowed values: " + allowedValues);
} else if (predicate.test(rowValue)) {
result.addError("The " + columnName + " value specified on the row " + row.getRowNum() + " of sheet "
+ sheet.getSheetName() + " is not valid: " + rowValue + ". Allowed values: " + allowedValues);
}
}
}
private List<String> getAllEntityTypes(Context context) {
try {
return entityTypeService.findAll(context).stream()
.peek(entityType -> uncacheEntity(context, entityType))
.map(entityType -> entityType.getLabel())
.collect(Collectors.toList());
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private List<String> getAllMetadataFields(Context context) {
try {
return metadataFieldService.findAll(context).stream()
.peek(metadataField -> uncacheEntity(context, metadataField))
.map(metadataField -> metadataField.toString('.'))
.collect(Collectors.toList());
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private void uncacheEntity(Context context, ReloadableEntity<?> object) {
try {
context.uncacheEntity(object);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private boolean isNotInteger(String number) {
try {
Integer.parseInt(number);
} catch (Exception e) {
return true;
}
return false;
}
private boolean isNotBoolean(String value) {
return !ALLOWED_BOOLEAN_VALUES.contains(value);
}
private String[] splitByCommaAndTrim(String name) {
return Arrays.stream(name.split(",")).map(String::trim).toArray(String[]::new);
}
}
|
9246757234ed7e511319686ce6cc30b6af7826a5 | 260 | java | Java | crxtool-core/src/main/java/io/github/mike10004/crxtool/Crx2ProofAlgorithm.java | mike10004/crxtool | 452402e693dbe66faa6654aacca77613bf510e12 | [
"MIT"
] | 3 | 2018-06-08T07:50:28.000Z | 2022-02-22T02:41:49.000Z | crxtool-core/src/main/java/io/github/mike10004/crxtool/Crx2ProofAlgorithm.java | mike10004/crxtool | 452402e693dbe66faa6654aacca77613bf510e12 | [
"MIT"
] | 2 | 2018-10-09T18:01:40.000Z | 2019-07-02T17:26:08.000Z | crxtool-core/src/main/java/io/github/mike10004/crxtool/Crx2ProofAlgorithm.java | mike10004/crxtool | 452402e693dbe66faa6654aacca77613bf510e12 | [
"MIT"
] | 2 | 2018-06-08T07:50:33.000Z | 2020-06-05T06:46:39.000Z | 18.571429 | 61 | 0.707692 | 1,003,778 | package io.github.mike10004.crxtool;
public enum Crx2ProofAlgorithm implements CrxProofAlgorithm {
sha1_with_rsa();
private static final String KEY = "sha1_with_rsa";
@Override
public String crxFileHeaderKey() {
return KEY;
}
}
|
924676299d02b1161473e7f9ef72a41431a36fb9 | 290 | java | Java | quarkus-imperative/src/main/java/dev/nonava/techstacks/quarkus/imperative/greeting/domain/model/Username.java | fluxroot/techstacks | 6093cf706389f015cc4f962086d82266bc3cf2f9 | [
"MIT"
] | 1 | 2021-04-03T15:58:56.000Z | 2021-04-03T15:58:56.000Z | quarkus-imperative/src/main/java/dev/nonava/techstacks/quarkus/imperative/greeting/domain/model/Username.java | fluxroot/techstacks | 6093cf706389f015cc4f962086d82266bc3cf2f9 | [
"MIT"
] | null | null | null | quarkus-imperative/src/main/java/dev/nonava/techstacks/quarkus/imperative/greeting/domain/model/Username.java | fluxroot/techstacks | 6093cf706389f015cc4f962086d82266bc3cf2f9 | [
"MIT"
] | null | null | null | 18.125 | 71 | 0.737931 | 1,003,779 | /*
* Copyright 2021 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package dev.nonava.techstacks.quarkus.imperative.greeting.domain.model;
import lombok.Value;
@Value
public class Username {
String value;
}
|
924676dc2f22aa61d16e2e941ae25c073f87e00f | 1,205 | java | Java | toolkit/src/test/java/toolkit/instrumentation/asm/calltraces/TestInstrumented.java | margostino/amplifix | 3a4d4903bca79bdc553c750659b3a69cd0e1e8a8 | [
"Apache-2.0"
] | 1 | 2020-09-11T20:43:24.000Z | 2020-09-11T20:43:24.000Z | toolkit/src/test/java/toolkit/instrumentation/asm/calltraces/TestInstrumented.java | margostino/amplifix | 3a4d4903bca79bdc553c750659b3a69cd0e1e8a8 | [
"Apache-2.0"
] | null | null | null | toolkit/src/test/java/toolkit/instrumentation/asm/calltraces/TestInstrumented.java | margostino/amplifix | 3a4d4903bca79bdc553c750659b3a69cd0e1e8a8 | [
"Apache-2.0"
] | null | null | null | 30.897436 | 146 | 0.73195 | 1,003,780 | package toolkit.instrumentation.asm.calltraces;
import io.vertx.core.Vertx;
import org.gaussian.amplifix.toolkit.json.JsonCodec;
import toolkit.factory.domain.Status;
import java.time.Instant;
import static io.vertx.core.json.JsonObject.mapFrom;
import static java.lang.String.format;
/**
* Translate TestInstrumented into ASM API calls
* In /Users/martin.dagostino/workspace/amplifix/toolkit/build/classes/java/test/toolkit/instrumentation/asm/calltraces/
* java -cp .:/Users/martin.dagostino/workspace/amplifix/toolkit/bin/asm-all-5.2.jar jdk.internal.org.objectweb.asm.util.ASMifier TestInstrumented
*/
public class TestInstrumented {
public String sessionId;
public Instant createdAt;
public Status status;
public TestInstrumented(String sessionId, Instant createdAt, Status status) {
this.sessionId = sessionId;
this.createdAt = createdAt;
this.status = status;
}
//@LogEntry(logger="global")
public void mutate(Status status) {
this.status = status;
AmplifixStatic.send(this);
}
public void notMutate(Integer value) {
System.out.println(format("The object does not mutate. Value: %s", value));
}
} |
92467728c98dc7b18e5e1069492455381a4998aa | 644 | java | Java | pattern-tutor/pattern-tutor-syntax/src/main/java/com/pattern/tutor/syntax/garbage/Garbage.java | Zychaowill/pattern | a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd | [
"Apache-2.0"
] | 1 | 2018-07-05T07:43:42.000Z | 2018-07-05T07:43:42.000Z | pattern-tutor/pattern-tutor-syntax/src/main/java/com/pattern/tutor/syntax/garbage/Garbage.java | Zychaowill/pattern | a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd | [
"Apache-2.0"
] | null | null | null | pattern-tutor/pattern-tutor-syntax/src/main/java/com/pattern/tutor/syntax/garbage/Garbage.java | Zychaowill/pattern | a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd | [
"Apache-2.0"
] | 3 | 2019-01-25T14:23:27.000Z | 2019-08-24T08:37:04.000Z | 24.769231 | 112 | 0.614907 | 1,003,781 | package com.pattern.tutor.syntax.garbage;
public class Garbage {
public static void main(String[] args) {
while (!Chair.f) {
new Chair();
new String("To take up space.");
}
System.out.println("After all Chairs have been created:\ntotal created=" + Chair.created + ",total finalized="
+ Chair.finalized);
if (args.length > 0) {
if (args[0].equals("gc") || args[0].equals("all")) {
System.out.println("gc():");
System.gc();
}
if (args[0].equals("finalize") || args[0].equals("all")) {
System.out.println("runFinalization():");
System.runFinalization();
}
}
System.out.println("bye!");
}
}
|
Subsets and Splits