下面列出了java.util.AbstractMap.SimpleEntry#getKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static <T> boolean completePromise(int xid, ClusterResponse<T> response) {
if (!PROMISE_MAP.containsKey(xid)) {
return false;
}
SimpleEntry<ChannelPromise, ClusterResponse> entry = PROMISE_MAP.get(xid);
if (entry != null) {
ChannelPromise promise = entry.getKey();
if (promise.isDone() || promise.isCancelled()) {
return false;
}
entry.setValue(response);
promise.setSuccess();
return true;
}
return false;
}
/**
* Predicts probability and calculate its logarithmic loss using {@link Predictor#predict(FVec)}.
*
* @param predictor Predictor
* @param data test data
*/
static void predictAndLogLoss(Predictor predictor, List<SimpleEntry<Integer, FVec>> data) {
double sum = 0;
for (SimpleEntry<Integer, FVec> pair : data) {
double[] predicted = predictor.predict(pair.getValue());
double predValue = Math.min(Math.max(predicted[0], 1e-15), 1 - 1e-15);
int actual = pair.getKey();
sum = actual * Math.log(predValue) + (1 - actual) * Math.log(1 - predValue);
}
double logLoss = -sum / data.size();
System.out.println("Logloss: " + logLoss);
}
/**
* Handles message received over point-to-point links
*/
@Override
public void handleMessage(final Message message) {
// TODO: Implement stuff here
// System.out.println("OPT BFT --- Received unique authenticated message: " /*+
// message*/);
// Count votes for messages in a given position
if (message instanceof Message) {
final Message publicMessage = (Message) message;
final Payload payload = publicMessage.getPayload();
if (payload.getOpcode() == Payload.OpCode.BFT_CERTIFICATION) {
final SimpleEntry<Long, SignedMessage> data = (SimpleEntry<Long, SignedMessage>) payload.getData();
final long messagePosition = data.getKey();
final SignedMessage bftMessage = data.getValue();
recordVote(messagePosition, bftMessage, message.getSenderIndex());
}
}
}
@SuppressWarnings("unchecked")
private static String computeEncryptedPartials(final ApvssShareholder shareholder, final String secretName,
final Integer requesterId) throws NotFoundException {
// This server
final int serverIndex = shareholder.getIndex();
// Epoch information
final long epoch = shareholder.getEpoch();
// Return encrypted partials
final SimpleEntry<BigInteger, BigInteger> encryptedPartials = shareholder.computeEncryptedPartial(requesterId);
final BigInteger encryptedShare1Part = encryptedPartials.getKey();
final BigInteger encryptedShare2Part = encryptedPartials.getValue();
// Return the result in json
final JSONObject obj = new JSONObject();
obj.put("responder", new Integer(serverIndex));
obj.put("requester", new Integer(requesterId));
obj.put("epoch", new Long(epoch));
obj.put("share1_part", encryptedShare1Part.toString());
obj.put("share2_part", encryptedShare2Part.toString());
return obj.toJSONString() + "\n";
}
public static <T> boolean completePromise(int xid, ClusterResponse<T> response) {
if (!PROMISE_MAP.containsKey(xid)) {
return false;
}
SimpleEntry<ChannelPromise, ClusterResponse> entry = PROMISE_MAP.get(xid);
if (entry != null) {
ChannelPromise promise = entry.getKey();
if (promise.isDone() || promise.isCancelled()) {
return false;
}
entry.setValue(response);
promise.setSuccess();
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected void writeChildren(FreeColXMLWriter xw) throws XMLStreamException {
super.writeChildren(xw);
if (this.kv != null) {
for (SimpleEntry<String,StringTemplate> e : this.kv) {
xw.writeStartElement(PAIR_TAG);
String key = e.getKey(); // OK if null
if (key != null) xw.writeAttribute(VALUE_TAG, key);
e.getValue().toXML(xw); // value is always present
xw.writeEndElement();
}
}
}
@SuppressWarnings("unchecked")
@Override
public void endElement(String uri, String localName, String qName) {
SimpleEntry<String, String> element = elements.pop();
switch (qName) {
case "event":
case "struct":
case "array":
case "value":
String name = element.getKey();
Object value = objects.pop();
if (objects.isEmpty()) {
events.add((XMLEvent) value);
return;
}
if (value instanceof StringBuilder) {
value = ((StringBuilder) value).toString();
}
Object parent = objects.peek();
if (parent instanceof XMLEvent) {
((XMLEvent) parent).values.put(name, value);
}
if (parent instanceof Map) {
((Map<String, Object>) parent).put(name, value);
}
if (parent != null && parent.getClass().isArray()) {
int index = Integer.parseInt(element.getValue());
((Object[]) parent)[index] = value;
}
}
}
@SuppressWarnings("unchecked")
@Override
public void endElement(String uri, String localName, String qName) {
SimpleEntry<String, String> element = elements.pop();
switch (qName) {
case "event":
case "struct":
case "array":
case "value":
String name = element.getKey();
Object value = objects.pop();
if (objects.isEmpty()) {
events.add((XMLEvent) value);
return;
}
if (value instanceof StringBuilder) {
value = ((StringBuilder) value).toString();
}
Object parent = objects.peek();
if (parent instanceof XMLEvent) {
((XMLEvent) parent).values.put(name, value);
}
if (parent instanceof Map) {
((Map<String, Object>) parent).put(name, value);
}
if (parent != null && parent.getClass().isArray()) {
int index = Integer.parseInt(element.getValue());
((Object[]) parent)[index] = value;
}
}
}
private String getName(String key) {
SimpleEntry<String, String> entry = entryMap.get(key);
if(entry == null)
return "";
else
if(obf)
return entry.getValue();
else
return entry.getKey();
}
private static void printErrors(final List<ApvssShareholder> shareholders)
{
for (ApvssShareholder shareholder : shareholders)
{
System.out.println("Errors reported by shareholder with index = " + shareholder.getIndex() + ":");
for (SimpleEntry<Integer, ErrorCondition> alert : shareholder.alertLog.getAlerts())
{
int reportedShareholder = alert.getKey();
ErrorCondition error = alert.getValue();
System.out.println(" Shareholder[" + reportedShareholder + "] committed a " + error + " error");
}
}
}
public void readSecret() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException, IOException,
ResourceUnavailableException, BelowThresholdException, NoSuchAlgorithmException, CertificateException,
InvalidKeySpecException, InvalidKeyException, NoSuchProviderException, SignatureException,
BadArgumentException {
// Perform read to all servers
// Validate each result before adding it to the list
// On read, print the restored secret's public key
// Compare to the public key that was return getting the info of the secret
// TODO: Compare returned shares against (most common feldman commitments
// Print the secret to standard out
// Print status
System.out.println("-----------------------------------------------------------");
// Get public keys from the server
System.out.print("Accessing public key for secret: " + this.secretName + "... ");
final SimpleEntry<List<EcPoint>, Long> publicKeyAndEpoch = this.getServerVerificationKeys(secretName);
System.out.println(" (done)");
final List<EcPoint> publicKeys = publicKeyAndEpoch.getKey();
System.out.println("Stored Public key for secret: " + publicKeys.get(0));
System.out.println();
// Attempt recovery of the stored secret
System.out.println("Reading shares to decode secret: " + this.secretName);
final BigInteger recoveredSecret = this.readShares(publicKeys);
final EcPoint publicKeyOfSecret = CommonConfiguration.CURVE.multiply(CommonConfiguration.g, recoveredSecret);
System.out.println("Public key of recvered secret = " + publicKeyOfSecret);
boolean secretsMatch = publicKeyOfSecret.equals(publicKeys.get(0));
System.out.println("done.");
System.out.println();
if (secretsMatch) {
System.out.println("Value of secret: " + recoveredSecret);
} else {
System.err.println("Failed to recover secret");
System.exit(-1);
}
}
@SuppressWarnings("unchecked")
@Override
public void endElement(String uri, String localName, String qName) {
SimpleEntry<String, String> element = elements.pop();
switch (qName) {
case "event":
case "struct":
case "array":
case "value":
String name = element.getKey();
Object value = objects.pop();
if (objects.isEmpty()) {
events.add((XMLEvent) value);
return;
}
if (value instanceof StringBuilder) {
value = ((StringBuilder) value).toString();
}
Object parent = objects.peek();
if (parent instanceof XMLEvent) {
((XMLEvent) parent).values.put(name, value);
}
if (parent instanceof Map) {
((Map<String, Object>) parent).put(name, value);
}
if (parent != null && parent.getClass().isArray()) {
int index = Integer.parseInt(element.getValue());
((Object[]) parent)[index] = value;
}
}
}
private SimpleEntry<Float, String> classify(float value)
{
SimpleEntry<Float, String> foundClass = null;
for (SimpleEntry<Float, String> thresholdClass : thresholdList)
{
float classValue = thresholdClass.getKey();
if (value > classValue)
{
return thresholdClass;
}
}
return foundClass;
}
@Override
public int compare(SimpleEntry<Float, String> o1, SimpleEntry<Float, String> o2)
{
// Note: this comparator imposes orderings that are inconsistent with equals.
// Order is descending.
if (o1.getKey() > o2.getKey())
{
return -1;
}
if (o1.getKey() < o2.getKey())
{
return 1;
}
return 0;
}
private void findParametersWrappedInLocalVariables() {
for(StatementObject statement : nonMappedLeavesT2) {
for(VariableDeclaration declaration : statement.getVariableDeclarations()) {
AbstractExpression initializer = declaration.getInitializer();
if(initializer != null) {
for(String key : initializer.getCreationMap().keySet()) {
List<ObjectCreation> creations = initializer.getCreationMap().get(key);
for(ObjectCreation creation : creations) {
for(String argument : creation.arguments) {
SimpleEntry<VariableDeclaration, UMLOperation> v2 = getVariableDeclaration2(new Replacement("", argument, ReplacementType.VARIABLE_NAME));
SimpleEntry<VariableDeclaration, UMLOperation> v1 = getVariableDeclaration1(new Replacement(declaration.getVariableName(), "", ReplacementType.VARIABLE_NAME));
if(v2 != null && v1 != null) {
Set<AbstractCodeMapping> references = VariableReferenceExtractor.findReferences(v1.getKey(), v2.getKey(), mappings);
RenameVariableRefactoring ref = new RenameVariableRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references);
if(!existsConflictingExtractVariableRefactoring(ref) && !existsConflictingMergeVariableRefactoring(ref) && !existsConflictingSplitVariableRefactoring(ref)) {
variableRenames.add(ref);
if(!v1.getKey().getType().equals(v2.getKey().getType()) || !v1.getKey().getType().equalsQualified(v2.getKey().getType())) {
ChangeVariableTypeRefactoring refactoring = new ChangeVariableTypeRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references);
refactoring.addRelatedRefactoring(ref);
refactorings.add(refactoring);
}
}
}
}
}
}
}
}
}
}
public void writeSecret() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException,
IOException, ResourceUnavailableException, BelowThresholdException, InvalidKeySpecException,
NoSuchAlgorithmException, CertificateEncodingException, InterruptedException {
// Thresholdizes the given secret
// Stores each share to shareholder
// Initiates a dkg using that secret
// Outputs the public key of the secret to verify stored correctly
// Get n and t
final int numServers = serverConfiguration.getNumServers();
final int threshold = serverConfiguration.getReconstructionThreshold();
// Print status of key pair generation
System.out.println("-----------------------------------------------------------");
System.out.println("Generating shares of the provided secret...");
final EcPoint publicKeyOfSecret = CommonConfiguration.CURVE.multiply(CommonConfiguration.g, secretToStore);
System.out.println("Public key of secret = " + publicKeyOfSecret);
final BigInteger[] coefficients = Shamir.generateCoefficients(threshold);
coefficients[0] = secretToStore;
final ShamirShare[] shares = Shamir.generateShares(coefficients, numServers);
System.out.println("Generation of shares complete.");
System.out.println();
// Store shares and parameters to the shareholders
System.out.print("Storing shares to secret: " + this.secretName + "... ");
final Boolean storageSuccess = this.storeSecret(shares);
if (!storageSuccess) {
System.err.println("\nStorage failed");
System.exit(-1);
}
System.out.println(" (done)");
// Initiating DKG
System.out.print("Initiating DKG for secret: " + this.secretName + "... ");
final Boolean dkgSuccess = this.storeShares();
if (!dkgSuccess) {
System.out.println("DKG failed, secret is not available");
}
System.out.println(" (done)");
// Initiating DKG
Thread.sleep(5000);
System.out.println(" (done)");
// Verify DKG
// Get public keys from the server
System.out.print("Accessing public key for secret: " + this.secretName + "... ");
final SimpleEntry<List<EcPoint>, Long> publicKeyAndEpoch = this.getServerVerificationKeys(secretName);
System.out.println(" (done)");
final List<EcPoint> publicKeys = publicKeyAndEpoch.getKey();
System.out.println("Stored Public key for secret: " + publicKeys.get(0));
boolean secretsMatch = publicKeyOfSecret.equals(publicKeys.get(0));
System.out.println();
if (secretsMatch) {
System.out.println("DKG complete. Secret is now stored and available for reading.");
} else {
System.err.println("DKG complete but stored result does not match what we attempted to store.");
System.exit(-1);
}
}
/**
* Split a message into a list of text and link objects.
*
* @param player The {@code Player} who will see the result.
* @return A list of strings and buttons.
*/
public List<Object> splitLinks(Player player) {
final FreeColGameObject source = player.getGame()
.getMessageSource(this);
// Build a list of objects, initially containing just the plain
// text of the message.
List<Object> result = new ArrayList<>();
result.add(Messages.message(this));
for (SimpleEntry<String,StringTemplate> e : entryList()) {
// Then for each key, check if it can be made into a link.
// If not, ignore it.
String key = e.getKey();
String val = Messages.message(e.getValue());
if (val == null) continue;
Object b = Utility.getMessageButton(key, val, player, source);
if (b == null) continue;
// ...if so, find all instances of the replacement of the key
// in the object list texts, and replace them with buttons.
List<Object> next = new ArrayList<>();
for (Object o : result) {
if (o instanceof String) {
String str = (String)o;
int index, start = 0;
while ((index = str.indexOf(val, start)) >= 0) {
if (index > start) {
next.add(str.substring(start, index));
}
next.add(b);
start = index + val.length();
}
next.add(str.substring(start, str.length()));
} else {
next.add(o);
}
}
result = next;
}
return result;
}
@Override
public String toString() {
String contents = getContents();
regions.sort(Comparator.comparing((region) -> region.start));
List<SimpleEntry<Integer, CommentedRegion>> sorted = new ArrayList<>();
for (int index = 0; index < regions.size(); index++) {
sorted.add(new SimpleEntry<>(index, regions.get(index)));
}
List<SimpleEntry<Integer, String>> locations = new ArrayList<>();
sorted.stream().forEach(s -> {
locations.add(new SimpleEntry<>(s.getValue().start, "<" + s.getKey() + "<"));
locations.add(new SimpleEntry<>(s.getValue().end, ">" + s.getKey() + ">"));
});
locations.sort(Comparator.comparing(SimpleEntry::getKey));
StringBuilder result = new StringBuilder();
int lastOffset = 0;
for (int i = 0; i < locations.size(); i++) {
SimpleEntry<Integer, String> location = locations.get(i);
Integer offset = location.getKey();
String comment = location.getValue();
result.append(contents.substring(lastOffset, offset));
result.append(comment);
lastOffset = offset;
}
result.append(contents.substring(lastOffset, contents.length()));
String[] resultsArray = result.toString().replace("\t", " ").split("\r?\n");
int maxLineLength = Arrays.stream(resultsArray).map(r -> r.length()).reduce(Integer::max).get();
if (!result.substring(result.length() - 1, result.length()).equals("\n")) {
result.append("\n");
}
result.append(Strings.repeat("-", maxLineLength));
if (sorted.isEmpty()) {
for (String message : emptyMessages) {
result.append("\n");
result.append(message);
}
} else {
for (SimpleEntry<Integer, CommentedRegion> c : sorted) {
result.append("\n");
result.append(c.getKey());
result.append(": ");
result.append(c.getValue().text);
}
}
return result.toString();
}
@Override
protected void loadModel(URL directoryURL, String parms) {
File directory = null;
if("file".equals(directoryURL.getProtocol())) {
directory = Files.fileFromURL(directoryURL);
} else {
throw new GateRuntimeException("The dataDirectory for WekaWrapper must be a file: URL not "+directoryURL);
}
ArrayList<String> finalCommand = new ArrayList<>();
// we need the corpus representation here! Normally this is done from loadEngine and after
// load model, but we do it here. The load crm method only loads anything if it is still
// null, so we will do this only once anyway.
loadAndSetCorpusRepresentation(directoryURL);
CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget)corpusRepresentation;
SimpleEntry<String,Integer> modeAndNrC = findOutMode(data);
String mode = modeAndNrC.getKey();
Integer nrClasses = modeAndNrC.getValue();
// Instead of loading a model, this establishes a connection with the
// external wrapper process.
File commandFile = findWrapperCommand(directory, true);
String modelFileName = new File(directory,MODEL_BASENAME).getAbsolutePath();
finalCommand.add(commandFile.getAbsolutePath());
finalCommand.add(modelFileName);
finalCommand.add(mode);
finalCommand.add(nrClasses.toString());
// if we have a shell command prepend that, and if we have shell parms too, include them
if(shellcmd != null) {
finalCommand.add(0,shellcmd);
if(shellparms != null) {
String[] sps = shellparms.trim().split("\\s+");
int i=0; for(String sp : sps) { finalCommand.add(++i,sp); }
}
}
//System.err.println("Running: "+finalCommand);
// Create a fake Model jsut to make LF_Apply... happy which checks if this is null
model = MODEL_INSTANCE;
Map<String,String> env = new HashMap<>();
env.put(ENV_WRAPPER_HOME, wrapperhome);
process = Process4JsonStream.create(directory,env,finalCommand);
}
@Override
public void trainModel(File dataDirectory, String instanceType, String parms) {
ArrayList<String> finalCommand = new ArrayList<>();
CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget)corpusRepresentation;
SimpleEntry<String,Integer> modeAndNrC = findOutMode(data);
String mode = modeAndNrC.getKey();
Integer nrClasses = modeAndNrC.getValue();
// invoke wrapper for training
File commandFile = findWrapperCommand(dataDirectory, false);
// Export the data
// Note: any scaling was already done in the PR before calling this method!
// find out if we train classification or regression
// TODO: NOTE: not sure if classification/regression matters here as long as
// the actual exporter class does the right thing based on the corpus representation!
// TODO: we have to choose the correct target type here!!!
// NOTE: the last argument here are the parameters for the exporter method.
// we use the CSV exporter with parameters:
// -t: twofiles, export indep and dep into separate files
// -n: noheaders, do not add a header row
// Exporter.export(corpusRepresentation,
// Exporter.CSV_CL_MR, dataDirectory, instanceType, "-t -n");
corpusExporter.export();
String dataFileName = dataDirectory.getAbsolutePath()+File.separator;
String modelFileName = new File(dataDirectory, MODEL_BASENAME).getAbsolutePath();
finalCommand.add(commandFile.getAbsolutePath());
finalCommand.add(dataFileName);
finalCommand.add(modelFileName);
finalCommand.add(mode);
finalCommand.add(nrClasses.toString());
if(!parms.trim().isEmpty()) {
String[] tmp = parms.split("\\s+",-1);
finalCommand.addAll(Arrays.asList(tmp));
}
// if we have a shell command prepend that, and if we have shell parms too, include them
if(shellcmd != null) {
finalCommand.add(0,shellcmd);
if(shellparms != null) {
String[] sps = shellparms.trim().split("\\s+");
int i=0; for(String sp : sps) { finalCommand.add(++i,sp); }
}
}
//System.err.println("Running: ");
//for(int i=0; i<finalCommand.size();i++) {
// System.err.println(i+": >"+finalCommand.get(i)+"<");
//}
// Create a fake Model jsut to make LF_Apply... happy which checks if this is null
model = MODEL_INSTANCE;
Map<String,String> env = new HashMap<>();
env.put(ENV_WRAPPER_HOME,wrapperhome);
process = ProcessSimple.create(dataDirectory,env,finalCommand);
process.waitFor();
updateInfo();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
info.modelWhenTrained = sdf.format(new Date());
info.algorithmParameters = parms;
info.save(dataDirectory);
featureInfo.save(dataDirectory);
}