hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
e5954f027c152bcb42a57cbe77c5b51950b77cbd
| 7,063
|
/*
* 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.gearpump.sql.planner;
import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.config.CalciteConnectionConfig;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.linq4j.Enumerator;
import org.apache.calcite.linq4j.Queryable;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.tools.Frameworks;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
public class Connection implements CalciteConnection {
private final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
private String schema = null;
public SchemaPlus getRootSchema() {
return rootSchema;
}
public JavaTypeFactory getTypeFactory() {
return null;
}
public Properties getProperties() {
return null;
}
public Statement createStatement() throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return null;
}
public CallableStatement prepareCall(String sql) throws SQLException {
return null;
}
public String nativeSQL(String sql) throws SQLException {
return null;
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
public boolean getAutoCommit() throws SQLException {
return false;
}
public void commit() throws SQLException {
}
public void rollback() throws SQLException {
}
public void close() throws SQLException {
}
public boolean isClosed() throws SQLException {
return false;
}
public DatabaseMetaData getMetaData() throws SQLException {
return null;
}
public void setReadOnly(boolean readOnly) throws SQLException {
}
public boolean isReadOnly() throws SQLException {
return false;
}
public void setCatalog(String catalog) throws SQLException {
}
public String getCatalog() throws SQLException {
return null;
}
public void setTransactionIsolation(int level) throws SQLException {
}
public int getTransactionIsolation() throws SQLException {
return 0;
}
public SQLWarning getWarnings() throws SQLException {
return null;
}
public void clearWarnings() throws SQLException {
}
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
public void setHoldability(int holdability) throws SQLException {
}
public int getHoldability() throws SQLException {
return 0;
}
public Savepoint setSavepoint() throws SQLException {
return null;
}
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
public void rollback(Savepoint savepoint) throws SQLException {
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
public Clob createClob() throws SQLException {
return null;
}
public Blob createBlob() throws SQLException {
return null;
}
public NClob createNClob() throws SQLException {
return null;
}
public SQLXML createSQLXML() throws SQLException {
return null;
}
public boolean isValid(int timeout) throws SQLException {
return false;
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
public String getClientInfo(String name) throws SQLException {
return null;
}
public Properties getClientInfo() throws SQLException {
return null;
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
public void setSchema(String s) throws SQLException {
schema = s;
}
public String getSchema() throws SQLException {
return schema;
}
public void abort(Executor executor) throws SQLException {
}
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
public int getNetworkTimeout() throws SQLException {
return 0;
}
public CalciteConnectionConfig config() {
return null;
}
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public <T> Queryable<T> createQuery(Expression expression, Class<T> aClass) {
return null;
}
public <T> Queryable<T> createQuery(Expression expression, Type type) {
return null;
}
public <T> T execute(Expression expression, Class<T> aClass) {
return null;
}
public <T> T execute(Expression expression, Type type) {
return null;
}
public <T> Enumerator<T> executeQuery(Queryable<T> queryable) {
return null;
}
}
| 24.105802
| 148
| 0.74062
|
44297ae13e84a2cfd1f41b1164b1c32f9e671c89
| 366
|
package com.asha.nightowllib.paint;
import android.content.res.TypedArray;
import android.view.View;
/**
* Created by hzqiujiadi on 15/11/7.
* hzqiujiadi ashqalcn@gmail.com
*
* response for setup values and
* draw draw draw draw
*/
public interface IOwlPaint {
void draw(View view, Object value);
Object[] setup(View view, TypedArray a, int attr);
}
| 21.529412
| 54
| 0.724044
|
6d8af45f28293d634959bcec4b9eba2b8115d9d6
| 865
|
package eu.ha3.matmos.game.data.modules;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import eu.ha3.matmos.engine.core.interfaces.Data;
import eu.ha3.matmos.game.data.abstractions.module.Module;
import eu.ha3.matmos.game.data.abstractions.module.ModuleProcessor;
/*
--filenotes-placeholder
*/
public class M__ply_action extends ModuleProcessor implements Module
{
public M__ply_action(Data data)
{
super(data, "ply_action");
}
@Override
protected void doProcess()
{
EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
setValue("swing_progress16", (int) Math.floor(player.swingProgress * 16));
setValue("swinging", player.swingProgress != 0);
setValue("fall_distance1k", (int) (player.fallDistance * 1000));
setValue("item_use_duration", player.getItemInUseDuration());
}
}
| 27.903226
| 76
| 0.774566
|
a221ef5bac3d1b3b5c0ed2724d465e251ffa8635
| 2,767
|
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.DeviceManagementScriptDeviceState;
import com.microsoft.graph.models.Entity;
import com.microsoft.graph.requests.DeviceManagementScriptDeviceStateCollectionPage;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Device Management Script User State.
*/
public class DeviceManagementScriptUserState extends Entity implements IJsonBackedObject {
/**
* The Error Device Count.
* Error device count for specific user.
*/
@SerializedName(value = "errorDeviceCount", alternate = {"ErrorDeviceCount"})
@Expose
@Nullable
public Integer errorDeviceCount;
/**
* The Success Device Count.
* Success device count for specific user.
*/
@SerializedName(value = "successDeviceCount", alternate = {"SuccessDeviceCount"})
@Expose
@Nullable
public Integer successDeviceCount;
/**
* The User Principal Name.
* User principle name of specific user.
*/
@SerializedName(value = "userPrincipalName", alternate = {"UserPrincipalName"})
@Expose
@Nullable
public String userPrincipalName;
/**
* The Device Run States.
* List of run states for this script across all devices of specific user.
*/
@SerializedName(value = "deviceRunStates", alternate = {"DeviceRunStates"})
@Expose
@Nullable
public DeviceManagementScriptDeviceStateCollectionPage deviceRunStates;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
if (json.has("deviceRunStates")) {
deviceRunStates = serializer.deserializeObject(json.get("deviceRunStates"), DeviceManagementScriptDeviceStateCollectionPage.class);
}
}
}
| 33.743902
| 152
| 0.693531
|
03871ec39f0502fe09f33796776d323968967ca0
| 15,190
|
package org.ihtsdo.termserver.scripting.template;
import java.io.IOException;
import java.util.*;
import org.snomed.authoringtemplate.domain.ConceptTemplate;
import org.snomed.authoringtemplate.domain.logical.*;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.ihtsdo.otf.rest.client.terminologyserver.pojo.Component;
import org.ihtsdo.otf.rest.client.terminologyserver.pojo.Task;
import org.ihtsdo.otf.utils.StringUtils;
import org.ihtsdo.otf.exception.TermServerScriptException;
import org.ihtsdo.termserver.scripting.TermServerScript;
import org.ihtsdo.termserver.scripting.client.TemplateServiceClient;
import org.ihtsdo.termserver.scripting.domain.*;
import org.ihtsdo.termserver.scripting.fixes.BatchFix;
import org.ihtsdo.termserver.scripting.util.SnomedUtils;
abstract public class TemplateFix extends BatchFix {
protected Set<Concept> exclusions;
protected List<String> exclusionWords;
protected List<String> inclusionWords;
protected boolean includeComplexTemplates = true;
protected boolean includeOrphanet = true;
protected List<Concept> complexTemplateAttributes;
protected boolean includeDueTos = false;
protected boolean excludeSdMultiRG = false;
protected Set<Concept> explicitExclusions;
String[] templateNames;
List<Template> templates = new ArrayList<>();
TemplateServiceClient tsc = new TemplateServiceClient(null, null);
Map<Concept, Template> conceptToTemplateMap = new HashMap<>();
protected TemplateFix(BatchFix clone) {
super(clone);
}
protected void init(String[] args) throws TermServerScriptException {
if (args != null) {
super.init(args);
}
AttributeGroup.useDefaultValues = true;
//We'll check these now so we know if there's some parsing error
char id = 'A';
for (int x = 0; x < templateNames.length; x++, id++) {
Template t = loadLocalTemplate(id, templateNames[x]);
subsetECL = t.getDomain();
validateTemplate(t);
info ("Validated template: " + templateNames[x]);
}
}
public void postInit(String[] tabNames, String[] columnHeadings, boolean csvOutput) throws TermServerScriptException {
initTemplatesAndExclusions();
super.postInit(tabNames, columnHeadings, csvOutput);
info ("Post initialisation complete, with multiple tabs");
}
private void importExplicitExclusions() throws TermServerScriptException {
explicitExclusions = new HashSet<>();
print("Loading Explicit Exclusions " + inputFile + "...");
if (!inputFile.canRead()) {
throw new TermServerScriptException("Cannot read: " + inputFile);
}
List<String> lines;
try {
lines = Files.readLines(inputFile, Charsets.UTF_8);
} catch (IOException e) {
throw new TermServerScriptException("Failure while reading: " + inputFile, e);
}
debug("Processing Explicit Exclusions File");
for (String line : lines) {
String sctId = line.split(TAB)[0];
Concept excluded = gl.getConcept(sctId, false, true); //Validate concept exists
explicitExclusions.add(excluded);
}
addSummaryInformation("Explicitly excluded concepts specified", explicitExclusions.size());
}
public void postInit() throws TermServerScriptException {
initTemplatesAndExclusions();
super.postInit();
info ("Post initialisation complete");
}
private void initTemplatesAndExclusions() throws TermServerScriptException {
if (subHierarchyStr != null) {
subHierarchy = gl.getConcept(subHierarchyStr);
}
//Only load templates now if we've not already done so
if (templates.isEmpty()) {
char id = 'A';
for (int x = 0; x < templateNames.length; x++, id++) {
Template t = loadLocalTemplate(id, templateNames[x]);
validateTemplate(t);
templates.add(t);
info ("Loaded template: " + t);
if (StringUtils.isEmpty(subsetECL)) {
subsetECL = t.getDomain();
info("Subset ECL set to " + subsetECL);
}
}
info(templates.size() + " Templates loaded successfully");
}
if (exclusions == null) {
exclusions = new HashSet<>();
}
if (excludeHierarchies == null) {
excludeHierarchies = new String[] {};
}
for (String thisExclude : excludeHierarchies) {
info("Setting exclusion of " + thisExclude + " subHierarchy.");
exclusions.addAll(gl.getConcept(thisExclude).getDescendents(NOT_SET));
}
//Note add words as lower case as we do all lower case matching
if (exclusionWords == null) {
exclusionWords = new ArrayList<>();
}
if (inputFile != null) {
importExplicitExclusions();
}
if (!includeComplexTemplates) {
if (!includeDueTos) {
exclusionWords.add("due to");
}
exclusionWords.add("co-occurrent");
exclusionWords.add("on examination");
exclusionWords.add("complex");
exclusionWords.add("associated");
exclusionWords.add("after");
exclusionWords.add("complication");
exclusionWords.add("with");
exclusionWords.add("without");
} else {
warn ("Including complex templates");
}
complexTemplateAttributes = new ArrayList<>();
if (!includeDueTos) {
complexTemplateAttributes.add(DUE_TO);
}
complexTemplateAttributes.add(AFTER);
complexTemplateAttributes.add(gl.getConcept("726633004")); //|Temporally related to (attribute)|
complexTemplateAttributes.add(gl.getConcept("288556008")); //|Before (attribute)|
complexTemplateAttributes.add(gl.getConcept("371881003")); //|During (attribute)|
complexTemplateAttributes.add(gl.getConcept("363713009")); //|Has interpretation (attribute)|
complexTemplateAttributes.add(gl.getConcept("363714003")); //|Interprets (attribute)|
complexTemplateAttributes.add(gl.getConcept("47429007")); //|Associated with (attribute)
}
private void validateTemplate(Template t) throws TermServerScriptException {
//Is the Domain specified by the template valid? No point running if it selects no rows
boolean useLocalStoreIfSimple = false;
String ecl = t.getDomain();
if (!getArchiveManager().isAllowStaleData() && findConcepts(ecl, false, useLocalStoreIfSimple).size() == 0) {
throw new TermServerScriptException("Template domain: " + ecl + " returned 0 rows");
}
//Ensure that any repeated instances of identically named slots have the same value
Map<String, String> namedSlots = new HashMap<>();
for (AttributeGroup g : t.getAttributeGroups()) {
for (Attribute a : g.getAttributes()) {
//Does this attribute have a named slot?
if (!StringUtils.isEmpty(a.getValueSlotName())) {
String attributeClause = a.toString().replaceAll(" ", " ");
String attributeClauseValue = attributeClause.substring(attributeClause.indexOf("=") + 1).trim();
if (namedSlots.containsKey(a.getValueSlotName())) {
//TODO This comparison should be made without FSNs involved
if (!attributeClauseValue.equals(namedSlots.get(a.getValueSlotName()))) {
String first = attributeClauseValue;
String second = namedSlots.get(a.getValueSlotName());
String diff = StringUtils.difference(first, second);
String detail = a.getValueSlotName() + " -> " + first + " vs " + second + " difference is '" + diff + "'";
throw new IllegalArgumentException("Named slots sharing the same name must have identical slot definition: " + detail);
}
} else {
namedSlots.put(a.getValueSlotName(), attributeClauseValue);
}
}
}
}
}
protected Template loadLocalTemplate (char id, String fileName) throws TermServerScriptException {
try {
TermServerScript.info("Loading local template " + id + ": " + fileName );
ConceptTemplate ct = tsc.loadLocalConceptTemplate(fileName);
LogicalTemplate lt = tsc.parseLogicalTemplate(ct.getLogicalTemplate());
Template t = new Template(id, lt, fileName);
t.setDomain(ct.getDomain());
t.setDocumentation(ct.getDocumentation());
return t;
} catch (IOException e) {
throw new TermServerScriptException("Unable to load template " + fileName, e);
}
}
protected Template loadTemplate (char id, String templateName) throws TermServerScriptException {
try {
TermServerScript.info("Loading remote template " + id + ": " + templateName );
ConceptTemplate ct = tsc.loadLogicalTemplate(templateName);
LogicalTemplate lt = tsc.parseLogicalTemplate(ct.getLogicalTemplate());
Template t = new Template(id, lt, templateName);
t.setDomain(ct.getDomain());
t.setDocumentation(ct.getDocumentation());
return t;
} catch (IOException e) {
throw new TermServerScriptException("Unable to load template " + templateName, e);
}
}
protected Set<Concept> findTemplateMatches(Template t, Collection<Concept> concepts, Set<Concept> misalignedConcepts, Integer exclusionReport, CharacteristicType charType) throws TermServerScriptException {
Set<Concept> matches = new HashSet<Concept>();
info ("Examining " + concepts.size() + " concepts against template " + t);
int conceptsExamined = 0;
for (Concept c : concepts) {
if (!c.isActive()) {
warn ("Ignoring inactive concept returned by ECL: " + c);
continue;
}
if (!isExcluded(c, exclusionReport)) {
if (TemplateUtils.matchesTemplate(c, t, this, charType)) {
//Do we already have a template for this concept?
//Assign the most specific template if so (TODO Don't assume order indicates complexity!)
if (conceptToTemplateMap.containsKey(c)) {
Template existing = conceptToTemplateMap.get(c);
Template moreSpecific = t.getId() > existing.getId() ? t : existing;
warn( c + "matches two templates: " + t.getId() + " & " + existing.getId() + " using most specific " + moreSpecific.getId());
conceptToTemplateMap.put(c, moreSpecific);
} else {
conceptToTemplateMap.put(c, t);
}
matches.add(c);
} else {
if (misalignedConcepts != null) {
misalignedConcepts.add(c);
}
}
} else {
//Only count exclusions for the first pass
if (t.getId() == 'A') {
incrementSummaryInformation("Concepts excluded");
}
}
if (++conceptsExamined % 1000 == 0) {
print(".");
}
}
println("");
addSummaryInformation("Concepts in \"" + t.getDomain() + "\" matching template " + t.getId(), matches.size());
return matches;
}
protected boolean isExcluded(Concept c, Integer exclusionReport) throws TermServerScriptException {
//These hierarchies have been excluded
if (exclusions.contains(c)) {
if (exclusionReport != null) {
incrementSummaryInformation("Concepts excluded due to hierarchial exclusion");
report (exclusionReport, c, "Hierarchial exclusion");
}
return true;
}
//Are we excluding sufficiently defined concepts with more than one substantial role group?
if (excludeSdMultiRG && c.getDefinitionStatus().equals(DefinitionStatus.FULLY_DEFINED)) {
boolean firstSubstantialRGDetected = false;
for (RelationshipGroup g : c.getRelationshipGroups(CharacteristicType.INFERRED_RELATIONSHIP)) {
if (g.size() > 1) {
if (firstSubstantialRGDetected) {
//So we're now on our 2nd one
if (exclusionReport != null) {
incrementSummaryInformation("Concepts excluded due to SD with multiple substantial role groups");
report (exclusionReport, c, "Multi-RG exclusion");
}
return true;
} else {
firstSubstantialRGDetected = true;
}
}
}
}
if (!includeOrphanet && gl.isOrphanetConcept(c)) {
if (exclusionReport != null) {
incrementSummaryInformation("Orphanet concepts excluded");
report (exclusionReport, c, "Orphanet exclusion");
}
return true;
}
if (StringUtils.isEmpty(c.getFsn())) {
if (exclusionReport != null) {
warn("Skipping concept with no FSN: " + c.getConceptId());
report (exclusionReport, c, "No FSN");
}
return true;
}
//We could ignore on the basis of a word, or SCTID
String fsn = " " + c.getFsn().toLowerCase();
String pt = " " + c.getPreferredSynonym().toLowerCase();
for (String word : exclusionWords) {
if (fsn.contains(word) || pt.contains(word)) {
if (exclusionReport != null) {
incrementSummaryInformation("Concepts excluded due to lexical match ");
incrementSummaryInformation("Concepts excluded due to lexical match (" + word + ")");
report (exclusionReport, c, "Lexical exclusion", word);
}
return true;
}
}
if (inclusionWords.size() > 0 && !containsInclusionWord(c)) {
incrementSummaryInformation("Concepts excluded due to lexical match failure");
report (exclusionReport, c, "Lexical inclusion failure");
return true;
}
//We're excluding complex templates that have a due to, or "after" attribute
if (!includeComplexTemplates && isComplex(c)) {
if (exclusionReport != null) {
incrementSummaryInformation("Concepts excluded due to complexity");
report (exclusionReport, c, "Complex templates excluded");
}
return true;
}
return false;
}
protected boolean isComplex(Concept c) {
for (Concept excludedType : complexTemplateAttributes) {
for (Relationship r : c.getRelationships(CharacteristicType.INFERRED_RELATIONSHIP, ActiveState.ACTIVE)) {
if (r.getType().equals(excludedType)) {
return true;
}
}
}
return false;
}
@Override
public void report (Task task, Component component, Severity severity, ReportActionType actionType, Object... details) throws TermServerScriptException {
Concept c = (Concept)component;
char relevantTemplate = ' ';
if (conceptToTemplateMap != null && conceptToTemplateMap.containsKey(c)) {
relevantTemplate = conceptToTemplateMap.get(c).getId();
}
super.report (task, component, severity, actionType, SnomedUtils.translateDefnStatus(c.getDefinitionStatus()), relevantTemplate, details);
}
protected boolean containsInclusionWord(Concept c) {
String fsn = c.getFsn().toLowerCase();
String pt = c.getPreferredSynonym().toLowerCase();
for (String word : inclusionWords) {
if (fsn.contains(word) || pt.contains(word)) {
return true;
}
}
return false;
}
protected void outputMetaData() throws TermServerScriptException {
info("Outputting metadata tab");
String user = jobRun == null ? "System" : jobRun.getUser();
writeToReportFile (SECONDARY_REPORT, "Requested by: " + user);
writeToReportFile (SECONDARY_REPORT, QUOTE + "Run against: " + subsetECL + QUOTE);
writeToReportFile (SECONDARY_REPORT, "Project: " + project);
if (!StringUtils.isEmpty(subsetECL)) {
writeToReportFile (SECONDARY_REPORT, "Concepts considered: " + findConcepts(subsetECL).size());
}
writeToReportFile (SECONDARY_REPORT, "Templates: " );
for (Template t : templates) {
writeToReportFile (SECONDARY_REPORT,TAB + "Name: " + t.getName());
writeToReportFile (SECONDARY_REPORT,QUOTE + TAB + "Domain: " + t.getDomain() + QUOTE);
writeToReportFile (SECONDARY_REPORT,TAB + "Documentation: " + t.getDocumentation());
String stl = t.getLogicalTemplate().toString();
stl = SnomedUtils.populateFSNs(stl);
writeToReportFile (SECONDARY_REPORT,QUOTE + TAB + "STL: " + stl + QUOTE);
if (!StringUtils.isEmpty(t.getDomain())) {
writeToReportFile (SECONDARY_REPORT, TAB + "Concepts considered: " + findConcepts(t.getDomain()).size());
}
writeToReportFile (SECONDARY_REPORT,TAB);
}
}
}
| 37.321867
| 207
| 0.7079
|
6bf8658343e9a25f917eda9f4dfa539c74170cc7
| 6,435
|
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.logging;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.MoreObjects;
import com.google.logging.v2.LogMetric;
import java.io.Serializable;
import java.util.Objects;
/**
* Cloud Logging metrics describe logs-based metric. The value of the metric is the number of
* log entries that match a logs filter (see {@link #getFilter()}).
*
* @see <a href="https://cloud.google.com/logging/docs/view/logs_based_metrics">Logs-based Metrics
* </a>
*/
public class MetricInfo implements Serializable {
private static final long serialVersionUID = 666208243838820325L;
private final String name;
private final String description;
private final String filter;
/** A builder for {@code MetricInfo} objects. */
public abstract static class Builder {
Builder() {}
/**
* Sets the name of the metric. Example: {@code severe-errors}. Metric identifiers are limited
* to 1000 characters and can include only the following characters: {@code A-Z}, {@code a-z},
* {@code 0-9}, and the special characters {@code _-.,+!*',()%/\}. The forward-slash character
* ({@code /}) denotes a hierarchy of name pieces, and it cannot be the first character of the
* name.
*/
public abstract Builder setName(String name);
/** Sets an optional description for this metric. Used for documentation purpose. */
public abstract Builder setDescription(String description);
/**
* Sets an advanced logs filter. The value of the metric is the number of log entries that match
* this filter. Example: {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
*
* @see <a href="https://cloud.google.com/logging/docs/view/advanced_filters">Advanced Log
* Filters</a>
*/
public abstract Builder setFilter(String filter);
/** Creates a {@code MetricInfo} object for this builder. */
public abstract MetricInfo build();
}
static final class BuilderImpl extends Builder {
private String name;
private String description;
private String filter;
BuilderImpl(String name, String filter) {
this.name = name;
this.filter = filter;
}
BuilderImpl(MetricInfo metric) {
this.name = metric.name;
this.description = metric.description;
this.filter = metric.filter;
}
@Override
public Builder setName(String name) {
this.name = name;
return this;
}
@Override
public Builder setDescription(String description) {
this.description = description;
return this;
}
@Override
public Builder setFilter(String filter) {
this.filter = filter;
return this;
}
@Override
public MetricInfo build() {
return new MetricInfo(this);
}
}
MetricInfo(BuilderImpl builder) {
this.name = checkNotNull(builder.name);
this.filter = checkNotNull(builder.filter);
this.description = builder.description;
}
/**
* Returns the name of the metric. Example: {@code severe-errors}. Metric identifiers are limited
* to 1000 characters and can include only the following characters: {@code A-Z}, {@code a-z},
* {@code 0-9}, and the special characters {@code _-.,+!*',()%/\}. The forward-slash character
* ({@code /}) denotes a hierarchy of name pieces, and it cannot be the first character of the
* name.
*/
public String getName() {
return name;
}
/** Returns an optional description for this metric. Used for documentation purpose. */
public String getDescription() {
return description;
}
/**
* Returns an advanced logs filter. The value of the metric is the number of log entries that
* match this filter. Example: {@code logName=projects/my-projectid/logs/syslog AND
* severity>=ERROR}.
*
* @see <a href="https://cloud.google.com/logging/docs/view/advanced_filters">Advanced Log
* Filters</a>
*/
public String getFilter() {
return filter;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("description", description)
.add("filter", filter)
.toString();
}
final boolean baseEquals(MetricInfo metricInfo) {
return Objects.equals(name, metricInfo.name)
&& Objects.equals(description, metricInfo.description)
&& Objects.equals(filter, metricInfo.filter);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !(obj.getClass().equals(MetricInfo.class))) {
return false;
}
return baseEquals((MetricInfo) obj);
}
@Override
public int hashCode() {
return Objects.hash(name, description, filter);
}
/** Returns a builder for this {@code MetricInfo} object. */
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* Returns a builder for {@code MetricInfo} objects given the name of the metric and its filter.
*/
public static Builder newBuilder(String name, String filter) {
return new BuilderImpl(name, filter);
}
/** Creates a {@code MetricInfo} object given the name of the metric and its filter. */
public static MetricInfo of(String name, String filter) {
return new BuilderImpl(name, filter).build();
}
LogMetric toPb() {
LogMetric.Builder builder = LogMetric.newBuilder().setName(name).setFilter(filter);
if (description != null) {
builder.setDescription(description);
}
return builder.build();
}
static MetricInfo fromPb(LogMetric metricPb) {
Builder builder = newBuilder(metricPb.getName(), metricPb.getFilter());
if (!metricPb.getDescription().equals("")) {
builder.setDescription(metricPb.getDescription());
}
return builder.build();
}
}
| 30.642857
| 100
| 0.679254
|
948fd74722d6f0f6a08afa2a164578f1d0685fdb
| 533
|
package org.prosolo.services.assessment.data.grading;
/**
* @author stefanvuckovic
* @date 2018-01-17
* @since 1.2.0
*/
public interface GradeDataVisitor<T> {
T visit(ManualSimpleGradeData gradeData);
T visit(AutomaticGradeData gradeData);
T visit(ExternalToolAutoGradeData gradeData);
T visit(CompletionAutoGradeData gradeData);
T visit(NongradedGradeData gradeData);
T visit(RubricGradeData gradeData);
T visit(DescriptiveRubricGradeData gradeData);
T visit(PointRubricGradeData gradeData);
}
| 28.052632
| 53
| 0.757974
|
31d3ac405495d9a9772cfab73035a88c02d1b5ec
| 2,466
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.example.plasma;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.Display;
import android.view.WindowManager;
public class Plasma extends Activity {
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
Log.i("Plasma", displaySize.toString());
setContentView(new PlasmaView(this, displaySize.x, displaySize.y));
}
// load our native library
static {
System.loadLibrary("plasma");
}
}
// Custom view for rendering plasma.
// Note: suppressing lint warning for ViewConstructor since it is
// manually set from the activity and not used in any layout.
@SuppressLint("ViewConstructor")
class PlasmaView extends View {
private Bitmap mBitmap;
private long mStartTime;
// implemented by libPlasma.so
private static native void renderPlasma(Bitmap bitmap, long time_ms);
public PlasmaView(Context context, int width, int height) {
super(context);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Log.i("bitmaptest", mBitmap.getWidth() + " | " + mBitmap.getHeight());
mStartTime = System.currentTimeMillis();
}
@Override
protected void onDraw(Canvas canvas) {
renderPlasma(mBitmap, System.currentTimeMillis() - mStartTime);
canvas.drawBitmap(mBitmap, 0, 0, null);
Log.i("bitmaptest", mBitmap.getWidth() + " | " + mBitmap.getHeight());
// force a redraw, with a different time-based pattern.
invalidate();
}
}
| 32.88
| 75
| 0.751014
|
e547d8ea2f79555f964bead1296b63494e42b8e9
| 1,133
|
package com.unascribed.yttr.network;
import com.unascribed.yttr.client.particle.VoidBallParticle;
import com.unascribed.yttr.init.YNetwork;
import com.unascribed.yttr.network.concrete.NetworkContext;
import com.unascribed.yttr.network.concrete.S2CMessage;
import com.unascribed.yttr.network.concrete.annotation.field.MarshalledAs;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
public class MessageS2CVoidBall extends S2CMessage {
@MarshalledAs("f32")
public float x;
@MarshalledAs("f32")
public float y;
@MarshalledAs("f32")
public float z;
@MarshalledAs("f32")
public float r;
public MessageS2CVoidBall(NetworkContext ctx) {
super(ctx);
}
public MessageS2CVoidBall(float x, float y, float z, float r) {
super(YNetwork.CONTEXT);
this.x = x;
this.y = y;
this.z = z;
this.r = r;
}
@Override
@Environment(EnvType.CLIENT)
protected void handle(MinecraftClient mc, ClientPlayerEntity player) {
mc.particleManager.addParticle(new VoidBallParticle(mc.world, x, y, z, r));
}
}
| 26.348837
| 77
| 0.772286
|
e9c6ad07c0f4b71990992b9b05ce7ae6c309e9c8
| 7,200
|
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.releng.generators;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.io.File;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @version 1.0
* @author
*/
public class ErrorTracker {
// List of test logs expected at end of build
private Vector testLogs = new Vector();
// Platforms keyed on
private Hashtable platforms = new Hashtable();
private Hashtable logFiles = new Hashtable();
private Hashtable typesMap = new Hashtable();
private Vector typesList = new Vector();
public static void main(String[] args) {
// For testing only. Should not be invoked
ErrorTracker anInstance = new ErrorTracker();
anInstance.loadFile("C:\\junk\\testManifest.xml");
String[] theTypes = anInstance.getTypes();
for (int i=0; i < theTypes.length; i++) {
// System.out.println("Type: " + theTypes[i]);
PlatformStatus[] thePlatforms = anInstance.getPlatforms(theTypes[i]);
for (int j=0; j < thePlatforms.length; j++) {
// System.out.println("Out ID: " + thePlatforms[j].getId());
}
}
}
public void loadFile(String fileName) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser=null;
try {
parser = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
}
try {
Document document = parser.parse(fileName);
NodeList elements = document.getElementsByTagName("platform");
int elementCount = elements.getLength();
for (int i = 0; i < elementCount; i++) {
PlatformStatus aPlatform = new PlatformStatus((Element) elements.item(i));
//System.out.println("ID: " + aPlatform.getId());
platforms.put(aPlatform.getId(), aPlatform);
Node zipType = elements.item(i).getParentNode();
String zipTypeName = (String) zipType.getAttributes().getNamedItem("name").getNodeValue();
Vector aVector = (Vector) typesMap.get(zipTypeName);
if (aVector == null) {
typesList.add(zipTypeName);
aVector = new Vector();
typesMap.put(zipTypeName, aVector);
}
aVector.add(aPlatform.getId());
}
NodeList effectedFiles = document.getElementsByTagName("effectedFile");
int effectedFilesCount = effectedFiles.getLength();
for (int i = 0; i < effectedFilesCount; i++) {
Node anEffectedFile = effectedFiles.item(i);
Node logFile = anEffectedFile.getParentNode();
String logFileName = (String) logFile.getAttributes().getNamedItem("name").getNodeValue();
logFileName=convertPathDelimiters(logFileName);
String effectedFileID = (String) anEffectedFile.getAttributes().getNamedItem("id").getNodeValue();
//System.out.println(logFileName);
Vector aVector = (Vector) logFiles.get(logFileName);
if (aVector == null) {
aVector = new Vector();
logFiles.put(logFileName, aVector);
}
PlatformStatus ps=(PlatformStatus) platforms.get(effectedFileID);
if (ps!=null)
aVector.addElement(ps);
}
// store a list of the test logs expected after testing
NodeList testLogList = document.getElementsByTagName("logFile");
int testLogCount = testLogList.getLength();
for (int i = 0; i < testLogCount; i++) {
Node testLog = testLogList.item(i);
String testLogName = (String) testLog.getAttributes().getNamedItem("name").getNodeValue();
Node typeNode=testLog.getAttributes().getNamedItem("type");
String type="test";
if (typeNode!=null){
type = typeNode.getNodeValue();
}
if (testLogName.endsWith(".xml")&&type.equals("test")){
testLogs.add(testLogName);
//System.out.println(testLogName);
}
}
// // Test this mess.
// Object[] results = platforms.values().toArray();
// for (int i=0; i < results.length; i++) {
// PlatformStatus ap = (PlatformStatus) results[i];
// System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed());
// }
//
// Enumeration anEnumeration = logFiles.keys();
// while (anEnumeration.hasMoreElements()) {
// String aKey = (String) anEnumeration.nextElement();
// System.out.println("Whack a key: " + aKey);
// ((PlatformStatus) logFiles.get(aKey)).setPassed(false);
// }
//
// results = platforms.values().toArray();
// for (int i=0; i < results.length; i++) {
// PlatformStatus ap = (PlatformStatus) results[i];
// System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed());
// }
} catch (IOException e) {
System.out.println("IOException: " + fileName);
// e.printStackTrace();
} catch (SAXException e) {
System.out.println("SAXException: " + fileName);
e.printStackTrace();
}
}
public void registerError(String fileName) {
// System.out.println("Found an error in: " + fileName);
if (logFiles.containsKey(fileName)) {
Vector aVector = (Vector) logFiles.get(fileName);
for (int i = 0; i < aVector.size(); i++) {
((PlatformStatus) aVector.elementAt(i)).registerError();
}
} else {
// If a log file is not specified explicitly it effects
// all "platforms" except JDT
Enumeration values = platforms.elements();
while (values.hasMoreElements()) {
PlatformStatus aValue = (PlatformStatus) values.nextElement();
if (!aValue.getId().equals("JA") &&
!aValue.getId().equals("EW") &&
!aValue.getId().equals("EA")) {
aValue.registerError();
}
}
}
}
public boolean hasErrors(String id) {
return ((PlatformStatus) platforms.get(id)).hasErrors();
}
// Answer a string array of the zip type names in the order they appear in
// the .xml file.
public String[] getTypes() {
return (String[]) typesList.toArray(new String[typesList.size()]);
}
// Answer an array of PlatformStatus objects for a given type.
public PlatformStatus[] getPlatforms(String type) {
Vector platformIDs = (Vector) typesMap.get(type);
PlatformStatus[] result = new PlatformStatus[platformIDs.size()];
for (int i = 0; i < platformIDs.size(); i++) {
result[i] = (PlatformStatus) platforms.get((String) platformIDs.elementAt(i));
}
return result;
}
/**
* Returns the testLogs.
* @return Vector
*/
public Vector getTestLogs() {
return testLogs;
}
private String convertPathDelimiters(String path){
return new File(path).getPath();
}
}
| 32
| 106
| 0.660694
|
a39781258c8294744eb166d772d6ec1c9d97b184
| 10,330
|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2002-2018 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jsch;
public class KeyPairDSA extends KeyPair{
private byte[] P_array;
private byte[] Q_array;
private byte[] G_array;
private byte[] pub_array;
private byte[] prv_array;
//private int key_size=0;
private int key_size=1024;
public KeyPairDSA(JSch jsch){
this(jsch, null, null, null, null, null);
}
public KeyPairDSA(JSch jsch,
byte[] P_array,
byte[] Q_array,
byte[] G_array,
byte[] pub_array,
byte[] prv_array){
super(jsch);
this.P_array = P_array;
this.Q_array = Q_array;
this.G_array = G_array;
this.pub_array = pub_array;
this.prv_array = prv_array;
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
}
void generate(int key_size) throws JSchException{
this.key_size=key_size;
try{
Class c=Class.forName(jsch.getConfig("keypairgen.dsa"));
KeyPairGenDSA keypairgen=(KeyPairGenDSA)(c.newInstance());
keypairgen.init(key_size);
P_array=keypairgen.getP();
Q_array=keypairgen.getQ();
G_array=keypairgen.getG();
pub_array=keypairgen.getY();
prv_array=keypairgen.getX();
keypairgen=null;
}
catch(Exception e){
//System.err.println("KeyPairDSA: "+e);
if(e instanceof Throwable)
throw new JSchException(e.toString(), (Throwable)e);
throw new JSchException(e.toString());
}
}
private static final byte[] begin=Util.str2byte("-----BEGIN DSA PRIVATE KEY-----");
private static final byte[] end=Util.str2byte("-----END DSA PRIVATE KEY-----");
byte[] getBegin(){ return begin; }
byte[] getEnd(){ return end; }
byte[] getPrivateKey(){
int content=
1+countLength(1) + 1 + // INTEGER
1+countLength(P_array.length) + P_array.length + // INTEGER P
1+countLength(Q_array.length) + Q_array.length + // INTEGER Q
1+countLength(G_array.length) + G_array.length + // INTEGER G
1+countLength(pub_array.length) + pub_array.length + // INTEGER pub
1+countLength(prv_array.length) + prv_array.length; // INTEGER prv
int total=
1+countLength(content)+content; // SEQUENCE
byte[] plain=new byte[total];
int index=0;
index=writeSEQUENCE(plain, index, content);
index=writeINTEGER(plain, index, new byte[1]); // 0
index=writeINTEGER(plain, index, P_array);
index=writeINTEGER(plain, index, Q_array);
index=writeINTEGER(plain, index, G_array);
index=writeINTEGER(plain, index, pub_array);
index=writeINTEGER(plain, index, prv_array);
return plain;
}
boolean parse(byte[] plain){
try{
if(vendor==VENDOR_FSECURE){
if(plain[0]!=0x30){ // FSecure
Buffer buf=new Buffer(plain);
buf.getInt();
P_array=buf.getMPIntBits();
G_array=buf.getMPIntBits();
Q_array=buf.getMPIntBits();
pub_array=buf.getMPIntBits();
prv_array=buf.getMPIntBits();
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
return true;
}
return false;
}
else if(vendor==VENDOR_PUTTY){
Buffer buf=new Buffer(plain);
buf.skip(plain.length);
try {
byte[][] tmp = buf.getBytes(1, "");
prv_array = tmp[0];
}
catch(JSchException e){
return false;
}
return true;
}
int index=0;
int length=0;
if(plain[index]!=0x30)return false;
index++; // SEQUENCE
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
if(plain[index]!=0x02)return false;
index++; // INTEGER
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
P_array=new byte[length];
System.arraycopy(plain, index, P_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
Q_array=new byte[length];
System.arraycopy(plain, index, Q_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
G_array=new byte[length];
System.arraycopy(plain, index, G_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
pub_array=new byte[length];
System.arraycopy(plain, index, pub_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
prv_array=new byte[length];
System.arraycopy(plain, index, prv_array, 0, length);
index+=length;
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
}
catch(Exception e){
//System.err.println(e);
//e.printStackTrace();
return false;
}
return true;
}
public byte[] getPublicKeyBlob(){
byte[] foo=super.getPublicKeyBlob();
if(foo!=null) return foo;
if(P_array==null) return null;
byte[][] tmp = new byte[5][];
tmp[0] = sshdss;
tmp[1] = P_array;
tmp[2] = Q_array;
tmp[3] = G_array;
tmp[4] = pub_array;
return Buffer.fromBytes(tmp).buffer;
}
private static final byte[] sshdss=Util.str2byte("ssh-dss");
byte[] getKeyTypeName(){return sshdss;}
public int getKeyType(){return DSA;}
public int getKeySize(){
return key_size;
}
public byte[] getSignature(byte[] data){
try{
Class c=Class.forName((String)jsch.getConfig("signature.dss"));
SignatureDSA dsa=(SignatureDSA)(c.newInstance());
dsa.init();
dsa.setPrvKey(prv_array, P_array, Q_array, G_array);
dsa.update(data);
byte[] sig = dsa.sign();
byte[][] tmp = new byte[2][];
tmp[0] = sshdss;
tmp[1] = sig;
return Buffer.fromBytes(tmp).buffer;
}
catch(Exception e){
//System.err.println("e "+e);
}
return null;
}
public byte[] getSignature(byte[] data, String alg){
return getSignature(data);
}
public Signature getVerifier(){
try{
Class c=Class.forName((String)jsch.getConfig("signature.dss"));
SignatureDSA dsa=(SignatureDSA)(c.newInstance());
dsa.init();
if(pub_array == null && P_array == null && getPublicKeyBlob()!=null){
Buffer buf = new Buffer(getPublicKeyBlob());
buf.getString();
P_array = buf.getString();
Q_array = buf.getString();
G_array = buf.getString();
pub_array = buf.getString();
}
dsa.setPubKey(pub_array, P_array, Q_array, G_array);
return dsa;
}
catch(Exception e){
//System.err.println("e "+e);
}
return null;
}
public Signature getVerifier(String alg){
return getVerifier();
}
static KeyPair fromSSHAgent(JSch jsch, Buffer buf) throws JSchException {
byte[][] tmp = buf.getBytes(7, "invalid key format");
byte[] P_array = tmp[1];
byte[] Q_array = tmp[2];
byte[] G_array = tmp[3];
byte[] pub_array = tmp[4];
byte[] prv_array = tmp[5];
KeyPairDSA kpair = new KeyPairDSA(jsch,
P_array, Q_array, G_array,
pub_array, prv_array);
kpair.publicKeyComment = new String(tmp[6]);
kpair.vendor=VENDOR_OPENSSH;
return kpair;
}
public byte[] forSSHAgent() throws JSchException {
if(isEncrypted()){
throw new JSchException("key is encrypted.");
}
Buffer buf = new Buffer();
buf.putString(sshdss);
buf.putString(P_array);
buf.putString(Q_array);
buf.putString(G_array);
buf.putString(pub_array);
buf.putString(prv_array);
buf.putString(Util.str2byte(publicKeyComment));
byte[] result = new byte[buf.getLength()];
buf.getByte(result, 0, result.length);
return result;
}
public void dispose(){
super.dispose();
Util.bzero(prv_array);
}
}
| 30.293255
| 85
| 0.620716
|
f1439eb0dbe3f0f9b484d80be43ab007f43a626f
| 5,560
|
package com.alibaba.ververica.connectors.hologres.api.table;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.GenericArrayData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
import com.alibaba.ververica.connectors.hologres.utils.PostgresTypeUtil;
import java.io.Serializable;
import java.sql.Types;
/** An interface to transform other data type T to RowData. */
public interface RowDataReader<T> extends Serializable {
static <T> RowDataReader.FieldReader<T> createFieldReader(
LogicalType fieldType,
int hologresType,
String hologresTypeName,
RowDataReader<T> rowDataReader,
int index) {
switch (hologresType) {
case Types.CHAR:
case Types.VARCHAR:
return (obj) -> rowDataReader.readString(obj, index);
case Types.BIT:
case Types.BOOLEAN:
return (obj) -> rowDataReader.readBoolean(obj, index);
case Types.BINARY:
case Types.VARBINARY:
return (obj) -> rowDataReader.readBinary(obj, index);
case Types.NUMERIC:
case Types.DECIMAL:
int decimalPrecision = LogicalTypeChecks.getPrecision(fieldType);
int decimalScale = LogicalTypeChecks.getScale(fieldType);
return (obj) ->
rowDataReader.readDecimal(obj, index, decimalPrecision, decimalScale);
case Types.TINYINT:
return (obj) -> rowDataReader.readByte(obj, index);
case Types.SMALLINT:
return (obj) -> rowDataReader.readShort(obj, index);
case Types.INTEGER:
return (obj) -> rowDataReader.readInt(obj, index);
case Types.DATE:
return (obj) -> rowDataReader.readDate(obj, index);
case Types.BIGINT:
return (obj) -> rowDataReader.readLong(obj, index);
case Types.REAL:
case Types.FLOAT:
return (obj) -> rowDataReader.readFloat(obj, index);
case Types.DOUBLE:
return (obj) -> rowDataReader.readDouble(obj, index);
case Types.TIMESTAMP:
if (hologresTypeName.equals(PostgresTypeUtil.PG_TIMESTAMPTZ)) {
return (obj) -> rowDataReader.readTimestamptz(obj, index);
} else {
return (obj) -> rowDataReader.readTimestamptz(obj, index);
}
case Types.TIMESTAMP_WITH_TIMEZONE:
return (obj) -> rowDataReader.readTimestamptz(obj, index);
case Types.ARRAY:
return createArrayFieldReader(fieldType, hologresTypeName, rowDataReader, index);
case Types.OTHER:
return (obj) -> rowDataReader.readObject(obj, index);
default:
throw new IllegalArgumentException(
String.format(
"Hologres sink does not support data type %s for now", fieldType));
}
}
static <T> RowDataReader.FieldReader<T> createArrayFieldReader(
LogicalType fieldType,
String hologresTypeName,
RowDataReader<T> rowDataReader,
int index) {
switch (hologresTypeName) {
case "_bool":
return (obj) -> rowDataReader.readBooleanArray(obj, index);
case "_int4":
return (obj) -> rowDataReader.readIntArray(obj, index);
case "_int8":
return (obj) -> rowDataReader.readLongArray(obj, index);
case "_float8":
return (obj) -> rowDataReader.readDoubleArray(obj, index);
case "_float4":
return (obj) -> rowDataReader.readFloatArray(obj, index);
case "_varchar":
case "_text":
return (obj) -> rowDataReader.readStringArray(obj, index);
default:
throw new UnsupportedOperationException(
"Hologres does not support array type " + hologresTypeName);
}
}
void checkHologresTypeSupported(int hologresType, String typeName);
Boolean readBoolean(T record, int index);
Byte readByte(T record, int index);
Short readShort(T record, int index);
Integer readInt(T record, int index);
Float readFloat(T record, int index);
Double readDouble(T record, int index);
StringData readString(T record, int index);
Integer readDate(T record, int index);
Long readLong(T record, int index);
TimestampData readTimestamptz(T record, int index);
TimestampData readTimestamp(T record, int index);
Object readObject(T record, int index);
byte[] readBinary(T record, int index);
DecimalData readDecimal(T record, int index, int decimalPrecision, int decimalScale);
GenericArrayData readIntArray(T record, int index);
GenericArrayData readLongArray(T record, int index);
GenericArrayData readFloatArray(T record, int index);
GenericArrayData readDoubleArray(T record, int index);
GenericArrayData readBooleanArray(T record, int index);
GenericArrayData readStringArray(T record, int index);
/** FieldReader. */
interface FieldReader<T> extends Serializable {
Object readValue(T value);
}
}
| 38.344828
| 99
| 0.618345
|
4a1453ae456893f5196b42318ebb42b03724e405
| 2,053
|
package seedu.sugarmummy.model.recmf;
import static java.util.Objects.requireNonNull;
import static seedu.sugarmummy.commons.util.AppUtil.checkArgument;
/**
* Represents the name of <code>Food</code> in the recommended food list. Guarantees: immutable; is valid as declared in
* {@link #isValidName(String)}
*/
public class FoodName implements Comparable<FoodName> {
public static final String MESSAGE_CONSTRAINTS = "Names should only contain alphabets, numbers, and whitespace. "
+ "It should not be blank or longer than 30 characters";
/*
* The first character of the food must not be a whitespace,
* otherwise " " (a blank string) becomes a valid input.
*/
private static final String VALIDATION_REGEX = "[\\p{Alnum}][\\p{Alnum} ]*";
public final String foodName;
/**
* Constructs a {@code FoodName}.
*
* @param foodName a valid food name
*/
public FoodName(String foodName) {
requireNonNull(foodName);
checkArgument(isValidName(foodName), MESSAGE_CONSTRAINTS);
this.foodName = foodName;
}
/**
* Returns true if a given string is a valid food name. A name is considered valid if it does not contain special
* characters and its length is less than 30 characters.
*/
public static boolean isValidName(String test) {
return test.matches(VALIDATION_REGEX) && test.length() <= 30;
}
public String getFoodName() {
return foodName;
}
@Override
public String toString() {
return foodName;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof FoodName)) {
return false;
}
return foodName.equalsIgnoreCase(((FoodName) other).foodName);
}
@Override
public int hashCode() {
return foodName.hashCode();
}
@Override
public int compareTo(FoodName another) {
return foodName.compareTo(another.foodName);
}
}
| 28.513889
| 120
| 0.646858
|
72c1e38f113d46ceeb87fd7a97bcce571cbbb564
| 186
|
package ro.ovidiuconeaac.businesslayer.beans;
import ro.ovidiuconeac.models.Sweet;
/**
* Created by ovidiu on 2/7/17.
*/
public interface SweetsBean {
Sweet getRandomSweet();
}
| 15.5
| 45
| 0.731183
|
6ec64549af6d5fa83d7f4a55c69b83b8df9d5bf4
| 411
|
package com.zype.android.webapi.events.plan;
import com.zype.android.webapi.RequestTicket;
import com.zype.android.webapi.events.DataEvent;
import com.zype.android.webapi.model.plan.PlanResponse;
/**
* Created by Evgeny Cherkasov on 22.06.2018
*/
public class PlanEvent extends DataEvent<PlanResponse> {
public PlanEvent(RequestTicket ticket, PlanResponse data) {
super(ticket, data);
}
}
| 24.176471
| 63
| 0.756691
|
646160e4edb50121b3612e949e94bb5b23f4a7a7
| 2,907
|
package org.qbit.messanger.userservice.web;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.qbit.messanger.userservice.converter.UserUserDtoConverter;
import org.qbit.messanger.userservice.dto.UserDto;
import org.qbit.messanger.userservice.service.UserService;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
import static org.qbit.messanger.userservice.fixture.DataSupplier.*;
@ExtendWith(MockitoExtension.class)
class UserResourceTest {
@Mock
UserService userService;
@Spy
UserUserDtoConverter converter;
@InjectMocks
UserResource restResource;
@Test
void whenIsGivenUserId_thenGetTheUser() {
Optional<UserDto> expectedUser = Optional.of(new UserDto(testUserId));
when(userService.getUser(expectedUser.get().getUserId())).thenReturn(expectedUser);
UserDto actualUsr = restResource.getUser(testUserId);
assertThat(actualUsr.getUserId(), is(equalTo(expectedUser.get().getUserId())));
}
@Test
void whenClientAdUserById_thenAddTheUser() {
UserDto expectedUser = new UserDto(testUserId);
when(userService.addUser(expectedUser)).thenReturn(expectedUser);
UserDto actualUsr = restResource.addUser(expectedUser);
assertThat(actualUsr.getUserId(), is(equalTo(expectedUser.getUserId())));
}
@Test
void whenClientQueryAllUser_thenReturnUsers() {
List<UserDto> expectedUsers = getUsersDto("t1", "t2", "t3");
when(userService.getUsers()).thenReturn(expectedUsers);
List<UserDto> actualUsers = restResource.getUsers();
assertThatActuallListIsEqualToExpecteList(expectedUsers, actualUsers);
}
@Test
void whenClientDeleteUserByUserId_thenDeleteTheUser() {
doNothing().when(userService).deleteUser(testUserId);
restResource.deleteUser(testUserId);
verify(userService).deleteUser(testUserId);
}
private void assertThatActuallListIsEqualToExpecteList(List<UserDto> expectedUsers, List<UserDto> actualUsers) {
assertThat(actualUsers.size(), is(equalTo(expectedUsers.size())));
List<String> actualIds = actualUsers.stream()
.map(UserDto::getUserId)
.collect(Collectors.toList());
List<String> expectedIds = expectedUsers.stream()
.map(UserDto::getUserId)
.collect(toList());
for(int i =0; i < actualIds.size(); i++){
assertThat(actualIds.get(i), is(equalTo(expectedIds.get(i))));
}
}
}
| 32.662921
| 116
| 0.71861
|
dd715f047c083c6800ff187a1866e52264b94719
| 431
|
class RubikRight extends RubikFront {
public RubikRight(Rubik rubik) {
super(rubik.getGrid());
}
@Override
public RubikFront left() {
return super.rightView().left().leftView();
}
@Override
public RubikFront right() {
return super.rightView().right().leftView();
}
@Override
public RubikFront half() {
return super.rightView().half().leftView();
}
}
| 18.73913
| 52
| 0.596288
|
619aace2a05c1409c4a23b0603916df5c405ce51
| 568
|
package game;
public interface Strategy {
public void attack(Monster m);
}
// TODO create a strategy for each hero type
/* - MageStrategy
- void attack(Monster)
- WarriorStrategy
- void attack(Monster)
- PriestStrategy
- void attack(Monster)
*/
/* Attack algorithm
if hero type weapon found use it (x3 weapon damage)
else if counter weapon found use it (x2 weapon damage)
else basic attack (no bonus)
*/
//class MageStrategy implements Strategy {}
//class WarriorStrategy implements Strategy {}
//class PriestStrategy implements Strategy {}
| 19.586207
| 56
| 0.728873
|
d6db303e7be032983f272d2b4070583b363a8a1b
| 671
|
package com.example.supernotes.designpattern.builder;
import com.example.supernotes.designpattern.builder.carpart.Engine;
import com.example.supernotes.designpattern.builder.carpart.SeatBelt;
import com.example.supernotes.designpattern.builder.carpart.WindScreen;
public class Program {
public static void main(String[] args) {
Car car = new CarBuilder()
.addWheels(4)
.addSeatBelt(new SeatBelt("brand"))
.addColor("Green")
.addWindScreen(new WindScreen("WindScreen"))
.addEngine(new Engine("V8"))
.build();
System.out.println(car.toString());
}
}
| 33.55
| 71
| 0.648286
|
2c768eca26d3508283d2119ea58fa46e7b880739
| 3,967
|
/*
* Copyright (c) 2016 PayMaya Philippines, Inc.
*
* 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.paymaya.sdk.android.payment;
import android.util.Base64;
import android.util.Log;
import com.paymaya.sdk.android.BuildConfig;
import com.paymaya.sdk.android.PayMayaConfig;
import com.paymaya.sdk.android.common.network.AndroidClient;
import com.paymaya.sdk.android.common.network.Request;
import com.paymaya.sdk.android.common.network.Response;
import com.paymaya.sdk.android.common.utils.JSONUtils;
import com.paymaya.sdk.android.payment.models.Card;
import com.paymaya.sdk.android.payment.models.PaymentToken;
import org.json.JSONException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class PayMayaPayment {
private Card mCard;
private String mClientKey;
private String mUuidIdempotentKey;
/**
* @param clientKey Public API key
* @param card User's Credit Card details
*/
public PayMayaPayment(String clientKey, Card card) {
mClientKey = clientKey;
mCard = card;
mUuidIdempotentKey = UUID.randomUUID().toString();
}
/**
* Request and returns a payment token
*
* @return PaymentToken
* @throws PayMayaPaymentException
*/
public PaymentToken getPaymentToken() throws PayMayaPaymentException {
try {
String productionEndpoint = BuildConfig.API_PAYMENTS_ENDPOINT_PRODUCTION + "/payment-tokens";
String sandboxEndpoint = BuildConfig.API_PAYMENTS_ENDPOINT_SANDBOX + "/payment-tokens";
String envEndpoint = PayMayaConfig.getEnvironment() == PayMayaConfig.ENVIRONMENT_PRODUCTION ? productionEndpoint : sandboxEndpoint;
Log.d("@fromPayMayaPayment", "envEndpoint = " + envEndpoint);
Request request = new Request(Request.Method.POST, envEndpoint);
byte[] body = JSONUtils.toJSON(mCard).toString().getBytes();
request.setBody(body);
String key = mClientKey + ":";
String authorization = Base64.encodeToString(key.getBytes(), Base64.DEFAULT);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Basic " + authorization);
headers.put("Content-Length", Integer.toString(body.length));
headers.put("Idempotent-Token", mUuidIdempotentKey);
request.setHeaders(headers);
AndroidClient androidClient = new AndroidClient();
Response response = androidClient.call(request);
//check errors
return JSONUtils.fromJSONPaymentToken(response.getResponse());
} catch (JSONException je) {
throw new PayMayaPaymentException("Unknown Error", je);
} catch (PayMayaPaymentException ppe) {
throw new PayMayaPaymentException(ppe.getMessage());
}
}
}
| 39.67
| 143
| 0.706579
|
2028a151d4396dbf7d03d7db0c2755cc91e8cb71
| 1,278
|
package basewindow.transformation;
import basewindow.BaseWindow;
public class ScaleAboutPoint extends Transformation
{
public double x;
public double y;
public double z;
public double posX;
public double posY;
public double posZ;
public ScaleAboutPoint(BaseWindow window, double x, double y, double z, double posX, double posY, double posZ)
{
super(window);
this.x = x;
this.y = y;
this.z = z;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
}
public void apply()
{
transform(window, x, y, z, posX, posY, posZ);
}
@Override
public void applyToWindow()
{
}
public static void transform(BaseWindow window, double x, double y, double z, double posX, double posY, double posZ)
{
transform(window, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, posX * window.absoluteWidth, posY * window.absoluteHeight, posZ * window.absoluteDepth, 1);
transform(window, x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
transform(window, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -posX * window.absoluteWidth, -posY * window.absoluteHeight, -posZ * window.absoluteDepth, 1);
}
}
| 26.625
| 160
| 0.578247
|
d15285c6e06c76e4aa380b2ec932fd3f242c6b81
| 1,812
|
package ftn.ktsnvt.culturalofferings.dto;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
public class NewsDTO {
private Long id;
@NotBlank(message = "News title cannot be empty")
private String title;
@NotBlank(message = "News text cannot be empty")
private String text;
private Date date;
private List<Long> images;
@NotNull(message = "Cultural offering id must be provided")
@Positive(message = "Cultural offering id must be a positive number")
private Long culturalOffering;
@NotNull(message = "User id must be provided")
@Positive(message = "User id must be a positive number")
private Long user;
public NewsDTO() {}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<Long> getImages() {
return images;
}
public void setImages(List<Long> images) {
this.images = images;
}
public Long getCulturalOffering() {
return culturalOffering;
}
public void setCulturalOffering(Long culturalOffering) {
this.culturalOffering = culturalOffering;
}
public Long getUser() {
return user;
}
public void setUser(Long user) {
this.user = user;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
| 20.827586
| 73
| 0.630795
|
1e2ebe63b893211f35e2f7f1cdce65fd9d8d0c83
| 2,420
|
/*
* Copyright (c) 2008-2016, GigaSpaces Technologies, 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 org.openspaces.utest.persistency.cassandra.cache;
import com.gigaspaces.internal.utils.collections.ConcurrentHashSet;
import junit.framework.Assert;
import org.junit.Test;
import org.openspaces.persistency.cassandra.NamedLockProvider;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
public class NamedLockProviderTest {
private final Random random = new Random();
private final int _numberOfConcurrentClients = 10;
private final int _maxID = 500;
private final NamedLockProvider _namedLock = new NamedLockProvider();
private final Set<ReentrantLock> _locks = new ConcurrentHashSet<ReentrantLock>();
private final Set<Integer> _lockIDs = new ConcurrentHashSet<Integer>();
private volatile boolean _wait = true;
private volatile boolean _run = true;
@Test
public void test() throws Exception {
LockProviderClient[] clients = new LockProviderClient[_numberOfConcurrentClients];
for (int i = 0; i < clients.length; i++) {
clients[i] = new LockProviderClient();
clients[i].start();
}
_wait = false;
Thread.sleep(100);
_run = false;
for (int i = 0; i < clients.length; i++)
clients[i].join();
Assert.assertEquals("Unexpected number of locks created", _lockIDs.size(), _locks.size());
}
private class LockProviderClient extends Thread {
@Override
public void run() {
while (_wait) ;
while (_run) {
int lockID = random.nextInt(_maxID);
ReentrantLock lock = _namedLock.forName("" + lockID);
_locks.add(lock);
_lockIDs.add(lockID);
}
}
}
}
| 31.025641
| 98
| 0.673554
|
9ca988782076e69094f114c032e71d4ace74ee5c
| 2,789
|
package me.skywave.helloapplication.front.dialog;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import me.skywave.helloapplication.R;
import me.skywave.helloapplication.utils.Utils;
import me.skywave.helloapplication.utils.local_storage.HostInformation;
import me.skywave.helloapplication.utils.local_storage.HostStorage;
import me.skywave.helloapplication.background.BackgroundUtils;
public class HostFeedbackDialog extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host_density_dialog);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(getIntent().getIntExtra("noti_id", 0));
String hostId = Utils.getHostId(this);
HostInformation hostInformation = new HostStorage(this).getHost(hostId);
if (hostInformation == null) {
Intent intent = new Intent(this, HostEditDialog.class);
intent.putExtra("do_scan", true);
startActivity(intent);
finish();
return;
}
if (!hostInformation.isAllowed()) {
Toast.makeText(this, "This host is blocked by the user.", Toast.LENGTH_SHORT).show();
finish();
return;
}
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.format("How many people are in '%s'?", hostInformation.getName()));
setTitle(String.format("Feedback %s", hostInformation.getName()));
Button lowButton = (Button) findViewById(R.id.low_button);
Button middleButton = (Button) findViewById(R.id.middle_button);
Button highButton = (Button) findViewById(R.id.high_button);
lowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendAndFinish(1);
}
});
middleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendAndFinish(2);
}
});
highButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendAndFinish(3);
}
});
}
private void sendAndFinish(int density) {
BackgroundUtils.scanAndSend(this, density);
finish();
}
}
| 33.202381
| 99
| 0.66081
|
1e4280e23b92305241eaa2f77ea328fd26add787
| 16,395
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.action.search.type;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.action.support.BaseAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.trove.ExtTIntArrayList;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.controller.ShardDoc;
import org.elasticsearch.search.internal.InternalSearchRequest;
import org.elasticsearch.search.query.QuerySearchResultProvider;
import org.elasticsearch.threadpool.ThreadPool;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.elasticsearch.action.search.type.TransportSearchHelper.*;
/**
* @author kimchy (shay.banon)
*/
public abstract class TransportSearchTypeAction extends BaseAction<SearchRequest, SearchResponse> {
protected final ThreadPool threadPool;
protected final ClusterService clusterService;
protected final SearchServiceTransportAction searchService;
protected final SearchPhaseController searchPhaseController;
protected final TransportSearchCache searchCache;
public TransportSearchTypeAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
TransportSearchCache searchCache, SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.searchCache = searchCache;
this.searchService = searchService;
this.searchPhaseController = searchPhaseController;
}
protected abstract class BaseAsyncAction<FirstResult extends SearchPhaseResult> {
protected final ActionListener<SearchResponse> listener;
protected final GroupShardsIterator shardsIts;
protected final SearchRequest request;
protected final DiscoveryNodes nodes;
protected final int expectedSuccessfulOps;
protected final int expectedTotalOps;
protected final AtomicInteger successulOps = new AtomicInteger();
protected final AtomicInteger totalOps = new AtomicInteger();
protected final Collection<ShardSearchFailure> shardFailures = searchCache.obtainShardFailures();
protected volatile ShardDoc[] sortedShardList;
protected final long startTime = System.currentTimeMillis();
protected BaseAsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
this.request = request;
this.listener = listener;
ClusterState clusterState = clusterService.state();
nodes = clusterState.nodes();
request.indices(clusterState.metaData().concreteIndices(request.indices()));
for (String index : request.indices()) {
clusterState.blocks().indexBlockedRaiseException(ClusterBlockLevel.READ, index);
}
shardsIts = clusterService.operationRouting().searchShards(clusterState, request.indices(), request.queryHint(), request.routing());
expectedSuccessfulOps = shardsIts.size();
expectedTotalOps = shardsIts.totalSizeActive();
if (expectedSuccessfulOps == 0) {
// not search shards to search on...
throw new SearchPhaseExecutionException("initial", "No indices / shards to search on, requested indices are " + Arrays.toString(request.indices()), buildShardFailures());
}
}
public void start() {
// count the local operations, and perform the non local ones
int localOperations = 0;
for (final ShardIterator shardIt : shardsIts) {
final ShardRouting shard = shardIt.nextActiveOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
localOperations++;
} else {
// do the remote operation here, the localAsync flag is not relevant
performFirstPhase(shardIt.reset());
}
} else {
// really, no shards active in this group
onFirstPhaseResult(null, shardIt, null);
}
}
// we have local operations, perform them now
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
request.beforeLocalFork();
threadPool.execute(new Runnable() {
@Override public void run() {
for (final ShardIterator shardIt : shardsIts) {
final ShardRouting shard = shardIt.reset().nextActiveOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
performFirstPhase(shardIt.reset());
}
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
if (localAsync) {
request.beforeLocalFork();
}
for (final ShardIterator shardIt : shardsIts) {
final ShardRouting shard = shardIt.reset().nextActiveOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
if (localAsync) {
threadPool.execute(new Runnable() {
@Override public void run() {
performFirstPhase(shardIt.reset());
}
});
} else {
performFirstPhase(shardIt.reset());
}
}
}
}
}
}
}
private void performFirstPhase(final ShardIterator shardIt) {
final ShardRouting shard = shardIt.nextActiveOrNull();
if (shard == null) {
// no more active shards... (we should not really get here, but just for safety)
onFirstPhaseResult(null, shardIt, null);
} else {
DiscoveryNode node = nodes.get(shard.currentNodeId());
if (node == null) {
onFirstPhaseResult(shard, shardIt, null);
} else {
sendExecuteFirstPhase(node, internalSearchRequest(shard, shardsIts.size(), request), new SearchServiceListener<FirstResult>() {
@Override public void onResult(FirstResult result) {
onFirstPhaseResult(shard, result, shardIt);
}
@Override public void onFailure(Throwable t) {
onFirstPhaseResult(shard, shardIt, t);
}
});
}
}
}
private void onFirstPhaseResult(ShardRouting shard, FirstResult result, ShardIterator shardIt) {
result.shardTarget(new SearchShardTarget(shard.currentNodeId(), shard.index(), shard.id()));
processFirstPhaseResult(shard, result);
// increment all the "future" shards to update the total ops since we some may work and some may not...
// and when that happens, we break on total ops, so we must maintain them
while (shardIt.hasNextActive()) {
totalOps.incrementAndGet();
shardIt.nextActive();
}
if (successulOps.incrementAndGet() == expectedSuccessfulOps ||
totalOps.incrementAndGet() == expectedTotalOps) {
try {
moveToSecondPhase();
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "] while moving to second phase", e);
}
invokeListener(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
}
}
}
private void onFirstPhaseResult(@Nullable ShardRouting shard, final ShardIterator shardIt, Throwable t) {
if (totalOps.incrementAndGet() == expectedTotalOps) {
// e is null when there is no next active....
if (logger.isDebugEnabled()) {
if (t != null) {
if (shard != null) {
logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
// no more shards, add a failure
if (t == null) {
// no active shards
shardFailures.add(new ShardSearchFailure("No active shards", new SearchShardTarget(null, shardIt.shardId().index().name(), shardIt.shardId().id())));
} else {
shardFailures.add(new ShardSearchFailure(t));
}
if (successulOps.get() == 0) {
// no successful ops, raise an exception
invokeListener(new SearchPhaseExecutionException(firstPhaseName(), "total failure", buildShardFailures()));
} else {
try {
moveToSecondPhase();
} catch (Exception e) {
invokeListener(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
}
}
} else {
if (shardIt.hasNextActive()) {
// trace log this exception
if (logger.isTraceEnabled()) {
if (t != null) {
if (shard != null) {
logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.trace(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
performFirstPhase(shardIt);
} else {
// no more shards active, add a failure
// e is null when there is no next active....
if (logger.isDebugEnabled()) {
if (t != null) {
if (shard != null) {
logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
if (t == null) {
// no active shards
shardFailures.add(new ShardSearchFailure("No active shards", new SearchShardTarget(null, shardIt.shardId().index().name(), shardIt.shardId().id())));
} else {
shardFailures.add(new ShardSearchFailure(t));
}
}
}
}
/**
* Builds how long it took to execute the search.
*/
protected final long buildTookInMillis() {
return System.currentTimeMillis() - startTime;
}
/**
* Builds the shard failures, and releases the cache (meaning this should only be called once!).
*/
protected final ShardSearchFailure[] buildShardFailures() {
return TransportSearchHelper.buildShardFailures(shardFailures, searchCache);
}
/**
* Releases shard targets that are not used in the docsIdsToLoad.
*/
protected void releaseIrrelevantSearchContexts(Map<SearchShardTarget, QuerySearchResultProvider> queryResults,
Map<SearchShardTarget, ExtTIntArrayList> docIdsToLoad) {
if (docIdsToLoad == null) {
return;
}
// we only release search context that we did not fetch from if we are not scrolling
if (request.scroll() == null) {
for (Map.Entry<SearchShardTarget, QuerySearchResultProvider> entry : queryResults.entrySet()) {
if (!docIdsToLoad.containsKey(entry.getKey())) {
DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node != null) { // should not happen (==null) but safeguard anyhow
searchService.sendFreeContext(node, entry.getValue().id());
}
}
}
}
}
protected void invokeListener(final SearchResponse response) {
if (request.listenerThreaded()) {
threadPool.execute(new Runnable() {
@Override public void run() {
listener.onResponse(response);
}
});
} else {
listener.onResponse(response);
}
}
protected void invokeListener(final Throwable t) {
if (request.listenerThreaded()) {
threadPool.execute(new Runnable() {
@Override public void run() {
listener.onFailure(t);
}
});
} else {
listener.onFailure(t);
}
}
protected abstract void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<FirstResult> listener);
protected abstract void processFirstPhaseResult(ShardRouting shard, FirstResult result);
protected abstract void moveToSecondPhase() throws Exception;
protected abstract String firstPhaseName();
}
}
| 45.415512
| 186
| 0.556755
|
d703b39fc04dfaab5528bb193e45acec919cb323
| 215
|
class Solution {
public int hammingDistance(int x, int y) {
int s = x ^ y;
int sum = 0;
while (s != 0) {
sum++;
s &= s - 1;
}
return sum;
}
}
| 16.538462
| 46
| 0.372093
|
e35b8da98bbe2aa7b4d6d129daf4a7a89cd9a09d
| 515
|
package com.wxw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* URL http://localhost:8000/
* @author weixiaowei
* @desc: 秒杀注册中心
* @date: 2021/7/11
*/
@EnableEurekaServer
@SpringBootApplication
public class SecKillEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(SecKillEurekaApplication.class,args);
}
}
| 25.75
| 74
| 0.776699
|
6b826b7c4218ffa49b274885226ab51bcb4eb92a
| 3,273
|
/*******************************************************************************
* Copyright (c) 2007, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.apt.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.type.ErrorType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVisitor;
import org.eclipse.jdt.internal.compiler.apt.dispatch.BaseProcessingEnvImpl;
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
/**
* Implementation of the {@link ErrorType} interface.
*/
public class ErrorTypeImpl extends DeclaredTypeImpl implements ErrorType {
/* package */ ErrorTypeImpl(BaseProcessingEnvImpl env, ReferenceBinding binding) {
super(env, binding);
}
/* (non-Javadoc)
* @see javax.lang.model.type.DeclaredType#asElement()
*/
@Override
public Element asElement() {
return this._env.getFactory().newElement((ReferenceBinding) this._binding);
}
/* (non-Javadoc)
* @see javax.lang.model.type.DeclaredType#getEnclosingType()
*/
@Override
public TypeMirror getEnclosingType() {
return NoTypeImpl.NO_TYPE_NONE;
}
@Override
public List<? extends TypeMirror> getTypeArguments() {
ReferenceBinding binding = (ReferenceBinding)_binding;
if (binding.isParameterizedType()) {
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding)_binding;
TypeBinding[] arguments = ptb.arguments;
int length = arguments == null ? 0 : arguments.length;
if (length == 0) return Collections.emptyList();
List<TypeMirror> args = new ArrayList<TypeMirror>(length);
for (TypeBinding arg : arguments) {
args.add(_env.getFactory().newTypeMirror(arg));
}
return Collections.unmodifiableList(args);
}
if (binding.isGenericType()) {
TypeVariableBinding[] typeVariables = binding.typeVariables();
List<TypeMirror> args = new ArrayList<TypeMirror>(typeVariables.length);
for (TypeBinding arg : typeVariables) {
args.add(_env.getFactory().newTypeMirror(arg));
}
return Collections.unmodifiableList(args);
}
return Collections.emptyList();
}
/* (non-Javadoc)
* @see javax.lang.model.type.TypeMirror#accept(javax.lang.model.type.TypeVisitor, java.lang.Object)
*/
@Override
public <R, P> R accept(TypeVisitor<R, P> v, P p) {
return v.visitError(this, p);
}
/* (non-Javadoc)
* @see javax.lang.model.type.TypeMirror#getKind()
*/
@Override
public TypeKind getKind() {
return TypeKind.ERROR;
}
@Override
public String toString() {
return new String(_binding.readableName());
}
}
| 32.405941
| 101
| 0.713107
|
d3dfeb39e62bd4580428cd22d295435a62c36560
| 2,423
|
/*-
* #%L
* Mastodon Collections
* %%
* Copyright (C) 2015 - 2021 Tobias Pietzsch, Jean-Yves Tinevez
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.mastodon.pool;
import org.mastodon.io.AttributeSerializer;
/**
* Provides serialization of (parts of) a {@link PoolObject} of type {@code O}
* to a byte array.
* <p>
* This can be used for undo/redo and raw i/o.
* </p>
*
* @param <O>
* type of object.
*
* @author Tobias Pietzsch
*/
public class PoolObjectAttributeSerializer< O extends PoolObject< O, ?, ? > > implements AttributeSerializer< O >
{
private final int offset;
private final int length;
public PoolObjectAttributeSerializer(
final int offset,
final int length )
{
this.offset = offset;
this.length = length;
}
@Override
public int getNumBytes()
{
return length;
}
@Override
public void getBytes( final O obj, final byte[] bytes )
{
obj.access.getBytes( bytes, 0, length, offset );
}
@Override
public void setBytes( final O obj, final byte[] bytes )
{
obj.access.putBytes( bytes, 0, length, offset );
}
@Override
public void notifySet( final O obj )
{}
}
| 29.91358
| 113
| 0.722658
|
2a438ce6c2a65a9557251410557e1efb6774d274
| 745
|
package com.fenbi.newbull.mvc.web.configure;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
@RestController
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handle(NullPointerException ex) {
log.info("got exception", ex);
return new ResponseEntity<>("some thing is wrong", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
| 33.863636
| 93
| 0.810738
|
9885542091fa5c7c1468d7fc54883a12f0d032e6
| 2,206
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.browser_ui.widget.textbubble;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.StringRes;
import org.chromium.components.browser_ui.widget.R;
import org.chromium.ui.widget.RectProvider;
/**
* UI component that handles showing a text callout bubble with a preceding image.
*/
public class ImageTextBubble extends TextBubble {
/**
* Constructs a {@link ImageTextBubble} instance.
* @param context Context to draw resources from.
* @param rootView The {@link View} to use for size calculations and for display.
* @param stringId The id of the string resource for the text that should be shown.
* @param accessibilityStringId The id of the string resource of the accessibility text.
* @param showArrow Whether the bubble should have an arrow.
* @param anchorRectProvider The {@link RectProvider} used to anchor the text bubble.
* @param imageDrawableId The resource id of the image to show at the start of the text bubble.
* @param isAccessibilityEnabled Whether accessibility mode is enabled. Used to determine bubble
* text and dismiss UX.
*/
public ImageTextBubble(Context context, View rootView, @StringRes int stringId,
@StringRes int accessibilityStringId, boolean showArrow,
RectProvider anchorRectProvider, int imageDrawableId, boolean isAccessibilityEnabled) {
super(context, rootView, stringId, accessibilityStringId, showArrow, anchorRectProvider,
isAccessibilityEnabled);
((ImageView) mContentView.findViewById(R.id.image)).setImageResource(imageDrawableId);
}
@Override
protected View createContentView() {
View view =
LayoutInflater.from(mContext).inflate(R.layout.textbubble_text_with_image, null);
setText((TextView) view.findViewById(R.id.message));
return view;
}
}
| 44.12
| 100
| 0.736174
|
f9c1c538163e7423c2e3259c223e589dc9dc09d9
| 862
|
package com.iec2016018.CCWarmup.Algos.Sorting.Hybrids;
import java.util.Arrays;
public class Radix {
/*
R A D I X S O R T --
ABOUT :
> The lower bound for comparison based sorting algorithm (Merge Sort,
Heap Sort, Quick Sort.. etc) is Q(nLogn), i.e, they cannot do better
than nLogn
> Counting sort is a linear time sorting algorithm that sort in O(n+k) time
when elements are in range from 1 to k
COMPLEXITY :
VARIATIONS :
** NOTE ** Following codes are not tested yet. Learn this at your own risk
*/
// ========================================================== P R A C T I C E H E R E ============================
//------------------------------------- radix sort with complexity d * (n+b);
}
| 22.684211
| 120
| 0.476798
|
9dd045a50fe64068cbad3e590416a0e96b0baf18
| 1,704
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.lang.api.concern;
/**
* This interface is used to document the concept and meaning of <em>accessibility</em> (of a user-interface). We
* provide advanced support especially via {@link #WAI_ARIA} within this project and via this marker interface you can
* find the related spots. However, descriptive information such as meaningful alt-texts have to be defined by the
* developers of actual UIs and can not be generated automatically by the framework. Please support people with
* disabilities by enriching your application with semantical information - we already do our best to make this easy for
* you. Have a look at the known subinterfaces and implementing classes to get an overview of our supporting code.
*
* @deprecated over-engineered. Will be deleted in a future release.
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 4.0.0
*/
@Deprecated
public abstract interface Accessibility {
/**
* The Web Acessibility initiative (WAI) has created a standardized framework called
* <a href="http://www.w3.org/WAI/intro/aria.php">WAI-ARIA</a> that aims to support accessibility for rich Internet
* applications (ARIA). <br>
* The main concept is to add semantical information to UI elements via specialized attributes. The most important of
* these attributes is the role attribute. While this is already handled inside our framework there are some
* descriptive informations required that have to be set by the UI developer.
*/
String WAI_ARIA = "http://www.w3.org/WAI/intro/aria.php";
}
| 54.967742
| 120
| 0.758216
|
46ef8a77ac84150db9bcd5e917effbe8cd4987c1
| 2,328
|
/**
* <a href=“http://www.openolat.org“>
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* 03.02.2012 by frentix GmbH, http://www.frentix.com
* <p>
**/
package org.olat.user;
import org.olat.basesecurity.IdentityNames;
import org.olat.core.id.User;
import org.olat.core.id.UserConstants;
/**
* <h3>Description:</h3>
* This bean implements a method to print out the users display name. The default implementation prints
* firsname lastname.
* <pre>
* firstname lastname
* </pre>
* <p>
* Inherit from this bean and inject it to the usermanager to modify this behavior
* <p>
* Initial Date: 02.03.2012 <br>
*
* @author Florian Gnaegi, frentix GmbH, http://www.frentix.com
*/
public class UserDisplayNameCreator {
/**
* Returns the users displayable name, e.g. "Firstname Lastname"
*
* @param user
* @return
*/
public String getUserDisplayName(User user) {
if (user == null) return "unknown user";
// use first and lastname for display purpose
String first = user.getProperty(UserConstants.FIRSTNAME, null);
String last = user.getProperty(UserConstants.LASTNAME, null);
return getDisplayName(first, last);
}
public String getUserDisplayName(IdentityNames identity) {
return getDisplayName(identity.getFirstName(), identity.getLastName());
}
protected String getDisplayName(String firstName, String lastName) {
// expect null values to make it robust agains NPE and remove whitespace
String combined = (firstName == null? "" : firstName) + " " + (lastName == null? "" : lastName);
combined = combined.trim();
if (combined.length() == 0) combined = "unknown user";
return combined;
}
}
| 33.73913
| 104
| 0.712199
|
ad02946b1ac43d226a51684091cec999b306be84
| 2,198
|
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* 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.fastffi.impl;
import com.alibaba.fastffi.CXXHead;
import com.alibaba.fastffi.CXXOperator;
import com.alibaba.fastffi.CXXReference;
import com.alibaba.fastffi.CXXValue;
import com.alibaba.fastffi.FFIFactory;
import com.alibaba.fastffi.FFIGen;
import com.alibaba.fastffi.FFITypeAlias;
import com.alibaba.fastffi.FFIVector;
/**
* To support new templates (e.g., {@code Bean}, simply define a new class:
* <pre>
* @FFIGen
* @FFITypeAlias("std::vector")
* @CXXTemplate(cxx = "bean", java = "Bean")
* class BeanVector<E> extends CXXStdVector<E> {
* @FFIFactory
* interface Factory<E> {
* BeanVector<E> create();
* }
* }
*
* This class is mainly used by FFIMirror, where all type mapping are predefined.
* In that case, we can infer the type mapping from Java type system
* without any CXXTemplate annotation.
* </pre>
* @param <E>
*/
@FFIGen
@FFITypeAlias("std::vector")
@CXXHead(system = "vector")
public interface CXXStdVector<E> extends FFIVector<E> {
@FFIFactory
interface Factory<E> extends FFIVector.Factory<E> {
CXXStdVector<E> create();
CXXStdVector<E> create(int capacity);
}
long size();
boolean empty();
void push_back(@CXXReference E e);
@CXXOperator("[]")
@CXXReference E get(long index);
@CXXOperator("[]")
void set(long index, @CXXReference E value);
long data();
long capacity();
void reserve(long cap);
void resize(long size);
void clear();
@CXXOperator("delete")
void dispose();
}
| 28.545455
| 81
| 0.692448
|
1dc36b0f9210866e9c3734bad9da869085e7b3dc
| 1,474
|
/*
* Nimrod/G
* https://github.com/UQ-RCC/nimrodg
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2021 The University of Queensland
*
* 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 au.edu.uq.rcc.nimrodg.agent.messages;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
public final class AgentSubmit extends AgentMessage {
private final NetworkJob m_Job;
private AgentSubmit(UUID agentUuid, Instant timestamp, NetworkJob job) {
super(agentUuid, timestamp);
Objects.requireNonNull(job, "job");
m_Job = job;
}
@Override
public Type getType() {
return Type.Submit;
}
public NetworkJob getJob() {
return m_Job;
}
public static class Builder extends AgentMessage.Builder<Builder> {
private NetworkJob job;
public Builder job(NetworkJob job) {
this.job = job;
return this;
}
@Override
public AgentSubmit build() {
return new AgentSubmit(agentUuid, timestamp, job);
}
}
}
| 24.983051
| 75
| 0.729986
|
6b6482e24b40ecdf657fa4d1ce27882480c09396
| 4,071
|
/*
* File: AbstractKernelizableBinaryCategorizerOnlineLearner.java
* Authors: Justin Basilico
* Company: Sandia National Laboratories
* Project: Cognitive Foundry Learning Core
*
* Copyright April 04, 2011, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government. Export
* of this program may require a license from the United States Government.
*
*/
package gov.sandia.cognition.learning.algorithm.perceptron;
import gov.sandia.cognition.learning.algorithm.perceptron.kernel.KernelBinaryCategorizerOnlineLearnerAdapter;
import gov.sandia.cognition.learning.algorithm.SupervisedBatchAndIncrementalLearner;
import gov.sandia.cognition.learning.data.InputOutputPair;
import gov.sandia.cognition.learning.function.categorization.DefaultKernelBinaryCategorizer;
import gov.sandia.cognition.learning.function.kernel.Kernel;
import gov.sandia.cognition.math.matrix.VectorFactory;
/**
* An abstract implementation of the {@code KernelizableBinaryCategorizerOnlineLearner}
* interface. It handles a lot of the convenience methods to string them
* together, making it necessary for sub-classes to only implement one
* update method.
*
* @author Justin Basilico
* @since 3.3.0
*/
public abstract class AbstractKernelizableBinaryCategorizerOnlineLearner
extends AbstractOnlineLinearBinaryCategorizerLearner
implements KernelizableBinaryCategorizerOnlineLearner
{
/**
* Creates a new {@code AbstractKernelizableBinaryCategorizerOnlineLearner}.
*/
public AbstractKernelizableBinaryCategorizerOnlineLearner()
{
super();
}
/**
* Creates a new {@code AbstractKernelizableBinaryCategorizerOnlineLearner}
* with the given vector factory.
*
* @param vectorFactory
* The vector factory to use.
*/
public AbstractKernelizableBinaryCategorizerOnlineLearner(
final VectorFactory<?> vectorFactory)
{
super(vectorFactory);
}
@Override
public <InputType> DefaultKernelBinaryCategorizer<InputType> createInitialLearnedObject(
final Kernel<? super InputType> kernel)
{
return new DefaultKernelBinaryCategorizer<InputType>(
kernel);
}
@Override
public <InputType> void update(
final DefaultKernelBinaryCategorizer<InputType> target,
final Iterable<? extends InputOutputPair<? extends InputType, Boolean>> data)
{
for (InputOutputPair<? extends InputType, Boolean> example : data)
{
this.update(target, example);
}
}
@Override
public <InputType> void update(
final DefaultKernelBinaryCategorizer<InputType> target,
final InputOutputPair<? extends InputType, Boolean> data)
{
this.update(target, data.getInput(), data.getOutput());
}
@Override
public <InputType> void update(
final DefaultKernelBinaryCategorizer<InputType> target,
final InputType input,
final Boolean output)
{
this.update(target, input, (boolean) output);
}
@Override
public <InputType> DefaultKernelBinaryCategorizer<InputType> learn(
final Kernel<? super InputType> kernel,
final Iterable<? extends InputOutputPair<? extends InputType, Boolean>> data)
{
// Create the object.
final DefaultKernelBinaryCategorizer<InputType>
result = this.createInitialLearnedObject(kernel);
// Update it.
this.update(result, data);
// Return the result.
return result;
}
@Override
public <InputType> SupervisedBatchAndIncrementalLearner<InputType, Boolean, DefaultKernelBinaryCategorizer<InputType>> createKernelLearner(
final Kernel<? super InputType> kernel)
{
// Create the kernel wrapper for the learner.
return new KernelBinaryCategorizerOnlineLearnerAdapter<InputType>(
kernel, this);
}
}
| 34.210084
| 143
| 0.709162
|
cb81b955acf6e8c12127a7b82fe41f84bb3e08d7
| 507
|
package org.mharris.artifactory.artifactoryscanner.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.Date;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Artifact {
private String repo;
private String path;
private String name;
private String type;
private long size;
private Date created;
private String createdBy;
private Date modified;
private String modifiedBy;
private Date updated;
}
| 22.043478
| 61
| 0.757396
|
6ddfb2cb04cafe61f4221c34f194508857c40673
| 3,054
|
/*******************************************************************************
* 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 net.adoptopenjdk.stf;
import net.adoptopenjdk.stf.extensions.core.StfCoreExtension;
import net.adoptopenjdk.stf.extensions.core.StfCoreExtension.Echo;
import net.adoptopenjdk.stf.plugin.interfaces.StfPluginInterface;
import net.adoptopenjdk.stf.processes.ExpectedOutcome;
import net.adoptopenjdk.stf.processes.definitions.JavaProcessDefinition;
import net.adoptopenjdk.stf.processes.definitions.LoadTestProcessDefinition;
import net.adoptopenjdk.stf.runner.modes.HelpTextGenerator;
/**
* This is a test plugin that runs the Locker test alongside a mini-mix workload.
*
* The Locker test was created to exercise lock contention against String and array objects.
*/
public class LockingLoadTest implements StfPluginInterface {
public void help(HelpTextGenerator help) throws StfException {
help.outputSection("LockingLoadTest tests lock contention against String and array objects"
+ "on a multithreaded environment.");
help.outputText("");
}
public void pluginInit(StfCoreExtension stf) throws StfException {
}
public void setUp(StfCoreExtension test) throws StfException {
}
public void execute(StfCoreExtension test) throws StfException {
String miniMixInventory = "/openjdk.test.load/config/inventories/mix/mini-mix.xml";
String lockingInventory = "/openjdk.test.load/config/inventories/locking/locking.xml";
LoadTestProcessDefinition loadTestInvocation = test.createLoadTestSpecification()
.addPrereqJarToClasspath(JavaProcessDefinition.JarId.JUNIT)
.addPrereqJarToClasspath(JavaProcessDefinition.JarId.HAMCREST)
.addProjectToClasspath("openjdk.test.locking")
.addProjectToClasspath("openjdk.test.lang") // For mini-mix inventory
.addProjectToClasspath("openjdk.test.util") // For mini-mix inventory
.addProjectToClasspath("openjdk.test.math") // For mini-mix inventory
.setTimeLimit("30s")
.addSuite("mini-mix")
.setSuiteThreadCount(2)
.setSuiteInventory(miniMixInventory)
.setSuiteRandomSelection()
.addSuite("locking")
.setSuiteThreadCount(2)
.setSuiteInventory(lockingInventory)
.setSuiteRandomSelection();
test.doRunForegroundProcess("Run locking load test", "LLT", Echo.ECHO_ON,
ExpectedOutcome.cleanRun().within("35m"),
loadTestInvocation);
}
public void tearDown(StfCoreExtension stf) throws StfException {
}
}
| 43.628571
| 93
| 0.740995
|
72d527a0c2a4de57ce168e8aac3cd9890a59dabf
| 561
|
package com.trasier.client.util;
import com.trasier.client.api.ContentType;
import org.junit.Test;
import static com.trasier.client.util.ContentTypeResolver.resolveFromPayload;
import static org.junit.Assert.assertEquals;
public class ContentTypeResolverTest {
@Test
public void resolveContentType() {
assertEquals(ContentType.XML, resolveFromPayload("<project></project>"));
assertEquals(ContentType.JSON, resolveFromPayload("{project:[version: 123]}"));
assertEquals(ContentType.TEXT, resolveFromPayload("Hello"));
}
}
| 31.166667
| 87
| 0.755793
|
6d8dc6313da652572a4763830c4c8a3a970684f8
| 687
|
package org.jtwig.unit.util;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.jtwig.util.FilePath.path;
public class FilePathTest {
@Test
public void pathTest() throws Exception {
assertThat(path("/test/test").parent().toString(), equalTo("/test"));
assertThat(path("/test/test").parent().append("one").toString(), equalTo("/test/one"));
assertThat(path("/test", "test").parent().toString(), equalTo("/test"));
}
@Test
public void normalize() throws Exception {
assertThat(path("/test/../hello").normalize(), equalTo("/hello"));
}
}
| 31.227273
| 95
| 0.668122
|
dd22ee7a3b9eb0fe668582351fd1df23042c5527
| 1,940
|
package com.hjh.files.sync.client;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.util.Asserts;
import com.hjh.files.sync.common.HLogFactory;
import com.hjh.files.sync.common.ILog;
import com.hjh.files.sync.common.RemoteFile;
import com.hjh.files.sync.common.StopAble;
import com.hjh.files.sync.common.util.MD5;
import com.hjh.files.sync.common.util.RemoteFileUtil;
public class FileCopyBySimple implements FileCopy {
private static ILog logger = HLogFactory.create(FileCopyBySimple.class);
private ClientFolder client_folder;
private int block_size;
public FileCopyBySimple(ClientFolder client_folder, int block_size) {
this.client_folder = client_folder;
this.block_size = block_size;
}
@Override
public void copy(StopAble stop, RemoteFile from, File target, String md5) throws IOException {
Asserts.check(!target.exists(), "file already exist:" + target.getAbsolutePath());
target.createNewFile();
int totalParts = RemoteFileUtil.countPart(from.length(), this.block_size);
FileOutputStream out = new FileOutputStream(target);
try {
for (int i = 0; i < totalParts; i++) {
byte[] part_data = client_folder.getFromManage().part(from.path(), i, block_size);
out.write(part_data);
logger.debug(String.format("[%s] [%s] [%d/%d] receive part data %d K", this.client_folder.getName(),
from.path(), i + 1, totalParts, part_data.length / 1024));
part_data = null;
if (stop.isStop()) {
return;
}
}
} finally {
out.close();
out = null;
}
String target_md5 = MD5.md5(target);
if (!md5.equals(target_md5)) {
logger.stdout("clear dirty file : " + target.getAbsolutePath());
Asserts.check(target.delete(), "can not clear dirty file:" + target.getAbsolutePath());
throw new RuntimeException(
"can not fetch correct data from remote for:" + from.path() + ":" + target_md5 + ":" + md5);
}
}
}
| 31.290323
| 104
| 0.715464
|
bc40feec0aa070827f2036509a1b556572de2e32
| 88
|
package space.dubovitsky.thymeleaf.object;
public enum Gender {
MALE, FEMALE;
}
| 11
| 42
| 0.715909
|
e11815f37a0ee6a3be8d5417620635bee421fc2d
| 3,427
|
package com.ld.codeGenerate.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the t145 database table.
*
*/
@Entity
@Table(name = "t145")
public class MemberArticle implements Serializable {
/**
* serial No
*/
private static final long serialVersionUID = 3098326858653427003L;
// article id
private Long articleId;
private Date createDateTime;
private String createUserId;
private Date updateDateTime;
private String updateUserId;
private Boolean delFlag;
// article no
private String articleNo;
// article name
private String articleName;
// article quantity
private Integer articleQuantity;
// quantity unit
private String quantityUnit;
// corresponding points
private Integer point;
public MemberArticle() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "V400301", unique = true, nullable = false)
public Long getArticleId() {
return this.articleId;
}
public void setArticleId(Long articleId) {
this.articleId = articleId;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "C999991", nullable = false)
public Date getCreateDateTime() {
return this.createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
@Column(name = "C999992", nullable = false, length = 8)
public String getCreateUserId() {
return this.createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "C999993", nullable = false)
public Date getUpdateDateTime() {
return this.updateDateTime;
}
public void setUpdateDateTime(Date updateDateTime) {
this.updateDateTime = updateDateTime;
}
@Column(name = "C999994", nullable = false, length = 8)
public String getUpdateUserId() {
return this.updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
@Column(name = "C999995", nullable = false)
public Boolean getDelFlag() {
return this.delFlag;
}
public void setDelFlag(Boolean delFlag) {
this.delFlag = delFlag;
}
@Column(name = "V400302", nullable = false, length = 8)
public String getArticleNo() {
return this.articleNo;
}
public void setArticleNo(String articleNo) {
this.articleNo = articleNo;
}
@Column(name = "V400303", nullable = false, length = 32)
public String getArticleName() {
return this.articleName;
}
public void setArticleName(String articleName) {
this.articleName = articleName;
}
@Column(name = "V400304", nullable = false)
public Integer getArticleQuantity() {
return this.articleQuantity;
}
public void setArticleQuantity(Integer articleQuantity) {
this.articleQuantity = articleQuantity;
}
@Column(name = "V400305", length = 6)
public String getQuantityUnit() {
return this.quantityUnit;
}
public void setQuantityUnit(String quantityUnit) {
this.quantityUnit = quantityUnit;
}
@Column(name = "V400306", nullable = false)
public Integer getPoint() {
return this.point;
}
public void setPoint(Integer point) {
this.point = point;
}
}
| 22.398693
| 67
| 0.744091
|
c4543296fbf3d19a6a0898e45d28185094cd70f8
| 1,437
|
/*
* Copyright 2012 Amadeus s.a.s.
* 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.ariatemplates.attester.junit;
import java.util.Map;
import org.junit.runner.Description;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
public abstract class MessageHandler {
static protected <T> T treeToValue(JsonNode node, Class<T> valueType) {
if (node == null) {
return null;
}
try {
return JsonInputStream.getObjectMapper().treeToValue(node, valueType);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public abstract void handleMessage(JsonNode message);
protected Description getCorrespondingTest(JsonNode message, Map<Integer, Description> tests) {
Integer id = message.get("taskId").asInt();
return tests.get(id);
}
}
| 32.659091
| 99
| 0.705637
|
94b7d9a8551848b1daeffa995464af8f4cdfdc0c
| 2,118
|
/* 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.flowable.cmmn.rest.service.api.runtime.caze;
import java.util.List;
import io.swagger.annotations.ApiModelProperty;
/**
* @author Tijs Rademakers
*/
public class ChangePlanItemStateRequest {
protected List<String> activatePlanItemDefinitionIds;
protected List<String> moveToAvailablePlanItemDefinitionIds;
protected List<String> terminatePlanItemDefinitionIds;
public List<String> getActivatePlanItemDefinitionIds() {
return activatePlanItemDefinitionIds;
}
@ApiModelProperty(value = "plan item definition ids to be activated")
public void setActivatePlanItemDefinitionIds(List<String> activatePlanItemDefinitionIds) {
this.activatePlanItemDefinitionIds = activatePlanItemDefinitionIds;
}
public List<String> getMoveToAvailablePlanItemDefinitionIds() {
return moveToAvailablePlanItemDefinitionIds;
}
@ApiModelProperty(value = "plan item definition ids to be moved to available state")
public void setMoveToAvailablePlanItemDefinitionIds(List<String> moveToAvailablePlanItemDefinitionIds) {
this.moveToAvailablePlanItemDefinitionIds = moveToAvailablePlanItemDefinitionIds;
}
public List<String> getTerminatePlanItemDefinitionIds() {
return terminatePlanItemDefinitionIds;
}
@ApiModelProperty(value = "plan item definition ids to be terminated")
public void setTerminatePlanItemDefinitionIds(List<String> terminatePlanItemDefinitionIds) {
this.terminatePlanItemDefinitionIds = terminatePlanItemDefinitionIds;
}
}
| 37.821429
| 108
| 0.772427
|
6c79e897175e9faec95d1d75978de7c22a5d71cf
| 247
|
package com.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}
| 20.583333
| 90
| 0.716599
|
f873154f7ecb7cb50b5fcd325d32f2914d7b31d6
| 1,989
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.cdi.tck.tests.event.observer.priority.contextLifecycleEvent;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.interceptor.Interceptor;
import org.jboss.cdi.tck.util.ActionSequence;
public class ApplicationScopedObserver {
public static final String A = "A";
public static final String B = "B";
public static final String C = "C";
public static final String D = "D";
public void first(@Observes @Initialized(ApplicationScoped.class) @Priority(Interceptor.Priority.APPLICATION - 100) Object obj) {
ActionSequence.addAction(A);
}
public void second(@Observes @Initialized(ApplicationScoped.class) Object obj) {
ActionSequence.addAction(B);
}
public void third(@Observes @Initialized(ApplicationScoped.class) @Priority(Interceptor.Priority.APPLICATION + 600) Object obj) {
ActionSequence.addAction(C);
}
public void forth(@Observes @Initialized(ApplicationScoped.class) @Priority(Interceptor.Priority.APPLICATION + 700) Object obj) {
ActionSequence.addAction(D);
}
}
| 39.78
| 133
| 0.75264
|
de456c861b0569a023b28f18aa439c3920ffe925
| 1,323
|
package betterwithaddons.util;
import betterwithaddons.item.ItemTea;
import betterwithaddons.item.ModItems;
import betterwithaddons.util.TeaType.ItemType;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import javax.annotation.Nullable;
public class IngredientTea extends Ingredient {
TeaType type;
ItemType itemType;
public IngredientTea(TeaType type, ItemType itemType) {
super(0);
this.type = type;
this.itemType = itemType;
}
@Override
public boolean apply(@Nullable ItemStack stack) {
return stack != null && stack.getItem() instanceof ItemTea && ItemTea.getType(stack) == type && ItemTea.getItemType(stack) == itemType;
}
@Override
public ItemStack[] getMatchingStacks() {
return new ItemStack[]{getTeaStack()};
}
public ItemStack getTeaStack() {
switch (itemType) {
case Leaves:
return ModItems.TEA_LEAVES.getStack(type);
case Soaked:
return ModItems.TEA_SOAKED.getStack(type);
case Wilted:
return ModItems.TEA_WILTED.getStack(type);
case Powder:
return ModItems.TEA_POWDER.getStack(type);
default:
return ItemStack.EMPTY;
}
}
}
| 28.76087
| 143
| 0.644747
|
4e85d0c2ba2588ac581f35533cae8e815f5d080b
| 654
|
package evolved.model;
import evolved.model.compute.Operator;
import java.util.Set;
public class ComponentBuilderConfiguration {
private final Set<String> inputKeys;
private final String outputKey;
private final Operator operator;
public ComponentBuilderConfiguration(Set<String> inputKeys, String outputKey, Operator operator) {
this.inputKeys = inputKeys;
this.outputKey = outputKey;
this.operator = operator;
}
Set<String> getInputKeys() {
return inputKeys;
}
Operator getOperator() {
return operator;
}
String getOutputKey() {
return outputKey;
}
}
| 20.4375
| 102
| 0.678899
|
0244ce918341ef9951db4028108e579e9066f3c7
| 1,383
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package ch.qos.logback.core.status;
import java.util.ArrayList;
import java.util.List;
// Referenced classes of package ch.qos.logback.core.status:
// StatusListener, Status
public class StatusListenerAsList
implements StatusListener
{
public StatusListenerAsList()
{
// 0 0:aload_0
// 1 1:invokespecial #13 <Method void Object()>
statusList = ((List) (new ArrayList()));
// 2 4:aload_0
// 3 5:new #15 <Class ArrayList>
// 4 8:dup
// 5 9:invokespecial #16 <Method void ArrayList()>
// 6 12:putfield #18 <Field List statusList>
// 7 15:return
}
public void addStatusEvent(Status status)
{
statusList.add(((Object) (status)));
// 0 0:aload_0
// 1 1:getfield #18 <Field List statusList>
// 2 4:aload_1
// 3 5:invokeinterface #27 <Method boolean List.add(Object)>
// 4 10:pop
// 5 11:return
}
public List getStatusList()
{
return statusList;
// 0 0:aload_0
// 1 1:getfield #18 <Field List statusList>
// 2 4:areturn
}
List statusList;
}
| 27.117647
| 68
| 0.573391
|
d148d29e099a1e5c4948cfa30dd241b1e3697d51
| 7,360
|
package streetmap.view.general;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import language.Messages;
import streetmap.globals.Constant;
import streetmap.globals.Variable;
import streetmap.model.DataBase;
import streetmap.model.command.CommandList;
import streetmap.observer.CommandListObserver;
import streetmap.observer.TourStateObserver;
import streetmap.solver.ComputTourDialog;
import streetmap.solver.ComputeTourTask;
import streetmap.task.LoadDataBaseTask;
import streetmap.task.RedoTask;
import streetmap.task.SaveAsDataBaseTask;
import streetmap.task.SaveDataBaseTask;
import streetmap.task.Task;
import streetmap.task.UndoTask;
import streetmap.task.WaitingDialog;
import streetmap.view.graphicalElements.JMenuHover;
import streetmap.view.graphicalElements.JMenuItemLingual;
@SuppressWarnings("serial")
public class MTMenuBar extends JMenuBar implements ActionListener, CommandListObserver, TourStateObserver {
private MainView mainView;
/* menu */
private JMenuHover menuFile;
private JMenuItemLingual menuItemNew;
private JMenuItemLingual menuItemLoad;
private JMenuItemLingual menuItemSave;
private JMenuItemLingual menuItemSaveAs;
private JMenuItemLingual menuItemEnd;
private JMenuHover menuEdit;
private JMenuItemLingual menuItemUndo;
private JMenuItemLingual menuItemRedo;
private JMenuItemLingual menuItemComputeTour;
private JMenuItemLingual menuItemTourQuality;
public MTMenuBar(MainView mainView) {
this.mainView = mainView;
CommandList.getInstance().registerCommandListObserver(this);
createMenuFile();
createMenuEdit();
add(Box.createHorizontalGlue());
add(new JLabel(Constant.COPYRIGHT + " tommy-13 "));
// register menu items as for this action listener
for(Component c : getComponents()) {
if(c instanceof JMenuHover) {
JMenuHover menu = (JMenuHover) c;
for(Component cmi : menu.getMenuComponents()) {
if(cmi instanceof JMenuItem) {
JMenuItem menuItem = (JMenuItem) cmi;
menuItem.addActionListener(this);
}
}
}
}
}
private void createMenuFile() {
menuFile = new JMenuHover("MenuBar.MenuFile");
menuFile.setMnemonic(Messages.getString("Mnemonic.File").charAt(0));
menuItemNew = new JMenuItemLingual("MenuBar.MenuItemNew");
menuItemNew.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK));
menuFile.add(menuItemNew);
menuFile.addSeparator();
menuItemLoad = new JMenuItemLingual("MenuBar.MenuItemLoad");
menuItemLoad.setAccelerator(KeyStroke.getKeyStroke('L', InputEvent.CTRL_DOWN_MASK));
menuFile.add(menuItemLoad);
menuItemSave = new JMenuItemLingual("MenuBar.MenuItemSave");
menuItemSave.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK));
menuFile.add(menuItemSave);
menuItemSaveAs = new JMenuItemLingual("MenuBar.MenuItemSaveAs");
menuItemSaveAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
menuFile.add(menuItemSaveAs);
menuFile.addSeparator();
menuItemEnd = new JMenuItemLingual("MenuBar.MenuItemEnd");
menuItemEnd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK));
menuFile.add(menuItemEnd);
add(menuFile);
}
private void createMenuEdit() {
menuEdit = new JMenuHover("MenuBar.MenuEdit");
menuEdit.setMnemonic(Messages.getString("Mnemonic.Edit").charAt(0));
menuItemUndo = new JMenuItemLingual("MenuBar.MenuItemUndo");
menuItemUndo.setEnabled(false);
menuItemUndo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK));
menuEdit.add(menuItemUndo);
menuItemRedo = new JMenuItemLingual("MenuBar.MenuItemRedo");
menuItemRedo.setEnabled(false);
menuItemRedo.setAccelerator(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK));
menuEdit.add(menuItemRedo);
menuEdit.addSeparator();
menuItemComputeTour = new JMenuItemLingual("MenuBar.MenuItemComputeTour");
menuItemComputeTour.setAccelerator(KeyStroke.getKeyStroke('T', InputEvent.CTRL_DOWN_MASK));
menuEdit.add(menuItemComputeTour);
menuItemTourQuality = new JMenuItemLingual("MenuBar.MenuItemTourQuality");
menuItemTourQuality.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK));
menuEdit.add(menuItemTourQuality);
add(menuEdit);
}
public void createNewFile() {
DataBase dataBase = DataBase.getInstance();
int answer = JOptionPane.OK_OPTION;
if(dataBase.isSavingNecessary()) {
answer = JOptionPane.showConfirmDialog(mainView,
Messages.getString("DataLoseWarning.ConfirmText"),
Messages.getString("DataLoseWarning.ConfirmTitle"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
}
if(answer == JOptionPane.OK_OPTION) {
CommandList.getInstance().reset();
mainView.reset();
dataBase.reset();
}
}
public void loadFile() {
int answer = JOptionPane.OK_OPTION;
if(DataBase.getInstance().isSavingNecessary()) {
answer = JOptionPane.showConfirmDialog(mainView,
Messages.getString("DataLoseWarning.ConfirmText"),
Messages.getString("DataLoseWarning.ConfirmTitle"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
}
if(answer == JOptionPane.OK_OPTION) {
Task task = new LoadDataBaseTask(mainView);
new WaitingDialog(task);
if(task.isDone()) {
CommandList.getInstance().reset();
mainView.reset();
}
}
}
public void saveFile(boolean saveAs) {
Task task = saveAs ? new SaveAsDataBaseTask(mainView) : new SaveDataBaseTask(mainView);
new WaitingDialog(task);
}
public void enableInput(boolean enabled) {
menuEdit.setEnabled(enabled);
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("MenuBar.MenuItemNew")) {
createNewFile();
return;
}
if(actionCommand.equals("MenuBar.MenuItemSave")) {
saveFile(false);
return;
}
if(actionCommand.equals("MenuBar.MenuItemSaveAs")) {
saveFile(true);
return;
}
if(actionCommand.equals("MenuBar.MenuItemLoad")) {
loadFile();
return;
}
if(actionCommand.equals("MenuBar.MenuItemEnd")) {
mainView.endProgram();
return;
}
if(actionCommand.equals("MenuBar.MenuItemUndo")) {
Task task = new UndoTask(mainView);
task.execute();
return;
}
if(actionCommand.equals("MenuBar.MenuItemRedo")) {
Task task = new RedoTask(mainView);
task.execute();
return;
}
if(actionCommand.equals("MenuBar.MenuItemComputeTour")) {
ComputeTourTask task = new ComputeTourTask(Variable.solverThreads);
new ComputTourDialog(mainView, task);
return;
}
if(actionCommand.equals("MenuBar.MenuItemTourQuality")) {
new QualityDialog(mainView);
return;
}
}
@Override
public void fireUndoStackState(boolean isEmpty) {
menuItemUndo.setEnabled(!isEmpty);
}
@Override
public void fireRedoStackState(boolean isEmpty) {
menuItemRedo.setEnabled(!isEmpty);
}
@Override
public void firePartialPathChanged(int id) {}
@Override
public void fireTourClosed() {
enableInput(true);
}
}
| 29.206349
| 117
| 0.762092
|
335d3e593443162bc262308904dce67df1e46809
| 4,766
|
package org.dontpanic.spanners.springmvc.controllers;
import org.dontpanic.spanners.springmvc.domain.Spanner;
import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException;
import org.dontpanic.spanners.springmvc.services.SpannersService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.ui.ModelMap;
import java.time.LocalTime;
import java.util.List;
import java.util.function.Supplier;
import static org.dontpanic.spanners.springmvc.controllers.DisplaySpannersController.*;
import static org.dontpanic.spanners.springmvc.stubs.SpannersStubs.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Test for page that displays list of spanners
* User: Stevie
* Date: 05/10/13
*/
@RunWith(MockitoJUnitRunner.class)
public class DisplaySpannersControllerTest {
@Mock private SpannersService spannersService;
@Mock private Supplier<LocalTime> currentTime;
@InjectMocks private DisplaySpannersController controller = new DisplaySpannersController();
@Before
public void initMocks() {
when(currentTime.get()).thenReturn(LocalTime.NOON);
}
/**
* Test that page shows list of spanners
*/
@Test
public void testDisplaySpanners() {
// Stub behaviours - list of spanners
when(spannersService.findAll()).thenReturn(SPANNERS);
// Call the controller
ModelMap model = new ModelMap();
String view = controller.displaySpanners(model);
// Assert that we forward to correct page
assertEquals("view name", VIEW_DISPLAY_SPANNERS, view);
// Assert that spanners are in model
@SuppressWarnings("unchecked")
List<Spanner> spannersInModel = (List<Spanner>)model.get(MODEL_ATTRIBUTE_SPANNERS);
assertNotNull(MODEL_ATTRIBUTE_SPANNERS + " is null", spannersInModel);
assertEquals(SPANNERS, spannersInModel);
}
@Test
public void testTimeOfDayGreetingMorning() {
// Set the current time to 9AM
when(currentTime.get()).thenReturn(LocalTime.of(9,0));
// Call the controller
ModelMap model = new ModelMap();
controller.displaySpanners(model);
// Assert that time of day greeting is morning
String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING);
assertEquals(GREETING_MORNING, greeting);
}
@Test
public void testTimeOfDayGreetingAfternoon() {
// Set the current time to 2PM
when(currentTime.get()).thenReturn(LocalTime.of(14,0));
// Call the controller
ModelMap model = new ModelMap();
controller.displaySpanners(model);
// Assert that time of day greeting is afternoon
String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING);
assertEquals(GREETING_AFTERNOON, greeting);
}
@Test
public void testTimeOfDayGreetingEvening() {
// Set the current time to 8PM
when(currentTime.get()).thenReturn(LocalTime.of(20,0));
// Call the controller
ModelMap model = new ModelMap();
controller.displaySpanners(model);
// Assert that time of day greeting is evening
String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING);
assertEquals(GREETING_EVENING, greeting);
}
/**
* Test for delete spaner action on display spanners page
*/
@Test
public void testDeleteSpanner() throws Exception {
// Stub behaviours - spanner exists to be deleted
when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER);
// Request a spanner is deleted
ModelMap model = new ModelMap();
String view = controller.deleteSpanner(SPANNER_ID, model);
// Verify that spanner was deleted
verify(spannersService).delete(SPANNER);
// Assert spanners list page is shown after deletion
assertEquals("view name", VIEW_DISPLAY_SPANNERS, view);
}
/**
* Test attempt to delete a spanner that does not exist
*/
@Test
public void testDeleteSpannerNotFound() {
// Stub behaviours - spanner to be deleted does not exist
when(spannersService.findOne(SPANNER_ID)).thenReturn(null);
// Request a spanner is deleted
try {
controller.deleteSpanner(SPANNER_ID, new ModelMap());
fail("Expected: SpannerNotFoundException");
} catch(SpannerNotFoundException notFoundEx) {
assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId());
}
}
}
| 31.562914
| 96
| 0.690516
|
c3515e96d454a231afdc0f7be1110f8391c497bd
| 1,514
|
/* вор, который ворует самые ценные посылки и игнорирует все остальное.
* Вор принимает в конструкторе переменную int – минимальную стоимость посылки, которую он будет воровать.
* Также, в данном классе должен присутствовать метод getStolenValue,
* который возвращает суммарную стоимость всех посылок, которые он своровал.
* Воровство происходит следующим образом: вместо посылки, которая пришла вору,
* он отдает новую, такую же, только с нулевой ценностью и содержимым посылки "stones instead of {content}".
* */
package week4.logging.mailsIndustry;
public class Thief implements MailService {
private final int minValue;
private int stolenValue = 0;
public Thief(int minValue) {
this.minValue = minValue;
}
private MailPackage stealPackage(MailPackage mailPackage) {
Package newContent = new Package(
"stones instead of " + mailPackage.getContent().getContent(),
0
);
stolenValue += mailPackage.getContent().getPrice();
return new MailPackage(mailPackage.getFrom(), mailPackage.getTo(), newContent);
}
public int getStolenValue() {
return stolenValue;
}
@Override
public Sendable processMail(Sendable mail) {
if (!(mail instanceof MailPackage))
return mail;
MailPackage mailPackage = (MailPackage) mail;
if (mailPackage.getContent().getPrice() < minValue) {
return mail;
}
return stealPackage(mailPackage);
}
}
| 35.209302
| 108
| 0.68362
|
6638f0140269ca1b5d94c2cb4b5b1390be3916b0
| 280
|
package com.edomingues.icalexchange365.repository;
import com.edomingues.icalexchange365.model.AuthorizationState;
public interface AuthorizationStateRepository {
public AuthorizationState load(String state);
public void save(AuthorizationState authorizationState);
}
| 25.454545
| 63
| 0.835714
|
49694d6ca9747e9231b8da825c2b7ca5b853afeb
| 2,532
|
package de.uni_hildesheim.sse.monitoring.runtime.recordingStrategiesElements;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import de.uni_hildesheim.sse.monitoring.runtime.recordingStrategies.
RecorderStrategy;
/**
* Defines a message element which transports recording of threads e.g. over
* network.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
public class RegisterElement extends RecordingStrategiesElement {
/**
* Stores the thread identification.
*/
private long threadId;
/**
* Stores the id of the new thread.
*/
private long newId;
/**
* The number of nano seconds in {@link #threadId}.
*/
private long threadTicks;
/**
* The current time in nano seconds.
*/
private long now;
/**
* Creates a new message.
*
* @param threadId the identification of the thread to be registered
* @param newId the new thread
* @param threadTicks the ticks of <code>threadId</code>
* @param now the current time in nano seconds
*
* @since 1.00
*/
public RegisterElement(long threadId, long newId, long threadTicks,
long now) {
this.threadId = threadId;
this.newId = newId;
this.threadTicks = threadTicks;
this.now = now;
}
/**
* Creates a new message without explicit information.
*
* @since 1.00
*/
public RegisterElement() {
}
/**
* {@inheritDoc}
*/
@Override
public void send(DataOutputStream out) throws IOException {
out.writeLong(threadId);
out.writeLong(newId);
out.writeLong(threadTicks);
out.writeLong(now);
}
/**
* {@inheritDoc}
*/
@Override
public void read(DataInputStream in) throws IOException {
threadId = in.readLong();
newId = in.readLong();
threadTicks = in.readLong();
now = in.readLong();
}
/**
* {@inheritDoc}
*/
@Override
public int getIdentification() {
return Constants.REGISTER;
}
/**
* {@inheritDoc}
*/
@Override
public void process(RecorderStrategy strategy) {
strategy.register(threadId, newId, threadTicks, now);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
}
}
| 22.607143
| 78
| 0.571485
|
923626506f61ef69e90ef4b1dcd796565d76b61a
| 10,852
|
package com.concordium.sdk.transactions;
import com.concordium.sdk.crypto.ed25519.ED25519ResultCode;
import com.concordium.sdk.crypto.ed25519.ED25519SecretKey;
import com.concordium.sdk.exceptions.ED25519Exception;
import com.concordium.sdk.exceptions.TransactionCreationException;
import lombok.val;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
public class TransferWithMemoTransactionTest {
@Test
public void testCreateTransferWithMemo() {
try {
val transaction = TransferWithMemoTransaction
.builder()
.memo(Memo.from(new byte[]{1, 2, 3, 4, 5}))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(TransactionSigner.from(
SignerEntry.from(Index.from(0), Index.from(0),
ED25519SecretKey.from("7100071c835a0a35e86dccba7ee9d10b89e36d1e596771cdc8ee36a17f7abbf2")),
SignerEntry.from(Index.from(0), Index.from(1),
ED25519SecretKey.from("cd20ea0127cddf77cf2c20a18ec4516a99528a72e642ac7deb92131a9d108ae9"))
))
.build();
assertEquals("2cf00d7d5064ab6f70102a8bba4082b7d85b9b411f981f00b5994adc0b461083", transaction.getHash().asHex());
assertArrayEquals(TestUtils.EXPECTED_BLOCK_ITEM_TRANSFER_WITH_MEMO_VERSIONED_BYTES, TestUtils.signedByteArrayToUnsigned(transaction.getBytes()));
} catch (TransactionCreationException e) {
fail("Unexpected error: " + e.getMessage());
}
}
@Test
public void testCreateTransferWithMemoTransactionWithoutMemoFails() {
try {
TransferWithMemoTransaction
.builder()
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Memo cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferWithMemoTransactionWithoutSenderFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Sender cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutReceiverFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Receiver cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutAmountFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Amount cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutNonceFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. AccountNonce cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutExpiryFails() {
try {
AccountAddress sender = AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc");
AccountAddress receiver = AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM");
CCDAmount amount = CCDAmount.fromMicro(17);
AccountNonce accountNonce = AccountNonce.from(78910);
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(sender)
.receiver(receiver)
.amount(amount)
.nonce(accountNonce)
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Expiry cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutSignerShouldFail() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Signer cannot be null or empty")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithInvalidSignerFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("3JwD2Wm3nMbsowCwb1iGEpnt47UQgdrtnq2qT6opJc3z2AgCrc"))
.receiver(AccountAddress.from("3hYXYEPuGyhFcVRhSk2cVgKBhzVcAryjPskYk4SecpwGnoHhuM"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getSignerWithMalformedSecretKey())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
val inner = (ED25519Exception) e.getInner();
if (!inner.getCode().equals(ED25519ResultCode.MALFORMED_SECRET_KEY))
fail("Unexpected error: " + e.getMessage());
}
}
private TransactionSigner getValidSigner() {
ED25519SecretKey firstSecretKey = ED25519SecretKey.from("7100071c835a0a35e86dccba7ee9d10b89e36d1e596771cdc8ee36a17f7abbf2");
ED25519SecretKey secondSecretKey = ED25519SecretKey.from("cd20ea0127cddf77cf2c20a18ec4516a99528a72e642ac7deb92131a9d108ae9");
return TransactionSigner.from(
SignerEntry.from(Index.from(0), Index.from(0),
firstSecretKey),
SignerEntry.from(Index.from(0), Index.from(1),
secondSecretKey));
}
private TransactionSigner getSignerWithMalformedSecretKey() {
return new TransactionSigner() {
@Override
public TransactionSigner put(Index credentialIndex, Index keyIndex, Signer signer) {
return this;
}
@Override
public TransactionSignature sign(byte[] message) throws ED25519Exception {
throw ED25519Exception.from(ED25519ResultCode.MALFORMED_SECRET_KEY);
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
};
}
}
| 44.842975
| 157
| 0.589845
|
5cd07c2c47f4b363baba2ae32621e69ad6505412
| 1,288
|
package org.fluentjava.iwant.core;
import java.util.SortedSet;
import java.util.TreeSet;
public class Workspace {
private final String name;
private final SortedSet<Target<?>> targets;
private Workspace(String name, SortedSet<Target<?>> targets) {
this.name = name;
this.targets = targets;
}
public String name() {
return name;
}
public SortedSet<Target<?>> targets() {
return targets;
}
public static WorkspaceSpecification with() {
return new WorkspaceSpecification();
}
public static class WorkspaceSpecification {
private String name;
private final SortedSet<Target<?>> targets = new TreeSet<Target<?>>();
public WorkspaceSpecification name(String name) {
this.name = name;
return this;
}
public TargetSpecification target(String name) {
return new TargetSpecification(name);
}
/**
* TODO combine with the other TargetBuilder
*/
public class TargetSpecification {
private final String name;
public TargetSpecification(String name) {
this.name = name;
}
public WorkspaceSpecification content(Content content) {
targets.add(new Target<Content>(name, content));
return WorkspaceSpecification.this;
}
}
public Workspace endWorkspace() {
return new Workspace(name, targets);
}
}
}
| 19.223881
| 72
| 0.710404
|
c99a24d47c89f10b55b7fc27338078bd36d25b67
| 1,831
|
package org.jayhenri.store_manager.service.store;
import org.jayhenri.store_manager.interfaces.service.other.EmployeeServiceI;
import org.jayhenri.store_manager.model.store.Employee;
import org.jayhenri.store_manager.repository.store.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
/**
* The type Employee service.
*/
@Service
public class EmployeeService implements EmployeeServiceI {
private final EmployeeRepository employeeRepository;
/**
* Instantiates a new Employee service.
*
* @param employeeRepository the employee repository
*/
@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
// this.orderDBService = orderDBService;
}
public boolean existsByPhoneNumber(String phoneNumber) {
return employeeRepository.existsByPhoneNumber(phoneNumber);
}
public void add(Employee employee) {
employeeRepository.save(employee);
}
public void remove(Employee employee) {
employeeRepository.delete(employee);
}
public void update(Employee employee) {
employeeRepository.save(employee);
}
public List<Employee> findAll() {
return employeeRepository.findAll();
}
public boolean existsById(UUID uuid) {
return employeeRepository.existsById(uuid);
}
public Employee getById(UUID uuid) {
return employeeRepository.getById(uuid);
}
public boolean existsByEmail(String email) {
return employeeRepository.existsByEmail(email);
}
public Employee getByEmail(String email) {
return employeeRepository.getByEmail(email);
}
}
| 23.779221
| 76
| 0.724194
|
336ea0df0b1f29d54c8a5567ba6057bf47615271
| 1,264
|
/*
* Copyright 2017 Michele Milidoni <michelemilidoni@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.milidoni.wespeak_online.util;
import javax.persistence.EntityManager;
/**
*
* @author Michele Milidoni <michelemilidoni@gmail.com>
*/
public class TestUtil {
public static void cleanTables(EntityManager em) {
System.out.print("Cleaning tables... ");
String[] tables = {"resource", "phone_call", "topic", "user"};
em.getTransaction().begin();
for (String table : tables) {
em.createNativeQuery(
" delete from `" + table + "`"
).executeUpdate();
}
em.getTransaction().commit();
System.out.println("done!");
}
}
| 32.410256
| 75
| 0.663766
|
9416f4489883f899b6664160d2684e3806bd09b9
| 1,622
|
/**
* ListApps - lists all 3rd party installed apps
*
* @author (Brendan Manning)
* @version (0.0.1)
*/
import java.io.*;
import java.lang.*;
import java.lang.String;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class listapps
{
public static void main(String[] args) {
//this method should never get called
//but if it does, show a copyright notice
System.out.println("ListApps - part of jLinux (c) 2016 Brendan Manning");
}
public static List list() {
List apps = new ArrayList();
String al = "";
String fName;
File appsFolder = new File(jLinuxInfo.appsLocation());
File[] appsList = appsFolder.listFiles();
//System.out.println("The following apps are currently installed:");
for (int i = 0; i < appsList.length; i++) {
if(appsList[i].isFile()) {
fName = appsList[i].getName();
if(fName.startsWith(".")) {
//ignore dot files
} else {
if(jLinuxInfo.guiEnabled() == false) {
System.out.println("[" + fName.replace(".jar", "") + "]");
apps.add(appsList[i].getAbsolutePath());
}
if(jLinuxInfo.guiEnabled()) {
al += fName.replace(".jar", "") + "\n";
}
}
}
}
/* if GUI was enabled, print the list now */
if(jLinuxInfo.guiEnabled()) {
o.echo(true, al);
}
return apps;
}
}
| 31.803922
| 82
| 0.505549
|
5574c1c4c845c584f095ca3ae1b98ba20d2af296
| 2,757
|
/*
* (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Anahide Tchertchian
*/
package org.nuxeo.theme.styling.service.registries;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.nuxeo.runtime.model.ContributionFragmentRegistry;
import org.nuxeo.theme.styling.service.descriptors.FlavorDescriptor;
/**
* Registry for theme flavors, handling merge of registered {@link FlavorDescriptor} elements.
*
* @since 5.5
*/
public class FlavorRegistry extends ContributionFragmentRegistry<FlavorDescriptor> {
protected Map<String, FlavorDescriptor> themePageFlavors = new HashMap<String, FlavorDescriptor>();
@Override
public String getContributionId(FlavorDescriptor contrib) {
return contrib.getName();
}
@Override
public void contributionUpdated(String id, FlavorDescriptor contrib, FlavorDescriptor newOrigContrib) {
themePageFlavors.put(id, contrib);
}
@Override
public synchronized void removeContribution(FlavorDescriptor contrib) {
removeContribution(contrib, true);
}
@Override
public void contributionRemoved(String id, FlavorDescriptor origContrib) {
themePageFlavors.remove(id);
}
@Override
public FlavorDescriptor clone(FlavorDescriptor orig) {
if (orig == null) {
return null;
}
return orig.clone();
}
@Override
public void merge(FlavorDescriptor src, FlavorDescriptor dst) {
dst.merge(src);
}
public FlavorDescriptor getFlavor(String id) {
return themePageFlavors.get(id);
}
public List<FlavorDescriptor> getFlavorsExtending(String flavor) {
List<FlavorDescriptor> res = new ArrayList<FlavorDescriptor>();
for (FlavorDescriptor f : themePageFlavors.values()) {
if (f != null) {
String extendsFlavor = f.getExtendsFlavor();
if (!StringUtils.isBlank(extendsFlavor) && extendsFlavor.equals(flavor)) {
res.add(f);
}
}
}
return res;
}
}
| 30.633333
| 107
| 0.689518
|
607c5eb73424cb3fd352de17df5fc2a7a28f1e22
| 1,282
|
package lt.samerdokas.gdd.batch;
import java.nio.file.Paths;
import java.util.Locale;
class Env {
public static boolean isTerminalCompatible() {
return Boolean.parseBoolean(System.getenv().getOrDefault("GDD_UNICODE_TERMINAL", "false").toLowerCase(Locale.ROOT));
}
public static String getServiceURL() {
return System.getenv().getOrDefault("GDD_SERVICE_URL", "https://gdd.samerdokas.lt/api/GetDownloadInfo");
}
public static String getDownloadPath() {
return System.getenv().getOrDefault("GDD_DOWNLOAD_PATH", Paths.get(System.getProperty("user.home", "."),"Downloads", "GDD").toString());
}
public static int getWorkerCount() {
return getEnvInteger("GDD_WORKERS", 4);
}
public static int getDownloadRetryCount() {
return getEnvInteger("GDD_DOWNLOAD_RETRIES", 10);
}
public static int getDownloadRetryDelaySeconds() {
return getEnvInteger("GDD_DOWNLOAD_RETRY_DELAY", 10);
}
private static int getEnvInteger(String name, int defaultValue) {
try {
return Integer.parseInt(System.getenv().getOrDefault(name, String.valueOf(defaultValue)));
} catch (NumberFormatException e) {
return defaultValue;
}
}
}
| 32.871795
| 144
| 0.670047
|
cd9fea3e888ab754ff8fcd48f37de96038823a8b
| 892
|
package com.acgist.snail.utils;
import java.lang.reflect.InvocationTargetException;
import org.junit.jupiter.api.Test;
import com.acgist.snail.pojo.entity.TaskEntity;
public class PropertyDescriptorTest extends Performance {
@Test
public void testRead() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
TaskEntity task = new TaskEntity();
task.setId("1234");
PropertyDescriptor descriptor = new PropertyDescriptor("id", task.getClass());
this.log(descriptor.getReadMethod().invoke(task));
}
@Test
public void testWrite() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
TaskEntity task = new TaskEntity();
PropertyDescriptor descriptor = new PropertyDescriptor("id", task.getClass());
this.log(task.getId());
descriptor.getWriteMethod().invoke(task, "1234");
this.log(task.getId());
}
}
| 30.758621
| 109
| 0.776906
|
c9727183c57fde88b53cfb7c8f81608eaa8868d6
| 254
|
package com.wisdom.acm.base.vo;
import lombok.Data;
@Data
public class BaseBoVo {
/**
* 主键
*/
private Integer id;
/**
* 业务对象代码
*/
private String boCode;
/**
* 业务对象名称
*/
private String boName;
}
| 10.583333
| 31
| 0.519685
|
aba2db8a7800d6dbddf0f012b61de7079531eccd
| 13,834
|
package cat.yoink.dream.impl.module.combat;
import cat.yoink.dream.api.module.Category;
import cat.yoink.dream.api.module.Module;
import cat.yoink.dream.api.setting.Setting;
import cat.yoink.dream.api.setting.SettingType;
import cat.yoink.dream.mixin.mixins.accessor.IMinecraft;
import net.minecraft.block.Block;
import net.minecraft.block.BlockObsidian;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.client.CPacketEntityAction;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class Surround extends Module {
private final Setting jumpDisable = new Setting.Builder(SettingType.BOOLEAN).setName("Toggle on Jump")
.setModule(this).setBooleanValue(true).build();
private final Setting autoToggle = new Setting.Builder(SettingType.BOOLEAN).setName("Toggles").setModule(this)
.setBooleanValue(true).build();
private final Setting chainPopToggle = new Setting.Builder(SettingType.BOOLEAN).setName("TotemPopToggle")
.setModule(this).setBooleanValue(true).build();
public Surround(String name, String description, Category category) {
super(name, description, category);
addSetting(jumpDisable);
addSetting(autoToggle);
addSetting(chainPopToggle);
}
public static boolean hasNeighbour(BlockPos blockPos) {
for (EnumFacing side : EnumFacing.values()) {
BlockPos neighbour = blockPos.offset(side);
if (!Minecraft.getMinecraft().world.getBlockState(neighbour).getMaterial().isReplaceable())
return true;
}
return false;
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (mc.player == null)
return;
if (!mc.player.onGround && jumpDisable.getBooleanValue()) {
toggle();
return;
}
final Vec3d vec3d = getInterpolatedPos(mc.player, 0);
BlockPos northBlockPos = new BlockPos(vec3d).north();
BlockPos southBlockPos = new BlockPos(vec3d).south();
BlockPos eastBlockPos = new BlockPos(vec3d).east();
BlockPos westBlockPos = new BlockPos(vec3d).west();
final int newSlot = findBlockInHotbar();
if (newSlot == -1)
return;
final BlockPos centerPos = mc.player.getPosition();
double y = centerPos.getY();
double x = centerPos.getX();
double z = centerPos.getZ();
final Vec3d plusPlus = new Vec3d(x + 0.5, y, z + 0.5);
final Vec3d plusMinus = new Vec3d(x + 0.5, y, z - 0.5);
final Vec3d minusMinus = new Vec3d(x - 0.5, y, z - 0.5);
final Vec3d minusPlus = new Vec3d(x - 0.5, y, z + 0.5);
final int oldSlot = mc.player.inventory.currentItem;
mc.player.inventory.currentItem = newSlot;
if (!hasNeighbour(northBlockPos)) {
for (EnumFacing side : EnumFacing.values()) {
BlockPos neighbour = northBlockPos.offset(side);
if (hasNeighbour(neighbour)) {
northBlockPos = neighbour;
break;
}
}
}
if (!hasNeighbour(southBlockPos)) {
for (EnumFacing side : EnumFacing.values()) {
BlockPos neighbour = southBlockPos.offset(side);
if (hasNeighbour(neighbour)) {
southBlockPos = neighbour;
break;
}
}
}
if (!hasNeighbour(eastBlockPos)) {
for (EnumFacing side : EnumFacing.values()) {
BlockPos neighbour = eastBlockPos.offset(side);
if (hasNeighbour(neighbour)) {
eastBlockPos = neighbour;
break;
}
}
}
if (!hasNeighbour(westBlockPos)) {
for (EnumFacing side : EnumFacing.values()) {
BlockPos neighbour = westBlockPos.offset(side);
if (hasNeighbour(neighbour)) {
westBlockPos = neighbour;
break;
}
}
}
if (mc.world.getBlockState(northBlockPos).getMaterial().isReplaceable() && isEntitiesEmpty(northBlockPos)) {
if (mc.player.onGround) {
if (getDst(plusPlus) < getDst(plusMinus) && getDst(plusPlus) < getDst(minusMinus)
&& getDst(plusPlus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
if (getDst(plusMinus) < getDst(plusPlus) && getDst(plusMinus) < getDst(minusMinus)
&& getDst(plusMinus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusMinus) < getDst(plusPlus) && getDst(minusMinus) < getDst(plusMinus)
&& getDst(minusMinus) < getDst(minusPlus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusPlus) < getDst(plusPlus) && getDst(minusPlus) < getDst(plusMinus)
&& getDst(minusPlus) < getDst(minusMinus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
}
placeBlockScaffold(northBlockPos, true);
}
if (mc.world.getBlockState(southBlockPos).getMaterial().isReplaceable() && isEntitiesEmpty(southBlockPos)) {
if (mc.player.onGround) {
if (getDst(plusPlus) < getDst(plusMinus) && getDst(plusPlus) < getDst(minusMinus)
&& getDst(plusPlus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
if (getDst(plusMinus) < getDst(plusPlus) && getDst(plusMinus) < getDst(minusMinus)
&& getDst(plusMinus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusMinus) < getDst(plusPlus) && getDst(minusMinus) < getDst(plusMinus)
&& getDst(minusMinus) < getDst(minusPlus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusPlus) < getDst(plusPlus) && getDst(minusPlus) < getDst(plusMinus)
&& getDst(minusPlus) < getDst(minusMinus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
}
placeBlockScaffold(southBlockPos, true);
}
if (mc.world.getBlockState(eastBlockPos).getMaterial().isReplaceable() && isEntitiesEmpty(eastBlockPos)) {
if (mc.player.onGround) {
if (getDst(plusPlus) < getDst(plusMinus) && getDst(plusPlus) < getDst(minusMinus)
&& getDst(plusPlus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
if (getDst(plusMinus) < getDst(plusPlus) && getDst(plusMinus) < getDst(minusMinus)
&& getDst(plusMinus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusMinus) < getDst(plusPlus) && getDst(minusMinus) < getDst(plusMinus)
&& getDst(minusMinus) < getDst(minusPlus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusPlus) < getDst(plusPlus) && getDst(minusPlus) < getDst(plusMinus)
&& getDst(minusPlus) < getDst(minusMinus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
}
placeBlockScaffold(eastBlockPos, true);
}
if (mc.world.getBlockState(westBlockPos).getMaterial().isReplaceable() && isEntitiesEmpty(westBlockPos)) {
if (mc.player.onGround) {
if (getDst(plusPlus) < getDst(plusMinus) && getDst(plusPlus) < getDst(minusMinus)
&& getDst(plusPlus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
if (getDst(plusMinus) < getDst(plusPlus) && getDst(plusMinus) < getDst(minusMinus)
&& getDst(plusMinus) < getDst(minusPlus)) {
x = centerPos.getX() + 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusMinus) < getDst(plusPlus) && getDst(minusMinus) < getDst(plusMinus)
&& getDst(minusMinus) < getDst(minusPlus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() - 0.5;
centerPlayer(x, y, z);
}
if (getDst(minusPlus) < getDst(plusPlus) && getDst(minusPlus) < getDst(plusMinus)
&& getDst(minusPlus) < getDst(minusMinus)) {
x = centerPos.getX() - 0.5;
z = centerPos.getZ() + 0.5;
centerPlayer(x, y, z);
}
}
placeBlockScaffold(westBlockPos, true);
}
mc.player.inventory.currentItem = oldSlot;
if ((autoToggle.getBooleanValue() || chainPopToggle.getBooleanValue())
&& (mc.world.getBlockState(new BlockPos(vec3d).north()).getBlock() == Blocks.OBSIDIAN
|| mc.world.getBlockState(new BlockPos(vec3d).north()).getBlock() == Blocks.BEDROCK)
&& (mc.world.getBlockState(new BlockPos(vec3d).south()).getBlock() == Blocks.OBSIDIAN
|| mc.world.getBlockState(new BlockPos(vec3d).south()).getBlock() == Blocks.BEDROCK)
&& (mc.world.getBlockState(new BlockPos(vec3d).west()).getBlock() == Blocks.OBSIDIAN
|| mc.world.getBlockState(new BlockPos(vec3d).west()).getBlock() == Blocks.BEDROCK)
&& (mc.world.getBlockState(new BlockPos(vec3d).east()).getBlock() == Blocks.OBSIDIAN
|| mc.world.getBlockState(new BlockPos(vec3d).east()).getBlock() == Blocks.BEDROCK)) {
chainPopToggle.setBooleanValue(false);
toggle();
}
}
private int findBlockInHotbar() {
for (int i = 0; i < 9; ++i) {
final ItemStack stack = mc.player.inventory.getStackInSlot(i);
if (stack != ItemStack.EMPTY && stack.getItem() instanceof ItemBlock) {
final Block block = ((ItemBlock) stack.getItem()).getBlock();
if (block instanceof BlockObsidian) {
return i;
}
}
}
return -1;
}
private void centerPlayer(double x, double y, double z) {
mc.player.connection.sendPacket(new CPacketPlayer.Position(x, y, z, true));
mc.player.setPosition(x, y, z);
}
private double getDst(Vec3d vec) {
return mc.player.getDistance(vec.x, vec.y, vec.z);
}
private boolean isEntitiesEmpty(BlockPos pos) {
return mc.world.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(pos)).stream()
.filter(e -> !(e instanceof EntityItem) && !(e instanceof EntityXPOrb)).count() == 0;
}
public static void placeBlockScaffold(BlockPos pos, boolean rotate) {
for (EnumFacing side : EnumFacing.values()) {
final BlockPos neighbor = pos.offset(side);
final EnumFacing side2 = side.getOpposite();
if (!canBeClicked(neighbor))
continue;
final Vec3d hitVec = new Vec3d(neighbor).add(new Vec3d(0.5, 0.5, 0.5))
.add(new Vec3d(side2.getDirectionVec()).scale(0.5));
if (rotate)
faceVectorPacketInstant(hitVec);
Minecraft.getMinecraft().player.connection.sendPacket(new CPacketEntityAction(
Minecraft.getMinecraft().player, CPacketEntityAction.Action.START_SNEAKING));
processRightClickBlock(neighbor, side2, hitVec);
Minecraft.getMinecraft().player.swingArm(EnumHand.MAIN_HAND);
((IMinecraft) Minecraft.getMinecraft()).setRightClickDelayTimer(0);
Minecraft.getMinecraft().player.connection.sendPacket(
new CPacketEntityAction(Minecraft.getMinecraft().player, CPacketEntityAction.Action.STOP_SNEAKING));
return;
}
}
private static PlayerControllerMP getPlayerController() {
return Minecraft.getMinecraft().playerController;
}
public static void processRightClickBlock(BlockPos pos, EnumFacing side, Vec3d hitVec) {
getPlayerController().processRightClickBlock(Minecraft.getMinecraft().player, Minecraft.getMinecraft().world,
pos, side, hitVec, EnumHand.MAIN_HAND);
}
public static boolean canBeClicked(BlockPos pos) {
return Minecraft.getMinecraft().world.getBlockState(pos).getBlock()
.canCollideCheck(Minecraft.getMinecraft().world.getBlockState(pos), false);
}
public static void faceVectorPacketInstant(Vec3d vec) {
final float[] rotations = getNeededRotations2(vec);
Minecraft.getMinecraft().player.connection.sendPacket(
new CPacketPlayer.Rotation(rotations[0], rotations[1], Minecraft.getMinecraft().player.onGround));
}
private static float[] getNeededRotations2(Vec3d vec) {
final Vec3d eyesPos = getEyesPos();
final double diffX = vec.x - eyesPos.x;
final double diffY = vec.y - eyesPos.y;
final double diffZ = vec.z - eyesPos.z;
final double diffXZ = Math.sqrt(diffX * diffX + diffZ * diffZ);
final float yaw = (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F;
final float pitch = (float) -Math.toDegrees(Math.atan2(diffY, diffXZ));
return new float[] {
Minecraft.getMinecraft().player.rotationYaw
+ MathHelper.wrapDegrees(yaw - Minecraft.getMinecraft().player.rotationYaw),
Minecraft.getMinecraft().player.rotationPitch
+ MathHelper.wrapDegrees(pitch - Minecraft.getMinecraft().player.rotationPitch) };
}
public static Vec3d getEyesPos() {
return new Vec3d(Minecraft.getMinecraft().player.posX,
Minecraft.getMinecraft().player.posY + Minecraft.getMinecraft().player.getEyeHeight(),
Minecraft.getMinecraft().player.posZ);
}
public static Vec3d getInterpolatedPos(Entity entity, float ticks) {
return new Vec3d(entity.lastTickPosX, entity.lastTickPosY, entity.lastTickPosZ)
.add(getInterpolatedAmount(entity, ticks));
}
public static Vec3d getInterpolatedAmount(Entity entity, double ticks) {
return getInterpolatedAmount(entity, ticks, ticks, ticks);
}
public static Vec3d getInterpolatedAmount(Entity entity, double x, double y, double z) {
return new Vec3d((entity.posX - entity.lastTickPosX) * x, (entity.posY - entity.lastTickPosY) * y,
(entity.posZ - entity.lastTickPosZ) * z);
}
}
| 38.427778
| 111
| 0.692569
|
9a8d7d592ff7c97ad0c4cf60cd9ae74f80249ddb
| 2,761
|
/*
* Copyright 2016-2021 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 cn.istarxc.movie.service.impl;
import cn.istarxc.movie.entity.MovieScreenwriter;
import cn.istarxc.movie.repository.MovieScreenwriterRepository;
import cn.istarxc.movie.service.MovieScreenwriterService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* relationship between screenwriters and movies service implementation
*
* @author Cherlas
* @since 2022-02-07 22:09:55
*/
@Service("movieScreenwriterService")
@AllArgsConstructor
public class MovieScreenwriterServiceImpl implements MovieScreenwriterService {
private MovieScreenwriterRepository movieScreenwriterRepository;
@Override
public Mono<MovieScreenwriter> save(MovieScreenwriter movieScreenwriter) {
return movieScreenwriterRepository.save(movieScreenwriter);
}
@Override
public Flux<MovieScreenwriter> saveAll(Iterable<MovieScreenwriter> movieScreenwriters) {
return movieScreenwriterRepository.saveAll(movieScreenwriters);
}
@Override
public Mono<MovieScreenwriter> findById(Integer id) {
return movieScreenwriterRepository.findById(id);
}
@Override
public Mono<Boolean> existsById(Integer id) {
return movieScreenwriterRepository.existsById(id);
}
@Override
public Flux<MovieScreenwriter> findAll() {
return movieScreenwriterRepository.findAll();
}
@Override
public Flux<MovieScreenwriter> findAllById(Iterable<Integer> ids) {
return movieScreenwriterRepository.findAllById(ids);
}
@Override
public Mono<Long> count() {
return movieScreenwriterRepository.count();
}
@Override
public Mono<Void> deleteById(Integer id) {
return movieScreenwriterRepository.deleteById(id);
}
@Override
public Mono<Void> delete(MovieScreenwriter movieScreenwriter) {
return movieScreenwriterRepository.delete(movieScreenwriter);
}
@Override
public Mono<Void> deleteAllById(Iterable<Integer> ids) {
return movieScreenwriterRepository.deleteAllById(ids);
}
}
| 31.375
| 92
| 0.749366
|
350942826610640ea0c94d6c08a9b7ba618614f5
| 3,690
|
package com.dat3m.svcomp.utils;
import static com.dat3m.dartagnan.program.utils.EType.INIT;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.IntStream;
import com.dat3m.dartagnan.program.Program;
import com.dat3m.dartagnan.wmm.filter.FilterBasic;
import com.dat3m.svcomp.options.SVCOMPOptions;
public class SVCOMPWitness {
private Program program;
private SVCOMPOptions options;
public SVCOMPWitness(Program p, SVCOMPOptions o) {
this.program = p;
this.options = o;
}
public void write() {
String programFilePath = options.getProgramFilePath().substring(0, options.getProgramFilePath().lastIndexOf('.')) + ".c";
String programName = programFilePath.substring(programFilePath.lastIndexOf('/'), programFilePath.lastIndexOf('.'));
File newTextFile = new File("./output/" + programName + ".graphml");
FileWriter fw;
try {
fw = new FileWriter(newTextFile);
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fw.write("<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n");
fw.write(" <graph edgedefault=\"directed\">\n");
fw.write(" <data key=\"witness-type\">violation_witness</data>\n");
fw.write(" <data key=\"producer\">Dat3M</data>\n");
fw.write(" <data key=\"specification\">CHECK( init(main()), LTL(G ! call(__VERIFIER_error())) )</data>\n");
fw.write(" <data key=\"programfile\">" + programFilePath + "</data>\n");
fw.write(" <data key=\"architecture\">32bit</data>\n");
fw.write(" <data key=\"programhash\">" + checksum() + "</data>\n");
fw.write(" <data key=\"sourcecodelang\">C</data>\n");
fw.write(" <node id=\"N0\"> <data key=\"entry\">true</data> </node>\n");
fw.write(" <edge source=\"N0\" target=\"N1\"> <data key=\"createThread\">0</data> <data key=\"enterFunction\">main</data> </edge>\n");
fw.write(" <node id=\"N1\"> </node>\n");
int threadCount = program.getThreads().size() - program.getCache().getEvents(FilterBasic.get(INIT)).size();
for(int i : IntStream.range(1, threadCount-1).toArray()) {
fw.write(" <edge source=\"N" + i + "\" target=\"N" + (i+1) + "\"> <data key=\"createThread\">" + i + "</data> </edge>\n");
fw.write(" <node id=\"N" + (i+1) + "\"> </node>\n");
}
fw.write(" <edge source=\"N" + (threadCount-1) + "\" target=\"N" + threadCount + "\"> <data key=\"createThread\">" + (threadCount-1) + "</data> </edge>\n");
fw.write(" <node id=\"N" + threadCount + "\"> <data key=\"violation\">true</data> </node>\n");
fw.write(" </graph>\n");
fw.write("</graphml>\n");
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private String checksum() {
String output = null;
String input = options.getProgramFilePath();
try {
Process proc = Runtime.getRuntime().exec("sha256sum " + input);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
proc.waitFor();
} catch(InterruptedException e) {
System.out.println(e.getMessage());
System.exit(0);
}
while(read.ready()) {
output = read.readLine();
}
if(proc.exitValue() == 1) {
BufferedReader error = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while(error.ready()) {
System.out.println(error.readLine());
}
System.exit(0);
}
} catch(IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
output = output.substring(0, output.lastIndexOf(' '));
return output;
}
}
| 40.108696
| 162
| 0.636043
|
c2dc220dce8d9988817f1a56189b354b99a484c7
| 159
|
package com.example.uas_usecase_2301847404.game;
public class InfantryHero extends Heroes{
public InfantryHero() {
this.HeroType = Heroes.INFANTRY;
}
}
| 15.9
| 48
| 0.773585
|
6c122c4e44397e5a2537de33f68e2cd663509669
| 5,787
|
/*
* Copyright 2015-2016 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.frontend.editor.plugins.field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.PropertyType;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.easymock.Capture;
import org.hippoecm.frontend.HippoTester;
import org.hippoecm.frontend.plugin.config.IClusterConfig;
import org.hippoecm.frontend.plugin.config.IPluginConfig;
import org.hippoecm.frontend.plugin.config.PropertyDescriptor;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.and;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.createNiceMock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TemplateParameterEditorTest {
private static final String PROPERTY_NAME = "a-test-property-name";
private static final String ADD_FIELD_LINK = "dummy-panel:form:tpe:properties:0:value:add";
private WicketTester tester;
private FormTester formTester;
private IPluginConfig pluginConfig;
private Map<Object, Object> propertyValues = new HashMap<>();
@Before
public void setUp(){
tester = new HippoTester();
pluginConfig = createMockPluginConfig();
}
@Test
public void inputSingleValueShouldStoreToBackEnd(){
final IClusterConfig cluster = createMockClusterConfig(Arrays.asList(PROPERTY_NAME), false);
tester.startComponentInPage(new DummyDialog("dummy-panel", Model.of(pluginConfig), cluster, true));
tester.assertComponent("dummy-panel:form:tpe", TemplateParameterEditor.class);
formTester = tester.newFormTester("dummy-panel:form");
formTester.setValue("tpe:properties:0:value:widget", "a test input value");
formTester.submit();
assertEquals("a test input value", propertyValues.get(PROPERTY_NAME));
}
@Test
public void inputMultipleValuesShouldStoreToBackEnd(){
final IClusterConfig cluster = createMockClusterConfig(Arrays.asList(PROPERTY_NAME), true);
tester.startComponentInPage(new DummyDialog("dummy-panel", Model.of(pluginConfig), cluster, true));
tester.assertComponent("dummy-panel:form:tpe", TemplateParameterEditor.class);
formTester = tester.newFormTester("dummy-panel:form");
//add two input fields
tester.executeAjaxEvent(ADD_FIELD_LINK, "onclick");
tester.executeAjaxEvent(ADD_FIELD_LINK, "onclick");
tester.assertComponent("dummy-panel:form:tpe:properties:0:value:values:0:value", TextField.class);
tester.assertComponent("dummy-panel:form:tpe:properties:0:value:values:1:value", TextField.class);
// set two test values
formTester.setValue("tpe:properties:0:value:values:0:value", "input-value-1");
formTester.setValue("tpe:properties:0:value:values:1:value", "input-value-2");
formTester.submit();
String[] storedValues = (String[]) propertyValues.get(PROPERTY_NAME);
assertNotNull(storedValues);
assertTrue(storedValues.length == 2);
assertEquals("input-value-1", storedValues[0]);
assertEquals("input-value-2", storedValues[1]);
}
private IClusterConfig createMockClusterConfig(final List<String> propertyNames, final boolean isMultiple) {
IClusterConfig clusterConfig = createNiceMock(IClusterConfig.class);
final List<PropertyDescriptor> mockProperties = new ArrayList<>();
propertyNames.forEach(name -> mockProperties.add(new PropertyDescriptor(name, PropertyType.STRING, isMultiple)));
expect(clusterConfig.getPropertyDescriptors()).andReturn(mockProperties).anyTimes();
replay(clusterConfig);
return clusterConfig;
}
private IPluginConfig createMockPluginConfig() {
IPluginConfig mockConfig = createNiceMock(IPluginConfig.class);
expect(mockConfig.getName()).andReturn("mock-plugin-config").anyTimes();
final Capture<String> keyArgument = new Capture<>();
expect(mockConfig.getStringArray(
and(
capture(keyArgument),
isA(String.class)
)))
.andAnswer(() -> (String[]) propertyValues.get(keyArgument.getValue())).anyTimes();
final Capture<Object> valueArgument = new Capture<>();
expect(mockConfig.put(
and(
capture(keyArgument),
isA(String.class)
),
capture(valueArgument)))
.andAnswer(() -> {
propertyValues.put(keyArgument.getValue(), valueArgument.getValue());
return null;
}).anyTimes();
replay(mockConfig);
return mockConfig;
}
}
| 38.324503
| 121
| 0.703473
|
472f34bd6c3170e9a005c9dac55a71f9bf5255a2
| 355
|
package com.ethanco.sample.view;
import java.util.Collection;
/**
* Created by EthanCo on 2016/9/30.
*/
public interface IListView<M> {
void onRefreshSuccess(Collection<M> collection);
void onRefreshFailed(String error);
void onLoadMoreSuccess(Collection<M> collection);
void onLoadMoreFailed(String error);
void loadEnd();
}
| 17.75
| 53
| 0.721127
|
b90385344f1e09d1ee8a3fe54e5d0cf7c4957323
| 461
|
package io.github.avivcarmis.confEager.sources;
import io.github.avivcarmis.confEager.ConfEagerSource;
/**
* Out of the box source to map Environment Variables
*/
public class ConfEagerSourceEnvironmentVariables extends ConfEagerSource {
public static final ConfEagerSource INSTANCE = new ConfEagerSourceEnvironmentVariables();
@Override
public String getValueOrNull(String propertyName) {
return System.getenv(propertyName);
}
}
| 25.611111
| 93
| 0.778742
|
bd15a9e58409a371a1e969b455fecf555ee9b74e
| 31,198
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package studentmanagement;
import database.Connect;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import main.Keyboard;
import notifications.Message;
import notifications.SavedStatusNotice;
import notifications.WarningMessage;
/**
*
* @author Nadun
*/
public class CardMarkingStartupScreen extends javax.swing.JFrame {
/**
* Creates new form CardMarkingStartupScreen
*/
private DefaultTableModel dtm;
private static CardMarkingStartupScreen instance=new CardMarkingStartupScreen();
public CardMarkingStartupScreen() {
initComponents();
dtm=(DefaultTableModel) courseTabel.getModel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize);
}
public static CardMarkingStartupScreen getInstance(){
return instance;
}
private void setDate(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
String currentDate=sdf.format(date.getTime());
currentDateTxt.setText(currentDate);
}
public void showInterface(){
retrieveData();
if(dtm.getRowCount()>0){
courseTabel.setRowSelectionInterval(0, 0);
showSelectedCourse();
}
setDate();
instance.setVisible(true);
}
private void showSelectedCourse(){
int selectedRow = courseTabel.getSelectedRow();
String course = dtm.getValueAt(selectedRow, 1).toString();
String institute = dtm.getValueAt(selectedRow, 2).toString();
String city = dtm.getValueAt(selectedRow, 3).toString();
courseNameLbl.setText(course);
instituteLabel.setText(institute);
cityLabel.setText(city);
}
private void cleanTable(){
dtm.getDataVector().removeAllElements();
dtm.fireTableDataChanged();
}
private void addCourse(int id,String courseName,String institute,String city){
dtm.addRow(new Object[]{id,courseName,institute,city});
}
private void retrieveData(){
cleanTable();
String query="SELECT inst.*,cour.* FROM institution inst INNER JOIN course cour ON inst.id="
+ "cour.institution_id WHERE inst.delete_status=0 AND cour.delete_status=0";
Connect c=new Connect();
ResultSet r=c.getQuery(query);
try {
while(r.next()){
int courseID=r.getInt("cour.id");
String courseName=r.getString("cour.name");
String institute=r.getString("inst.name");
String city=r.getString("inst.city");
addCourse(courseID, courseName, institute, city);
}
} catch (SQLException ex) {
Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void retrieveData(String query){
cleanTable();
Connect c=new Connect();
ResultSet r=c.getQuery(query);
try {
while(r.next()){
int ID=r.getInt("cour.id");
String courseName=r.getString("cour.name");
String institute=r.getString("inst.name");
String city=r.getString("inst.city");
addCourse(ID, courseName, institute, city);
}
} catch (SQLException ex) {
Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jButton5 = new javax.swing.JButton();
jPanel7 = new javax.swing.JPanel();
nextBtn = new javax.swing.JButton();
cancelBtn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
courseTabel = new javax.swing.JTable();
currentDateTxt = new javax.swing.JLabel();
courseNameLbl = new javax.swing.JLabel();
instituteLabel = new javax.swing.JLabel();
cityLabel = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
searchBtn = new javax.swing.JButton();
removeSearchBtn = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
courseTxt = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
instituteTxt = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
cityTxt = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
setUndecorated(true);
jPanel3.setBackground(new java.awt.Color(7, 1, 36));
jPanel3.setPreferredSize(new java.awt.Dimension(1366, 768));
jPanel2.setBackground(new java.awt.Color(24, 25, 54));
jLabel10.setFont(new java.awt.Font("Swis721 LtEx BT", 1, 33)); // NOI18N
jLabel10.setForeground(new java.awt.Color(153, 153, 153));
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("Card Marking");
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/cardmarker-icon.png"))); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel4.setBackground(new java.awt.Color(24, 25, 54));
jPanel5.setBackground(new java.awt.Color(7, 1, 36));
jPanel5.setLayout(new java.awt.GridLayout(1, 0, 4, 0));
jButton5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/home.png"))); // NOI18N
jButton5.setFocusPainted(false);
jButton5.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/home-selected.png"))); // NOI18N
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jPanel5.add(jButton5);
jPanel7.setBackground(new java.awt.Color(7, 1, 36));
jPanel7.setPreferredSize(new java.awt.Dimension(140, 46));
jPanel7.setLayout(new java.awt.GridLayout(1, 0));
nextBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/next-2.png"))); // NOI18N
nextBtn.setBorder(null);
nextBtn.setFocusPainted(false);
nextBtn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/next-2-selected.png"))); // NOI18N
nextBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextBtnActionPerformed(evt);
}
});
jPanel7.add(nextBtn);
cancelBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/close.png"))); // NOI18N
cancelBtn.setBorder(null);
cancelBtn.setFocusPainted(false);
cancelBtn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/close-selected.png"))); // NOI18N
cancelBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelBtnActionPerformed(evt);
}
});
jPanel7.add(cancelBtn);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jScrollPane1.setBackground(new java.awt.Color(7, 1, 36));
jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(24, 25, 54), 2));
courseTabel.setBackground(new java.awt.Color(7, 1, 36));
courseTabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(24, 25, 54)));
courseTabel.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 17)); // NOI18N
courseTabel.setForeground(new java.awt.Color(102, 102, 102));
courseTabel.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Course ID", "Course Name", "Institute", "City / Town"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
courseTabel.setFocusable(false);
courseTabel.setGridColor(new java.awt.Color(24, 25, 54));
courseTabel.setRowHeight(30);
courseTabel.setSelectionBackground(new java.awt.Color(24, 25, 54));
courseTabel.setSelectionForeground(new java.awt.Color(153, 153, 153));
courseTabel.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
courseTabel.getTableHeader().setReorderingAllowed(false);
courseTabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
courseTabelMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
courseTabelMousePressed(evt);
}
});
jScrollPane1.setViewportView(courseTabel);
courseTabel.getColumnModel().getColumn(0).setResizable(false);
courseTabel.getColumnModel().getColumn(0).setPreferredWidth(60);
courseTabel.getColumnModel().getColumn(1).setResizable(false);
courseTabel.getColumnModel().getColumn(1).setPreferredWidth(350);
courseTabel.getColumnModel().getColumn(2).setResizable(false);
courseTabel.getColumnModel().getColumn(2).setPreferredWidth(150);
courseTabel.getColumnModel().getColumn(3).setResizable(false);
courseTabel.getColumnModel().getColumn(3).setPreferredWidth(150);
currentDateTxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
currentDateTxt.setForeground(new java.awt.Color(102, 102, 102));
currentDateTxt.setText("Current Date");
courseNameLbl.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
courseNameLbl.setForeground(new java.awt.Color(102, 102, 102));
instituteLabel.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
instituteLabel.setForeground(new java.awt.Color(102, 102, 102));
cityLabel.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
cityLabel.setForeground(new java.awt.Color(102, 102, 102));
jLabel5.setFont(new java.awt.Font("Swis721 LtEx BT", 1, 22)); // NOI18N
jLabel5.setForeground(new java.awt.Color(153, 153, 153));
jLabel5.setText("Search");
jPanel6.setBackground(new java.awt.Color(7, 1, 36));
jPanel6.setLayout(new java.awt.GridLayout(0, 1, 0, 3));
searchBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/search.png"))); // NOI18N
searchBtn.setBorder(null);
searchBtn.setFocusPainted(false);
searchBtn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/search-selected.png"))); // NOI18N
searchBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchBtnActionPerformed(evt);
}
});
jPanel6.add(searchBtn);
removeSearchBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/removeSearch.png"))); // NOI18N
removeSearchBtn.setBorder(null);
removeSearchBtn.setFocusPainted(false);
removeSearchBtn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/removeSearch-selected.png"))); // NOI18N
removeSearchBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeSearchBtnActionPerformed(evt);
}
});
jPanel6.add(removeSearchBtn);
jLabel6.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
jLabel6.setForeground(new java.awt.Color(102, 102, 102));
jLabel6.setText("Course Name");
courseTxt.setBackground(new java.awt.Color(7, 1, 36));
courseTxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 17)); // NOI18N
courseTxt.setForeground(new java.awt.Color(102, 102, 102));
courseTxt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(24, 25, 54)));
courseTxt.setCaretColor(new java.awt.Color(153, 153, 153));
jLabel7.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
jLabel7.setForeground(new java.awt.Color(102, 102, 102));
jLabel7.setText("Institute");
instituteTxt.setBackground(new java.awt.Color(7, 1, 36));
instituteTxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 17)); // NOI18N
instituteTxt.setForeground(new java.awt.Color(102, 102, 102));
instituteTxt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(24, 25, 54)));
instituteTxt.setCaretColor(new java.awt.Color(153, 153, 153));
jLabel8.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 22)); // NOI18N
jLabel8.setForeground(new java.awt.Color(102, 102, 102));
jLabel8.setText("City / Town");
cityTxt.setBackground(new java.awt.Color(7, 1, 36));
cityTxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 17)); // NOI18N
cityTxt.setForeground(new java.awt.Color(102, 102, 102));
cityTxt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(24, 25, 54)));
cityTxt.setCaretColor(new java.awt.Color(153, 153, 153));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 975, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cityTxt)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(courseTxt)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(instituteTxt)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(currentDateTxt, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cityLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(instituteLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(courseNameLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(courseTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(instituteTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cityTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 196, Short.MAX_VALUE)
.addComponent(courseNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(instituteLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cityLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(currentDateTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void nextBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextBtnActionPerformed
int rowCount = dtm.getRowCount();
int selectedRowCount=courseTabel.getSelectedRowCount();
if(rowCount==0){
WarningMessage.getInstance().showInterface("Firstly create a course");
}else if(selectedRowCount==0){
Message.getInstance().showInterface("Select one course to start", "card marking process");
}else{
int selectedRow=courseTabel.getSelectedRow();
String courseID = dtm.getValueAt(selectedRow, 0).toString();
String courseName = dtm.getValueAt(selectedRow, 1).toString();
String institute = dtm.getValueAt(selectedRow, 2).toString();
String city = dtm.getValueAt(selectedRow, 3).toString();
CardMarker.getInstance().showInterface(courseID, courseName, institute, city);
}
}//GEN-LAST:event_nextBtnActionPerformed
private void courseTabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_courseTabelMouseClicked
showSelectedCourse();
}//GEN-LAST:event_courseTabelMouseClicked
private void courseTabelMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_courseTabelMousePressed
}//GEN-LAST:event_courseTabelMousePressed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
SavedStatusNotice.getInstance().disposeMessage();
WarningMessage.getInstance().disposeMessage();
Message.getInstance().disposeMessage();
Keyboard.getInstance().hideInterface();
this.dispose();
}//GEN-LAST:event_jButton5ActionPerformed
private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed
SavedStatusNotice.getInstance().disposeMessage();
WarningMessage.getInstance().disposeMessage();
Message.getInstance().disposeMessage();
Keyboard.getInstance().hideInterface();
this.dispose();
}//GEN-LAST:event_cancelBtnActionPerformed
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
String course=courseTxt.getText();
String institute = instituteTxt.getText();
String city = cityTxt.getText();
String query="SELECT inst.*,cour.* FROM institution inst INNER JOIN course cour ON inst.id="
+ "cour.institution_id WHERE inst.city LIKE '"+city+"%' AND inst.name LIKE '"+institute+"%'"
+ " AND cour.name LIKE '%"+course+"%' AND inst.delete_status=0 AND cour.delete_status=0";
retrieveData(query);
}//GEN-LAST:event_searchBtnActionPerformed
private void removeSearchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSearchBtnActionPerformed
courseTxt.setText("");
instituteTxt.setText("");
cityTxt.setText("");
retrieveData();
}//GEN-LAST:event_removeSearchBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CardMarkingStartupScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CardMarkingStartupScreen().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelBtn;
private javax.swing.JLabel cityLabel;
private javax.swing.JTextField cityTxt;
private javax.swing.JLabel courseNameLbl;
private javax.swing.JTable courseTabel;
private javax.swing.JTextField courseTxt;
private javax.swing.JLabel currentDateTxt;
private javax.swing.JLabel instituteLabel;
private javax.swing.JTextField instituteTxt;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton nextBtn;
private javax.swing.JButton removeSearchBtn;
private javax.swing.JButton searchBtn;
// End of variables declaration//GEN-END:variables
}
| 51.652318
| 193
| 0.664466
|
339d32cd9d8c52ad0e0b9bb8fbcfc3a8f697bd1c
| 650
|
package Heranca;
/*
HERANCA = usar palavra extends na classe
As classes que recebem a herança do pai tem acesso aos seus metodos e atributos, não sendo preciso reescrever código
*/
public class Main {
public static void main(String[] args) {
Car carro = new Car();
carro.go();
System.out.println("SPEED::"+carro.velocidade);
System.out.println("PORTAS::"+carro.portas);
/////////////////////////////////////////////////////////
Bike bici = new Bike();
bici.stop();
System.out.println("SPEED::"+bici.velocidade);
System.out.println("PEDAIS::" +bici.pedais);
}
}
| 24.074074
| 116
| 0.566154
|
0ee218eacfe4f04ac070bcb6e2bd6f4f8fe6c25e
| 2,360
|
package com.fzjk.guanwang.config;
import com.fzjk.guanwang.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
// //ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器
// @Bean
// public ViewResolver myViewResolver() {
// return new MyViewResolver();
// }
//
// //自定义了一个自己的视图解析器myViewResolver
// public static class MyViewResolver implements ViewResolver{
// @Override
// public View resolveViewName(String viewName, Locale locale) throws Exception {
// return null;
// }
// }
//上传的绝对路径
@Value("${spring.servlet.multipart.location}")
private String staticImgPath;
/**
* 虚拟路径
* 1.如果图片存放的目录是在target/classes/static/upload/imgs下面,@value里面不用"/**"直接"/"
* 2.如果图片存放在项目外的本地盘符中,需要加"/**",否则无法浏览器无法获取静态资源
*/
@Value("/upload/imgs/**")
private String imgPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//浏览器访问的虚拟路径(浏览器默认无法访问工程项目外的本地文件)
registry.addResourceHandler(imgPath).
addResourceLocations("file:/"+staticImgPath);//必须是file:绝对路径名
}
//配置视图控制器:视图控制器作用是将前台路径不经controller直接forward到view。
// @Override
// public void addViewControllers(ViewControllerRegistry registry) {
//// registry.addViewController("/list/1").setViewName("/list/about_1");
//// registry.addViewController("/index.html").setViewName("index");
// }
//配置管理员系统拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
/*配置LoginInterceptor拦截器的拦截路径*/
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**") //拦截admin下面的所有页面
.excludePathPatterns("/admin") //不拦截admin登录页面
.excludePathPatterns("/admin/login"); //不拦截登录时的post请求页面,否则被拦截无法登录
}
}
| 32.777778
| 88
| 0.705508
|
5559871e63314f6e292e34b003d8ede10559646b
| 7,088
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.logic.v2016_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The X12 delimiter override settings.
*/
public class X12DelimiterOverrides {
/**
* The protocol version.
*/
@JsonProperty(value = "protocolVersion")
private String protocolVersion;
/**
* The message id.
*/
@JsonProperty(value = "messageId")
private String messageId;
/**
* The data element separator.
*/
@JsonProperty(value = "dataElementSeparator", required = true)
private int dataElementSeparator;
/**
* The component separator.
*/
@JsonProperty(value = "componentSeparator", required = true)
private int componentSeparator;
/**
* The segment terminator.
*/
@JsonProperty(value = "segmentTerminator", required = true)
private int segmentTerminator;
/**
* The segment terminator suffix. Possible values include: 'NotSpecified',
* 'None', 'CR', 'LF', 'CRLF'.
*/
@JsonProperty(value = "segmentTerminatorSuffix", required = true)
private SegmentTerminatorSuffix segmentTerminatorSuffix;
/**
* The replacement character.
*/
@JsonProperty(value = "replaceCharacter", required = true)
private int replaceCharacter;
/**
* The value indicating whether to replace separators in payload.
*/
@JsonProperty(value = "replaceSeparatorsInPayload", required = true)
private boolean replaceSeparatorsInPayload;
/**
* The target namespace on which this delimiter settings has to be applied.
*/
@JsonProperty(value = "targetNamespace")
private String targetNamespace;
/**
* Get the protocol version.
*
* @return the protocolVersion value
*/
public String protocolVersion() {
return this.protocolVersion;
}
/**
* Set the protocol version.
*
* @param protocolVersion the protocolVersion value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withProtocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
return this;
}
/**
* Get the message id.
*
* @return the messageId value
*/
public String messageId() {
return this.messageId;
}
/**
* Set the message id.
*
* @param messageId the messageId value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withMessageId(String messageId) {
this.messageId = messageId;
return this;
}
/**
* Get the data element separator.
*
* @return the dataElementSeparator value
*/
public int dataElementSeparator() {
return this.dataElementSeparator;
}
/**
* Set the data element separator.
*
* @param dataElementSeparator the dataElementSeparator value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withDataElementSeparator(int dataElementSeparator) {
this.dataElementSeparator = dataElementSeparator;
return this;
}
/**
* Get the component separator.
*
* @return the componentSeparator value
*/
public int componentSeparator() {
return this.componentSeparator;
}
/**
* Set the component separator.
*
* @param componentSeparator the componentSeparator value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withComponentSeparator(int componentSeparator) {
this.componentSeparator = componentSeparator;
return this;
}
/**
* Get the segment terminator.
*
* @return the segmentTerminator value
*/
public int segmentTerminator() {
return this.segmentTerminator;
}
/**
* Set the segment terminator.
*
* @param segmentTerminator the segmentTerminator value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withSegmentTerminator(int segmentTerminator) {
this.segmentTerminator = segmentTerminator;
return this;
}
/**
* Get the segment terminator suffix. Possible values include: 'NotSpecified', 'None', 'CR', 'LF', 'CRLF'.
*
* @return the segmentTerminatorSuffix value
*/
public SegmentTerminatorSuffix segmentTerminatorSuffix() {
return this.segmentTerminatorSuffix;
}
/**
* Set the segment terminator suffix. Possible values include: 'NotSpecified', 'None', 'CR', 'LF', 'CRLF'.
*
* @param segmentTerminatorSuffix the segmentTerminatorSuffix value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withSegmentTerminatorSuffix(SegmentTerminatorSuffix segmentTerminatorSuffix) {
this.segmentTerminatorSuffix = segmentTerminatorSuffix;
return this;
}
/**
* Get the replacement character.
*
* @return the replaceCharacter value
*/
public int replaceCharacter() {
return this.replaceCharacter;
}
/**
* Set the replacement character.
*
* @param replaceCharacter the replaceCharacter value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withReplaceCharacter(int replaceCharacter) {
this.replaceCharacter = replaceCharacter;
return this;
}
/**
* Get the value indicating whether to replace separators in payload.
*
* @return the replaceSeparatorsInPayload value
*/
public boolean replaceSeparatorsInPayload() {
return this.replaceSeparatorsInPayload;
}
/**
* Set the value indicating whether to replace separators in payload.
*
* @param replaceSeparatorsInPayload the replaceSeparatorsInPayload value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withReplaceSeparatorsInPayload(boolean replaceSeparatorsInPayload) {
this.replaceSeparatorsInPayload = replaceSeparatorsInPayload;
return this;
}
/**
* Get the target namespace on which this delimiter settings has to be applied.
*
* @return the targetNamespace value
*/
public String targetNamespace() {
return this.targetNamespace;
}
/**
* Set the target namespace on which this delimiter settings has to be applied.
*
* @param targetNamespace the targetNamespace value to set
* @return the X12DelimiterOverrides object itself.
*/
public X12DelimiterOverrides withTargetNamespace(String targetNamespace) {
this.targetNamespace = targetNamespace;
return this;
}
}
| 28.01581
| 111
| 0.665632
|
568067df5b6b12529b93996668dfc244e353e979
| 5,308
|
/*
* Copyright 2016 Code Above Lab LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codeabovelab.dm.common.meter;
import com.codahale.metrics.Metric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* The task for watchdog. <p/>
* Only one task can correspond for each metric.
*/
public final class WatchdogTask {
private static final Logger LOG = LoggerFactory.getLogger(WatchdogTask.class);
private final Metric metric;
private final String name;
private final List<LimitChecker> limitCheckers = new CopyOnWriteArrayList<>();
private final AtomicReference<ScheduledFuture<?>> scheduledRef = new AtomicReference<>();
private final Runnable task = new WatchdogTaskRunnable(this);
private final Watchdog watchdog;
private volatile WatchdogTaskState state;
WatchdogTask(Watchdog watchdog, Metric metric, String name) {
this.watchdog = watchdog;
Assert.hasText(name, "name can't be null or empty");
Assert.notNull(metric, "metric can't be null");
this.metric = metric;
this.name = name;
// stub state mean that all limits in normal state
this.state = new WatchdogTaskState(name, System.currentTimeMillis(), Collections.emptyList());
}
/**
* period between checks
* @return
*/
private long getPeriod() {
// find minimal period
long min = -1;
for(LimitChecker limitChecker: limitCheckers) {
long period = limitChecker.getPeriod();
if(min == -1 || period < min) {
min = period;
}
}
return min;
}
void schedule() {
cancel();
//schedule
long period = getPeriod();
if(period > 0) {
ScheduledFuture<?> scheduledFuture = this.watchdog.scheduledExecutorService.scheduleWithFixedDelay(task,
period, period, TimeUnit.MILLISECONDS);
if(!this.scheduledRef.compareAndSet(null, scheduledFuture)) {
//something already scheduled
scheduledFuture.cancel(true);
}
}
}
void cancel() {
// cancel old schedule
ScheduledFuture<?> oldScheduled = this.scheduledRef.getAndSet(null);
if(oldScheduled != null) {
oldScheduled.cancel(true);
}
}
public void addLimitChecker(LimitChecker limitChecker) {
//Assert.notNull(limitChecker);
limitCheckers.add(limitChecker);
schedule();
}
public void removeLimitChecker(LimitChecker limitChecker) {
//Assert.notNull(limitChecker);
limitCheckers.remove(limitChecker);
schedule();
}
/**
* state of watched limits.
* @return state, never null
*/
public WatchdogTaskState getState() {
return state;
}
public Metric getMetric() {
return metric;
}
/**
* True if no limit checkers
* @return
*/
public boolean isEmpty() {
return limitCheckers.isEmpty();
}
private void updateState(LimitCheckContext context, List<LimitExcess> excesses) {
final List<LimitExcess> unmodifiableList = Collections.unmodifiableList(excesses);
this.state = new WatchdogTaskState(this.name, System.currentTimeMillis(), unmodifiableList);
if(!excesses.isEmpty()) {
LimitExcessEvent event = new LimitExcessEvent(context, unmodifiableList);
this.watchdog.fireLimitExcess(event);
}
}
private static class WatchdogTaskRunnable implements Runnable {
private final WatchdogTask watchdogTask;
WatchdogTaskRunnable(WatchdogTask watchdogTask) {
this.watchdogTask = watchdogTask;
}
@Override
public void run() {
List<LimitExcess> excesses = new ArrayList<>();
LimitCheckContext limitCheckContext = new LimitCheckContext(watchdogTask.metric, watchdogTask.name);
for(LimitChecker limitChecker: watchdogTask.limitCheckers) {
LimitExcess excess = null;
try {
excess = limitChecker.check(limitCheckContext);
} catch (Exception e) {
LOG.error("Limit check error", e);
}
if(excess != null) {
excesses.add(excess);
}
}
this.watchdogTask.updateState(limitCheckContext, excesses);
}
}
}
| 32.564417
| 116
| 0.642615
|
5a3f28f8e5d1beb13eb6a7258c80738dc1f265d5
| 1,162
|
/*
* Copyright (c) 2018-present, Aaron J. Halbert.
*
* 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.aaronhalbert.nosurfforreddit.ui.utils.webview;
import android.webkit.WebView;
import androidx.fragment.app.FragmentActivity;
// also see NoSurfWebViewClient; Dagger injects correct version based on API level
public class NoSurfWebViewClientApiLevelBelow24 extends NoSurfWebViewClient {
public NoSurfWebViewClientApiLevelBelow24(FragmentActivity hostFragmentActivity) {
super(hostFragmentActivity);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return processUrl(url);
}
}
| 35.212121
| 112
| 0.767642
|
e7efc7e4d96dcfdd52361b6ee3e6fd2458b7ef29
| 894
|
package main.actions.lib;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
public abstract class ModAction implements Action {
// Define shared fields
private String targetUserID;
private String targetUserName;
private String adminID;
private String adminName;
public ModAction(String targetUserID, String targetUserName, String adminID, String adminName) {
this.targetUserID = targetUserID;
this.targetUserName = targetUserName;
this.adminID = adminID;
this.adminName = adminName;
}
public String getTargetUserID() {
return targetUserID;
}
public String getTargetUserName() {
return targetUserName;
}
public String getAdminID() {
return adminID;
}
public String getAdminName() {
return adminName;
}
// Define shared functions
public abstract boolean execute(Guild guild, TextChannel channelOfExecution);
}
| 22.923077
| 97
| 0.771812
|
6ce955619d95a49fd4820b19fb419ec4376b5094
| 1,804
|
/**
*
* Copyright (c) 2006-2017, Speedment, 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.speedment.common.codegen.internal.java.view.trait;
import com.speedment.common.codegen.Generator;
import com.speedment.common.codegen.Transform;
import com.speedment.common.codegen.model.trait.HasImports;
import static com.speedment.common.codegen.internal.util.CollectorUtil.joinIfNotEmpty;
import static com.speedment.common.codegen.util.Formatting.dnl;
import static com.speedment.common.codegen.util.Formatting.nl;
/**
* A trait with the functionality to render models with the trait
* {@link HasImports}.
*
* @author Emil Forslund
* @param <M> The model type
* @see Transform
*/
public interface HasImportsView<M extends HasImports<M>> extends
Transform<M, String> {
/**
* Render the imports-part of the model separated by new-line characters and
* appended by two new-line characters.
*
* @param gen the generator
* @param model the model
* @return the generated code
*/
default String renderImports(Generator gen, M model) {
return gen.onEach(model.getImports())
.distinct().sorted()
.collect(joinIfNotEmpty(nl(), "", dnl()));
}
}
| 35.372549
| 86
| 0.709534
|
ca154eb513e123cb6c366988162d291362f60f55
| 3,513
|
package com.baomidou.config;
import java.io.File;
import java.nio.charset.Charset;
/**
* 定义常量
*
* @author YangHu, tangguo
* @since 2016/8/31
*/
public class ConstVal {
public static final String MODULENAME = "ModuleName";
public static final String ENTITY = "Entity";
public static final String SERIVCE = "Service";
public static final String SERVICEIMPL = "ServiceImpl";
public static final String MAPPER = "Mapper";
public static final String VO = "VO";
public static final String XML = "Xml";
public static final String JSP = "Jsp";
public static final String CONTROLLER = "Controller";
public static final String DEGRADEDFEIGNCLIEN = "DegradedFeignClien";
public static final String APICONTROLLER = "ApiController";
public static final String FEIGNCLIENT = "FeignClient";
public static final String ENTITY_PATH = "entity_path";
public static final String SERIVCE_PATH = "serivce_path";
public static final String SERVICEIMPL_PATH = "serviceimpl_path";
public static final String MAPPER_PATH = "mapper_path";
public static final String VO_PATH = "vo_path";
public static final String XML_PATH = "xml_path";
public static final String JSP_PATH = "jsp_path";
public static final String CONTROLLER_PATH = "controller_path";
public static final String JAVA_TMPDIR = "java.io.tmpdir";
public static final String UTF8 = Charset.forName("UTF-8").name();
public static final String UNDERLINE = "_";
public static final String JAVA_SUFFIX = ".java";
public static final String XML_SUFFIX = ".xml";
public static final String JSP_SUFFIX = ".ftl";
public static final String TEMPLATE_ENTITY = "/template/entity.java.vm";
public static final String TEMPLATE_MAPPER = "/template/mapper.java.vm";
public static final String TEMPLATE_VO = "/template/vo.java.vm";
public static final String TEMPLATE_XML = "/template/mapper.xml.vm";
public static final String TEMPLATE_JSP = "/template/list.jsp.vm";
public static final String TEMPLATE_ADD = "/template/add.jsp.vm";
public static final String TEMPLATE_EDIT = "/template/edit.jsp.vm";
public static final String TEMPLATE_VIEW = "/template/view.jsp.vm";
public static final String TEMPLATE_SERVICE = "/template/service.java.vm";
public static final String TEMPLATE_SERVICEIMPL = "/template/serviceImpl.java.vm";
public static final String TEMPLATE_CONTROLLER = "/template/controller.java.vm";
public static final String ENTITY_NAME = File.separator + "%s" + JAVA_SUFFIX;
public static final String MAPPER_NAME = File.separator + "%s" + "Dao" + JAVA_SUFFIX;
public static final String XML_NAME = File.separator + "%s" + "Dao" + XML_SUFFIX;
public static final String JSP_NAME = File.separator + "%s" + JSP_SUFFIX;
public static final String SERVICE_NAME = File.separator + "%s" + SERIVCE + JAVA_SUFFIX;
public static final String SERVICEIMPL_NAME = File.separator + "%s" + SERVICEIMPL + JAVA_SUFFIX;
public static final String CONTROLLER_NAME = File.separator + "%s" + CONTROLLER + JAVA_SUFFIX;
// 配置使用classloader加载资源
public static final String VM_LOADPATH_KEY = "file.resource.loader.class";
public static final String VM_LOADPATH_VALUE = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";
public static final String SUPERD_MAPPER_CLASS = "com.baomidou.mybatisplus.mapper.BaseMapper";
public static final String SUPERD_SERVICE_CLASS = "com.baomidou.mybatisplus.service.Service";
public static final String SUPERD_SERVICEIMPL_CLASS = "com.baomidou.mybatisplus.service.impl.ServiceImpl";
}
| 47.472973
| 118
| 0.768005
|
0b564d17a991d37f0eab965f60819ac981be6449
| 941
|
package it.pagopa.pagopa.apiconfig.entity;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "CODIFICHE", schema = "NODO4_CFG")
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@ToString
public class Codifiche {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "OBJ_ID", nullable = false)
private Long objId;
@Column(name = "ID_CODIFICA", nullable = false, length = 35)
private String idCodifica;
@Column(name = "DESCRIZIONE", length = 35)
private String descrizione;
}
| 24.128205
| 64
| 0.77152
|
6f0d825b7e69ce79ab9714490df0652132bd753e
| 2,637
|
package edu.pasudo123.board.core.config.auth;
import edu.pasudo123.board.core.config.auth.dto.OAuthAttributesDto;
import edu.pasudo123.board.core.config.auth.dto.SessionUserDto;
import edu.pasudo123.board.core.user.model.User;
import edu.pasudo123.board.core.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Collections;
/**
* Created by pasudo123 on 2019-08-05
* Blog: https://pasudo123.tistory.com/
* Email: oraedoa@gmail.com
**/
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private final UserRepository userRepository;
private final HttpSession httpSession;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2UserService delegate = new DefaultOAuth2UserService();
OAuth2User oAuth2User = delegate.loadUser(userRequest);
String nameAttributeKey = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
String registrationId = userRequest.getClientRegistration().getRegistrationId();
OAuthAttributesDto oAuthAttributes = OAuthAttributesDto.of(registrationId, oAuth2User.getAttributes());
User user = saveOrUpdate(oAuthAttributes);
httpSession.setAttribute("user", new SessionUserDto(user));
return CustomOAuth2User.builder()
.user(user)
.authorities(Collections.singleton(new SimpleGrantedAuthority(user.getRoleKey())))
.attributes(oAuthAttributes.getAttributes())
.nameAttributeKey(nameAttributeKey)
.build();
}
private User saveOrUpdate(OAuthAttributesDto oAuthAttributesDto) {
User user = userRepository.findByUserRegistrationId(oAuthAttributesDto.getUserRegistrationId())
.orElseGet(oAuthAttributesDto::toEntity);
return userRepository.save(user);
}
}
| 42.532258
| 140
| 0.780432
|
622b86300563f801fb28f7819869786c998537e3
| 594
|
package com.zeligsoft.domain.omg.corba.api.IDL;
import com.zeligsoft.base.zdl.staticapi.core.ZObject;
import com.zeligsoft.base.zdl.staticapi.functions.TypeSelectPredicate;
public interface CORBAAnonymousSequence extends ZObject {
org.eclipse.uml2.uml.DataType asDataType();
/**
* A predicate which returns true if the Object is an
* instance of CORBAAnonymousSequence
*/
static final TypeSelectPredicate<CORBAAnonymousSequence> type = new TypeSelectPredicate<CORBAAnonymousSequence>(
"CORBADomain::IDL::CORBAAnonymousSequence", //$NON-NLS-1$
CORBAAnonymousSequence.class);
}
| 34.941176
| 113
| 0.799663
|
144ee6b78149e511de11f2242c2be330ca4b499f
| 240
|
package com.java.gmall.cart.constants;
/**
* @author jiangli
* @since 2020/1/31 16:25
*/
public interface CartConstant {
/* redis key 前缀*/
// 购物车前缀
String GMALL_CART = "gmall:cart:";
// sku价格前缀
String GMALL_SKU = "gmall:sku:";
}
| 15
| 38
| 0.658333
|
5a50124f2ea41077f9c84f088a7ab7f615beb4c4
| 277
|
package com.windrises.design.mode.decorator;
/**
* 矩形长方形
*
* @author liuhaozhen
* @version Revision 1.0.0
* @date 2020/6/10 10:52
*/
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
| 17.3125
| 47
| 0.646209
|
376af26cd5b8a30dcd3dde3b98cb85a7f74bee16
| 1,804
|
package com.javadesignpattern.strategy.season.java2;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
/**
* 一、集合框架的概述
*
* 1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
* 说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)
*
* 2.1 数组在存储多个数据方面的特点:
* > 一旦初始化以后,其长度就确定了。
* > 数组一旦定义好,其元素的类型也就确定了。我们也就只能操作指定类型的数据了。
* 比如:String[] arr;int[] arr1;Object[] arr2;
* 2.2 数组在存储多个数据方面的缺点:
* > 一旦初始化以后,其长度就不可修改。
* > 数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同时效率不高。
* > 获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用
* > 数组存储数据的特点:有序、可重复。对于无序、不可重复的需求,不能满足。
*
* 二、集合框架
* |----Collection接口:单列集合,用来存储一个一个的对象
* |----List接口:存储有序的、可重复的数据。 -->“动态”数组
* |----ArrayList、LinkedList、Vector
*
* |----Set接口:存储无序的、不可重复的数据 -->高中讲的“集合”
* |----HashSet、LinkedHashSet、TreeSet
*
* |----Map接口:双列集合,用来存储一对(key - value)一对的数据 -->高中函数:y = f(x)
* |----HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
*
*
* 三、Collection接口中的方法的使用
*
*
* @create 2019 下午 4:08
*/
public class CollectionTest {
@Test
public void test1(){
Collection coll = new ArrayList();
//add(Object e):将元素e添加到集合coll中
coll.add("AA");
coll.add("BB");
coll.add(123);//自动装箱
coll.add(new Date());
//size():获取添加的元素的个数
System.out.println(coll.size());//4
//addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中
Collection coll1 = new ArrayList();
coll1.add(456);
coll1.add("CC");
coll.addAll(coll1);
System.out.println(coll.size());//6
System.out.println(coll);
//clear():清空集合元素
coll.clear();
//isEmpty():判断当前集合是否为空
System.out.println(coll.isEmpty());
}
}
| 24.053333
| 71
| 0.588137
|
0e60505e4280001b54ef127dd584f8d49620bf9e
| 1,923
|
package io.ebean.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to control which ToMany relationships are preferred as 'joins' rather than
* as 'secondary joins' (query fetches).
* <p>
* Ebean automatically limits the number of SQL joins to ToMany relationships to avoid
* SQL cartesian product and to honor SQL first row / max rows limits. It does this by
* allowing the first ToMany relationship/path that has been defined on a query to be
* included in the main query as a join and then converting any remaining ToMany
* relationship/path to "query joins".
* </p>
* <p>
* Without explicit use of <code>@FetchPreference</code> the first path that contains a
* ToMany is included in the main query as a join.
* </p>
*
* <p>
* Indicate to Ebean the preferred relationships to join to.
* </p>
* <h2>Example</h2>
* <p>
* Prefer joins to 'participants' over 'messages'
* </p>
* <pre>{@code
*
* @FetchPreference(1)
* @OneToMany(mappedBy = "conversation")
* List<Participation> participants;
*
* @FetchPreference(2)
* @OneToMany(mappedBy = "conversation")
* List<Message> messages;
*
* }</pre>
*
* <h2>Example query that is impacted</h2>
* <pre>{@code
*
* // Without @FetchPreference the first ToMany which
* // is "messages" is joined and "participants" is
* // query joined (executed as a secondary query)
*
* Ebean.find(Conversation.class)
* .fetch("messages") // <- first ToMany path Ebean sees
* .fetch("participants") // <- second ToMany path Ebean sees
* .findList();
*
* }</pre>
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface FetchPreference {
/**
* The fetch preference used - low value means higher preference.
*/
int value();
}
| 29.584615
| 87
| 0.683827
|
211cf08835732c11493cff80aa7768321321518d
| 237
|
package xyz.erupt.annotation.sub_field.sub_edit;
import xyz.erupt.annotation.constant.AnnotationConst;
public @interface CheckboxType {
String id() default AnnotationConst.ID;
String label() default AnnotationConst.LABEL;
}
| 19.75
| 53
| 0.78481
|
c553b7d3e232ced144f8bb370fede94ee6af2fc2
| 7,160
|
package com.suheng.structure.gson;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ByteTest {
private static final byte HEAD = 0x02;
private static final byte TAIL = 0x03;
@Before
public void before() {
System.out.println("-------------------开始测试-------------------");
}
@After
public void after() {
System.out.println("-------------------结束测试-------------------");
}
@Test
public void testBasic() {
byte b = 48;
byte[] data = new byte[2];
data[0] = b;
data[1] = 33;
System.out.println("head: " + HEAD + ", tail: " + TAIL + ", b: " + b + ", charb: " + ByteUtil.byteToChar(b)
+ ", data: " + ByteUtil.byteArrayToString(data));
char c = '龟';
byte[] charArray = ByteUtil.intToByteArray(c);
//char ch = 0x2EF3;//字符型与整型可互转
char ch = 0x31E3;//字符型与整型可互转,汉字Unicode编码范围:https://www.qqxiuzi.cn/zh/hanzi-unicode-bianma.php
//charArray = ByteUtil.intToByteArray(ch);
//int ch = 65535+65536;//字符型与整型可互转,Java一个汉字占几个字节:https://www.cnblogs.com/duguxiaobiao/p/9128817.html
System.out.println("charArray: " + ByteUtil.byteArrayToHex(charArray) + ", number: " + ByteUtil.byteArrayToInt(charArray)
+ ", ch: " + ch + ", charArray: " + ByteUtil.byteArrayToHex(ByteUtil.intToByteArray(ch)));
//toBinaryString:用二进制表示数;bitCount:二进制表示中1的个数。
System.out.println("binary: " + Integer.toBinaryString(9) + ", " + Integer.bitCount(9));
int i = 257;
int j = i << 3;//<<:左移运算符,<<1相当于乘以2,<<2相当于乘以4,以此类推
int k = i >> 2;//>>:右移运算符,>>1相当于除以2,>>2相当于除以4,以此类推
System.out.println("i: " + i + ", j: " + j + ", k: " + k + "\n" + "i binary: " + Integer.toBinaryString(i)
+ ", j binary: " + Integer.toBinaryString(j) + ", k binary: " + Integer.toBinaryString(k));
//当将一个int型强制类型转换为byte型的时候,最高的三个字节会被砍掉,只留下最低的8位赋值给byte型。
byte a = (byte) i;//1 2 4 8 16 32 64
byte d = (byte) j;
System.out.println("a: " + a + ", a binary: " + Integer.toBinaryString(a)
+ ", d: " + d + ", d binary: " + Integer.toBinaryString(d));
//https://blog.csdn.net/chenchao2017/article/details/79733278?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.nonecase
//在计算机中数值是以该数的补码形式存在的.https://blog.csdn.net/afsvsv/article/details/94553228
//原码:最高位表示符号位,"1"表示负号,"0"表示正号,其它位存放该数的二进制的绝对值,是最简单的机器数表示法。如10000010,最高位是1表示这是一个负数,
//其它位是0000010,值为2,所以10000010表示的是-2;同理00000010表示的是2。原码最大的问题就在于一个数加上他的相反数不等于零,如10000010+0000010是
//是不等于0的。
//反码:正数的反码等于原码;负数的反码等于原码除符号位外其它位按位取反,如:-2(10000010)的反码为11111101。
//补码:正数的补码等于原码,负数的补码等于反码+1,如:-2(10000010)的补码为11111110。或负数的补码等于原码自低位向高位,尾数的第一个‘1’及其右边的‘0’保持不变,左边的各位按位取反,符号位不变。
}
private byte[] makeCmd() {
byte[] data;
int integer = 770;
byte[] array = ByteUtil.intToByteArray(integer);
System.out.println(integer + " byte hex: " + ByteUtil.byteArrayToHex(array));
String text = "韦帮杰";
System.out.println(text + " byte hex: " + ByteUtil.byteArrayToHex(text.getBytes()));
array = new byte[ByteUtil.INT_DATA_BYTE_LEN];
array[3] = 0;
array[2] = 0;
array[1] = TAIL;
array[0] = HEAD;
System.out.println("test normal data have head or tail hex: " + ByteUtil.byteArrayToHex(array)
+ ", value: " + ByteUtil.byteArrayToInt(array));
//头尾各占1字节、命令和类型各1字节、包类型1字节、长度4字节、错误码1字节、校验和4字节,共14字节
byte[] buffer = new byte[maxBuffer];
int offset = 0;
buffer[offset++] = HEAD;
byte cmd = 0x31;
buffer[offset++] = cmd;
data = text.getBytes();
byte[] dataLen = ByteUtil.intToByteArray(data.length);
System.arraycopy(dataLen, 0, buffer, offset, dataLen.length);
offset += dataLen.length;
System.arraycopy(data, 0, buffer, offset, data.length);
offset += data.length;
data = "adgagagagadgakaekgla;mgdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddakdmgamdadsfmlkgfssafafadfafadfafadfafdadfafsmfgmgadfafakflafalfalfa".getBytes();
dataLen = ByteUtil.intToByteArray(data.length);
System.arraycopy(dataLen, 0, buffer, offset, dataLen.length);
offset += dataLen.length;
System.arraycopy(data, 0, buffer, offset, data.length);
offset += data.length;
buffer[offset++] = TAIL;
byte[] protocol = new byte[offset];
System.arraycopy(buffer, 0, protocol, 0, protocol.length);
//byte[] dataLen = int2Bytes(data.length);
System.out.println("protocol send= " + new String(protocol) + ", dataLen:" + ByteUtil.byteArrayToInt(dataLen));
return protocol;
}
private byte[] receive;
private int offset = 0, maxBuffer = 1024;
@Test
public void testMakeCmd() {
byte[] buffer = this.makeCmd();
int index = 0;
final int length = buffer.length;
while (index < length) {
if (buffer[index] == HEAD) {
receive = new byte[maxBuffer];
offset = 0;
}
receive[offset++] = buffer[index];
if (buffer[index] == TAIL) {
byte[] protocol = new byte[offset];
System.arraycopy(receive, 0, protocol, 0, offset);
parseProtocol(protocol);
}
index++;
}
}
private void parseProtocol(byte[] protocol) {
if (protocol == null || protocol.length < 2) {
return;
}
if ((protocol[0] != HEAD) && (protocol[protocol.length - 1] != TAIL)) {
return;
}
System.out.println("protocol receive: " + new String(protocol));
int offset = 1;
byte cmd = protocol[offset++];
if (cmd == 0x31) {
byte[] dataLen = new byte[4];
System.arraycopy(protocol, offset, dataLen, 0, dataLen.length);
offset += dataLen.length;
int len = ByteUtil.byteArrayToInt(dataLen);
byte[] data = new byte[len];
System.arraycopy(protocol, offset, data, 0, data.length);
offset += data.length;
String name = new String(data);
System.out.println("dataLen = " + len + ", name: " + name);
dataLen = new byte[4];
System.arraycopy(protocol, offset, dataLen, 0, dataLen.length);
offset += dataLen.length;
len = ByteUtil.byteArrayToInt(dataLen);
data = new byte[len];
System.arraycopy(protocol, offset, data, 0, data.length);
offset += data.length;
name = new String(data);
System.out.println("dataLen = " + len + ", name: " + name);
}
}
}
| 39.777778
| 261
| 0.588128
|
f678b91dd0a177f1c7187c4643321416e2e82614
| 45,552
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.android.tools.idea.common.scene;
import static com.android.SdkConstants.ANDROID_URI;
import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
import com.android.SdkConstants;
import com.android.ide.common.resources.configuration.LayoutDirectionQualifier;
import com.android.resources.LayoutDirection;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.devices.Device;
import com.android.tools.adtui.common.AdtUiUtils;
import com.android.tools.adtui.common.SwingCoordinate;
import com.android.tools.idea.common.model.AndroidDpCoordinate;
import com.android.tools.idea.common.model.Coordinates;
import com.android.tools.idea.common.model.NlComponent;
import com.android.tools.idea.common.model.NlModel;
import com.android.tools.idea.common.model.SelectionListener;
import com.android.tools.idea.common.model.SelectionModel;
import com.android.tools.idea.common.scene.draw.DisplayList;
import com.android.tools.idea.common.scene.target.AnchorTarget;
import com.android.tools.idea.common.scene.target.LassoTarget;
import com.android.tools.idea.common.scene.target.MultiComponentTarget;
import com.android.tools.idea.common.scene.target.Target;
import com.android.tools.idea.common.surface.DesignSurface;
import com.android.tools.idea.common.surface.SceneView;
import com.android.tools.idea.configurations.Configuration;
import com.android.tools.idea.rendering.RenderLogger;
import com.android.tools.idea.rendering.RenderService;
import com.android.tools.idea.rendering.RenderTask;
import com.android.tools.idea.uibuilder.api.ViewHandler;
import com.android.tools.idea.uibuilder.handlers.constraint.SecondarySelector;
import com.android.tools.idea.uibuilder.handlers.constraint.draw.ConstraintLayoutDecorator;
import com.android.tools.idea.uibuilder.model.NlComponentHelperKt;
import com.android.tools.idea.uibuilder.scene.decorator.DecoratorUtilities;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ui.JBUI;
import java.awt.*;
import java.awt.event.InputEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.intellij.lang.annotations.JdkConstants;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ide.PooledThreadExecutor;
/**
* A Scene contains a hierarchy of SceneComponent representing the bounds
* of the widgets being layed out. Multiple NlModel can be used to populate
* a Scene.
* <p>
* Methods in this class must be called in the dispatch thread.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
public class Scene implements SelectionListener, Disposable {
@SwingCoordinate
private static final int DRAG_THRESHOLD = JBUI.scale(10);
private static final String PREFERENCE_KEY_PREFIX = "ScenePreference";
private static final String SHOW_TOOLTIP_KEY = PREFERENCE_KEY_PREFIX + "ShowToolTip";
private static Boolean SHOW_TOOLTIP_VALUE = null;
private final DesignSurface myDesignSurface;
private final SceneManager mySceneManager;
private static final boolean DEBUG = false;
private final HashMap<NlComponent, SceneComponent> mySceneComponents = new HashMap<>();
private SceneComponent myRoot;
private boolean myIsAnimated = true; // animate layout changes
public static final int NO_LAYOUT = 0;
public static final int IMMEDIATE_LAYOUT = 1;
public static final int ANIMATED_LAYOUT = 2;
private long myDisplayListVersion = 1;
private Target myOverTarget;
private Target mySnapTarget;
private SceneComponent myCurrentComponent;
NlComponent myLastHoverConstraintComponent = null;
@MagicConstant(intValues = {NO_LAYOUT, IMMEDIATE_LAYOUT, ANIMATED_LAYOUT})
private int mNeedsLayout = NO_LAYOUT;
@AndroidDpCoordinate protected int myPressedMouseX;
@AndroidDpCoordinate protected int myPressedMouseY;
@AndroidDpCoordinate private int myLastMouseX;
@AndroidDpCoordinate private int myLastMouseY;
@NotNull private final SceneHitListener myHoverListener;
@NotNull private final SceneHitListener myHitListener;
@NotNull private final SceneHitListener myFindListener;
@NotNull private final SceneHitListener mySnapListener;
@Nullable private Target myHitTarget = null;
private Cursor myMouseCursor;
private SceneComponent myHitComponent;
List<SceneComponent> myNewSelectedComponentsOnRelease = new ArrayList<>();
List<SceneComponent> myNewSelectedComponentsOnDown = new ArrayList<>();
Set<SceneComponent> myHoveredComponents = new HashSet<>();
private boolean myIsLiveRenderingEnabled;
public enum FilterType {ALL, ANCHOR, VERTICAL_ANCHOR, HORIZONTAL_ANCHOR, BASELINE_ANCHOR, NONE, RESIZE}
@NotNull private FilterType myFilterType = FilterType.NONE;
public Scene(@NotNull SceneManager sceneManager, @NotNull DesignSurface surface, @NotNull boolean useLiveRendering) {
myDesignSurface = surface;
mySceneManager = sceneManager;
SelectionModel selectionModel = myDesignSurface.getSelectionModel();
myHoverListener = new SceneHitListener(selectionModel);
myHitListener = new SceneHitListener(selectionModel);
myFindListener = new SceneHitListener(selectionModel);
mySnapListener = new SceneHitListener(selectionModel);
selectionModel.addListener(this);
myHoverListener.setTargetFilter(target -> {
if (target instanceof AnchorTarget) {
AnchorTarget anchorTarget = (AnchorTarget)target;
if (myHitTarget == null) {
// Not interacting with any Target, avoid to hover to edge AnchorTarget.
return !anchorTarget.isEdge();
}
else if (myHitTarget instanceof AnchorTarget) {
// Interacting with AnchorTarget, only hovers on connectible AnchorTargets.
return ((AnchorTarget)myHitTarget).isConnectible(anchorTarget);
}
}
return true;
});
myIsLiveRenderingEnabled = useLiveRendering;
Disposer.register(sceneManager, this);
}
public static void setTooltipVisibility(boolean visible) {
SHOW_TOOLTIP_VALUE = visible;
PropertiesComponent.getInstance().setValue(SHOW_TOOLTIP_KEY, visible);
}
public static boolean getTooltipVisibility() {
if (SHOW_TOOLTIP_VALUE != null) {
return SHOW_TOOLTIP_VALUE;
}
// Here we assume that setValue is controlled by this class only.
SHOW_TOOLTIP_VALUE = PropertiesComponent.getInstance().getBoolean(SHOW_TOOLTIP_KEY, false);
return SHOW_TOOLTIP_VALUE;
}
@Override
public void dispose() {
myDesignSurface.getSelectionModel().removeListener(this);
}
@NotNull
public SceneManager getSceneManager() {
return mySceneManager;
}
public boolean supportsRTL() {
return true;
}
/**
* Return true if the designed content is resizable, false otherwise
*/
public boolean isResizeAvailable() {
Configuration configuration = mySceneManager.getModel().getConfiguration();
Device device = configuration.getCachedDevice();
if (device == null) {
return false;
}
return true;
}
public boolean isInRTL() {
Configuration configuration = mySceneManager.getModel().getConfiguration();
LayoutDirectionQualifier qualifier = configuration.getFullConfig().getLayoutDirectionQualifier();
if (qualifier == null) {
return false;
}
return qualifier.getValue() == LayoutDirection.RTL;
}
public int getRenderedApiLevel() {
// TODO: Update to support multi-model
Configuration configuration = mySceneManager.getModel().getConfiguration();
IAndroidTarget target = configuration.getTarget();
if (target != null) {
return target.getVersion().getApiLevel();
}
return AndroidVersion.VersionCodes.BASE;
}
//region Accessors
/////////////////////////////////////////////////////////////////////////////
/**
* Return the current animation status
*
* @return true if layout updates will animate
*/
public boolean isAnimated() {
return myIsAnimated;
}
/**
* Set the layout updates to animate or not
*
* @param animated true to animate the changes
*/
public void setAnimated(boolean animated) {
myIsAnimated = animated;
}
/**
* Return the SceneComponent corresponding to the given NlComponent, if existing
*
* @param component the NlComponent to use
* @return the SceneComponent paired to the given NlComponent, if found
*/
@Nullable
public SceneComponent getSceneComponent(@Nullable NlComponent component) {
if (component == null) {
return null;
}
return mySceneComponents.get(component);
}
@NotNull
public DesignSurface getDesignSurface() {
return myDesignSurface;
}
/**
* Return the SceneComponent corresponding to the given component id, if found
*
* @param componentId the component id to look for
* @return the SceneComponent paired to the given component id, if found
*/
@Nullable
public SceneComponent getSceneComponent(@NotNull String componentId) {
if (myRoot == null) {
return null;
}
return myRoot.getSceneComponent(componentId);
}
public List<NlComponent> getSelection() {
return myDesignSurface.getSelectionModel().getSelection();
}
@Nullable
public Object getSecondarySelection() {
return myDesignSurface.getSelectionModel().getSecondarySelection();
}
/**
* Return the current SceneComponent root in the Scene
*
* @return the root SceneComponent
*/
@Nullable
public SceneComponent getRoot() {
return myRoot;
}
public Cursor getMouseCursor() {
return myMouseCursor;
}
public boolean isCtrlMetaDown() {
int modifiersEx = getModifiersEx();
int ctrlMetaDownMask = AdtUiUtils.getActionMask();
return (modifiersEx & ctrlMetaDownMask) != 0;
}
public boolean isShiftDown() {
int modifiersEx = getModifiersEx();
return (modifiersEx & InputEvent.SHIFT_DOWN_MASK) != 0;
}
public boolean isAltDown() {
int modifiersEx = getModifiersEx();
return (modifiersEx & InputEvent.ALT_DOWN_MASK) != 0;
}
@JdkConstants.InputEventMask
private int getModifiersEx() {
return myDesignSurface.getInteractionManager().getLastModifiersEx();
}
//endregion
/////////////////////////////////////////////////////////////////////////////
//region Update / Maintenance of the tree
/////////////////////////////////////////////////////////////////////////////
/**
* Add the given SceneComponent to the Scene
*
* @param component component to add
*/
public void addComponent(@NotNull SceneComponent component) {
mySceneComponents.put(component.getNlComponent(), component);
needsRebuildList();
}
/**
* Remove teh given SceneComponent from the Scene
*
* @param component component to remove
*/
public void removeComponent(@NotNull SceneComponent component) {
component.removeFromParent();
mySceneComponents.remove(component.getNlComponent(), component);
needsRebuildList();
}
void removeAllComponents() {
for (Iterator<Map.Entry<NlComponent, SceneComponent>> it = mySceneComponents.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<NlComponent, SceneComponent> entry = it.next();
entry.getValue().removeFromParent();
it.remove();
}
}
//endregion
/////////////////////////////////////////////////////////////////////////////
//region SelectionModel listener callback
/////////////////////////////////////////////////////////////////////////////
@Override
public void selectionChanged(@NotNull SelectionModel model, @NotNull List<NlComponent> selection) {
if (myRoot != null) {
markSelection(myRoot, model);
}
}
/**
* Given a {@link SelectionModel}, marks the corresponding SceneComponent as selected.
*/
private static void markSelection(SceneComponent component, SelectionModel model) {
component.setSelected(model.isSelected(component.getNlComponent()));
component.setHighlighted(model.isHighlighted(component.getNlComponent()));
for (SceneComponent child : component.getChildren()) {
markSelection(child, model);
}
}
//endregion
/////////////////////////////////////////////////////////////////////////////
//region Painting
/////////////////////////////////////////////////////////////////////////////
/**
* Paint the current scene into the given display list
*
* @param displayList
* @param time
* @return true if we need to repaint the screen
*/
public void buildDisplayList(@NotNull DisplayList displayList, long time, SceneView sceneView) {
buildDisplayList(displayList, time, SceneContext.get(sceneView));
}
/**
* Paint the current scene into the given display list
*
* @param displayList
* @param time
* @return true if we need to repaint the screen
*/
public void buildDisplayList(@NotNull DisplayList displayList, long time) {
layout(time, SceneContext.get());
buildDisplayList(displayList, time, SceneContext.get());
}
public void repaint() {
myDesignSurface.repaint();
}
/**
* Paint the current scene into the given display list
*
* @param displayList
* @param time
*/
public void buildDisplayList(@NotNull DisplayList displayList, long time, SceneContext sceneContext) {
if (myRoot != null) {
// clear the objects and release
sceneContext.getScenePicker().foreachObject(o -> {
if (o instanceof SecondarySelector) {
((SecondarySelector)o).release();
}
});
sceneContext.getScenePicker().reset();
myRoot.buildDisplayList(time, displayList, sceneContext);
if (DEBUG) {
System.out.println("========= DISPLAY LIST ======== \n" + displayList.serialize());
}
}
else {
if (DEBUG) {
System.out.println("Scene:Paint() - NO ROOT ");
}
}
}
/**
* Layout targets
*
* @param time
* @param sceneContext
* @return true if we need to repaint the screen
*/
public boolean layout(long time, SceneContext sceneContext) {
boolean needsToRebuildDisplayList = false;
if (myRoot != null) {
needsToRebuildDisplayList = myRoot.layout(sceneContext, time);
if (needsToRebuildDisplayList) {
needsRebuildList();
}
}
return needsToRebuildDisplayList;
}
/**
* Select the given components
*
* @param components The components to select
*/
public void select(List<SceneComponent> components) {
if (myDesignSurface != null) {
ArrayList<NlComponent> nlComponents = new ArrayList<>();
if (isShiftDown() || isCtrlMetaDown()) {
List<NlComponent> selection = myDesignSurface.getSelectionModel().getSelection();
nlComponents.addAll(selection);
}
for (SceneComponent sceneComponent : components) {
NlComponent nlComponent = sceneComponent.getNlComponent();
if ((isShiftDown() || isCtrlMetaDown()) && nlComponents.contains(nlComponent)) {
// if shift is pressed and the component is already selected, remove it from the selection
nlComponents.remove(nlComponent);
}
else {
nlComponents.add(nlComponent);
}
}
myDesignSurface.getSelectionModel().setSelection(nlComponents);
}
}
//endregion
/////////////////////////////////////////////////////////////////////////////
//region Mouse Handling
/////////////////////////////////////////////////////////////////////////////
/**
* Supports hover
*
* @param x
* @param y
*/
public void mouseHover(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
myLastMouseX = x;
myLastMouseY = y;
if (myLastHoverConstraintComponent != null) { // clear hover constraint
myLastHoverConstraintComponent.putClientProperty(ConstraintLayoutDecorator.CONSTRAINT_HOVER, null);
myLastHoverConstraintComponent = null;
needsRebuildList();
}
if (myRoot != null) {
myHoverListener.find(transform, myRoot, x, y, modifiersEx);
mySnapListener.find(transform, myRoot, x, y, modifiersEx);
}
repaint();
Target closestTarget = myHoverListener.getClosestTarget(modifiersEx);
String tooltip = null;
if (myOverTarget != closestTarget) {
if (myOverTarget != null) {
myOverTarget.setMouseHovered(false);
myOverTarget = null;
needsRebuildList();
}
if (closestTarget != null) {
closestTarget.setMouseHovered(true);
myOverTarget = closestTarget;
needsRebuildList();
}
}
if (closestTarget != null) {
tooltip = closestTarget.getToolTipText();
Target snapTarget = myHoverListener.getFilteredTarget(closestTarget);
if (snapTarget != mySnapTarget) {
if (mySnapTarget != null) {
mySnapTarget.setMouseHovered(false);
mySnapTarget = null;
needsRebuildList();
}
if (snapTarget != null) {
snapTarget.setMouseHovered(true);
mySnapTarget = closestTarget;
needsRebuildList();
}
}
}
updateHoveredComponentsDrawState();
SceneComponent closestComponent = myHoverListener.getClosestComponent();
if (closestComponent != null && tooltip == null) {
tooltip = closestComponent.getNlComponent().getTooltipText();
}
if (myCurrentComponent != closestComponent) {
if (myCurrentComponent != null) {
myCurrentComponent.setDrawState(SceneComponent.DrawState.NORMAL);
myCurrentComponent = null;
}
if (closestComponent != null) {
closestComponent.setDrawState(SceneComponent.DrawState.HOVER);
myCurrentComponent = closestComponent;
}
needsRebuildList();
}
if (closestComponent == null
|| closestComponent.getNlComponent().isRoot()
&& myHitTarget == null) {
SecondarySelector ss = getSecondarySelector(transform, x, y);
if (ss != null) {
NlComponent component = ss.getComponent();
myLastHoverConstraintComponent = ss.getComponent();
tooltip = getConstraintToolTip(ss);
component.putClientProperty(ConstraintLayoutDecorator.CONSTRAINT_HOVER, ss.getConstraint());
needsRebuildList();
}
}
if (getTooltipVisibility()) {
getDesignSurface().setDesignToolTip(tooltip);
}
setCursor(transform, x, y, modifiersEx);
}
@NotNull
private String getConstraintToolTip(@NotNull SecondarySelector ss) {
NlComponent component = ss.getComponent();
String tooltip;
String connect = "", target = "";
SecondarySelector.Constraint connection = ss.getConstraint();
if (isInRTL()) {
if (connection == SecondarySelector.Constraint.LEFT) {
connection = SecondarySelector.Constraint.RIGHT;
} else if (connection == SecondarySelector.Constraint.RIGHT) {
connection = SecondarySelector.Constraint.LEFT;
}
}
switch (connection) {
case LEFT:
connect = SdkConstants.ATTR_LAYOUT_START_TO_START_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
connect = SdkConstants.ATTR_LAYOUT_START_TO_END_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
break;
case RIGHT:
connect = SdkConstants.ATTR_LAYOUT_END_TO_START_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
connect = SdkConstants.ATTR_LAYOUT_END_TO_END_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
break;
case TOP:
connect = SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
connect = SdkConstants.ATTR_LAYOUT_TOP_TO_BOTTOM_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
break;
case BOTTOM:
connect = SdkConstants.ATTR_LAYOUT_BOTTOM_TO_TOP_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
connect = SdkConstants.ATTR_LAYOUT_BOTTOM_TO_BOTTOM_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
if (target != null) {
break;
}
break;
case BASELINE:
connect = SdkConstants.ATTR_LAYOUT_BASELINE_TO_BASELINE_OF;
target = component.getAttribute(SdkConstants.SHERPA_URI, connect);
break;
}
try {
connect = connect.substring("layout_constraint".length(), connect.length() - 2).replace("_to", " to ").toLowerCase();
target = target.substring(target.indexOf("/") + 1);
tooltip = component.getTooltipText() + " " + connect + " of " + target;
}
catch (Exception ex) {
tooltip = "";
}
return tooltip;
}
/** Updates the draw state of components being hovered. */
private void updateHoveredComponentsDrawState() {
List<SceneComponent> hitComponents = myHoverListener.getHitComponents();
// Update draw state for currently hovered components.
for (SceneComponent component : hitComponents) {
// Skip closest/current component. Not handled here.
if (component != myCurrentComponent ) {
NlComponent nlComponent = component.getAuthoritativeNlComponent();
if (DecoratorUtilities.getTryingToConnectState(nlComponent) != null) {
// Draw as hovered when creating constraints.
component.setDrawState(SceneComponent.DrawState.HOVER);
}
else {
component.setDrawState(SceneComponent.DrawState.NORMAL);
}
}
myHoveredComponents.remove(component);
}
Iterator<SceneComponent> iterator = myHoveredComponents.iterator();
// Components not being hovered anymore are set to normal.
while(iterator.hasNext()) {
SceneComponent component = iterator.next();
component.setDrawState(SceneComponent.DrawState.NORMAL);
iterator.remove();
}
// Keep current hovered components.
myHoveredComponents.addAll(hitComponents);
}
private void setCursor(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
myMouseCursor = Cursor.getDefaultCursor();
if (myCurrentComponent != null && myCurrentComponent.isDragging()) {
myMouseCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
return;
}
if (myOverTarget != null) {
myMouseCursor = myOverTarget.getMouseCursor(modifiersEx);
return;
}
SceneComponent component = findComponent(transform, x, y);
if (component != null && component.getParent() != null) {
myMouseCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
}
}
private void delegateMouseDownToSelection(@AndroidDpCoordinate int x, @AndroidDpCoordinate int y, SceneComponent currentComponent) {
// update other selected widgets
java.util.List<NlComponent> selection = getSelection();
if (selection.size() > 1) {
for (NlComponent nlComponent : selection) {
if (nlComponent == currentComponent.getNlComponent()) {
continue;
}
SceneComponent c = currentComponent.getScene().getSceneComponent(nlComponent);
if (c != null && c != currentComponent) {
for (Target target : c.getTargets()) {
if (target instanceof MultiComponentTarget) {
target.mouseDown(x, y);
}
}
}
}
}
}
private void delegateMouseDragToSelection(@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@Nullable Target closestTarget,
@NotNull SceneComponent currentComponent,
@NotNull SceneContext context) {
// update other selected widgets
java.util.List<NlComponent> selection = getSelection();
if (selection.size() > 1) {
for (NlComponent nlComponent : selection) {
if (nlComponent == currentComponent.getNlComponent()) {
continue;
}
SceneComponent c = currentComponent.getScene().getSceneComponent(nlComponent);
if (c != null && c != currentComponent) {
for (Target target : c.getTargets()) {
if (target instanceof MultiComponentTarget) {
ArrayList<Target> list = new ArrayList<>();
list.add(closestTarget);
target.mouseDrag(x, y, list, context);
}
}
}
}
}
}
private void delegateMouseReleaseToSelection(@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@Nullable Target closestTarget,
@NotNull SceneComponent currentComponent) {
// update other selected widgets
java.util.List<NlComponent> selection = getSelection();
if (selection.size() > 1) {
int count = selection.size();
for (int i = 0; i < count; i++) {
NlComponent nlComponent = selection.get(i);
if (nlComponent == currentComponent.getNlComponent()) {
continue;
}
SceneComponent c = currentComponent.getScene().getSceneComponent(nlComponent);
if (c != null) {
for (Target target : c.getTargets()) {
if (target instanceof MultiComponentTarget) {
target.mouseRelease(x, y, Collections.singletonList(closestTarget));
}
}
}
}
}
}
private void delegateMouseCancelToSelection(@NotNull SceneComponent currentComponent) {
// update other selected widgets
NlComponent currentNlComponent = currentComponent.getNlComponent();
Scene scene = currentComponent.getScene();
List<SceneComponent> otherComponents = getSelection().stream().filter(it -> it != currentNlComponent)
.map(it -> scene.getSceneComponent(it))
.filter(it -> it != null)
.collect(Collectors.toList());
for (SceneComponent c : otherComponents) {
List<Target> targets = c.getTargets();
for (Target t : targets) {
if (t instanceof MultiComponentTarget) {
t.mouseCancel();
}
}
}
}
public void mouseDown(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
myPressedMouseX = x;
myPressedMouseY = y;
mNeedsLayout = NO_LAYOUT;
myLastMouseX = x;
myLastMouseY = y;
myFilterType = FilterType.NONE;
if (myRoot == null) {
return;
}
myNewSelectedComponentsOnDown.clear();
myHitListener.setTargetFilter(it -> {
if (it instanceof AnchorTarget) {
return !((AnchorTarget)it).isEdge();
}
return true;
});
SecondarySelector secondarySelector = getSecondarySelector(transform, x, y);
myHitListener.find(transform, myRoot, x, y, modifiersEx);
myHitTarget = myHitListener.getClosestTarget(modifiersEx);
myHitComponent = myHitListener.getClosestComponent();
if (myHitTarget != null) {
myHitTarget.mouseDown(x, y);
if (myHitTarget instanceof MultiComponentTarget) {
delegateMouseDownToSelection(x, y, myHitTarget.getComponent());
}
}
else if (myHitComponent != null && !inCurrentSelection(myHitComponent)) {
myNewSelectedComponentsOnDown.add(myHitComponent);
select(myNewSelectedComponentsOnDown);
}
else if (findSelectionOfCurve(secondarySelector)) {
return;
}
myHitListener.setTargetFilter(null);
}
/**
* @return The {@link SecondarySelector} (if any) from drawn objects at a given android coordinate.
*/
@Nullable
public static SecondarySelector getSecondarySelector(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y) {
Object obj = transform.findClickedGraphics(transform.getSwingXDip(x), transform.getSwingYDip(y));
if (obj != null && obj instanceof SecondarySelector) {
return (SecondarySelector)obj;
}
return null;
}
public void mouseDrag(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
if (myLastMouseX == x && myLastMouseY == y) {
return;
}
myLastMouseX = x;
myLastMouseY = y;
if (myHitTarget != null) {
// if component is not yet being dragged, is not selected and is only moved a tiny bit, then dont do anything as the user is just trying to select it.
if (!myHitTarget.getComponent().isDragging() &&
!myDesignSurface.getSelectionModel().isSelected(myHitTarget.getComponent().getNlComponent()) &&
isWithinThreshold(myPressedMouseX, x, transform) &&
isWithinThreshold(myPressedMouseY, y, transform)) {
return;
}
LassoTarget lassoTarget = null;
if (myHitTarget instanceof LassoTarget) {
lassoTarget = (LassoTarget)myHitTarget;
if (lassoTarget.getSelectWhileDragging() && lassoTarget.getHasChanged()) {
myNewSelectedComponentsOnRelease.clear();
myNewSelectedComponentsOnRelease.addAll(lassoTarget.getIntersectingComponents());
select(myNewSelectedComponentsOnRelease);
lassoTarget.clearHasChanged();
}
}
myHitListener.setTargetFilter(target -> myHitTarget != target);
myHitListener.find(transform, myRoot, x, y, modifiersEx);
SceneComponent targetComponent = myHitTarget.getComponent();
if (lassoTarget == null // No need to select LassoTarget's component.
&& targetComponent != null
&& !inCurrentSelection(targetComponent)) {
// Select the target's component when it is first being dragged.
myNewSelectedComponentsOnRelease.clear();
myNewSelectedComponentsOnRelease.add(targetComponent);
select(myNewSelectedComponentsOnRelease);
}
myHitTarget.mouseDrag(x, y, myHitListener.myHitTargets, transform);
if (myHitTarget instanceof MultiComponentTarget) {
delegateMouseDragToSelection(x, y, myHitListener.getClosestTarget(modifiersEx), myHitTarget.getComponent(), transform);
}
myHitListener.setTargetFilter(null);
}
mouseHover(transform, x, y, modifiersEx);
requestLayoutIfNeeded();
}
private static boolean isWithinThreshold(@AndroidDpCoordinate int pos1, @AndroidDpCoordinate int pos2, SceneContext transform) {
@SwingCoordinate int pos3 = transform.getSwingDimensionDip(pos1);
@SwingCoordinate int pos4 = transform.getSwingDimensionDip(pos2);
return Math.abs(pos3 - pos4) < DRAG_THRESHOLD;
}
/**
* Trigger layout if this {@link Scene} is marked to re-layout.
* If there was no layout request, this function does nothing.
* <p>
* To mark re-layout, use {@link #markNeedsLayout(int)} with {@link #IMMEDIATE_LAYOUT} and
* {@link #ANIMATED_LAYOUT}.
* <p>
* Note that this function doesn't reset the mark. To clear the mark, use {@link #markNeedsLayout(int)}
* with {@link #NO_LAYOUT} flag.
* <p>
* If it needs to layout and live-rendering is enabled, re-render happens as well.
*
* @see #markNeedsLayout(int)
* @see #NO_LAYOUT
* @see #IMMEDIATE_LAYOUT
* @see #ANIMATED_LAYOUT
*/
public void requestLayoutIfNeeded() {
if (mNeedsLayout != NO_LAYOUT) {
SceneManager manager = myDesignSurface.getSceneManager();
if (manager == null) {
return;
}
// TODO: b/180067858 Clean up the render path. Currently mNeedsLayout is never ANIMATED_LAYOUT.
if (myIsLiveRenderingEnabled) {
manager.requestLayoutAndRender(mNeedsLayout == ANIMATED_LAYOUT);
}
else {
manager.requestLayout(mNeedsLayout == ANIMATED_LAYOUT);
}
}
}
private boolean findSelectionOfCurve(SecondarySelector ss) {
// find selection of curve
if (ss == null) {
return false;
}
NlComponent comp = ss.getComponent();
SecondarySelector.Constraint sub = ss.getConstraint();
myDesignSurface.getSelectionModel().setSecondarySelection(comp, sub);
return true;
}
/**
* handles MouseUP event
*/
public void mouseRelease(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
myLastMouseX = x;
myLastMouseY = y;
SceneComponent closestComponent = myHitListener.getClosestComponent();
if (myHitTarget != null) {
myHitListener.find(transform, myRoot, x, y, modifiersEx);
myHitTarget.mouseRelease(x, y, myHitListener.getHitTargets());
myHitTarget.getComponent().setDragging(false);
if (myHitTarget instanceof MultiComponentTarget) {
// TODO: Check if it is samw as started.
delegateMouseReleaseToSelection(x, y, myHitListener.getClosestTarget(modifiersEx), myHitTarget.getComponent());
}
}
myFilterType = FilterType.NONE;
myNewSelectedComponentsOnRelease.clear();
if (myHitComponent != null && closestComponent == myHitComponent) {
myNewSelectedComponentsOnRelease.add(myHitComponent);
}
if (myHitTarget != null) {
List<SceneComponent> changed = myHitTarget.newSelection();
if (changed != null) {
myNewSelectedComponentsOnRelease.clear();
myNewSelectedComponentsOnRelease.addAll(changed);
}
}
SecondarySelector secondarySelector = getSecondarySelector(transform, x, y);
boolean same = sameSelection();
if (same && myHitListener.getTopHitComponent() != closestComponent
&& isWithinThreshold(myPressedMouseX, x, transform)
&& isWithinThreshold(myPressedMouseY, y, transform)) {
// if the hit target ended up selecting the same component -- but
// we have a /different/ top component, we should select it instead.
// Let's only do that though if there was no drag action.
myNewSelectedComponentsOnRelease.clear();
myNewSelectedComponentsOnRelease.add(myHitListener.getTopHitComponent());
myHitTarget = null;
same = sameSelection();
}
if (secondarySelector == null && !same && (myHitTarget == null || myHitTarget.canChangeSelection())) {
select(myNewSelectedComponentsOnRelease);
}
else {
// TODO: Clear in findSelectionOfCurve.
myDesignSurface.getSelectionModel().clearSecondary();
findSelectionOfCurve(secondarySelector);
}
myHitTarget = null;
requestLayoutIfNeeded();
}
public void mouseCancel() {
if (myHitTarget != null) {
myHitTarget.mouseCancel();
myHitTarget.getComponent().setDragging(false);
if (myHitTarget instanceof MultiComponentTarget) {
delegateMouseCancelToSelection(myHitTarget.getComponent());
}
}
myFilterType = FilterType.NONE;
myNewSelectedComponentsOnRelease.clear();
myHitTarget = null;
requestLayoutIfNeeded();
}
private boolean inCurrentSelection(@NotNull SceneComponent component) {
List<NlComponent> currentSelection = myDesignSurface.getSelectionModel().getSelection();
return currentSelection.contains(component.getNlComponent());
}
private boolean sameSelection() {
if (!myNewSelectedComponentsOnRelease.isEmpty()
&& myNewSelectedComponentsOnRelease.size() == myNewSelectedComponentsOnDown.size()
&& myNewSelectedComponentsOnRelease.containsAll(myNewSelectedComponentsOnDown)) {
// we already applied the selection on mouseDown
return true;
}
List<NlComponent> currentSelection = myDesignSurface.getSelectionModel().getSelection();
if (myNewSelectedComponentsOnRelease.size() == currentSelection.size()) {
int count = currentSelection.size();
for (int i = 0; i < count; i++) {
NlComponent component = currentSelection.get(i);
SceneComponent sceneComponent = getSceneComponent(component);
if (!myNewSelectedComponentsOnRelease.contains(sceneComponent)) {
return false;
}
}
return true;
}
return false;
}
/**
* Set a flag to identify that the {@link Scene} needs to recompute the layout when {@link #requestLayoutIfNeeded()}
* is called.
*
* @param type Type of layout to recompute: {@link #NO_LAYOUT}, {@link #IMMEDIATE_LAYOUT}, {@link #ANIMATED_LAYOUT}
*/
public void markNeedsLayout(@MagicConstant(intValues = {NO_LAYOUT, IMMEDIATE_LAYOUT, ANIMATED_LAYOUT}) int type) {
mNeedsLayout = type;
}
public long getDisplayListVersion() {
return myDisplayListVersion;
}
// TODO: reduce visibility? Probably the modified SceneComponents should do this rather than
// requiring it to be done explicitly by the code that's modifying them.
public void needsRebuildList() {
myDisplayListVersion++;
}
//endregion
/////////////////////////////////////////////////////////////////////////////
/**
* Finds any components that overlap the given rectangle.
*
* @param x The top left x corner defining the selection rectangle.
* @param y The top left y corner defining the selection rectangle.
* @param width The w of the selection rectangle
* @param height The h of the selection rectangle
*/
public List<SceneComponent> findWithin(@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@AndroidDpCoordinate int width,
@AndroidDpCoordinate int height) {
List<SceneComponent> within = new ArrayList<>();
if (getRoot() != null) {
addWithin(within, getRoot(), x, y, width, height);
}
return within;
}
private static boolean addWithin(@NotNull List<SceneComponent> result,
@NotNull SceneComponent component,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@AndroidDpCoordinate int width,
@AndroidDpCoordinate int height) {
if (component.getDrawX() + component.getDrawWidth() <= x ||
x + width <= component.getDrawX() ||
component.getDrawY() + component.getDrawHeight() <= y ||
y + height <= component.getDrawY()) {
return false;
}
boolean found = false;
for (SceneComponent child : component.getChildren()) {
found |= addWithin(result, child, x, y, width, height);
}
if (!found) {
result.add(component);
}
return true;
}
@Nullable
public SceneComponent findComponent(@NotNull SceneContext transform, @AndroidDpCoordinate int x, @AndroidDpCoordinate int y) {
if (myRoot == null) {
return null;
}
myFindListener.find(transform, myRoot, x, y, 0);
return myFindListener.getClosestComponent();
}
@Nullable
public Target findTarget(@NotNull SceneContext transform,
@AndroidDpCoordinate int x,
@AndroidDpCoordinate int y,
@JdkConstants.InputEventMask int modifiersEx) {
if (myRoot == null) {
return null;
}
myFindListener.find(transform, myRoot, x, y, modifiersEx);
return myFindListener.getClosestTarget(modifiersEx);
}
public Collection<SceneComponent> getSceneComponents() {
return mySceneComponents.values();
}
public void setRoot(SceneComponent root) {
myRoot = root;
}
@NotNull
public FilterType getFilterType() {
return myFilterType;
}
public void setFilterType(@NotNull FilterType filterType) {
myFilterType = filterType;
}
@Nullable
public Target getInteractingTarget() {
return myHitTarget;
}
@NotNull
@AndroidDpCoordinate
public CompletableFuture<Dimension> measureWrapSize(@NotNull SceneComponent component) {
return measure(component, (n, namespace, localName) -> {
// Change attributes to wrap_content
if (ATTR_LAYOUT_WIDTH.equals(localName) && ANDROID_URI.equals(namespace)) {
return VALUE_WRAP_CONTENT;
}
if (ATTR_LAYOUT_HEIGHT.equals(localName) && ANDROID_URI.equals(namespace)) {
return VALUE_WRAP_CONTENT;
}
return null;
});
}
@NotNull
@AndroidDpCoordinate
private CompletableFuture<Dimension> measure(@NotNull SceneComponent component, @Nullable RenderTask.AttributeFilter filter) {
// TODO: Reuse snapshot!
NlComponent neleComponent = component.getNlComponent();
if (!neleComponent.getBackend().isValid()) {
return CompletableFuture.completedFuture(null);
}
NlModel model = neleComponent.getModel();
XmlFile xmlFile = model.getFile();
Module module = model.getModule();
RenderService renderService = RenderService.getInstance(module.getProject());
AndroidFacet facet = model.getFacet();
RenderLogger logger = renderService.createLogger(facet);
return renderService.taskBuilder(facet, model.getConfiguration())
.withLogger(logger)
.withPsiFile(xmlFile)
.build()
.thenCompose(task -> {
if (task == null) {
return CompletableFuture.completedFuture(null);
}
XmlTag tag = neleComponent.getTagDeprecated();
return task.measureChild(tag, filter).whenCompleteAsync((map, ex) -> task.dispose(), PooledThreadExecutor.INSTANCE);
})
.thenApply(viewInfo -> {
if (viewInfo == null) {
return null;
}
viewInfo = RenderService.getSafeBounds(viewInfo);
return new Dimension(Coordinates.pxToDp(getSceneManager(), viewInfo.getRight() - viewInfo.getLeft()),
Coordinates.pxToDp(getSceneManager(), viewInfo.getBottom() - viewInfo.getTop()));
});
}
/**
* Get the {@link Placeholder}s in the Scene without the ones belong to the {@param requester} and its children.
*
* @param requester the component which request {@link Placeholder}s
* @return list of the {@link Placeholder}s for requester
*/
public List<Placeholder> getPlaceholders(@Nullable SceneComponent requester) {
ImmutableList.Builder<Placeholder> builder = new ImmutableList.Builder<>();
doGetPlaceholders(builder, myRoot, requester);
return builder.build();
}
public boolean isLiveRenderingEnabled() {
return myIsLiveRenderingEnabled;
}
public void setLiveRenderingEnabled(boolean enabled) {
myIsLiveRenderingEnabled = enabled;
}
private static void doGetPlaceholders(@NotNull ImmutableList.Builder<Placeholder> builder,
@NotNull SceneComponent component,
@Nullable SceneComponent requester) {
if (component == requester) {
return;
}
NlComponent nlComponent = component.getNlComponent();
ViewHandler handler = NlComponentHelperKt.getViewHandler(nlComponent);
if (handler != null) {
builder.addAll(handler.getPlaceholders(component));
}
for (SceneComponent child : component.getChildren()) {
doGetPlaceholders(builder, child, requester);
}
}
public void setHitTarget(@Nullable Target hitTarget) {
myHitTarget = hitTarget;
}
}
| 35.952644
| 156
| 0.668072
|
c53c018e600c50f15b47ef25395f9cdb13b9d194
| 2,565
|
package com.Voxce.model;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user_cv")
public class UserCV {
private int user_cv_id;
private int user_id;
private int study_id;
private Date received_dt;
private int created_by;
private Date date_created;
private int modified_by;
private Date date_modified;
private String type;
private String filename;
private String file_description;
private byte[] data;
@Id
@GeneratedValue
@Column(name="user_cv_id")
public int getUser_cv_id() {
return user_cv_id;
}
public void setUser_cv_id(int user_cv_id) {
this.user_cv_id = user_cv_id;
}
@Column(name="user_id")
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
@Column(name="study_id")
public int getStudy_id() {
return study_id;
}
public void setStudy_id(int study_id) {
this.study_id = study_id;
}
@Column(name="received_dt")
public Date getReceived_dt() {
return received_dt;
}
public void setReceived_dt(Date received_dt) {
this.received_dt = received_dt;
}
@Column(name="created_by")
public int getCreated_by() {
return created_by;
}
public void setCreated_by(int created_by) {
this.created_by = created_by;
}
@Column(name="date_created")
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
@Column(name="modified_by")
public int getModified_by() {
return modified_by;
}
public void setModified_by(int modified_by) {
this.modified_by = modified_by;
}
@Column(name="date_modified")
public Date getDate_modified() {
return date_modified;
}
public void setDate_modified(Date date_modified) {
this.date_modified = date_modified;
}
@Column(name="filename")
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
@Column(name="file_description")
public String getFile_description() {
return file_description;
}
public void setFile_description(String file_description) {
this.file_description = file_description;
}
@Column(name="type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Column(name="data")
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
| 20.039063
| 59
| 0.733723
|
9e0f1a5a558d045d6bd2bfa24301187b536660be
| 12,570
|
package gq.gouq;
import javax.swing.*;
import javax.swing.event.ListDataListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.Timer;
/**
* Created by Mega
* Intellij IDEA
*/
public class Gui extends JFrame {
private JTabbedPane tabbedPane;
private JPanel panel1;
private JTextArea showPassword;
private JButton deletePassword;
private JTextField newUsage;
public JTextArea newPassword;
private JButton selectExportFile;
private JButton startExportButton;
private JComboBox showUsage;
private JButton addPassword;
private JButton selectImportFile;
private JTextField exportText;
private JTextField importText;
private JButton startImportButton;
private JButton generateRandomPassword;
private JButton sourceforgeSiteButton;
private JButton sourceCodeButton;
private JButton donateButton;
private JTextArea thisFreeSoftwareIsTextArea;
private KeyedTable passwords = new KeyedTable();
private GenerateRandom randomPassword;
public TimerTask save_passwords;
Gui(){
super("Gouq.gq Saveword");
setContentPane(panel1);
pack();
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/savewords.gpw"))) {
passwords = (KeyedTable) in.readObject();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
save_passwords = new TimerTask() {
@Override
public void run() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/savewords.gpw"))) {
out.writeObject(passwords);
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
};
Timer saving_timer = new Timer();
saving_timer.scheduleAtFixedRate(save_passwords, 1800, 1800);
addPassword.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (newUsage.getText().equals("") || newUsage.getText().equals(null)){
JOptionPane.showMessageDialog(null, "You have to enter an usage.", "Gouq.gq Saveword", JOptionPane.WARNING_MESSAGE);
} else if (newPassword.getText().equals("") || newPassword.getText().equals(null)){
JOptionPane.showMessageDialog(null, "You have to enter a password.", "Gouq.gq Saveword", JOptionPane.WARNING_MESSAGE);
} else {
if (passwords.getData(newUsage.getText()) != null) {
int ans = JOptionPane.showConfirmDialog(null, "This usage (" + newUsage.getText() + ") is already assigned.\nDo you want to overide it?", "Gouq.gq Saveword", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ans != JOptionPane.YES_OPTION)
return;
}
passwords.setData(newUsage.getText(), newPassword.getText());
updateShowUsageModel();
newPassword.setText("");
newUsage.setText("");
JOptionPane.showMessageDialog(null, "Successful", "Gouq.gq Saveword", JOptionPane.INFORMATION_MESSAGE);
save_passwords.run();
}
}
});
deletePassword.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (passwords.getData((String)showUsage.getSelectedItem()) != null){
int ans = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete the password for \""+(String) showUsage.getSelectedItem() + "\"?", "Gouq.gq Saveword", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ans == JOptionPane.YES_OPTION)
passwords.removeData((String)showUsage.getSelectedItem());
updateShowUsageModel();
}
save_passwords.run();
}
});
selectExportFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File("."));
fc.setDialogTitle("Gouq.gq Saveword");
fc.setFileFilter(new FileNameExtensionFilter(".gpw", "gpw"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.showOpenDialog(null);
exportText.setText(fc.getSelectedFile().getPath());
if (!exportText.getText().substring(exportText.getText().length() - 4, exportText.getText().length()).equals(".gpw"))
exportText.setText(exportText.getText() + ".gpw");
}
});
startExportButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(exportText.getText()))) {
out.writeObject(passwords);
out.close();
JOptionPane.showMessageDialog(null, "Successful", "Gouq.gq Saveword", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "Illegal file!", "Gouq.gq Saveword", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
}
}
});
startImportButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(importText.getText()))) {
KeyedTable table = (KeyedTable) in.readObject();
for (int i = 0; i < table.getSize() ; i++) {
boolean set = true;
if (passwords.hasData(table.getKeyAt(i)))
set = JOptionPane.showConfirmDialog(null, "The password for \"" + table.getKeyAt(i) + "\" already exists.\nDo you want to overide it?", "Gouq.gq Saveword", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
== JOptionPane.YES_OPTION;
if(set) passwords.setData(table.getKeyAt(i), table.getDataAt(i));
}
in.close();
JOptionPane.showMessageDialog(null, "Successful", "Gouq.gq Saveword", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "Illegal file!", "Gouq.gq Saveword", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
}
updateShowUsageModel();
save_passwords.run();
}
});
selectImportFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File("."));
fc.setDialogTitle("Gouq.gq Saveword");
fc.setFileFilter(new FileNameExtensionFilter(".gpw", "gpw"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.showOpenDialog(null);
importText.setText(fc.getSelectedFile().getPath());
if (!importText.getText().substring(importText.getText().length() - 4, importText.getText().length()).equals(".gpw"))
importText.setText(importText.getText() + ".gpw");
}
});
generateRandomPassword.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
randomPassword = new GenerateRandom(Main.gui);
setEnabled(false);
}
});
donateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(Desktop.isDesktopSupported())
{
try {
Desktop.getDesktop().browse(new URI("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G47UDT9NVW3EW"));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
sourceforgeSiteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(Desktop.isDesktopSupported())
{
try {
Desktop.getDesktop().browse(new URI("https://sourceforge.net/u/gouqgq/profile/"));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
sourceCodeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(Desktop.isDesktopSupported())
{
try {
Desktop.getDesktop().browse(new URI("https://github.com/GouqGq/Gouq.gq-Saveword"));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
thisFreeSoftwareIsTextArea.setText("This free software is brought to you by Gouq.gq, please consider donating to us by clicking the button down below. Alwas think of the license which was enclosed to this software (LICENSE.txt)");
updateShowUsageModel();
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
setLocation(gd.getDisplayMode().getWidth() / 2 - getWidth() / 2, gd.getDisplayMode().getHeight() / 2 - getHeight() / 2);
setDefaultLookAndFeelDecorated(true);
setResizable(true);
setVisible(true);
pack();
}
void updateShowUsageModel(){
showUsage.setModel(new ComboBoxModel() {
String select_name = "";
@Override
public void setSelectedItem(Object anItem) {
select_name = (String) anItem;
showPassword.setText((String) passwords.getData(select_name));
}
@Override
public Object getSelectedItem() {
return select_name;
}
@Override
public int getSize() {
return passwords.getSize();
}
@Override
public Object getElementAt(int index) {
return (String)passwords.getKeyAt(index);
}
@Override
public void addListDataListener(ListDataListener l) {
}
@Override
public void removeListDataListener(ListDataListener l) {
}
});
showPassword.setText("");
}
public void closeRandomGui(){
randomPassword.dispatchEvent(new WindowEvent(randomPassword, WindowEvent.WINDOW_CLOSING));
}
}
| 40.288462
| 250
| 0.575099
|
8fd3927ddc3551599455597e2a63fd26b02e36ba
| 1,960
|
/*
* IRClib -- A Java Internet Relay Chat library -- class SSLDefaultTrustManager
* Copyright (C) 2002 - 2006 Christoph Schwering <schwering@gmail.com>
*
* This library and the accompanying materials are made available under the
* terms of the
* - GNU Lesser General Public License,
* - Apache License, Version 2.0 and
* - Eclipse Public License v1.0.
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*/
package org.schwering.irc.lib.ssl;
import java.security.cert.X509Certificate;
/**
* The default <code>TrustManager</code> of the
* <code>SSLIRCConnection</code>.
* <p>
* It automatically accepts the X509 certificate.
* <p>
* In many cases you should change the <code>SSLIRCConnection</code>'s
* <code>SSLTrustManager</code>. For examle if you write an IRC client for human
* users, you may want to ask the user whether he accepts the server's
* certificate or not.
* @author Christoph Schwering <schwering@gmail.com>
* @since 1.10
* @version 2.00
* @see SSLIRCConnection
* @see SSLTrustManager
*/
public class SSLDefaultTrustManager implements SSLTrustManager {
/**
* The <code>X509Certificate</code>s which are accepted.
*/
protected X509Certificate[] accepted = new X509Certificate[0];
// ------------------------------
/**
* Trusts the complete certificate chain and returns <code>true</code>.
* @param chain The peer certificate chain.
* @return <code>true</code>.
*/
public boolean isTrusted(X509Certificate[] chain) {
accepted = chain;
return true;
}
// ------------------------------
/**
* Returns the accepted certificates. They are set in the
* <code>checkServerTrusted</code> method.
* @return A non-null (possibly empty) array of acceptable CA issuer
* certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return accepted;
}
}
| 30.153846
| 81
| 0.664796
|
9cf1bb4abb35d116c374a275c46a9d3e0410282d
| 835
|
package com.tvd12.ezydata.mongodb.testing.bean;
import java.util.List;
import com.tvd12.ezydata.mongodb.EzyMongoRepository;
import com.tvd12.ezyfox.annotation.EzyAutoImpl;
import com.tvd12.ezyfox.database.annotation.EzyQuery;
import com.tvd12.ezyfox.util.Next;
@EzyAutoImpl
public interface DuckRepo extends EzyMongoRepository<DuckId, Duck> {
@EzyQuery("{_id : ?0}")
Duck findDuckById(DuckId id);
@EzyQuery("{$query: {age: {$gte : ?0}}, $orderby : {age: -1}}")
List<Duck> findListByAge(int age, Next next);
@EzyQuery("{age: {$gte : ?0}}")
List<Duck> findListByAge2(int age);
@EzyQuery("{$query: {age: {$gte : ?0}}}")
int countByAge(int age, Next next);
@EzyQuery("{}")
void updateByAge();
@EzyQuery("{age : ?0}")
int deleteByAge(int age);
@EzyQuery("{$query: {age : ?0}}")
int deleteByAge2(int age);
}
| 23.857143
| 68
| 0.686228
|
3d1d244994c645031593a9bb8f57607dc8e43495
| 1,849
|
package es.ucm.fdi.iw.model;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@NamedQueries({
@NamedQuery(name="allComment",
query="select c from Comment c"),
@NamedQuery(name="commentsByID",
query="select c from Comment c where c.id = :idParam"),
@NamedQuery(name="CommentByRes",
query="select c from Comment c where c.location = :idResParam"),
@NamedQuery(name="CommentByOwner",
query="select c from Comment c where c.owner = :idOwnParam")
})
@Entity
public class Comment {
private long id;
private Restaurant location;
private Profile owner;
private String content;
//private Date date;
private int rateUp;
private int rateDown;
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(targetEntity=Restaurant.class)
public Restaurant getLocation() {
return location;
}
public void setLocation(Restaurant location) {
this.location = location;
}
@ManyToOne(targetEntity=Profile.class)
public Profile getOwner() {
return owner;
}
public void setOwner(Profile owner) {
this.owner = owner;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
public Date getDate() {
return date;rateUp
}
public void setDate(Date date) {
this.date = date;
}
*/
public int getRateUp() {
return rateUp;
}
public void setRateUp(int rateUp) {
this.rateUp += rateUp;
}
public int getRateDown() {
return rateDown;
}
public void setRateDown(int rateDown) {
this.rateDown -= rateDown;
}
public void resetRates() {
this.rateDown = 0;
this.rateUp = 0;
}
}
| 17.778846
| 65
| 0.713359
|
99bd0a30118f1460f865f64df42a9e5d591621ee
| 689
|
package io.lsdconsulting.lsd.distributed.mongo.integration.testapp.config;
import io.lsdconsulting.lsd.distributed.mongo.integration.testapp.repository.TestRepository;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import static io.lsdconsulting.lsd.distributed.mongo.integration.testapp.repository.TestRepository.setupDatabase;
@TestConfiguration
public class RepositoryConfig {
// This is because the configs in spring.factories run always before any test configs.
static {
setupDatabase();
}
@Bean
public TestRepository testRepository() {
return new TestRepository();
}
}
| 31.318182
| 113
| 0.786647
|
bd10da8407714d8c5a80a6872894f45d8fbcc84d
| 869
|
package br.com.fernando.chapter10_concurrencyUtilities.part00_intro;
public class Intro {
// Concurrency Utilities for Java EE provides a simple, standardized API for using concurrency from application components without compromising
// container integrity while still preserving the Java EE platform’s fundamental benefits.
//
// Java EE containers such as the EJB or web container do not allow using common Java SE concurrency APIs such as java.util.concurrent.ThreadPoolExecutor,
// java.lang.Thread, or java.util.Timer directly.
//
// This is because all application code is run on a thread managed by the container, and each container typically expects all access to container-supplied
// objects to occur on the same thread.
// This allows the container to manage the resources and provide centralized administration.
}
| 57.933333
| 159
| 0.771001
|
b131bd785e180ff49c47566040a58496c8a6de37
| 562
|
package com.neomind.samples;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
@RunWith(JUnit4.class)
public class NashornTest
{
@Test
public void doTest() throws Exception
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println(engine.getClass().getName());
System.out.println("Result:" + engine.eval("function f() { return 1; }; f() + 1;"));
}
}
| 23.416667
| 86
| 0.74911
|
4f0273041edf31604ca6a5093783210ef7390e80
| 8,033
|
package weiboclient4j;
import weiboclient4j.model.Friendship;
import weiboclient4j.model.User;
import weiboclient4j.model.UserIdList;
import weiboclient4j.model.UserList;
import weiboclient4j.params.Paging;
import weiboclient4j.params.Remark;
import weiboclient4j.params.ScreenName;
import weiboclient4j.params.SourceScreenName;
import weiboclient4j.params.SourceUid;
import weiboclient4j.params.Suid;
import weiboclient4j.params.TargetScreenName;
import weiboclient4j.params.TargetUid;
import weiboclient4j.params.Uid;
/**
* @author Hover Ruan
*/
public class FriendshipService extends AbstractService {
public FriendshipService(WeiboClient client) {
super(client);
}
public UserList getFriends(Uid uid) throws WeiboClientException {
return getFriends(uid, Paging.EMPTY);
}
public UserList getFriends(Uid uid, Paging paging) throws WeiboClientException {
return getFriends(uid, ScreenName.EMPTY, paging);
}
public UserList getFriends(ScreenName screenName) throws WeiboClientException {
return getFriends(screenName, Paging.EMPTY);
}
public UserList getFriends(ScreenName screenName, Paging paging) throws WeiboClientException {
return getFriends(Uid.EMPTY, screenName, paging);
}
private UserList getFriends(Uid uid, ScreenName screenName, Paging paging) throws WeiboClientException {
return doGet("friendships/friends",
paging, withParams(uid, screenName), UserList.class);
}
public UserIdList getFriendsIds(Uid uid) throws WeiboClientException {
return getFriendsIds(uid, Paging.EMPTY);
}
public UserIdList getFriendsIds(Uid uid, Paging paging) throws WeiboClientException {
return getFriendsIds(uid, ScreenName.EMPTY, paging);
}
public UserIdList getFriendsIds(ScreenName screenName) throws WeiboClientException {
return getFriendsIds(screenName, Paging.EMPTY);
}
public UserIdList getFriendsIds(ScreenName screenName, Paging paging) throws WeiboClientException {
return getFriendsIds(Uid.EMPTY, screenName, paging);
}
private UserIdList getFriendsIds(Uid uid, ScreenName screenName, Paging paging) throws WeiboClientException {
return doGet("friendships/friends/ids",
paging, withParams(uid, screenName), UserIdList.class);
}
public UserList getFriendsInCommon(Uid uid) throws WeiboClientException {
return getFriendsInCommon(uid, Suid.EMPTY);
}
public UserList getFriendsInCommon(Uid uid, Paging paging) throws WeiboClientException {
return getFriendsInCommon(uid, Suid.EMPTY, paging);
}
public UserList getFriendsInCommon(Uid uid, Suid suid) throws WeiboClientException {
return getFriendsInCommon(uid, suid, Paging.EMPTY);
}
public UserList getFriendsInCommon(Uid uid, Suid suid, Paging paging) throws WeiboClientException {
return doGet("friendships/friends/in_common",
paging, withParams(uid, suid), UserList.class);
}
public UserList getFriendsBilateral(Uid uid) throws WeiboClientException {
return getFriendsBilateral(uid, Paging.EMPTY);
}
public UserList getFriendsBilateral(Uid uid, Paging paging) throws WeiboClientException {
return doGet("friendships/friends/bilateral",
paging, withParams(uid), UserList.class);
}
public UserIdList getFriendsBilateralIds(Uid uid) throws WeiboClientException {
return getFriendsBilateralIds(uid, Paging.EMPTY);
}
public UserIdList getFriendsBilateralIds(Uid uid, Paging paging) throws WeiboClientException {
return doGet("friendships/friends/bilateral/ids",
paging, withParams(uid), UserIdList.class);
}
public UserList getFollowers(ScreenName screenName) throws WeiboClientException {
return getFollowers(screenName, Paging.EMPTY);
}
public UserList getFollowers(ScreenName screenName, Paging paging) throws WeiboClientException {
return getFollowers(Uid.EMPTY, screenName, paging);
}
public UserList getFollowers(Uid uid) throws WeiboClientException {
return getFollowers(uid, Paging.EMPTY);
}
public UserList getFollowers(Uid uid, Paging paging) throws WeiboClientException {
return getFollowers(uid, ScreenName.EMPTY, paging);
}
public UserList getFollowers(Uid uid, ScreenName screenName, Paging paging) throws WeiboClientException {
return doGet("friendships/followers",
paging, withParams(uid, screenName), UserList.class);
}
public UserIdList getFollowersIds(ScreenName screenName) throws WeiboClientException {
return getFollowersIds(screenName, Paging.EMPTY);
}
public UserIdList getFollowersIds(ScreenName screenName, Paging paging) throws WeiboClientException {
return getFollowersIds(Uid.EMPTY, screenName, paging);
}
public UserIdList getFollowersIds(Uid uid) throws WeiboClientException {
return getFollowersIds(uid, Paging.EMPTY);
}
public UserIdList getFollowersIds(Uid uid, Paging paging) throws WeiboClientException {
return getFollowersIds(uid, ScreenName.EMPTY, paging);
}
public UserIdList getFollowersIds(Uid uid, ScreenName screenName, Paging paging) throws WeiboClientException {
return doGet("friendships/followers/ids",
paging, withParams(uid, screenName), UserIdList.class);
}
public UserList getActiveFollowers(Uid uid) throws WeiboClientException {
return getActiveFollowers(uid, Paging.EMPTY);
}
public UserList getActiveFollowers(Uid uid, Paging paging) throws WeiboClientException {
return doGet("friendships/followers/active",
paging, withParams(uid), UserList.class);
}
public UserList getChainFollowers(Uid uid) throws WeiboClientException {
return getChainFollowers(uid, Paging.EMPTY);
}
public UserList getChainFollowers(Uid uid, Paging paging) throws WeiboClientException {
return doGet("friendships/friends_chain/followers",
paging, withParams(uid), UserList.class);
}
public Friendship show(SourceUid sourceUid, TargetUid targetUid) throws WeiboClientException {
return show(sourceUid, SourceScreenName.EMPTY, targetUid, TargetScreenName.EMPTY);
}
public Friendship show(SourceScreenName sourceScreenName, TargetScreenName targetScreenName)
throws WeiboClientException {
return show(SourceUid.EMPTY, sourceScreenName, TargetUid.EMPTY, targetScreenName);
}
public Friendship show(SourceUid sourceUid, SourceScreenName sourceScreenName,
TargetUid targetUid, TargetScreenName targetScreenName) throws WeiboClientException {
return doGet("friendships/show",
withParams(sourceUid, sourceScreenName, targetUid, targetScreenName), Friendship.class);
}
public User create(Uid uid) throws WeiboClientException {
return create(uid, ScreenName.EMPTY);
}
public User create(ScreenName screenName) throws WeiboClientException {
return create(Uid.EMPTY, screenName);
}
public User create(Uid uid, ScreenName screenName) throws WeiboClientException {
return doPost("friendships/create",
withParams(uid, screenName), User.class);
}
public User destroy(Uid uid) throws WeiboClientException {
return destroy(uid, ScreenName.EMPTY);
}
public User destroy(ScreenName screenName) throws WeiboClientException {
return destroy(Uid.EMPTY, screenName);
}
public User destroy(Uid uid, ScreenName screenName) throws WeiboClientException {
return doPost("friendships/destroy",
withParams(uid, screenName), User.class);
}
public User updateRemark(Uid uid, Remark remark) throws WeiboClientException {
return doPost("friendships/remark/update",
withParams(uid, remark), User.class);
}
}
| 38.435407
| 114
| 0.72725
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.