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
863d1331c5c621e46dd99c79313c5ddfc2c4a7c3
10,306
/* * Copyright 2017-2021 Micro Focus or one of its affiliates. * * 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.github.cafdataprocessing.workflow; import com.github.cafdataprocessing.workflow.model.Workflow; import com.google.common.base.Strings; import com.hpe.caf.api.ConfigurationException; import com.hpe.caf.worker.document.exceptions.DocumentWorkerTransientException; import com.hpe.caf.worker.document.extensibility.DocumentWorker; import com.hpe.caf.worker.document.model.Document; import com.hpe.caf.worker.document.model.Field; import com.hpe.caf.worker.document.model.HealthMonitor; import com.hpe.caf.worker.document.model.ResponseCustomData; import com.hpe.caf.worker.document.model.Task; import java.util.Optional; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.ScriptException; import org.slf4j.MDC; /** * Worker that will examine task received for a workflow name, it will then look for a yaml file with the same * name on disk and add it to the task along with any settings required for the workflow. */ public final class WorkflowWorker implements DocumentWorker { private static final Logger LOG = LoggerFactory.getLogger(WorkflowWorker.class); private static final String TENANT_ID_KEY = "tenantId"; private static final String CORRELATION_ID_KEY = "correlationId"; private static final String SETTINGS_SERVICE_LAST_UPDATE_TIME_MILLIS_KEY = "settingsServiceLastUpdateTimeMillis"; private final WorkflowManager workflowManager; private final ScriptManager scriptManager; private final ArgumentsManager argumentsManager; private final FailureFieldsManager failureFieldsManager; /** * Instantiates a WorkflowWorker instance to process documents, evaluating them against the workflow referred to by * the document. * @param workflowWorkerConfiguration The worker's configuration * @param workflowManager Retrieves workflows from disk and stores them in the datastore * @param scriptManager Applies the scripts to the documents task object * @param argumentsManager Processes settings definitions and retrieves values from custom data, document fields or * the settings service * @param failureFieldsManager Processes the extra failure subfields that should be used during the workflow * @throws ConfigurationException when workflow directory is not set */ public WorkflowWorker(final WorkflowWorkerConfiguration workflowWorkerConfiguration, final WorkflowManager workflowManager, final ScriptManager scriptManager, final ArgumentsManager argumentsManager, final FailureFieldsManager failureFieldsManager ) throws ConfigurationException { final String workflowsDirectory = workflowWorkerConfiguration.getWorkflowsDirectory(); if(workflowsDirectory == null){ throw new ConfigurationException("No workflow storage directory was set. Unable to load available workflows."); } this.workflowManager = workflowManager; this.scriptManager = scriptManager; this.argumentsManager = argumentsManager; this.failureFieldsManager = failureFieldsManager; } /** * This method provides an opportunity for the worker to report if it has any problems which would prevent it * processing documents correctly. If the worker is healthy then it should simply return without calling the * health monitor. * * @param healthMonitor used to report the health of the application */ @Override public void checkHealth(final HealthMonitor healthMonitor) { try { argumentsManager.checkHealth(); } catch (final Exception e) { LOG.error("Problem encountered when contacting Settings Service to check health: ", e); healthMonitor.reportUnhealthy("Settings Service communication is unhealthy: " + e.getMessage()); } } /** * Processes a single document. Retrieving the workflow it refers to, evaluating the document against the workflow * to determine where it should be sent to and storing the workflow on the document so the next worker may * re-evaluate the document once it has finished its action. * * @param document the document to be processed. * @throws DocumentWorkerTransientException if the document could not be processed */ @Override public void processDocument(final Document document) throws DocumentWorkerTransientException { addMdcLoggingData(document.getTask()); // Get the workflow specification passed in final String customDataWorkflowName = document.getCustomData("workflowName"); final Field fieldWorkflowName = document.getField("CAF_WORKFLOW_NAME"); if(!Strings.isNullOrEmpty(customDataWorkflowName)){ fieldWorkflowName.set(customDataWorkflowName); } if(!fieldWorkflowName.hasValues()){ LOG.error(String.format("Workflow could not be retrieved from custom data for document [%s].", document.getReference())); document.addFailure("WORKFLOW_NOT_SPECIFIED", "Workflow could not be retrieved from custom data."); return; } if(fieldWorkflowName.getValues().size()>1){ LOG.error(String.format("Multiple workflows [%s] supplied in CAF_WORKFLOW_NAME field for document [%s].", String.join(",", fieldWorkflowName.getStringValues()), document.getReference())); document.addFailure("WORKFLOW_MULTIPLE_WORKFLOWS", "More than one workflow name was found in CAF_WORKFLOW_NAME field."); } final String workflowName = fieldWorkflowName.getStringValues().get(0); final Workflow workflow = workflowManager.get(workflowName); if (workflow == null) { final String errorMessage = String.format("Workflow [%s] is not available for document [%s].", workflowName, document.getReference()); LOG.error(errorMessage); document.addFailure("WORKFLOW_NOT_FOUND", errorMessage); return; } final Optional<Long> settingsServiceLastUpdateTimeMillisOpt; try { settingsServiceLastUpdateTimeMillisOpt = getSettingsServiceLastUpdateTimeMillis(document); } catch (final NumberFormatException e) { final String errorMessage = String.format( "Custom data property [%s] for document [%s] could not be converted to an instance of Long [%s]", SETTINGS_SERVICE_LAST_UPDATE_TIME_MILLIS_KEY, document.getReference(), e.getMessage()); LOG.error(errorMessage); document.addFailure("WORKFLOW_CUSTOM_DATA_INVALID", errorMessage); return; } failureFieldsManager.handleExtraFailureSubFields(document); argumentsManager.addArgumentsToDocument(workflow.getArguments(), document, settingsServiceLastUpdateTimeMillisOpt); try { scriptManager.applyScriptToDocument(workflow, document); } catch (final ScriptException e) { LOG.error(String.format("ScriptException for document [%s].\n%s\n", document.getReference(), e.toString())); document.addFailure("WORKFLOW_SCRIPT_EXCEPTION", e.getMessage()); } } private void addMdcLoggingData(final Task task) { // The logging pattern we use uses a tenantId and a correlationId: // // https://github.com/CAFapi/caf-logging/tree/v1.0.0#pattern // https://github.com/CAFapi/caf-logging/blob/v1.0.0/src/main/resources/logback.xml#L27 // // This function adds a tenantId and correlationID to the MDC (http://logback.qos.ch/manual/mdc.html), so that log messages from // *this* worker (workflow-worker) will contain these values. // // See also addMdcData in workflow-control.js, which performs similar logic to ensure log messages from *subsequent* workers in // the workflow also contain these values. // Get MDC data from custom data, creating a correlationId if it doesn't yet exist. final String tenantId = task.getCustomData(TENANT_ID_KEY); final String correlationId = WorkflowWorker.getOrCreateCorrelationId(task); // Add tenantId and correlationId to the MDC. if (tenantId != null) { MDC.put(TENANT_ID_KEY, tenantId); } MDC.put(CORRELATION_ID_KEY, correlationId); // Add MDC data to custom data so that its passed it onto the next worker. final ResponseCustomData responseCustomData = task.getResponse().getCustomData(); responseCustomData.put(TENANT_ID_KEY, tenantId); responseCustomData.put(CORRELATION_ID_KEY, correlationId); } private static String getOrCreateCorrelationId(final Task task) { final String correlationId = task.getCustomData(CORRELATION_ID_KEY); return (correlationId == null) ? UUID.randomUUID().toString() : correlationId; } private static Optional<Long> getSettingsServiceLastUpdateTimeMillis(final Document document) throws NumberFormatException { final String settingsServiceLastUpdateTimeString = document.getCustomData(SETTINGS_SERVICE_LAST_UPDATE_TIME_MILLIS_KEY); if (Strings.isNullOrEmpty(settingsServiceLastUpdateTimeString)) { return Optional.empty(); } return Optional.of(Long.parseLong(settingsServiceLastUpdateTimeString)); } }
47.712963
137
0.703086
3435e53c745a08a7494b2a2e44936f5dce61495f
3,792
package org.prebid.server.geolocation; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.record.City; import com.maxmind.geoip2.record.Continent; import com.maxmind.geoip2.record.Country; import com.maxmind.geoip2.record.Location; import com.maxmind.geoip2.record.Subdivision; import io.vertx.core.Future; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.internal.util.reflection.FieldSetter; import org.prebid.server.geolocation.model.GeoInfo; import java.io.IOException; import java.util.ArrayList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; public class MaxMindGeoLocationServiceTest { private static final String TEST_IP = "80.215.195.122"; private MaxMindGeoLocationService maxMindGeoLocationService; @Before public void setUp() { maxMindGeoLocationService = new MaxMindGeoLocationService(); } @Test public void lookupShouldReturnFailedFutureWhenDatabaseReaderWasNotSet() { // given and when final Future<GeoInfo> result = maxMindGeoLocationService.lookup(TEST_IP, null); // then assertTrue(result.failed()); assertThat(result.cause()) .hasMessage("Geo location database file hasn't been downloaded yet, try again later"); } @Test public void setDatabaseReaderShouldReturnFailedFutureIfDatabaseArchiveNotFound() { // given and when final Future<?> result = maxMindGeoLocationService.setDataPath("no_file"); // then assertTrue(result.failed()); assertThat(result.cause()) .hasMessageStartingWith("IO Exception occurred while trying to read an archive/db file: no_file"); } @Test public void lookupShouldReturnCountryIsoWhenDatabaseReaderWasSet() throws NoSuchFieldException, IOException, GeoIp2Exception { // given final Country country = new Country(null, null, null, "fr", null); final Continent continent = new Continent(null, "eu", null, null); final City city = new City(singletonList("test"), null, null, singletonMap("test", "Paris")); final Location location = new Location(null, null, 48.8566, 2.3522, null, null, null); final ArrayList<Subdivision> subdivisions = new ArrayList<>(); subdivisions.add(new Subdivision(null, null, null, "paris", null)); final CityResponse cityResponse = new CityResponse(city, continent, country, location, null, null, null, null, subdivisions, null); final DatabaseReader databaseReader = Mockito.mock(DatabaseReader.class); given(databaseReader.city(any())).willReturn(cityResponse); FieldSetter.setField(maxMindGeoLocationService, maxMindGeoLocationService.getClass().getDeclaredField("databaseReader"), databaseReader); // when final Future<GeoInfo> future = maxMindGeoLocationService.lookup(TEST_IP, null); // then assertThat(future.succeeded()).isTrue(); assertThat(future.result()) .isEqualTo(GeoInfo.builder() .vendor("maxmind") .continent("eu") .country("fr") .region("paris") .city("Paris") .lat(48.8566f) .lon(2.3522f) .build()); } }
38.693878
114
0.67827
e0615a70c7c4d168127b15bdb2de197689ffc0d5
67
package com.mrh0.buildersaddition.blocks; public class Bench { }
11.166667
41
0.776119
14855655ff7d57bdc80b7ef40d5a06567d8a1dbc
1,075
package org.kuali.ole.docstore.model.rdbms.bo; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; import java.io.Serializable; /** * Created with IntelliJ IDEA. * User: mjagan * Date: 7/15/13 * Time: 10:26 PM * To change this template use File | Settings | File Templates. */ public class FormerIdentifierRecord extends PersistableBusinessObjectBase implements Serializable { private String formerId; private String value; private String type; private String itemId; public String getFormerId() { return formerId; } public void setFormerId(String formerId) { this.formerId = formerId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } }
19.907407
73
0.646512
2d97ed88ef21effa4bc137cf102a7dbeda59674b
7,639
package org.hisp.dhis.ivb.util; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet; public class CovidIntroSnapshot { //Input params private String isoCode; private String whoRegion; private String unicefRegion; private String incomeLevel; private String gaviEligibleStatus; private String showIndType; private String includeComment; private String nonZeroCountries=""; private String showCovaxFacility; private String showWBSupport; private String showSource; private OrganisationUnitGroupSet unicefRegionsGroupSet; private List<OrganisationUnit> selOrgUnits = new ArrayList<>(); private List<String> indTypes = new ArrayList<>(); private String ouIdsByComma = "-1"; private String indTypesByComma = ""; private Integer flagAttributeId = 0; private Integer indTypeAttributeId = 0; private Integer generalDeGroupId = 0; private OrganisationUnit selOrgUnit; //other params private String curDateStr; private String deIdsByComma = "-1"; private Map<String, List<Integer>> it_deIdMap = new HashMap<>(); private Map<Integer, GenericTypeObj> deMap = new HashMap<>(); private Map<String, GenericDataVO> dataMap = new HashMap<>(); private Set<Integer> nonZeroOrgUnitIds = new HashSet<>(); private Set<Integer> filterDeIds = new HashSet<>(); private List<String> anonymousOuNames = new ArrayList<>(); private Map<String, OrganisationUnit> anonymousOuMap = new HashMap<>(); private String lastUpdated; private String dsIdsByComma = "-1"; private List<DataSet> selDataSets = new ArrayList<DataSet>(); private Map<Integer, List<GenericTypeObj>> ds_deMap = new HashMap<Integer, List<GenericTypeObj>>(); //------------------------------------------------------------------- //Getters & Setters //------------------------------------------------------------------- public OrganisationUnitGroupSet getUnicefRegionsGroupSet() { return unicefRegionsGroupSet; } public List<String> getAnonymousOuNames() { return anonymousOuNames; } public void setAnonymousOuNames(List<String> anonymousOuNames) { this.anonymousOuNames = anonymousOuNames; } public Map<String, OrganisationUnit> getAnonymousOuMap() { return anonymousOuMap; } public void setAnonymousOuMap(Map<String, OrganisationUnit> anonymousOuMap) { this.anonymousOuMap = anonymousOuMap; } public OrganisationUnit getSelOrgUnit() { return selOrgUnit; } public void setSelOrgUnit(OrganisationUnit selOrgUnit) { this.selOrgUnit = selOrgUnit; } public void setUnicefRegionsGroupSet(OrganisationUnitGroupSet unicefRegionsGroupSet) { this.unicefRegionsGroupSet = unicefRegionsGroupSet; } public List<OrganisationUnit> getSelOrgUnits() { return selOrgUnits; } public void setSelOrgUnits(List<OrganisationUnit> selOrgUnits) { this.selOrgUnits = selOrgUnits; } public List<DataSet> getSelDataSets() { return selDataSets; } public void setSelDataSets(List<DataSet> selDataSets) { this.selDataSets = selDataSets; } public Map<Integer, List<GenericTypeObj>> getDs_deMap() { return ds_deMap; } public void setDs_deMap(Map<Integer, List<GenericTypeObj>> ds_deMap) { this.ds_deMap = ds_deMap; } public String getOuIdsByComma() { return ouIdsByComma; } public void setOuIdsByComma(String ouIdsByComma) { this.ouIdsByComma = ouIdsByComma; } public String getDsIdsByComma() { return dsIdsByComma; } public void setDsIdsByComma(String dsIdsByComma) { this.dsIdsByComma = dsIdsByComma; } public Integer getFlagAttributeId() { return flagAttributeId; } public void setFlagAttributeId(Integer flagAttributeId) { this.flagAttributeId = flagAttributeId; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } public String getWhoRegion() { return whoRegion; } public void setWhoRegion(String whoRegion) { this.whoRegion = whoRegion; } public String getUnicefRegion() { return unicefRegion; } public void setUnicefRegion(String unicefRegion) { this.unicefRegion = unicefRegion; } public String getIncomeLevel() { return incomeLevel; } public void setIncomeLevel(String incomeLevel) { this.incomeLevel = incomeLevel; } public String getGaviEligibleStatus() { return gaviEligibleStatus; } public void setGaviEligibleStatus(String gaviEligibleStatus) { this.gaviEligibleStatus = gaviEligibleStatus; } public String getShowIndType() { return showIndType; } public void setShowIndType(String showIndType) { this.showIndType = showIndType; } public String getIncludeComment() { return includeComment; } public void setIncludeComment(String includeComment) { this.includeComment = includeComment; } public String getNonZeroCountries() { return nonZeroCountries; } public void setNonZeroCountries(String nonZeroCountries) { this.nonZeroCountries = nonZeroCountries; } public List<String> getIndTypes() { return indTypes; } public void setIndTypes(List<String> indTypes) { this.indTypes = indTypes; } public String getIndTypesByComma() { return indTypesByComma; } public void setIndTypesByComma(String indTypesByComma) { this.indTypesByComma = indTypesByComma; } public Integer getIndTypeAttributeId() { return indTypeAttributeId; } public void setIndTypeAttributeId(Integer indTypeAttributeId) { this.indTypeAttributeId = indTypeAttributeId; } public Map<String, List<Integer>> getIt_deIdMap() { return it_deIdMap; } public void setIt_deIdMap(Map<String, List<Integer>> it_deIdMap) { this.it_deIdMap = it_deIdMap; } public Map<Integer, GenericTypeObj> getDeMap() { return deMap; } public void setDeMap(Map<Integer, GenericTypeObj> deMap) { this.deMap = deMap; } public Map<String, GenericDataVO> getDataMap() { return dataMap; } public void setDataMap(Map<String, GenericDataVO> dataMap) { this.dataMap = dataMap; } public String getDeIdsByComma() { return deIdsByComma; } public void setDeIdsByComma(String deIdsByComma) { this.deIdsByComma = deIdsByComma; } public Set<Integer> getNonZeroOrgUnitIds() { return nonZeroOrgUnitIds; } public void setNonZeroOrgUnitIds(Set<Integer> nonZeroOrgUnitIds) { this.nonZeroOrgUnitIds = nonZeroOrgUnitIds; } public Integer getGeneralDeGroupId() { return generalDeGroupId; } public void setGeneralDeGroupId(Integer generalDeGroupId) { this.generalDeGroupId = generalDeGroupId; } public String getLastUpdated() { return lastUpdated; } public void setLastUpdated(String lastUpdated) { this.lastUpdated = lastUpdated; } public Set<Integer> getFilterDeIds() { return filterDeIds; } public void setFilterDeIds(Set<Integer> filterDeIds) { this.filterDeIds = filterDeIds; } public String getShowCovaxFacility() { return showCovaxFacility; } public void setShowCovaxFacility(String showCovaxFacility) { this.showCovaxFacility = showCovaxFacility; } public String getShowWBSupport() { return showWBSupport; } public void setShowWBSupport(String showWBSupport) { this.showWBSupport = showWBSupport; } public String getShowSource() { return showSource; } public void setShowSource(String showSource) { this.showSource = showSource; } public String getCurDateStr() { return curDateStr; } public void setCurDateStr(String curDateStr) { this.curDateStr = curDateStr; } }
23.504615
100
0.746433
791d7f44847bac0e843c55c5a9968f6053df5605
3,043
/* * 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.commons.geometry.euclidean.threed; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.geometry.core.partitioning.BoundarySource; import org.apache.commons.geometry.euclidean.threed.line.LineConvexSubset3D; import org.apache.commons.geometry.euclidean.threed.line.LinecastPoint3D; import org.apache.commons.geometry.euclidean.threed.line.Linecastable3D; /** Extension of the {@link BoundarySource} interface for Euclidean 3D space. */ public interface BoundarySource3D extends BoundarySource<PlaneConvexSubset>, Linecastable3D { /** Return a BSP tree constructed from the boundaries contained in this instance. * The default implementation creates a new, empty tree and inserts the * boundaries from this instance. * @return a BSP tree constructed from the boundaries in this instance */ default RegionBSPTree3D toTree() { final RegionBSPTree3D tree = RegionBSPTree3D.empty(); tree.insert(this); return tree; } /** {@inheritDoc} */ @Override default List<LinecastPoint3D> linecast(final LineConvexSubset3D subset) { return new BoundarySourceLinecaster3D(this).linecast(subset); } /** {@inheritDoc} */ @Override default LinecastPoint3D linecastFirst(final LineConvexSubset3D subset) { return new BoundarySourceLinecaster3D(this).linecastFirst(subset); } /** Return a {@link BoundarySource3D} instance containing the given boundaries. * @param boundaries boundaries to include in the boundary source * @return a boundary source containing the given boundaries */ static BoundarySource3D from(final PlaneConvexSubset... boundaries) { return from(Arrays.asList(boundaries)); } /** Return a {@link BoundarySource3D} instance containing the given boundaries. The given * collection is used directly as the source of the boundaries; no copy is made. * @param boundaries boundaries to include in the boundary source * @return a boundary source containing the given boundaries */ static BoundarySource3D from(final Collection<PlaneConvexSubset> boundaries) { return boundaries::stream; } }
41.684932
93
0.74466
edef623aad7eafd8a96770c960854a30c2c959ce
863
class ArithMeticDemo { public static void main(String[] args) { int result = 1 + 2; // result is now 3 System.out.println("1 + 2 = " + result); int original_result = result; result = result - 1; // result is now 2 System.out.println(original_result + " - 1 = " + result); original_result = result; result = result * 2; // result is now 4 System.out.println(original_result + " * 2 = " + result); original_result = result; result = result / 2; // result is now 2 System.out.println(original_result + " / 2 = " + result); original_result = result; result = result + 8; // result is now 10 System.out.println(original_result + " + 8 = " + result); original_result = result; result = result % 7; // result is now 3 (10%7 = 3[remainder]) System.out.println(original_result + " % 7 = " + result); } }
25.382353
59
0.617613
d445e79adf39ae594e21081431ef24da3a1b5638
1,088
package com.rabc.fangkuai.entity; import com.yyfly.common.entity.BaseEntity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Table; /** * @创建人 lin * @创建时间 2020/1/20 * @描述 */ @Data @Entity @Table(name = "imms_resource") public class Resource extends BaseEntity { /** * serialVersionUID */ private static final long serialVersionUID = -4091125312802177946L; /** * 无 */ public static final String TYPE_NONE = "0"; /** * 菜单 */ public static final String TYPE_MENU = "1"; /** * 功能 */ public static final String TYPE_FUNCTION = "2"; /** * 资源名称 */ private String resourceName; /** * path */ private String path; /** * 资源类型 * <ul> * <li> 0 - 无</li> * <li> 1 - 菜单</li> * <li> 2 - 功能</li> * </ul> */ private String type; /** * 权限标识 */ private String permission; /** * 上级 */ private String pid; /** * 备注 */ private String remark; }
14.90411
71
0.519301
145d90d3b4f0d08489467b83d84671e120a221f0
3,875
/* * 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.seaborne.delta.server.local.filestore; import java.io.IOException ; import java.io.OutputStream; import java.nio.file.Files ; import java.nio.file.Path; import org.apache.jena.atlas.RuntimeIOException; import org.apache.jena.atlas.io.IO; import org.seaborne.delta.lib.IOX; import org.seaborne.delta.lib.IOX.IOConsumer; /** * Record of a file in a {@link FileStore}. * <p> * It provides the path to the file, a path to an associated temporary fileused to perform * atomic writes to the file. * <p> * {@code FileEntry} are "write once". * <p> * The write sequence is * <pre> * FileStore fileStore = ... * FileEntry entry = fileStore.allocateFilename(); * OutputStream out = entry.openForWrite(); * ... write contents ... * entry.completeWrite(); * </pre> */ public class FileEntry { public final long version; public final Path datafile; private final Path tmpfile; // Only for openForWrite / completeWrite private OutputStream out = null ; private boolean haveWritten = false; /*package*/ FileEntry(long index, Path datafile, Path tmpfile) { this.version = index; this.datafile = datafile; this.tmpfile = tmpfile; } /** Atomically write the file */ public void write(IOConsumer<OutputStream> action) { if ( haveWritten ) throw new RuntimeIOException("FileEntry has already been written: "+datafile); IOX.safeWrite(datafile, tmpfile, action); haveWritten = true; } /** * Initiate the write process. The {@code Outstream} returned is to a * temporary file (same filing system) that is moved into place in * {@link #completeWrite}, making the writing of the file atomic. * <p> * Note that {@code Outstream.close} is idempotent - it is safe for the application to * close the {@code Outstream}. */ public OutputStream openForWrite( ) { if ( haveWritten ) throw new RuntimeIOException("FileEntry has already been written: "+datafile); try { return out = Files.newOutputStream(tmpfile) ; } catch (IOException ex) { throw IOX.exception(ex); } } /** * Complete the write process: closes the OutputStream allocated by * {@link #openForWrite} thenn * * <p> * Note that {@code Outstream.close} is idempotent - it is safe * for the application to close the {@code Outstream}. * <p> * The application must flush any buffered output prior to calling {@code completeWrite}. */ public void completeWrite() { IO.close(out); IOX.move(tmpfile, datafile); haveWritten = true; out = null ; } public String getDatafileName() { return datafile.toString(); } @Override public String toString() { // Dirctory is quite long. return String.format("FileEntry[%d, %s, %s]", version, datafile.getFileName(), tmpfile.getFileName(), datafile.getParent()); } }
33.991228
98
0.659871
31e6203f78ae3a6fede716fe416395f5f0e6ee3d
1,920
/** * 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.apimanagement.v2019_12_01.implementation; import com.microsoft.azure.management.apimanagement.v2019_12_01.ResourceLocationDataContract; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.ProxyResource; /** * Gateway details. */ @JsonFlatten public class GatewayContractInner extends ProxyResource { /** * Gateway location. */ @JsonProperty(value = "properties.locationData") private ResourceLocationDataContract locationData; /** * Gateway description. */ @JsonProperty(value = "properties.description") private String description; /** * Get gateway location. * * @return the locationData value */ public ResourceLocationDataContract locationData() { return this.locationData; } /** * Set gateway location. * * @param locationData the locationData value to set * @return the GatewayContractInner object itself. */ public GatewayContractInner withLocationData(ResourceLocationDataContract locationData) { this.locationData = locationData; return this; } /** * Get gateway description. * * @return the description value */ public String description() { return this.description; } /** * Set gateway description. * * @param description the description value to set * @return the GatewayContractInner object itself. */ public GatewayContractInner withDescription(String description) { this.description = description; return this; } }
25.945946
93
0.691667
f76543ad491c2be04580b8ff85847b23902ba1ae
2,611
/** * Copyright 2013 Dennis Ippel * * 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.rajawali3d.curves; import org.rajawali3d.math.vector.Vector3; public class QuadraticBezierCurve3D implements ICurve3D { private static final double DELTA = .00001; private Vector3 mPoint1; private Vector3 mControlPoint; private Vector3 mPoint2; private Vector3 mTmpPoint1; private Vector3 mTmpPoint2; private Vector3 mTmpPoint3; private Vector3 mTempPointNext=new Vector3(); private boolean mCalculateTangents; private Vector3 mCurrentTangent; public QuadraticBezierCurve3D() { mCurrentTangent = new Vector3(); } public QuadraticBezierCurve3D(Vector3 point1, Vector3 controlPoint, Vector3 point2) { this(); mTmpPoint1 = new Vector3(); mTmpPoint2 = new Vector3(); mTmpPoint3 = new Vector3(); addPoint(point1, controlPoint, point2); } /** * Add a Curve * * @param point1 * The first point * @param controlPoint * The control point * @param point2 * The second point */ public void addPoint(Vector3 point1, Vector3 controlPoint, Vector3 point2) { mPoint1 = point1; mControlPoint = controlPoint; mPoint2 = point2; } public void calculatePoint(Vector3 result, double t) { if (mCalculateTangents) { double prevt = t == 0 ? t + DELTA : t - DELTA; double nextt = t == 1 ? t - DELTA : t + DELTA; p(mCurrentTangent, prevt); p(mTempPointNext, nextt); mCurrentTangent.subtract(mTempPointNext); mCurrentTangent.multiply(.5f); mCurrentTangent.normalize(); } p(result, t); } private void p(Vector3 result, double t) { mTmpPoint1.setAll(mPoint1); mTmpPoint1.multiply((1.0f - t) * (1.0f - t)); mTmpPoint2.setAll(mControlPoint); mTmpPoint2.multiply(2 * (1.0f - t) * t); mTmpPoint3.setAll(mPoint2); mTmpPoint3.multiply(t * t); mTmpPoint2.add(mTmpPoint3); result.addAndSet(mTmpPoint1, mTmpPoint2); } public Vector3 getCurrentTangent() { return mCurrentTangent; } public void setCalculateTangents(boolean calculateTangents) { this.mCalculateTangents = calculateTangents; } }
27.484211
118
0.720414
22c0b62abc66524fdfc176925c3678aa53eccb30
222
package main; //This exception is thrown to stop parsing or execution of a BotScript program public class StopException extends RuntimeException{ public StopException(String message) { super(message); } }
24.666667
78
0.747748
485147c4c3042213cb3d8d633614a471df27d49b
4,054
package club.javafan.blog.common.mail.impl; import club.javafan.blog.common.mail.MailService; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; /** * @author 敲代码的长腿毛欧巴 * @date 2020/1/30 * 邮件发送类 */ @Service("mailService") @EnableAsync public class MailServiceImpl implements MailService { /** * 用户名 */ @Value("${spring.mail.username}") private String from; /** * JavaMail邮件发送服务 */ @Autowired private JavaMailSender mailSender; @Override @Async("threadTaskExecutor") public void sendSimpleMail(String to, String subject, String content, String[] cc) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); message.setFrom("敲代码的长腿毛欧巴" + "<" + from + ">"); mailSender.send(message); } @Override @Async("threadTaskExecutor") public void sendHtmlMail(String to, String subject, String content, String[] cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); buildHelper(to, subject, content, message, cc); mailSender.send(message); } @Override @Async("threadTaskExecutor") public void sendAttachmentMail(String to, String subject, String content, String filePath, String[] cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = buildHelper(to, subject, content, message); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); //添加附件,可多次调用该方法添加多个附件 helper.addAttachment(fileName, file); mailSender.send(message); } @Override @Async("threadTaskExecutor") public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId, String[] cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = buildHelper(to, subject, content, message); FileSystemResource res = new FileSystemResource(new File(rscPath)); //重复使用添加多个图片 helper.addInline(rscId, res); mailSender.send(message); } /** * 构建MimeMessageHelper * * @param to 给谁发送 * @param subject 主题 * @param content 内容 * @param message MimeMessage * @param cc 抄送 * @return MimeMessageHelper * @throws MessagingException */ private MimeMessageHelper buildHelper(String to, String subject, String content, MimeMessage message, String[] cc) throws MessagingException { MimeMessageHelper helper = new MimeMessageHelper(message, true); message.setFrom("敲代码的长腿毛欧巴" + "<" + from + ">"); helper.setTo(to); if (ArrayUtils.isNotEmpty(cc)) { helper.setCc(cc); } helper.setSubject(subject); helper.setText(content, true); return helper; } /** * 构建MimeMessageHelper * * @param to 给谁发送 * @param subject 主题 * @param content 内容 * @param message MimeMessage * @return MimeMessageHelper * @throws MessagingException */ private MimeMessageHelper buildHelper(String to, String subject, String content, MimeMessage message) throws MessagingException { return buildHelper(to, subject, content, message,null); } }
33.783333
152
0.693143
5e9eb4245cd6c7b4c88e48a30a09e7d38e9f46cc
2,467
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.python.api.streaming.data; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class SingleElementPushBackIteratorTest { @Test public void testPushBackIterator() { Collection<Integer> init = new ArrayList<>(); init.add(1); init.add(2); init.add(4); init.add(5); SingleElementPushBackIterator<Integer> iterator = new SingleElementPushBackIterator<>(init.iterator()); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(1, (int) iterator.next()); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(2, (int) iterator.next()); Assert.assertTrue(iterator.hasNext()); iterator.pushBack(3); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(3, (int) iterator.next()); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(4, (int) iterator.next()); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(5, (int) iterator.next()); Assert.assertFalse(iterator.hasNext()); iterator.pushBack(6); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(6, (int) iterator.next()); Assert.assertFalse(iterator.hasNext()); } @Test public void testSingleElementLimitation() { Collection<Integer> init = Collections.emptyList(); SingleElementPushBackIterator<Integer> iterator = new SingleElementPushBackIterator<>(init.iterator()); Assert.assertFalse(iterator.hasNext()); iterator.pushBack(1); try { iterator.pushBack(2); Assert.fail("Multiple elements could be pushed back."); } catch (IllegalStateException ignored) { // expected } } }
32.038961
105
0.743008
778a533fc334f6a32eca43043e53cae279b0bd15
3,629
package jenkins.plugins.docker_compose; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import java.io.IOException; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jenkins.tasks.SimpleBuildStep; import net.sf.json.JSONObject; /** * Docker Compose Builder * * @author <a href="mailto:[email protected]">João Galego</a> */ public class DockerComposeBuilder extends Builder implements SimpleBuildStep { // Logger private static final Logger LOGGER = LoggerFactory.getLogger(DockerComposeBuilder.class); // Constants private static final String DISPLAY_NAME = "Docker Compose Build Step"; private static final String EMPTY_FIELD_MESSAGE = "This field should not be empty"; // Form parameters public final boolean useCustomDockerComposeFile; public final String dockerComposeFile; private DockerComposeCommandOption option; @DataBoundConstructor public DockerComposeBuilder(boolean useCustomDockerComposeFile, String dockerComposeFile, DockerComposeCommandOption option) { this.useCustomDockerComposeFile = useCustomDockerComposeFile; this.dockerComposeFile = dockerComposeFile; this.option = option; } public boolean getUseCustomDockerComposeFile() { return useCustomDockerComposeFile; } public String getDockerComposeFile() { return dockerComposeFile; } public DockerComposeCommandOption getOption() { return option; } @Override public void perform(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { try{ LOGGER.info("Executing Docker Compose build step"); int exitCode = option.execute(build, workspace, launcher, listener, this); LOGGER.info("Exit code: {}", exitCode); if (exitCode == 0) { build.setResult(Result.SUCCESS); } else { build.setResult(Result.FAILURE); } } catch (DockerComposeCommandException ex) { LOGGER.error("Docker Compose build step failed to execute", ex); ex.printStackTrace(); build.setResult(Result.FAILURE); } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public DescriptorImpl() { load(); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { // Indicates that this builder can be used with all kinds of project types return true; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // Can also use req.bindJSON(this, formData) save(); return super.configure(req, formData); } @Override public String getDisplayName() { return DISPLAY_NAME; } public static DescriptorExtensionList<DockerComposeCommandOption, DockerComposeCommandOptionDescriptor> getOptionList() { return DockerComposeCommandOptionDescriptor.all(); } public FormValidation doCheckDockerComposeFile(@QueryParameter String value) { if(value.isEmpty()) { return FormValidation.error(EMPTY_FIELD_MESSAGE); } return FormValidation.ok(); } } }
25.921429
127
0.759713
e7de4b6894999abf7aacc0593bcf26183d186f17
6,310
package com.rbkmoney.threeds.server.service.testplatform; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.rbkmoney.threeds.server.domain.cardrange.ActionInd; import com.rbkmoney.threeds.server.domain.cardrange.CardRange; import com.rbkmoney.threeds.server.domain.root.emvco.PReq; import com.rbkmoney.threeds.server.domain.root.emvco.PRes; import com.rbkmoney.threeds.server.serialization.EnumWrapper; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static com.rbkmoney.threeds.server.domain.cardrange.ActionInd.ADD_CARD_RANGE_TO_CACHE; import static com.rbkmoney.threeds.server.domain.cardrange.ActionInd.DELETE_CARD_RANGE_FROM_CACHE; import static com.rbkmoney.threeds.server.domain.cardrange.ActionInd.MODIFY_CARD_RANGE_DATA; import static com.rbkmoney.threeds.server.utils.Collections.safeList; import static com.rbkmoney.threeds.server.utils.Wrappers.getValue; import static java.lang.Long.parseLong; public class TestPlatformCardRangesStorageService { private final Cache<String, Set<CardRange>> cardRangesById; public TestPlatformCardRangesStorageService() { this.cardRangesById = Caffeine.newBuilder() .maximumSize(1000) .build(); } public void updateCardRanges(PRes pRes) { String ulTestCaseId = pRes.getUlTestCaseId(); List<CardRange> cardRanges = cardRanges(pRes); if (!cardRanges.isEmpty()) { boolean isNeedStorageClear = isNeedStorageClear(pRes); Set<CardRange> storageCardRanges = getStorageCardRanges(ulTestCaseId); if (isNeedStorageClear) { storageCardRanges.clear(); } else { cardRanges.stream() .filter(cardRange -> getValue(cardRange.getActionInd()) == DELETE_CARD_RANGE_FROM_CACHE) .forEach(storageCardRanges::remove); } cardRanges.stream() .filter(cardRange -> getValue(cardRange.getActionInd()) == ADD_CARD_RANGE_TO_CACHE || getValue(cardRange.getActionInd()) == MODIFY_CARD_RANGE_DATA) .forEach(storageCardRanges::add); } } public boolean isValidCardRanges(PRes pRes) { String ulTestCaseId = pRes.getUlTestCaseId(); List<CardRange> cardRanges = cardRanges(pRes); boolean isNeedStorageClear = isNeedStorageClear(pRes); Set<CardRange> storageCardRanges = getStorageCardRanges(ulTestCaseId); if (!cardRanges.isEmpty() && !isNeedStorageClear && !storageCardRanges.isEmpty()) { return cardRanges.stream() .allMatch(cardRange -> isValidCardRange(storageCardRanges, cardRange)); } else { return true; } } public boolean isInCardRange(String ulTestCaseId, String acctNumber) { Set<CardRange> storageCardRanges = getStorageCardRanges(ulTestCaseId); if (storageCardRanges.isEmpty()) { return true; } return isInCardRange(storageCardRanges, parseLong(acctNumber)); } private boolean isInCardRange(Set<CardRange> storageCardRanges, Long acctNumber) { return storageCardRanges.stream() .anyMatch( cardRange -> parseLong(cardRange.getStartRange()) <= acctNumber && acctNumber <= parseLong(cardRange.getEndRange())); } private Set<CardRange> getStorageCardRanges(String ulTestCaseId) { Set<CardRange> cardRanges = cardRangesById.getIfPresent(ulTestCaseId); if (cardRanges == null) { cardRanges = new HashSet<>(); cardRangesById.put(ulTestCaseId, cardRanges); } return cardRanges; } private boolean isValidCardRange(Set<CardRange> storageCardRanges, CardRange cardRange) { long startRange = parseLong(cardRange.getStartRange()); long endRange = parseLong(cardRange.getEndRange()); ActionInd actionInd = getValue(cardRange.getActionInd()); switch (actionInd) { case ADD_CARD_RANGE_TO_CACHE: if (existsCardRange(storageCardRanges, startRange, endRange)) { return true; } return existsFreeSpaceForNewCardRange(storageCardRanges, startRange, endRange); case MODIFY_CARD_RANGE_DATA: case DELETE_CARD_RANGE_FROM_CACHE: return existsCardRange(storageCardRanges, startRange, endRange); default: throw new IllegalArgumentException( String.format("Action Indicator missing in Card Range Data, cardRange=%s", cardRange)); } } private boolean existsFreeSpaceForNewCardRange(Set<CardRange> storageCardRanges, long startRange, long endRange) { return storageCardRanges.stream() .allMatch( cardRange -> endRange < parseLong(cardRange.getStartRange()) || parseLong(cardRange.getEndRange()) < startRange); } private boolean existsCardRange(Set<CardRange> storageCardRanges, long startRange, long endRange) { return storageCardRanges.stream() .anyMatch( cardRange -> parseLong(cardRange.getStartRange()) == startRange && parseLong(cardRange.getEndRange()) == endRange); } private List<CardRange> cardRanges(PRes pRes) { return safeList(pRes.getCardRangeData()).stream() .peek(this::fillEmptyActionInd) .collect(Collectors.toList()); } private boolean isNeedStorageClear(PRes pRes) { return Optional.ofNullable((pRes.getRequestMessage())) .map(message -> (PReq) message) .map(PReq::getSerialNum) .isEmpty(); } private void fillEmptyActionInd(CardRange cardRange) { if (cardRange.getActionInd() == null) { EnumWrapper<ActionInd> addAction = new EnumWrapper<>(); addAction.setValue(ADD_CARD_RANGE_TO_CACHE); cardRange.setActionInd(addAction); } } }
40.709677
118
0.655309
cc4e7e043245f244d032588fcc7e6b00e4da6dee
1,402
package com.optimaize.webcrawlerverifier; /** * Result returned by the {@link KnownCrawlerDetector#detect} method. */ public class KnownCrawlerResult { private final String identifier; private final KnownCrawlerResultStatus status; public KnownCrawlerResult(String identifier, KnownCrawlerResultStatus status) { this.identifier = identifier; this.status = status; } /** * @see com.optimaize.webcrawlerverifier.bots.CrawlerData#getIdentifier() */ public String getIdentifier() { return identifier; } /** */ public KnownCrawlerResultStatus getStatus() { return status; } @Override public String toString() { return "KnownCrawlerResult{" + "identifier='" + identifier + '\'' + ", status=" + status + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; KnownCrawlerResult result = (KnownCrawlerResult) o; if (status != result.status) return false; if (!identifier.equals(result.identifier)) return false; return true; } @Override public int hashCode() { int result = identifier.hashCode(); result = 31 * result + status.hashCode(); return result; } }
22.612903
83
0.60271
141dba3839364c3d02a452018050c55ebabb0a76
11,463
/* * Copyright 2018 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.tools.jib.gradle; import com.google.cloud.tools.jib.api.JavaContainerBuilder; import com.google.cloud.tools.jib.api.JibContainerBuilder; import com.google.cloud.tools.jib.api.RegistryImage; import com.google.cloud.tools.jib.event.EventHandlers; import com.google.cloud.tools.jib.event.JibEventType; import com.google.cloud.tools.jib.event.events.LogEvent; import com.google.cloud.tools.jib.event.progress.ProgressEventHandler; import com.google.cloud.tools.jib.filesystem.AbsoluteUnixPath; import com.google.cloud.tools.jib.filesystem.DirectoryWalker; import com.google.cloud.tools.jib.plugins.common.JavaContainerBuilderHelper; import com.google.cloud.tools.jib.plugins.common.ProjectProperties; import com.google.cloud.tools.jib.plugins.common.PropertyNames; import com.google.cloud.tools.jib.plugins.common.TimerEventHandler; import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLoggerBuilder; import com.google.cloud.tools.jib.plugins.common.logging.ProgressDisplayGenerator; import com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor; import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.tools.ant.taskdefs.condition.Os; import org.gradle.api.GradleException; import org.gradle.api.JavaVersion; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.file.FileCollection; import org.gradle.api.logging.Logger; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.SourceSet; import org.gradle.jvm.tasks.Jar; /** Obtains information about a Gradle {@link Project} that uses Jib. */ class GradleProjectProperties implements ProjectProperties { /** Used to generate the User-Agent header and history metadata. */ private static final String TOOL_NAME = "jib-gradle-plugin"; /** Used for logging during main class inference. */ private static final String PLUGIN_NAME = "jib"; /** Used for logging during main class inference. */ private static final String JAR_PLUGIN_NAME = "'jar' task"; /** Name of the `main` {@link SourceSet} to use as source files. */ private static final String MAIN_SOURCE_SET_NAME = "main"; /** @return a GradleProjectProperties from the given project and logger. */ static GradleProjectProperties getForProject( Project project, Logger logger, AbsoluteUnixPath appRoot) { return new GradleProjectProperties(project, logger, appRoot); } static Path getExplodedWarDirectory(Project project) { return project.getBuildDir().toPath().resolve(ProjectProperties.EXPLODED_WAR_DIRECTORY_NAME); } private static EventHandlers makeEventHandlers( Project project, Logger logger, SingleThreadedExecutor singleThreadedExecutor) { ConsoleLoggerBuilder consoleLoggerBuilder = (isProgressFooterEnabled(project) ? ConsoleLoggerBuilder.rich(singleThreadedExecutor) : ConsoleLoggerBuilder.plain(singleThreadedExecutor).progress(logger::lifecycle)) .lifecycle(logger::lifecycle); if (logger.isDebugEnabled()) { consoleLoggerBuilder.debug(logger::debug); } if (logger.isInfoEnabled()) { consoleLoggerBuilder.info(logger::info); } if (logger.isWarnEnabled()) { consoleLoggerBuilder.warn(logger::warn); } if (logger.isErrorEnabled()) { consoleLoggerBuilder.error(logger::error); } ConsoleLogger consoleLogger = consoleLoggerBuilder.build(); return new EventHandlers() .add( JibEventType.LOGGING, logEvent -> consoleLogger.log(logEvent.getLevel(), logEvent.getMessage())) .add( JibEventType.TIMING, new TimerEventHandler(message -> consoleLogger.log(LogEvent.Level.DEBUG, message))) .add( JibEventType.PROGRESS, new ProgressEventHandler( update -> { List<String> footer = ProgressDisplayGenerator.generateProgressDisplay( update.getProgress(), update.getUnfinishedAllocations()); footer.add(""); consoleLogger.setFooter(footer); })); } private static boolean isProgressFooterEnabled(Project project) { if ("plain".equals(System.getProperty(PropertyNames.CONSOLE))) { return false; } switch (project.getGradle().getStartParameter().getConsoleOutput()) { case Plain: return false; case Auto: // Enables progress footer when ANSI is supported (Windows or TERM not 'dumb'). return Os.isFamily(Os.FAMILY_WINDOWS) || !"dumb".equals(System.getenv("TERM")); default: return true; } } private final Project project; private final SingleThreadedExecutor singleThreadedExecutor = new SingleThreadedExecutor(); private final EventHandlers eventHandlers; private final Logger logger; private final AbsoluteUnixPath appRoot; @VisibleForTesting GradleProjectProperties(Project project, Logger logger, AbsoluteUnixPath appRoot) { this.project = project; this.logger = logger; this.appRoot = appRoot; eventHandlers = makeEventHandlers(project, logger, singleThreadedExecutor); } @Override public JibContainerBuilder createContainerBuilder(RegistryImage baseImage) { try { if (isWarProject()) { logger.info("WAR project identified, creating WAR image: " + project.getDisplayName()); Path explodedWarPath = GradleProjectProperties.getExplodedWarDirectory(project); return JavaContainerBuilderHelper.fromExplodedWar(baseImage, explodedWarPath, appRoot); } JavaPluginConvention javaPluginConvention = project.getConvention().getPlugin(JavaPluginConvention.class); SourceSet mainSourceSet = javaPluginConvention.getSourceSets().getByName(MAIN_SOURCE_SET_NAME); FileCollection classesOutputDirectories = mainSourceSet.getOutput().getClassesDirs().filter(File::exists); Path resourcesOutputDirectory = mainSourceSet.getOutput().getResourcesDir().toPath(); FileCollection allFiles = mainSourceSet.getRuntimeClasspath(); FileCollection dependencyFiles = allFiles .minus(classesOutputDirectories) .filter(file -> !file.toPath().equals(resourcesOutputDirectory)); JavaContainerBuilder javaContainerBuilder = JavaContainerBuilder.from(baseImage).setAppRoot(appRoot); // Adds resource files if (Files.exists(resourcesOutputDirectory)) { javaContainerBuilder.addResources(resourcesOutputDirectory); } // Adds class files for (File classesOutputDirectory : classesOutputDirectories) { javaContainerBuilder.addClasses(classesOutputDirectory.toPath()); } if (classesOutputDirectories.isEmpty()) { logger.warn("No classes files were found - did you compile your project?"); } // Adds dependency files javaContainerBuilder.addDependencies( dependencyFiles .getFiles() .stream() .filter(File::exists) .map(File::toPath) .collect(Collectors.toList())); return javaContainerBuilder.toContainerBuilder(); } catch (IOException ex) { throw new GradleException("Obtaining project build output files failed", ex); } } @Override public List<Path> getClassFiles() throws IOException { // TODO: Consolidate with createContainerBuilder JavaPluginConvention javaPluginConvention = project.getConvention().getPlugin(JavaPluginConvention.class); SourceSet mainSourceSet = javaPluginConvention.getSourceSets().getByName(MAIN_SOURCE_SET_NAME); FileCollection classesOutputDirectories = mainSourceSet.getOutput().getClassesDirs().filter(File::exists); List<Path> classFiles = new ArrayList<>(); for (File classesOutputDirectory : classesOutputDirectories) { classFiles.addAll(new DirectoryWalker(classesOutputDirectory.toPath()).walk().asList()); } return classFiles; } @Override public void waitForLoggingThread() { singleThreadedExecutor.shutDownAndAwaitTermination(); } @Override public EventHandlers getEventHandlers() { return eventHandlers; } @Override public String getToolName() { return TOOL_NAME; } @Override public String getPluginName() { return PLUGIN_NAME; } @Nullable @Override public String getMainClassFromJar() { List<Task> jarTasks = new ArrayList<>(project.getTasksByName("jar", false)); if (jarTasks.size() != 1) { return null; } return (String) ((Jar) jarTasks.get(0)).getManifest().getAttributes().get("Main-Class"); } @Override public Path getDefaultCacheDirectory() { return project.getBuildDir().toPath().resolve(CACHE_DIRECTORY_NAME); } @Override public String getJarPluginName() { return JAR_PLUGIN_NAME; } @Override public boolean isWarProject() { return TaskCommon.isWarProject(project); } /** * Returns the input files for a task. * * @param extraDirectory the image's configured extra directory * @param project the gradle project * @return the input files to the task are all the output files for all the dependencies of the * {@code classes} task */ static FileCollection getInputFiles(File extraDirectory, Project project) { Task classesTask = project.getTasks().getByPath("classes"); Set<? extends Task> classesDependencies = classesTask.getTaskDependencies().getDependencies(classesTask); List<FileCollection> dependencyFileCollections = new ArrayList<>(); for (Task task : classesDependencies) { dependencyFileCollections.add(task.getOutputs().getFiles()); } if (Files.exists(extraDirectory.toPath())) { return project.files(dependencyFileCollections, extraDirectory); } else { return project.files(dependencyFileCollections); } } @Override public String getName() { return project.getName(); } @Override public String getVersion() { return project.getVersion().toString(); } @Override public int getMajorJavaVersion() { JavaVersion version = JavaVersion.current(); JavaPluginConvention javaPluginConvention = project.getConvention().findPlugin(JavaPluginConvention.class); if (javaPluginConvention != null) { version = javaPluginConvention.getTargetCompatibility(); } return Integer.valueOf(version.getMajorVersion()); } }
36.390476
99
0.721626
357b69f19032ef3591c9a1b897e312698ac54843
481
package io.github.tomszilagyi.svhu1972; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class TextPosition { public int page; public int line; public TextPosition() { this.page = 0; this.line = 0; } public TextPosition(int page, int line) { this.page = page; this.line = line; } public String toString() { return "tp["+this.page+":"+this.line+"]"; } }
19.24
49
0.617464
f74dbb38b7bc845aca87614ce6a92708179f5ac6
2,547
/* * Copyright 2014-2017 See AUTHORS file. * * 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.kotcrab.vis.editor.module.scene.system.inflater; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.kotcrab.vis.editor.Log; import com.kotcrab.vis.editor.module.project.FileAccessModule; import com.kotcrab.vis.editor.module.scene.AssetsLoadingMonitorModule; import com.kotcrab.vis.editor.util.gdx.DummyMusic; import com.kotcrab.vis.runtime.assets.MusicAsset; import com.kotcrab.vis.runtime.assets.VisAssetDescriptor; import com.kotcrab.vis.runtime.component.AssetReference; import com.kotcrab.vis.runtime.component.VisMusic; import com.kotcrab.vis.runtime.component.proto.ProtoVisMusic; import com.kotcrab.vis.runtime.system.inflater.InflaterSystem; /** @author Kotcrab */ public class EditorMusicInflater extends InflaterSystem { private FileAccessModule fileAccessModule; private AssetsLoadingMonitorModule loadingMonitor; private ComponentMapper<AssetReference> assetCm; private ComponentMapper<VisMusic> musicCm; private ComponentMapper<ProtoVisMusic> protoCm; public EditorMusicInflater () { super(Aspect.all(ProtoVisMusic.class, AssetReference.class)); } @Override protected void inserted (int entityId) { ProtoVisMusic protoVisMusic = protoCm.get(entityId); VisAssetDescriptor assetDescriptor = assetCm.get(entityId).asset; if (assetDescriptor instanceof MusicAsset) { String path = ((MusicAsset) assetDescriptor).getPath(); boolean exists = fileAccessModule.getAssetsFolder().child(path).exists(); if (exists == false) { String errorMsg = "Music file does not exist: " + path; Log.fatal(errorMsg); loadingMonitor.addFailedResource(assetDescriptor, new IllegalStateException(errorMsg)); } } else { throw new IllegalStateException("Unsupported asset descriptor for music inflater: " + assetDescriptor); } VisMusic music = musicCm.create(entityId); music.music = new DummyMusic(); protoVisMusic.fill(music); protoCm.remove(entityId); } }
36.385714
106
0.781311
2fb228ee9dbd99d63b019aa9f849a0e6cb8442a7
1,635
/* * Copyright 2010 BigData.mx * * 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 mx.bigdata.sat.cfd.examples; import java.io.FileInputStream; import java.security.PrivateKey; import java.security.cert.X509Certificate; import mx.bigdata.sat.cfd.CFDv2; import mx.bigdata.sat.cfd.schema.Comprobante; import mx.bigdata.sat.security.KeyLoaderEnumeration; import mx.bigdata.sat.security.factory.KeyLoaderFactory; public final class Main { public static void main(String[] args) throws Exception { CFDv2 cfd = new CFDv2(ExampleCFDFactory.createComprobante()); PrivateKey key = KeyLoaderFactory.createInstance( KeyLoaderEnumeration.PRIVATE_KEY_LOADER, new FileInputStream(args[0]), args[1] ).getKey(); X509Certificate cert = KeyLoaderFactory.createInstance( KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new FileInputStream(args[2]) ).getKey(); Comprobante sellado = cfd.sellarComprobante(key, cert); System.err.println(sellado.getSello()); cfd.validar(); cfd.verificar(); cfd.guardar(System.out); } }
32.058824
76
0.722324
21a0ba61e0868216d858a2e63eebd62247b26518
2,071
package com.kisslang.source.library.value.built_in.bool; import com.kisslang.source.library.Value; /* * Copyright (C) 2019 The KISSlang Project by Vitalii Vorobii * * 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. * */ public class LogicalValue implements Value { private final boolean value; public LogicalValue ( boolean value ) { this.value = value; } @Override public double asNumber () { if ( value == true ) { return 1; } return 0; } @Override public boolean asBoolean () { return value; } public static boolean toBoolean ( final String term ) { if ( term.equals ( "True" ) ) { return true; } else if ( term.equals ( "False" ) ) { return false; } throw new RuntimeException ( "Cannot cast " + term + " to Boolean..." ); } public String representBooleanAsString ( boolean value ) { //Python style return Boolean.toString ( value ).replaceFirst ( Character.toString ( Boolean.toString ( value ).charAt ( 0 ) ) , Character.toString ( Character.toUpperCase ( Boolean.toString ( value ).charAt ( 0 ) ) ) ); } @Override public String asString () { return representBooleanAsString ( value ); } @Override public boolean canBeRepresentedAsNumber () { return true; } @Override public String toString () { return asString ( ); } @Override public boolean isString () { return false; } }
26.551282
213
0.627716
b0f4ea61cf3cca6a54557c5f0b3758b832696a48
3,125
package lee.study.down.update; import java.util.Collections; import lee.study.down.boot.AbstractHttpDownBootstrap; import lee.study.down.boot.HttpDownBootstrapFactory; import lee.study.down.constant.HttpDownConstant; import lee.study.down.dispatch.HttpDownCallback; import lee.study.down.model.HttpDownInfo; import lee.study.down.model.HttpRequestInfo; import lee.study.down.model.TaskInfo; import lee.study.down.model.UpdateInfo; import lee.study.down.util.FileUtil; import lee.study.down.util.HttpDownUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class GithubUpdateService implements UpdateService { @Override public UpdateInfo check(float currVersion) throws Exception { UpdateInfo updateInfo = new UpdateInfo(); Document document = Jsoup.connect("https://github.com/monkeyWie/proxyee-down/releases").get(); Elements versions = document.select("h1.release-title.text-normal"); Collections.sort(versions, (v1, v2) -> { float version1 = Float.parseFloat(v1.text()); float version2 = Float.parseFloat(v2.text()); return version1 < version2 ? 1 : -1; }); float maxVersion = Float.parseFloat(versions.get(0).text()); if (maxVersion > currVersion) { updateInfo.setVersion(maxVersion); updateInfo.setVersionStr(versions.get(0).text()); Element releaseDiv = versions.get(0).parent().parent(); for (Element element : releaseDiv.select(".d-block.py-2")) { if (element.select("strong").text().indexOf("-jar.zip") != -1) { updateInfo.setUrl("https://github.com" + element.select("a").attr("href")); break; } } if (updateInfo.getUrl() == null) { return null; } updateInfo.setDesc(releaseDiv.select(".markdown-body").html()); return updateInfo; } return null; } @Override public AbstractHttpDownBootstrap update(UpdateInfo updateInfo, HttpDownCallback callback) throws Exception { HttpRequestInfo requestInfo = HttpDownUtil.buildGetRequest(updateInfo.getUrl()); TaskInfo taskInfo = HttpDownUtil .getTaskInfo(requestInfo, null, null, HttpDownConstant.clientSslContext, HttpDownConstant.clientLoopGroup) .setConnections(64) .setFileName("proxyee-down-jar.zip") .setFilePath( HttpDownConstant.HOME_PATH.substring(0, HttpDownConstant.HOME_PATH.length() - 1)); HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, requestInfo, null); AbstractHttpDownBootstrap bootstrap = HttpDownBootstrapFactory.create(httpDownInfo, 5, HttpDownConstant.clientSslContext, HttpDownConstant.clientLoopGroup, callback); FileUtil.deleteIfExists(bootstrap.getHttpDownInfo().getTaskInfo().buildTaskFilePath()); bootstrap.startDown(); return bootstrap; } public static void main(String[] args) throws Exception { GithubUpdateService githubUpdateService = new GithubUpdateService(); UpdateInfo updateInfo = githubUpdateService.check(1.0F); githubUpdateService.update(updateInfo, null); } }
41.118421
98
0.72576
d51281e3dec693fdd0008b11be564e7f9b289f2c
9,252
package com.tiantian.sams.controller; import com.tiantian.sams.model.Dormitory; import com.tiantian.sams.model.DormitoryChange; import com.tiantian.sams.model.DormitoryCheckInAndOut; import com.tiantian.sams.model.Student; import com.tiantian.sams.service.DormitoryService; import com.tiantian.sams.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Date; import java.util.List; @Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @Autowired private DormitoryService dormitoryService; private Student stu; private Dormitory dor; @GetMapping("/findAll") public String findAll(Model model){ //List<Student> students = studentService.findAll(); List<Student> studentsView = dormitoryService.findAllView(); //model.addAttribute("students",students); model.addAttribute("studentsView",studentsView); return "quireStudentAll"; } @GetMapping("findByStudentId") public String findByStudentId(String studentId, String quireType, Model model){ Student student = studentService.findByStudentId(studentId); stu = student; dor = dormitoryService.findByDorId(stu.getDormitoryId()); student.setDepartmentId(dormitoryService.findViewByStudentId(studentId).getDepartmentId()); model.addAttribute("student",student); if(quireType.equals("checkIn")) { return "updateStudentCheckIn"; }else if(quireType.equals("checkOut")) { return "updateStudentCheckOut"; }else if(quireType.equals("change")) { return "updateStudentChange"; }else if(quireType.equals("bysCheckOut")) { return "updateBYSStudentCheckOut"; }else { return "page-404"; } } @GetMapping("/findByDepartmentId") public String findByDepartmentId(Integer departmentId, Model model) { List<Student> studentsView = studentService.findViewByDepartmentId(departmentId); model.addAttribute("studentsView",studentsView); return "quireStudentByDepartmentId"; } @GetMapping("/findByCollege") public String findByCollege(String college, Model model) { List<Student> studentsView = studentService.findByCollege(college); model.addAttribute("studentsView",studentsView); return "quireStudentByCollege"; } @GetMapping("/findByStudentClass") public String findByStudentClass(String studentClass, Model model) { List<Student> studentsView = studentService.findByStudentClass(studentClass); model.addAttribute("studentsView",studentsView); return "quireStudentByStudentClass"; } private void fun_updateInAndOut(Student student, DormitoryCheckInAndOut check) { check.setDepartmentId(student.getDepartmentId()); check.setDormitoryId(student.getDormitoryId()); check.setBedNumber(student.getBedNumber()); check.setRecordTime(new Date()); check.setInAndOutDate(new Date()); dormitoryService.dormitoryCheckInAndOut(check); studentService.update(student); } @GetMapping("/updateInAndOut") public String updateInAndOut(String studentId, DormitoryCheckInAndOut check, String operateType, Model model){ Student student = studentService.findByStudentId(studentId); //更新dormitoryCheckInAndOut if (operateType.equals("checkIn") && student.getBedStatus()!=1) { check.setOperateName("入住"); student.setBedStatus(1); fun_updateInAndOut(student, check); System.out.println("入住成功!"); model.addAttribute("message","入住成功!"); return "updateStudentCheckInQuire"; }else if (operateType.equals("checkOut") && student.getBedStatus()!=0) { check.setOperateName("退宿"); student.setBedStatus(0); fun_updateInAndOut(student, check); System.out.println("退宿成功!"); model.addAttribute("message","退宿成功!"); return "updateStudentCheckOutQuire"; }else if (operateType.equals("bysCheckOut") && student.getBedStatus()!=0) { check.setOperateName("退宿"); student.setBedStatus(0); student.setStuStatus(0); fun_updateInAndOut(student, check); System.out.println("退宿成功!"); model.addAttribute("message","退宿成功!"); return "updateBYSStudentCheckOutQuire"; } System.out.println("操作失败,不可重复操作!"); model.addAttribute("message","操作失败,不可重复操作!"); return "updateStudentCheckInQuire"; } @PostMapping("/updateChange") public String updateChange(Student student, DormitoryChange change, Model model) { switch (student.getBedNumber()) { case 1: if (dormitoryService.findBed1ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,调宿失败!"); System.out.println("当前床位有人,调宿失败!"); } return "updateStudentChangeQuire"; case 2: if (dormitoryService.findBed2ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,调宿失败!"); System.out.println("当前床位有人,调宿失败!"); } return "updateStudentChangeQuire"; case 3: if (dormitoryService.findBed3ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,调宿失败!"); System.out.println("当前床位有人,调宿失败!"); } return "updateStudentChangeQuire"; case 4: if (dormitoryService.findBed4ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,调宿失败!"); System.out.println("当前床位有人,调宿失败!"); } return "updateStudentChangeQuire"; } //更新dormitoryChange if (student.getDepartmentId()!=stu.getDepartmentId() || student.getDormitoryId()!=stu.getDormitoryId() || student.getBedNumber()!=stu.getBedNumber()) { switch (stu.getBedNumber()) { case 1:dor.setBedStatus1(0);break; case 2:dor.setBedStatus2(0);break; case 3:dor.setBedStatus3(0);break; case 4:dor.setBedStatus4(0);break; } dormitoryService.dormitoryUpdate(dor); change.setChangeDate(new Date()); change.setRecordTime(new Date()); dormitoryService.dormitoryChange(change); studentService.update(student); } model.addAttribute("message","调宿成功!"); return "updateStudentChangeQuire"; } @PostMapping("/addStudent") public String addStudent(Student student, DormitoryCheckInAndOut check, Model model) { Student studentDB = studentService.findByStudentId(student.getStudentId()); if(studentDB!=null) { model.addAttribute("message","学号已被占用!"); return "addStudent"; } switch (student.getBedNumber()) { case 1: if (dormitoryService.findBed1ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,入住失败!"); System.out.println("当前床位有人,入住失败!"); return "addStudent"; } break; case 2: if (dormitoryService.findBed2ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,入住失败!"); System.out.println("当前床位有人,入住失败!"); return "addStudent"; } break; case 3: if (dormitoryService.findBed3ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,入住失败!"); System.out.println("当前床位有人,入住失败!"); return "addStudent"; } break; case 4: if (dormitoryService.findBed4ByDormitoryId(student.getDormitoryId())==1){ model.addAttribute("message","当前床位有人,入住失败!"); System.out.println("当前床位有人,入住失败!"); return "addStudent"; } break; } student.setRecordTime(new Date()); studentService.addStudent(student); check.setOperateName("入住"); check.setDormitoryId(student.getDormitoryId()); check.setRecordTime(new Date()); check.setInAndOutDate(new Date()); dormitoryService.dormitoryCheckInAndOut(check); return "addStudent"; } @GetMapping("/toAddStudent") public String toAddStudent(){ return "/addStudent"; } @GetMapping("/toDormitoryExchange") public String toDormitoryExchange(){ return "updateStudentExchange"; } }
42.054545
159
0.633593
1a4514d2850234fec8d0430eb3ecc07871038898
805
package abstractfactory.human; import java.util.Locale; import adapter.address.Address; public class People { private Locale local; private int id; protected static int idCount; protected int type; private Address address; public People(String local){ this.local = new Locale(local); this.id = getIdCount()+1; incrementId(); } public static synchronized int getIdCount() { return idCount; } public static synchronized void incrementId() { idCount++ ; } public void setLocal(Locale local) { this.local = local; } public Locale getLocal() { return local; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setAddress(Address address) { this.address = address; } public Address getAddress() { return address; } }
16.428571
48
0.701863
7db8905bea0855f2bf83f7c3e1b0dfa21c69a766
1,417
package com.microsoft.bingads.v11.api.test.entities.ad_extension.site_link.write; import com.microsoft.bingads.v11.api.test.entities.Util; import com.microsoft.bingads.v11.bulk.entities.BulkEntity; import com.microsoft.bingads.v11.bulk.entities.BulkSiteLinkAdExtension; import com.microsoft.bingads.v11.campaignmanagement.AdExtensionStatus; import com.microsoft.bingads.v11.campaignmanagement.SiteLinksAdExtension; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; public class BulkSiteLinkAdExtensionWriteWithDeletedStatusTest { @Test public void testWriteWithDeletedStatus() { BulkSiteLinkAdExtension adExtension = new BulkSiteLinkAdExtension(); adExtension.setSiteLinksAdExtension(new SiteLinksAdExtension()); adExtension.getSiteLinksAdExtension().setType("SiteLinksAdExtension"); adExtension.getSiteLinksAdExtension().setId(10L); adExtension.getSiteLinksAdExtension().setStatus(AdExtensionStatus.DELETED); ArrayList<BulkEntity> adExtensions = new ArrayList<BulkEntity>(); adExtensions.add(adExtension); ArrayList<BulkEntity> readBack = Util.WriteAndReadBack(adExtensions); Assert.assertEquals(1, readBack.size()); BulkSiteLinkAdExtension a = (BulkSiteLinkAdExtension) readBack.get(0); Assert.assertEquals(Util.toJson(adExtension), Util.toJson(a)); } }
45.709677
84
0.765702
51efa5d60b217944021bbfefc064e352a7c23902
4,003
package JiuChap3_DequeStackTrie; import java.util.Arrays; import java.util.Stack; /** * http://www.lintcode.com/en/problem/delete-digits/ * Created at 12:54 PM on 11/25/15. */ public class DelelteDigits { public static void main(String[] args) { String A = "10009876091"; //"134523"; //"30517"; int k = 4; DelelteDigits dd = new DelelteDigits(); String ans = dd.DeleteDigits(A, k); System.out.println(ans); } /** * @param A: A positive integer which has N digits, A is a string. * @param k: Remove k digits. * @return: A string */ public String DeleteDigits(String A, int k) { // write your code here String ans = MethodDP(A, k); return ans; } /** * wankunde's DP solution * http://blog.csdn.net/wankunde/article/details/43792369 * @param A * @param k * @return */ public String MethodDP(String A, int k) { String dp[][] = new String[A.length() - k][A.length()]; for (String[] dp1 : dp) Arrays.fill(dp1, ""); for (int i = 0; i < A.length() - k; i++) { for (int j = i; j < A.length(); j++) { if (i == 0) { String ss = A.substring(j, j + 1); if (j == 0 || (j > 0 && ss.compareTo(dp[i][j - 1]) < 0)) // if (j == 0 || (j > 0 && !ss.equals("0") && ss.compareTo(dp[i][j - 1]) < 0)) dp[i][j] = ss; else dp[i][j] = dp[i][j - 1]; } else { String x1 = dp[i - 1][j - 1] + A.substring(j, j + 1); if (i == j || (j > i && dp[i][j - 1].compareTo(x1) > 0)) dp[i][j] = x1; else dp[i][j] = dp[i][j - 1]; } } } String res = dp[A.length() - k - 1][A.length() - 1]; while (res.startsWith("0")) { res = res.substring(1); } return res; } /** * Using stack to solve nearest smallest number type of problem * @param A * @param k * @return */ public String MethodOn_k(String A, int k) { if (A == null || A.length() == 0 || k >= A.length()) { return ""; } StringBuilder sb = new StringBuilder(A); Stack<Character> stk = new Stack<>(); int count = 0; for (int i = 0; i <= sb.length(); ++i) { //if (i == sb.length()) { // Character other = '0'; //} //Character other = sb.charAt(i); //while (sb.charAt(sb.length()-1) ) Character right = i == sb.length() ? '0' : sb.charAt(i); while (!stk.isEmpty() && count != k) { if (stk.peek() <= right) { break; } else { Character cur = stk.pop(); count++; } } stk.push(right); } StringBuilder ans = new StringBuilder(); for (Character ch : stk) { //ans.insert(0, ch); ans.append(ch); } while (ans.charAt(0) == '0') { ans.deleteCharAt(0); } return ans.deleteCharAt(ans.length()-1).toString(); } /** * O(NK) * http://www.jiuzhang.com/solutions/delete-digits/ https://dev4future.wordpress.com/2015/06/23/delete-digits-lintcode/ */ public String MethodOnk(String A, int k) { if (A == null || A.length() == 0 || k >= A.length()) { return ""; } StringBuilder sb = new StringBuilder(A); while (k != 0) { for (int i = 0; i < sb.length(); ++i) { if (i == sb.length() - 1 || sb.charAt(i) > sb.charAt(i + 1)) { sb.deleteCharAt(i); k--; //continue; break; // need to re-loop again to find violation } } } int j = 0; while (j < sb.length() - 1 && sb.charAt(j) == '0') { j++; } sb.delete(0, j); return sb.toString(); } /** * http://stackoverflow.com/questions/13386107/java-how-to-remove-single-character-from-a-string */ private String remove(String A, int pos) { //String ans = A.substring(0, pos) + A.substring(pos+1, A.length()); StringBuilder sb = new StringBuilder(A); String ans = sb.deleteCharAt(pos).toString(); return ans; } }
26.865772
121
0.509118
e148a390003cf8a067f42eea3b9e89a0b08fb0fa
1,781
import javafx.geometry.Insets; import javafx.scene.Parent; import javafx.scene.control.*; import javafx.scene.layout.GridPane; public class View { private final Controller control; GridPane startView; Label selectStudentLabel = new Label("Select Student:"); ComboBox< Student > studentComboBox = new ComboBox<>(); Label selectCourseLabel = new Label("Select Course:"); ComboBox< Course > courseComboBox = new ComboBox<>(); Button gradeButton = new Button("Grade"); TextField gradeField = new TextField(""); Button showCourseInfoButton = new Button("Show Course Info"); Button showStudentInfoButton = new Button("Show Student Info"); TableView infoTable = new TableView(); public View(Controller control) { this.control = control; startView = new GridPane(); startView.setMinSize(300, 200); startView.setPadding(new Insets(10, 10, 10, 10)); startView.setVgap(5); startView.setHgap(1); startView.add(selectStudentLabel, 0, 0); startView.add(studentComboBox, 10, 0); studentComboBox.setItems(control.getStudents()); studentComboBox.getSelectionModel().selectFirst(); startView.add(selectCourseLabel, 0, 1); startView.add(courseComboBox, 10, 1); startView.add(gradeButton, 15, 1, 20, 1); startView.add(gradeField, 35, 1, 40, 1); courseComboBox.setItems(control.getCourses()); courseComboBox.getSelectionModel().selectFirst(); startView.add(showCourseInfoButton, 0, 5); startView.add(showStudentInfoButton, 10, 5); startView.add(infoTable, 0, 6, 30, 16); infoTable.setPlaceholder(new Label("")); } public Parent asParent() { return startView; } }
32.981481
67
0.668164
6d141cf414c60ac4eb0abf6f046a26a9afa87882
6,400
package com.codepath.android.lollipopexercise.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.graphics.Palette; import android.transition.Transition; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.codepath.android.lollipopexercise.R; import com.codepath.android.lollipopexercise.models.Contact; public class DetailsActivity extends AppCompatActivity { public static final String EXTRA_CONTACT = "EXTRA_CONTACT"; private Contact mContact; private ImageView ivProfile; private TextView tvName; private TextView tvPhone; private View vPalette; private FloatingActionButton fab; private Transition.TransitionListener mEnterTransitionListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); ivProfile = (ImageView) findViewById(R.id.ivProfile); tvName = (TextView) findViewById(R.id.tvName); tvPhone = (TextView) findViewById(R.id.tvPhone); vPalette = findViewById(R.id.vPalette); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setVisibility(View.INVISIBLE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String uri = "tel:" + mContact.getNumber(); Intent i = new Intent(Intent.ACTION_DIAL); i.setData(Uri.parse(uri)); startActivity(i); } }); // Extract contact from bundle mContact = (Contact)getIntent().getExtras().getSerializable(EXTRA_CONTACT); // Fill views with data Glide .with(DetailsActivity.this) .load(mContact.getThumbnailDrawable()) .asBitmap() .centerCrop() .into(new SimpleTarget<Bitmap>(160,160) { @Override public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { ivProfile.setImageBitmap(resource); Palette palette = Palette.from(resource).generate(); Palette.Swatch vibrant = palette.getVibrantSwatch(); if (vibrant != null) { vPalette.setBackgroundColor(palette.getVibrantSwatch().getRgb()); } } }); tvName.setText(mContact.getName()); tvPhone.setText(mContact.getNumber()); mEnterTransitionListener = new Transition.TransitionListener() { @Override public void onTransitionStart(@NonNull Transition transition) { } @Override public void onTransitionCancel(@NonNull Transition transition) { } @Override public void onTransitionPause(@NonNull Transition transition) { } @Override public void onTransitionResume(@NonNull Transition transition) { } @Override public void onTransitionEnd(@NonNull Transition transition) { enterReveal(fab); } }; getWindow().getEnterTransition().addListener(mEnterTransitionListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: exitReveal(fab); return true; } return super.onOptionsItemSelected(item); } void enterReveal(View myView) { // get the center for the clipping circle int cx = myView.getMeasuredWidth() / 2; int cy = myView.getMeasuredHeight() / 2; // get the final radius for the clipping circle int finalRadius = Math.max(myView.getWidth(), myView.getHeight()) / 2; // create the animator for this view (the start radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius); // make the view visible and start the animation myView.setVisibility(View.VISIBLE); anim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { getWindow().getEnterTransition().removeListener(mEnterTransitionListener); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); anim.start(); } void exitReveal(final View myView) { // get the center for the clipping circle int cx = myView.getMeasuredWidth() / 2; int cy = myView.getMeasuredHeight() / 2; // get the initial radius for the clipping circle int initialRadius = myView.getWidth() / 2; // create the animation (the final radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0); // make the view invisible when the animation is done anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); myView.setVisibility(View.INVISIBLE); supportFinishAfterTransition(); } }); // start the animation anim.start(); } @Override public void onBackPressed() { exitReveal(fab); } }
33.333333
97
0.624375
c6b5de9923bee7e86141972aeb175509d6973f73
1,032
package com.connectplusplus.wizapi.utils; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * class containing utility methods related to JSON-POJO operations * */ public class JsonUtils { private static final ObjectMapper mapper; static { // Initializations mapper = new ObjectMapper(); } /** * utility method to convert a POJO into a JSON valued string * */ public static <Type> String convertPojoToJson(Type pojo) { String json = null; try { json = mapper.writeValueAsString(pojo); } catch (JsonProcessingException e) { e.printStackTrace(); } return json; } /** * utility method to convert a JSON valued string into its corresponding POJO * */ public static <Type> Type convertJsonToPojo(String json, Class<Type> typeClass) { Type pojo = null; try { pojo = mapper.readValue(json, typeClass); } catch (IOException e) { e.printStackTrace(); } return pojo; } }
19.846154
82
0.704457
42604f48d0bec10ba66d4bfb949dc433f658758f
10,474
/** * Copyright 2016-2017 Red Hat, Inc, and 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.aerogear.digger.client.services; import com.google.common.collect.Lists; import com.offbytwo.jenkins.JenkinsServer; import com.offbytwo.jenkins.helper.BuildConsoleStreamListener; import com.offbytwo.jenkins.model.*; import org.aerogear.digger.client.model.BuildTriggerStatus; import org.aerogear.digger.client.model.LogStreamingOptions; import org.aerogear.digger.client.util.DiggerClientException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class BuildServiceTest { private BuildService service; @Mock JenkinsServer jenkinsServer; @Mock JobWithDetails mockJob; QueueReference queueReference = new QueueReference("https://jenkins.example.com/queue/item/123/"); @Before public void setUp() throws Exception { service = new BuildService(300, 50); // wait for 300 msecs for initial build, check every 50 msecs Mockito.when(jenkinsServer.getJob("TEST")).thenReturn(mockJob); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfJobCannotBeFound() throws Exception { service.build(jenkinsServer, "UNKNOWN", 10000); } @Test(expected = IllegalStateException.class) public void shouldThrowExceptionIfJenkinsDoesNotReturnQueueReference() throws Exception { Mockito.when(mockJob.build()).thenReturn(null); service.build(jenkinsServer, "TEST", 10000); } @Test(expected = IllegalStateException.class) public void shouldThrowExceptionIfQueueItemIsNullForReference() throws Exception { Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(null); service.build(jenkinsServer, "TEST", 10000); } @Test public void shouldReturnCancelledStatus() throws Exception { final QueueItem queueItem = new QueueItem(); queueItem.setCancelled(true); Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem); final BuildTriggerStatus buildTriggerStatus = service.build(jenkinsServer, "TEST", 10000); assertThat(buildTriggerStatus).isNotNull(); assertThat(buildTriggerStatus.getState()).isEqualTo(BuildTriggerStatus.State.CANCELLED_IN_QUEUE); } @Test public void shouldReturnStuckStatus() throws Exception { final QueueItem queueItem = new QueueItem(); queueItem.setStuck(true); Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem); final BuildTriggerStatus buildTriggerStatus = service.build(jenkinsServer, "TEST", 10000); assertThat(buildTriggerStatus).isNotNull(); assertThat(buildTriggerStatus.getState()).isEqualTo(BuildTriggerStatus.State.STUCK_IN_QUEUE); } @Test public void shouldReturnBuildNumber() throws Exception { final QueueItem queueItem = new QueueItem(); final Executable executable = new Executable(); executable.setNumber(98L); queueItem.setExecutable(executable); Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem); final BuildTriggerStatus buildTriggerStatus = service.build(jenkinsServer, "TEST", 10000); assertThat(buildTriggerStatus).isNotNull(); assertThat(buildTriggerStatus.getState()).isEqualTo(BuildTriggerStatus.State.STARTED_BUILDING); assertThat(buildTriggerStatus.getBuildNumber()).isEqualTo(98); } @Test public void shouldReturnBuildNumber_whenDidNotStartExecutingImmediately() throws Exception { final QueueItem queueItemNotBuildingYet = new QueueItem(); final QueueItem queueItemBuilding = new QueueItem(); queueItemBuilding.setExecutable(new Executable()); queueItemBuilding.getExecutable().setNumber(98L); Mockito.when(mockJob.build()).thenReturn(queueReference); // return `not-building` for the first 2 checks, then return `building` Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItemNotBuildingYet, queueItemNotBuildingYet, queueItemBuilding); final BuildTriggerStatus buildTriggerStatus = service.build(jenkinsServer, "TEST", 10000L); assertThat(buildTriggerStatus).isNotNull(); assertThat(buildTriggerStatus.getState()).isEqualTo(BuildTriggerStatus.State.STARTED_BUILDING); assertThat(buildTriggerStatus.getBuildNumber()).isEqualTo(98); Mockito.verify(jenkinsServer, Mockito.times(3)).getQueueItem(queueReference); } @Test public void shouldReturnTimeout() throws Exception { final QueueItem queueItemNotBuildingYet = new QueueItem(); Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItemNotBuildingYet); final BuildTriggerStatus buildTriggerStatus = service.build(jenkinsServer, "TEST", 500L); assertThat(buildTriggerStatus).isNotNull(); assertThat(buildTriggerStatus.getState()).isEqualTo(BuildTriggerStatus.State.TIMED_OUT); Mockito.verify(jenkinsServer, Mockito.atLeast(2)).getQueueItem(queueReference); } @Test(expected = DiggerClientException.class) public void shouldThrowExceptionIfJobForLogsCannotBeFound() throws Exception { when(jenkinsServer.getJob(anyString())).thenReturn(null); service.getBuildLogs(jenkinsServer, "artifact", 1); } @Test public void shouldFetchLogs() throws Exception { String expectedLogs = "test"; JobWithDetails job = mock(JobWithDetails.class); BuildWithDetails build = mock(BuildWithDetails.class); when(jenkinsServer.getJob(anyString())).thenReturn(job); when(job.getBuildByNumber(anyInt())).thenReturn(build); when(build.details()).thenReturn(build); when(build.getConsoleOutputText()).thenReturn(expectedLogs); String logs = service.getBuildLogs(jenkinsServer, "artifact", 1); assertThat(logs).isEqualTo(expectedLogs); } @Test(expected = DiggerClientException.class) public void shouldThrowExceptionIfJobForBuildHistoryCannotBeFound() throws Exception { when(jenkinsServer.getJob(anyString())).thenReturn(null); service.getBuildHistory(jenkinsServer, "does-not-exist"); } @Test public void shouldFetchBuildHistory() throws Exception { JobWithDetails job = mock(JobWithDetails.class); Build build1 = mock(Build.class); Build build2 = mock(Build.class); BuildWithDetails buildDetails1 = mock(BuildWithDetails.class); BuildWithDetails buildDetails2 = mock(BuildWithDetails.class); when(jenkinsServer.getJob(anyString())).thenReturn(job); when(job.getBuilds()).thenReturn(Lists.newArrayList(build1, build2)); when(build1.details()).thenReturn(buildDetails1); when(build2.details()).thenReturn(buildDetails2); final List<BuildWithDetails> detailsList = service.getBuildHistory(jenkinsServer, "some-job"); assertThat(detailsList).hasSize(2); assertThat(detailsList.get(0)).isSameAs(buildDetails1); assertThat(detailsList.get(1)).isSameAs(buildDetails2); } @Test public void shouldStreamBuildLogs() throws Exception { JobWithDetails job = mock(JobWithDetails.class); Build build = mock(Build.class); BuildWithDetails buildDetails = mock(BuildWithDetails.class); when(jenkinsServer.getJob(anyString())).thenReturn(job); when(job.getBuildByNumber(anyInt())).thenReturn(build); when(build.details()).thenReturn(buildDetails); LogStreamingOptions options = new LogStreamingOptions(new BuildConsoleStreamListener() { @Override public void onData(String s) { } @Override public void finished() { } }); service.streamBuildLogs(jenkinsServer, "some-job", 1, options); verify(buildDetails).streamConsoleOutput(options.getStreamListener(), options.getPollingInterval(), options.getPollingTimeout()); } @Test public void shouldReturnAborted() throws Exception { final QueueItem queueItem = new QueueItem(); final Executable executable = new Executable(); executable.setNumber(98L); queueItem.setExecutable(executable); final Build mockBuild = Mockito.mock(Build.class); final BuildWithDetails mockBuildWithDetails = Mockito.mock(BuildWithDetails.class); Mockito.when(mockJob.build()).thenReturn(queueReference); Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem); Mockito.when(mockJob.getBuildByNumber(98)).thenReturn(mockBuild); Mockito.when(mockBuild.details()).thenReturn(mockBuildWithDetails); Mockito.when(mockBuildWithDetails.getResult()).thenReturn(BuildResult.ABORTED); BuildWithDetails buildWithDetails = service.cancelBuild(jenkinsServer, "TEST", 98); assertThat(buildWithDetails.getResult()).isEqualTo(BuildResult.ABORTED); Mockito.verify(mockBuild, Mockito.times(1)).Stop(); } }
40.754864
145
0.729234
8fbc600c862b00dda7d7472768a65e1493f604a2
12,438
package de.uni_mannheim.informatik.dws.tnt.match.matchers; import java.io.File; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.time.DurationFormatUtils; import de.uni_mannheim.informatik.dws.tnt.match.ContextColumns; import de.uni_mannheim.informatik.dws.tnt.match.CorrespondenceFormatter; import de.uni_mannheim.informatik.dws.tnt.match.DisjointHeaders; import de.uni_mannheim.informatik.dws.tnt.match.TnTTask; import de.uni_mannheim.informatik.dws.tnt.match.data.MatchableTableColumn; import de.uni_mannheim.informatik.dws.tnt.match.data.MatchableTableDeterminant; import de.uni_mannheim.informatik.dws.tnt.match.data.MatchableTableRow; import de.uni_mannheim.informatik.dws.tnt.match.data.WebTables; import de.uni_mannheim.informatik.dws.tnt.match.recordmatching.DeterminantBasedDuplicateDetectionRule; import de.uni_mannheim.informatik.dws.tnt.match.recordmatching.blocking.DeterminantRecordBlockingKeyGenerator; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.CorrespondenceTransitivityMaterialiser; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.EqualHeaderComparator; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.ValueBasedSchemaMatcher; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.duplicatebased.DuplicateBasedSchemaVotingRule; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.refinement.DisjointHeaderMatchingRule; import de.uni_mannheim.informatik.dws.tnt.match.schemamatching.refinement.GraphBasedRefinement; import de.uni_mannheim.informatik.dws.winter.matching.MatchingEngine; import de.uni_mannheim.informatik.dws.winter.matching.aggregators.VotingAggregator; import de.uni_mannheim.informatik.dws.winter.matching.blockers.NoSchemaBlocker; import de.uni_mannheim.informatik.dws.winter.matching.blockers.StandardRecordBlocker; import de.uni_mannheim.informatik.dws.winter.model.Correspondence; import de.uni_mannheim.informatik.dws.winter.model.DataSet; import de.uni_mannheim.informatik.dws.winter.model.Matchable; import de.uni_mannheim.informatik.dws.winter.model.ParallelHashedDataSet; import de.uni_mannheim.informatik.dws.winter.processing.Processable; import de.uni_mannheim.informatik.dws.winter.processing.ProcessableCollection; public abstract class TableToTableMatcher extends TnTTask { public String getTaskName() { return this.getClass().getSimpleName(); } private long runtime = 0; /** * @return the runtime */ public long getRuntime() { return runtime; } private boolean verbose = false; public void setVerbose(boolean verbose) { this.verbose = verbose; } public boolean isVerbose() { return verbose; } protected WebTables web; protected Map<String, Set<String>> disjointHeaders; protected Processable<Correspondence<MatchableTableColumn, Matchable>> schemaCorrespondences; protected File logDirectory; protected boolean matchContextColumnsByHeader = true; public void setLogDirectory(File f) { logDirectory = f; } /** * @param disjointHeaders the disjointHeaders to set */ public void setDisjointHeaders(Map<String, Set<String>> disjointHeaders) { this.disjointHeaders = disjointHeaders; } /** * @return the disjointHeaders */ public Map<String, Set<String>> getDisjointHeaders() { return disjointHeaders; } /** * @param web the web to set */ public void setWebTables(WebTables web) { this.web = web; } /** * @param matchContextColumnsByHeader the matchContextColumnsByHeader to set */ public void setMatchContextColumnsByHeader(boolean matchContextColumnsByHeader) { this.matchContextColumnsByHeader = matchContextColumnsByHeader; } public Processable<Correspondence<MatchableTableColumn, Matchable>> getSchemaCorrespondences() { return schemaCorrespondences; } @Override public void initialise() throws Exception { } @Override public void match() throws Exception { long start = System.currentTimeMillis(); if(verbose) { System.out.println("*** Pair-wise Matcher ***"); } runMatching(); System.out.println(String.format("Schema Correspondences are a %s", getSchemaCorrespondences().getClass().getName())); if(verbose) { CorrespondenceFormatter.printAttributeClusters(getSchemaCorrespondences()); // CorrespondenceFormatter.printTableLinkageFrequency(getSchemaCorrespondences()); System.out.println("*** Pair-wise Refinement ***"); } schemaCorrespondences = runPairwiseRefinement(web, getSchemaCorrespondences(), new DisjointHeaders(disjointHeaders)); System.out.println(String.format("Schema Correspondences are a %s", getSchemaCorrespondences().getClass().getName())); if(verbose) { CorrespondenceFormatter.printAttributeClusters(getSchemaCorrespondences()); // CorrespondenceFormatter.printTableLinkageFrequency(getSchemaCorrespondences()); System.out.println("*** Graph-based Refinement ***"); } schemaCorrespondences = runGraphbasedRefinement(getSchemaCorrespondences(), new DisjointHeaders(disjointHeaders)); if(verbose) { CorrespondenceFormatter.printAttributeClusters(getSchemaCorrespondences()); // CorrespondenceFormatter.printTableLinkageFrequency(getSchemaCorrespondences()); System.out.println("*** Transitivity ***"); } schemaCorrespondences = applyTransitivity(schemaCorrespondences); if(verbose) { CorrespondenceFormatter.printAttributeClusters(getSchemaCorrespondences()); // CorrespondenceFormatter.printTableLinkageFrequency(getSchemaCorrespondences()); } long end = System.currentTimeMillis(); runtime = end-start; System.out.println(String.format("[%s] Matching finished after %s", this.getClass().getName(), DurationFormatUtils.formatDurationHMS(runtime))); } protected abstract void runMatching(); protected Processable<Correspondence<MatchableTableColumn, Matchable>> removeContextMatches(Processable<Correspondence<MatchableTableColumn, Matchable>> schemaCorrespondences) { // remove matches between context columns return schemaCorrespondences.where((c) -> !(ContextColumns.isContextColumn(c.getFirstRecord()) && ContextColumns.isContextColumn(c.getSecondRecord())) ); } protected Processable<Correspondence<MatchableTableColumn, Matchable>> runValueBased(WebTables web) { ValueBasedSchemaMatcher matcher = new ValueBasedSchemaMatcher(); Processable<Correspondence<MatchableTableColumn, Matchable>> cors = matcher.run(web.getRecords()); if(verbose) { for(Correspondence<MatchableTableColumn, Matchable> cor : cors.get()) { MatchableTableColumn c1 = cor.getFirstRecord(); MatchableTableColumn c2 = cor.getSecondRecord(); System.out.println(String.format("{%d}[%d]%s <-> {%d}[%d]%s (%f)", c1.getTableId(), c1.getColumnIndex(), c1.getHeader(), c2.getTableId(), c2.getColumnIndex(), c2.getHeader(), cor.getSimilarityScore())); } } return cors; } protected Processable<Correspondence<MatchableTableRow, MatchableTableDeterminant>> findDuplicates( WebTables web, Processable<Correspondence<MatchableTableDeterminant, MatchableTableColumn>> detCors) { MatchingEngine<MatchableTableRow, MatchableTableDeterminant> engine = new MatchingEngine<>(); DataSet<MatchableTableRow, MatchableTableDeterminant> ds = new ParallelHashedDataSet<>(web.getRecords().get()); DeterminantRecordBlockingKeyGenerator bkg = new DeterminantRecordBlockingKeyGenerator(); DeterminantBasedDuplicateDetectionRule rule = new DeterminantBasedDuplicateDetectionRule(0.0); Processable<Correspondence<MatchableTableRow, MatchableTableDeterminant>> duplicates = engine.runDuplicateDetection(ds, detCors, rule, new StandardRecordBlocker<>(bkg)); return duplicates; } protected Processable<Correspondence<MatchableTableColumn, MatchableTableRow>> runDuplicateBasedSchemaMatching(WebTables web, Processable<Correspondence<MatchableTableRow, MatchableTableDeterminant>> duplicates) { MatchingEngine<MatchableTableRow, MatchableTableColumn> engine = new MatchingEngine<>(); DuplicateBasedSchemaVotingRule rule = new DuplicateBasedSchemaVotingRule(0.0); VotingAggregator<MatchableTableColumn, MatchableTableRow> voteAggregator = new VotingAggregator<>(false, 1.0); NoSchemaBlocker<MatchableTableColumn, MatchableTableRow> schemaBlocker = new NoSchemaBlocker<>(); // we must flatten the duplicates, such that each determinant that created a duplicate is processed individually by the matching rule // only then can we group the votes by determinant and make sense of the number of votes Processable<Correspondence<MatchableTableRow, MatchableTableDeterminant>> flatDuplicates = new ProcessableCollection<>(); Correspondence.flatten(duplicates, flatDuplicates); Processable<Correspondence<MatchableTableColumn, MatchableTableRow>> schemaCorrespondences = engine.runDuplicateBasedSchemaMatching(web.getSchema(), web.getSchema(), flatDuplicates, rule, null, voteAggregator, schemaBlocker); return schemaCorrespondences; } protected Processable<Correspondence<MatchableTableColumn, Matchable>> runPairwiseRefinement(WebTables web, Processable<Correspondence<MatchableTableColumn, Matchable>> schemaCorrespondences, DisjointHeaders disjointHeaders) throws Exception { MatchingEngine<MatchableTableRow, MatchableTableColumn> engine = new MatchingEngine<>(); // run label-based matcher with equality comparator to generate correspondences EqualHeaderComparator labelComparator = new EqualHeaderComparator(); labelComparator.setMatchContextColumns(matchContextColumnsByHeader); Processable<Correspondence<MatchableTableColumn, MatchableTableColumn>> labelBasedCors = engine.runLabelBasedSchemaMatching(web.getSchema(), labelComparator, 1.0); labelBasedCors = labelBasedCors.where((c)->c.getFirstRecord().getDataSourceIdentifier()!=c.getSecondRecord().getDataSourceIdentifier()); // filter out correspondences between union context columns (are generated when creating the union tables) // - we cannot use the labels of union context columns for matching, because the names are generated // - generated columns for different union table clusters still have the same name, but this does not imply that they match! // labelBasedCors = labelBasedCors.where((c)->!ContextColumns.isRenamedUnionContextColumn(c.getFirstRecord().getHeader())); //BEGIN CHANGE // labelBasedCors = labelBasedCors.where((c)->!ContextColumns.isContextColumnIgnoreCase(c.getFirstRecord().getHeader())); //NEW CODE: labelBasedCors = labelBasedCors.where((c)->!ContextColumns.isRenamedUnionContextColumn(c.getFirstRecord().getHeader())); //EFFECT: changes result of t2t matching (at least for itunes), why? //END CHANGE // for(Correspondence<MatchableTableColumn, MatchableTableColumn> cor : labelBasedCors.get()) { // System.out.println(String.format("[LabelBased] %s <-> %s", cor.getFirstRecord(), cor.getSecondRecord())); // } // combine label- and value-based correspondences Processable<Correspondence<MatchableTableColumn, Matchable>> cors = schemaCorrespondences.append(Correspondence.toMatchable(labelBasedCors)).distinct(); // apply disjoint header rule to remove inconsistencies DisjointHeaderMatchingRule rule = new DisjointHeaderMatchingRule(disjointHeaders, 0.0); // rule.setVerbose(verbose); cors = cors.map(rule); return cors; } protected Processable<Correspondence<MatchableTableColumn, Matchable>> runGraphbasedRefinement(Processable<Correspondence<MatchableTableColumn, Matchable>> correspondences, DisjointHeaders disjointHeaders) { GraphBasedRefinement refiner = new GraphBasedRefinement(true); refiner.setVerbose(verbose); refiner.setLogDirectory(logDirectory); Processable<Correspondence<MatchableTableColumn, Matchable>> refined = refiner.match(correspondences, disjointHeaders); return refined; } protected Processable<Correspondence<MatchableTableColumn, Matchable>> applyTransitivity(Processable<Correspondence<MatchableTableColumn, Matchable>> correspondences) { CorrespondenceTransitivityMaterialiser transitivity = new CorrespondenceTransitivityMaterialiser(); Processable<Correspondence<MatchableTableColumn, Matchable>> transitiveCorrespondences = transitivity.aggregate(correspondences); correspondences = correspondences.append(transitiveCorrespondences); correspondences = correspondences.distinct(); return correspondences; } }
45.727941
244
0.799083
e3c39bafcaea90d7d2f759497ae698ab14186a9a
7,545
package inpro.incremental.sink; import inpro.incremental.PushBuffer; import inpro.incremental.unit.EditMessage; import inpro.incremental.unit.IU; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import com.mxgraph.layout.mxIGraphLayout; import com.mxgraph.layout.mxStackLayout; import com.mxgraph.layout.hierarchical.mxHierarchicalLayout; import com.mxgraph.model.mxCell; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.swing.mxGraphOutline; import com.mxgraph.view.mxGraph; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4String; /** * A viewer for IU networks using the JGraphX library. * @author Andreas Peldszus */ public class IUNetworkJGraphX extends PushBuffer { /** String, comma-separated, for what iu types to display */ @S4String(defaultValue = "") /** Property for string for iu types to display <br/> Beware that the iumodule that you hook this into must have links to the types you specify here (sll or grin). */ public final static String PROP_IU_TYPES = "iuTypes"; /** The string of comma separated iu types */ private List<String> iuTypes = new ArrayList<String>(); /** Frame for display of output */ JFrame f = new JFrame("IU Network"); /** The graph */ mxGraph graph; /** The graphical component to display the graph in */ mxGraphComponent graphComponent; /** The layout type of the graph */ mxIGraphLayout layout; public static final String GROUP_STYLE = "shape=swimlane;fontSize=9;fontStyle=1;startSize=20;horizontal=false;padding=5;"; public static final String NODE_STYLE = "shape=rectangle;rounded=true;fillColor=#FFFFFF;opacity=80;spacing=3;"; public static final String SLL_EDGE_STYLE = "strokewidth=1;"; public static final String GRIN_EDGE_STYLE = "strokewidth=1;dashed=1;"; /** * Sets up the IU Network listener */ @Override public void newProperties(PropertySheet ps) throws PropertyException { // setup list of IU types to display if (!ps.getString(PROP_IU_TYPES).isEmpty()) { String[] strings = ps.getString(PROP_IU_TYPES).split(","); for (String string : strings) { this.iuTypes.add(string); System.err.println("Displaying " + string); } } // setup graph graph = new mxGraph(); graph.setMultigraph(true); graph.setCellsBendable(false); graph.setCellsCloneable(false); graph.setCellsEditable(false); graph.setCellsResizable(false); graph.setAllowDanglingEdges(false); graph.setKeepEdgesInBackground(true); // setup layout layout = new mxStackLayout(graph, false); //mxCompactTreeLayout(graph); //mxHierarchicalLayout(graph); // mxFastOrganicLayout(graph); // new mxStackLayout(graph, true, 10, 0); layout.execute(graph.getDefaultParent()); // setup frame SwingUtilities.invokeLater(new Runnable() { public void run() { f.setLocation(0, 0); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(1000, 800); graphComponent = new mxGraphComponent(graph); graphComponent.setConnectable(false); f.getContentPane().add(BorderLayout.CENTER, graphComponent); // graphOutline in toolbar JPanel toolBar = new JPanel(); toolBar.setLayout(new BorderLayout()); final mxGraphOutline graphOutline = new mxGraphOutline(graphComponent); graphOutline.setPreferredSize(new Dimension(100, 100)); toolBar.add(graphOutline, BorderLayout.WEST); f.getContentPane().add(BorderLayout.NORTH, toolBar); // make it so f.setVisible(true); } }); } private class ConservedLink { public String from; public String to; public String type; public ConservedLink(String from, String to, String type) { this.from = from; this.to = to; this.type = type; } } @Override public void hypChange(Collection<? extends IU> ius, List<? extends EditMessage<? extends IU>> edits) { if (edits != null && !edits.isEmpty()) { Map<String,Object> groupsByIUType = new HashMap<String,Object>(); Map<String,Object> insertedNodesByIUID = new HashMap<String,Object>(); Queue<IU> iuProcessingQueue = new ArrayDeque<IU>(); iuProcessingQueue.addAll(new ArrayList<IU>(ius)); List<ConservedLink> ConservedLinks = new ArrayList<ConservedLink>(); // reset graph graph.removeCells(graph.getChildCells(graph.getDefaultParent(), true, true)); // fill graph graph.getModel().beginUpdate(); Object parent = graph.getDefaultParent(); try { // first step: add a node for each iu (and save the links for second step) while (!iuProcessingQueue.isEmpty()) { // get next IU IU iu = iuProcessingQueue.remove(); String id = Integer.toString(iu.getID()); String iuType = iu.getClass().getSimpleName(); // make sure strange IUs don't enter the graph // TODO: this is the very first IU causing problems here. need to fix the IU bootstrap bug if (iuType == "" || iuType == null) { continue; } // build a new iuType group, if it doesn't exist already if (! groupsByIUType.containsKey(iuType)) { // make new group and register it mxCell group = (mxCell)graph.insertVertex(parent, null, iuType, 0, 0, 0, 0, GROUP_STYLE); groupsByIUType.put(iuType, group); } // if there is no node in the graph yet for this IU, make one and follow the IUs links if (!insertedNodesByIUID.containsKey(id)) { // find the group to add this node to Object group = groupsByIUType.get(iuType); String label = iuType + " " + id+ "\n" + iu.toPayLoad().replace("\\n", "\n"); Object node = graph.insertVertex(group, id, label, 0, 0, 0, 0, NODE_STYLE); graph.updateCellSize(node); // save sll link for later, queue linked IU IU sll = iu.getSameLevelLink(); if (sll != null) { ConservedLinks.add(new ConservedLink(id, Integer.toString(sll.getID()), "sll")); iuProcessingQueue.add(sll); } // save grin links for later, queue linked IUs List<? extends IU> grin = iu.groundedIn(); if (grin != null) { for (IU gr : grin) { ConservedLinks.add(new ConservedLink(id, Integer.toString(gr.getID()), "grin")); } iuProcessingQueue.addAll(grin); } // store processed nodes insertedNodesByIUID.put(id, node); } } // then add all links for (ConservedLink l : ConservedLinks) { // get nodes Object from = insertedNodesByIUID.get(l.from); Object to = insertedNodesByIUID.get(l.to); String style = (l.type.equals("sll")) ? SLL_EDGE_STYLE : GRIN_EDGE_STYLE ; graph.insertEdge(parent, null, null, from, to, style); } } finally { graph.getModel().endUpdate(); } // arrange the group internal layout for (Object group : groupsByIUType.values()) { // mxCompactTreeLayout grouplayout = new mxCompactTreeLayout(graph); // grouplayout.setHorizontal(true); mxHierarchicalLayout grouplayout = new mxHierarchicalLayout(graph, SwingConstants.WEST); grouplayout.execute(group); } // arrange the overall graph layout layout.execute(graph.getDefaultParent()); } } }
34.769585
177
0.693439
74fbbd715640498cf066d16663624a29c598c51e
3,144
/* * Copyright 2017. Akshay Jain * * 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.akki.popularmovies.rest.model.video; import android.os.Parcel; import android.os.Parcelable; /** * Model class for movie video details */ public class MovieVideo implements Parcelable { private String id; private String iso_639_1; private String iso_3166_1; private String key; private String name; private String site; private Integer size; private String type; private MovieVideo(Parcel in) { id = in.readString(); iso_639_1 = in.readString(); iso_3166_1 = in.readString(); key = in.readString(); name = in.readString(); site = in.readString(); size = in.readInt(); type = in.readString(); } public static final Creator<MovieVideo> CREATOR = new Creator<MovieVideo>() { @Override public MovieVideo createFromParcel(Parcel in) { return new MovieVideo(in); } @Override public MovieVideo[] newArray(int size) { return new MovieVideo[size]; } }; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIso6391() { return iso_639_1; } public void setIso6391(String iso6391) { this.iso_639_1 = iso6391; } public String getIso31661() { return iso_3166_1; } public void setIso31661(String iso31661) { this.iso_3166_1 = iso31661; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id); dest.writeString(iso_639_1); dest.writeString(iso_3166_1); dest.writeString(key); dest.writeString(name); dest.writeString(site); dest.writeInt(size); dest.writeString(type); } }
22.297872
81
0.611641
2b1dbac4da8c7690bc1d18d4c02d992ac5b7eabd
1,628
//给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。 // // 输入为三个整数:day、month 和 year,分别表示日、月、年。 // // 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", //"Friday", "Saturday"}。 // // // // 示例 1: // // 输入:day = 31, month = 8, year = 2019 //输出:"Saturday" // // // 示例 2: // // 输入:day = 18, month = 7, year = 1999 //输出:"Sunday" // // // 示例 3: // // 输入:day = 15, month = 8, year = 1993 //输出:"Sunday" // // // // // 提示: // // // 给出的日期一定是在 1971 到 2100 年之间的有效日期。 // // Related Topics 数学 👍 75 👎 0 package com.uyaki.leetcode.editor.cn; /** * 一周中的第几天 */ public class P1185_DayOfTheWeek { public static void main(String[] args) { //测试代码 Solution solution = new P1185_DayOfTheWeek().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public String dayOfTheWeek(int day, int month, int year) { String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30}; /* 输入年份之前的年份的天数贡献 */ int days = 365 * (year - 1971) + (year - 1969) / 4; /* 输入年份中,输入月份之前的月份的天数贡献 */ for (int i = 0; i < month - 1; ++i) { days += monthDays[i]; } if ((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && month >= 3) { days += 1; } /* 输入月份中的天数贡献 */ days += day; return week[(days + 3) % 7]; } } //leetcode submit region end(Prohibit modification and deletion) }
22.929577
107
0.512899
56247ebd861e80438cf6cd4a9f7fd96e7b8f11f3
3,410
package de.olyro.pizza.models; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.olyro.pizza.Main; public class Order { public final String id; public final String name; public final boolean payed; public final List<OrderItem> items; public Order(String id, String name, boolean payed, List<OrderItem> items) { this.id = id; this.name = name; this.payed = payed; this.items = items; } public static List<Order> getOrders() throws SQLException { Gson gson = new GsonBuilder().create(); try (Connection connection = Main.getConnection()) { PreparedStatement s = connection .prepareStatement("SELECT * FROM orders WHERE hidden = false ORDER BY date"); ResultSet rs = s.executeQuery(); var result = new ArrayList<Order>(); while (rs.next()) { result.add(gson.fromJson(rs.getString("data"), Order.class)); } return result; } } public static Optional<Order> getOrder(String id) throws SQLException { Gson gson = new GsonBuilder().create(); try (Connection connection = Main.getConnection()) { PreparedStatement s = connection.prepareStatement("SELECT * FROM orders WHERE id = ?"); s.setString(1, id); ResultSet rs = s.executeQuery(); return rs.next() ? Optional.of(gson.fromJson(rs.getString("data"), Order.class)) : Optional.empty(); } } public static boolean deleteOrder(String id) throws SQLException { try (Connection connection = Main.getConnection()) { PreparedStatement s = connection.prepareStatement("DELETE FROM orders WHERE id = ?"); s.setString(1, id); int rs = s.executeUpdate(); return rs > 0; } } public static boolean createOrder(Order order) throws SQLException { Gson gson = new GsonBuilder().create(); try (Connection connection = Main.getConnection()) { PreparedStatement s = connection.prepareStatement("INSERT INTO orders (id, data) VALUES (?, ?)"); s.setString(1, order.id); s.setString(2, gson.toJson(order)); int rs = s.executeUpdate(); return rs > 0; } } public static boolean setPayed(Order order) throws SQLException { Gson gson = new GsonBuilder().create(); try (Connection connection = Main.getConnection()) { PreparedStatement s = connection.prepareStatement("UPDATE orders SET data = ? WHERE id = ?"); s.setString(1, gson.toJson(order)); s.setString(2, order.id); int rs = s.executeUpdate(); return rs > 0; } } public static boolean setPayed(String id, boolean hidden) throws SQLException { try (Connection connection = Main.getConnection()) { PreparedStatement s = connection.prepareStatement("UPDATE orders SET hidden = ? WHERE id = ?"); s.setBoolean(1, hidden); s.setString(2, id); int rs = s.executeUpdate(); return rs > 0; } } }
36.276596
112
0.609677
e3e33a39464041a5056258854bb261db0ed6cd7b
875
package com.ss.leetcode.medium; /** * @author Senn * @create 2022/2/15 11:05 */ public class Lee132 { int[] mins; int n; char[] cs; public int minCut(String s) { cs = s.toCharArray(); n = cs.length; mins = new int[n]; for (int i = 0; i < n; i++) { mins[i] = n; } for (int i = 0; i < n; i++) { expend(i, i); expend(i, i + 1); } return mins[n - 1]; } public void expend(int left, int right) { while (left > -1 && right < n && cs[left] == cs[right]) { int i = --left, j = ++right; if (i == -1) { mins[j - 1] = 0; } else { int cur = mins[j - 1]; int sub = mins[i] + 1; mins[j - 1] = Math.min(cur, sub); } } } }
19.444444
65
0.379429
232e7e90b1ba66b9466ca922d3dcea8a40d695ed
415
package CCPC; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i <t ; i++) { int a = sc.nextInt(); int b = sc.nextInt(); for(int j=0;j<=a && j<=b;j++){ if(((j^a) & (j^b)) == 0){ if(j==0) System.out.println(1); else System.out.println(j); break; } } } } }
18.863636
41
0.53253
2a6b5cbfca2db59b33a63a1026efb58109f3f3c4
1,980
package com.progwml6.natura.world.worldgen.trees; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.common.IWorldGenerator; public class BaseTreeGenerator implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { } public void generateTree(Random random, World world, BlockPos pos) { } @Nullable private static BlockPos getValidPos(World world, int x, int z, Block tree) { // get to the ground final BlockPos topPos = world.getHeight(new BlockPos(x, 0, z)); if (topPos.getY() == 0) { return null; } final MutableBlockPos pos = new MutableBlockPos(topPos); IBlockState blockState = world.getBlockState(pos); while (canReplace(blockState, world, pos)) { pos.move(EnumFacing.DOWN); if (pos.getY() <= 0) { return null; } blockState = world.getBlockState(pos); } if (tree instanceof IPlantable && blockState.getBlock().canSustainPlant(blockState, world, pos, EnumFacing.UP, (IPlantable) tree)) { return pos.up(); } return null; } public static boolean canReplace(IBlockState blockState, World world, BlockPos pos) { Block block = blockState.getBlock(); return block.isReplaceable(world, pos) && !blockState.getMaterial().isLiquid(); } }
28.285714
138
0.671212
8416effbe5a179ca61affcea4984d7c10f6e5ce3
1,850
package knife; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import javax.swing.JMenuItem; import burp.BurpExtender; import burp.HelperPlus; import burp.IBurpExtenderCallbacks; import burp.IContextMenuInvocation; import burp.IExtensionHelpers; import burp.IHttpRequestResponse; import config.DismissedTargets; public class DismissCancelMenu extends JMenuItem {//JMenuItem vs. JMenu public DismissCancelMenu(BurpExtender burp){ this.setText("^_^ Dismissed Cancle"); this.addActionListener(new Dismiss_Cancel_Action(burp,burp.invocation)); } } class Dismiss_Cancel_Action implements ActionListener{ //scope matching is actually String matching!! private IContextMenuInvocation invocation; public BurpExtender myburp; public IExtensionHelpers helpers; public PrintWriter stdout; public PrintWriter stderr; public IBurpExtenderCallbacks callbacks; //callbacks.printOutput(Integer.toString(invocation.getToolFlag()));//issue tab of target map is 16 public Dismiss_Cancel_Action(BurpExtender burp,IContextMenuInvocation invocation) { this.invocation = invocation; this.myburp = burp; this.helpers = burp.helpers; this.callbacks = BurpExtender.callbacks; this.stderr = burp.stderr; } @Override public void actionPerformed(ActionEvent e) { try{ IHttpRequestResponse[] messages = invocation.getSelectedMessages(); for(IHttpRequestResponse message:messages) { String url = new HelperPlus(helpers).getFullURL(message).toString(); String host = message.getHttpService().getHost(); if (url.contains("?")){ url = url.substring(0,url.indexOf("?")); } DismissedTargets.targets.remove(url); DismissedTargets.targets.remove(host); DismissedTargets.ShowToGUI(); } }catch (Exception e1) { e1.printStackTrace(stderr); } } }
28.90625
100
0.775676
4876e0b0a78c249b6367fd14b7b12d6d263fd96b
1,134
import java.lang.reflect.Array; import java.util.ArrayList; public class CalculaFitness implements Runnable { private Populacao populacao; private ArrayList<Cromossomo> cromossomos; private int iComeco, iFim; CalculaFitness(Populacao p, ArrayList cromossomos, int iComeco, int iFim) { this.populacao = p; this.cromossomos = cromossomos; this.iComeco = iComeco; this.iFim = iFim; } @Override public void run() { for (int i = iComeco; i < iFim; ++i) { if (i >= this.cromossomos.size() || this.populacao.verificarParada()) break; Cromossomo c = this.cromossomos.get(i), elemMaxFitness = this.populacao.getElemMaxFitness(); c.calcularFitness(); int fitness = c.getFitness(); populacao.addMeanFitness(fitness); if (elemMaxFitness == null || fitness > elemMaxFitness.getFitness()) { this.populacao.setElemMaxFitness(c); if (fitness == this.populacao.getnRainhas()) this.populacao.setAcabou(); } } } }
30.648649
104
0.599647
be1ff2d58383bbc4daf37887e2c157f9101e715a
4,109
package ozgurdbsync; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Main { // public static List<String> ordered = new ArrayList<>(); public static void main(String[] args) throws IOException, SQLException { if (args.length != 1) throw new RuntimeException("Usage: java -cp ./ozgurdbsynch.jar ozgurdbsync/Main path.ini.file"); Ini ini = new Ini(args[0]); Map<String, TableProps> tableProps = new HashMap<String, TableProps>(); Map<String, List<String>> deps = new HashMap<String, List<String>>(); for (int i = 0; i < ini.tableProps.size(); i++) { TableProps tp = ini.tableProps.get(i); ConArgs source = new ConArgs(); source.props = ini.srcProps; source.schema = tp.schema; source.table = tp.table; String tn = source.toFullTable(); tableProps.put(tn, tp); Con s = new Con(source); s.initMeta(); List<String> d = s.getDepends(); deps.put(tn, d); } for (Entry<String, List<String>> e : deps.entrySet()) { System.out.println("-- "+e.getKey() + "->" + e.getValue().toString()); } // boolean ready = false; // for (int i = 0; i < 10000; i++) { // if (ordered.size() == deps.size()) { // ready = true; // break; // } // for (Entry<String, List<String>> e : deps.entrySet()) { // String tn = e.getKey(); // if (ordered.contains(tn)) { // continue; // } // List<String> dps = e.getValue(); // if (dps.size() == 0) { // ordered.add(tn); // continue; // } // boolean notReady = false; // for (String string : dps) { // if (deps.containsKey(string)) // continue; // if (ordered.contains(string)) { // continue; // } // notReady = true; // } // if (notReady) // continue; // ordered.add(tn); // } // } System.out.println("--BEGIN"); Set<String> processed = new HashSet<>(); boolean success=false; for (int i = 0; i < 1000; i++) { if (processed.size() == tableProps.size()) { success=true; break; } for (Entry<String, TableProps> tpe : tableProps.entrySet()) { String tpname = tpe.getKey(); // System.out.println(tpname); if (processed.contains(tpname)) { continue; } List<String> weneed = deps.get(tpname); boolean notFound = false; if (weneed != null) { for (String str : weneed) { if (!processed.contains(str)) { notFound = true; break; } } } if (notFound) continue; processed.add(tpname); TableProps tp = tpe.getValue(); ConArgs source = new ConArgs(); source.props = ini.srcProps; source.schema = tp.schema; source.table = tp.table; System.out.println("--Schema comparison table:" + source.toFullTable()); ConArgs dest = new ConArgs(); dest.props = ini.destProps; dest.schema = tp.schema; dest.table = tp.table; Con s = new Con(source); s.initMeta(); Con d = new Con(dest); d.initMeta(); String cs = s.compareSchema(d); if (cs != null) { System.out.println(cs); System.exit(-1); } System.out.println("--Schema comparison success"); s.getData(); d.getData(); System.out.println("--Deletes"); List<PkeyValue> ret = s.diffDel(d); for (PkeyValue pkeyValue : ret) { String delStr = s.toSqlDelete(pkeyValue); System.out.println(delStr); } System.out.println("--Updates"); ret = s.diffUpdate(d); for (PkeyValue pkeyValue : ret) { String updateStr = d.toSqlUpdate(pkeyValue); System.out.println(updateStr); } System.out.println("--Inserts"); ret = s.diffInsert(d); for (PkeyValue pkeyValue : ret) { String insertStr = d.toSqlInsert(pkeyValue); System.out.println(insertStr); } System.out.println("--Diff data success"); s.disconnect(); d.disconnect(); } } if(success) { System.out.println("--END SUCCESS"); }else { System.out.println("--FAILED; CYCLIC DEPENDENCY"); } } }
24.458333
99
0.600146
e0a0ebb79c68bc6923b20d1995a827dacea46ee4
709
package com.example.change4change; public class TransactionEntry { private String lbID; private String lbTranstype; private String lbTransAmt; private String lbDateInfo; public TransactionEntry (String lbID,String lbTranstype,String lbTransAmt,String lbDateInfo) { this.lbID = lbID; this.lbTranstype = lbTranstype; this.lbTransAmt = lbTransAmt; this.lbDateInfo = lbDateInfo; } public String getLbID() { return lbID; } public String getLbTranstype() { return lbTranstype; } public String getLbTransAmt() { return lbTransAmt; } public String getLbDateInfo() { return lbDateInfo; } }
20.852941
98
0.655853
4deb685b7e4ed75a6e5906141a633b59d30cb955
415
package com.example.restservice.api.data; import com.example.restservice.service.data.Tag; import lombok.Builder; import lombok.Data; @Data @Builder public class TagDto { private final Long id; private final String name; public static TagDto createFrom(Tag tag) { return TagDto.builder() .id(tag.getId()) .name(tag.getName()) .build(); } }
20.75
48
0.628916
395133fe7bdfaa3702d90dcb9e520260eaf15405
2,195
/* * Copyright 2014 David Lukacs * * 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.lukacsd.aws.scheme.s3.model; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BillingData implements Serializable { private static final long serialVersionUID = 2979002773690118231L; private static final String BILLING_FILENAME_REGEX = "^[0-9]*-aws-billing-csv-([0-9]{4}-[0-9]{2}).csv.*$"; private String date; private String ccy; private Double total; private Double tax; public BillingData( String filename, String[ ] split ) { this.date = getDateFromFileName( filename ); this.ccy = split[ 23 ]; this.total = Double.valueOf( split[ 24 ] ); this.tax = Double.valueOf( split[ 26 ] ); if ( date == null || ccy == null || total == null || tax == null ) { throw new IllegalArgumentException( String.format( "Some values missing: filename[%s], line[%s]", filename, split ) ); } } private String getDateFromFileName( String filename ) { Pattern p = Pattern.compile( BILLING_FILENAME_REGEX ); Matcher m = p.matcher( filename ); if ( m.matches( ) ) { return m.group( 1 ); } return null; } public String getDate() { return date; } public String getCcy() { return ccy; } public Double getTotal() { return total; } public Double getTax() { return tax; } @Override public String toString() { return "BillingData [date=" + date + ", ccy=" + ccy + ", total=" + total + ", tax=" + tax + "]"; } }
30.486111
130
0.634169
270b277325e8e02636ca6df12ad37c20527254db
1,803
package com.hebaiyi.www.topviewmusic.bean; import com.google.gson.annotations.SerializedName; public class Channel { @SerializedName("name") private String name; @SerializedName("channelid") private int channelId; @SerializedName("thumb") private String picture; @SerializedName("ch_name") private String channelName; @SerializedName("value") private int value; @SerializedName("cate_name") private String cateName; @SerializedName("cate_sname") private String cateSname; @SerializedName("listen_num") private int listenNum; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getChannelId() { return channelId; } public void setChannelId(int channelId) { this.channelId = channelId; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getCateName() { return cateName; } public void setCateName(String cateName) { this.cateName = cateName; } public String getCateSname() { return cateSname; } public void setCateSname(String cateSname) { this.cateSname = cateSname; } public int getListenNum() { return listenNum; } public void setListenNum(int listenNum) { this.listenNum = listenNum; } }
18.978947
52
0.627842
dc89038467921f759620569b9d82a7911d3cdb04
1,483
/* * Copyright 2014-present IVK JSC. 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.broker.libupmq.foreign; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageEOFException; import javax.jms.StreamMessage; import com.broker.libupmq.message.UPMQStreamMessage; class ForeignStreamMessageConverter extends AbstractMessageConverter { @Override protected Message create() throws JMSException { return new UPMQStreamMessage(null); } @Override protected void populate(Message source, Message target) throws JMSException { StreamMessage from = (StreamMessage) source; StreamMessage to = (StreamMessage) target; // populate header super.populate(from, to); // populate body from.reset(); // make sure the message can be read try { while (true) { Object object = from.readObject(); to.writeObject(object); } } catch (MessageEOFException ignore) { // all done } } }
27.981132
78
0.743763
0647ac34b7db59efc1ba3cde3d75199770ff3861
416
package com.dciets.androidutils.application; import android.app.Activity; /** * Created by marc_ on 2016-03-07. */ public class MyActivity extends Activity { @Override protected void onResume() { super.onResume(); MyApplication.setCurrentActivity(this); } @Override protected void onPause() { super.onPause(); MyApplication.setCurrentActivity(null); } }
18.909091
47
0.661058
cd5e26afc043fdec4410c0fc8511cd8c3ca7b319
159
package org.kingtec.utils.Base; /** * Created by Verizon on 16/03/2018. */ public interface OnGetString<T extends Object> { String getString(T p); }
13.25
48
0.685535
0e19d60ba6b43b42e88c8b8aa2d817591d3b5d7b
3,491
package com.woshidaniu.daointerface; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import com.woshidaniu.common.dao.BaseDao; import com.woshidaniu.entities.JsglModel; import com.woshidaniu.entities.YhglModel; /** * * * 类名称:JsglDao 类描述: 角色管理数据层接口 创建人:Administrator 创建时间:2012-4-1 下午03:53:08 * 修改人:Administrator 修改时间:2012-4-1 下午03:53:08 修改备注: * * @version * */ @Component("jsglDao") public interface IJsglDao extends BaseDao<JsglModel> { /** * *@描述:增加角色信息 *@创建人:kangzhidong *@创建时间:2014-10-15下午06:24:32 *@修改人: *@修改时间: *@修改描述: *@param model */ public void zjJsxx(JsglModel model); /** * *@描述:修改角色信息 *@创建人:kangzhidong *@创建时间:2014-10-15下午06:24:32 *@修改人: *@修改时间: *@修改描述: *@param model */ public void xgJsxx(JsglModel model); /** * *@描述:删除角色信息 *@创建人:kangzhidong *@创建时间:2014-10-15下午06:24:32 *@修改人: *@修改时间: *@修改描述: *@param model */ public void scJsxx(JsglModel model); /** * *@描述:保存角色分配用户信息 *@创建人:kangzhidong *@创建时间:2014-10-16上午09:26:13 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public void zjJsyhfpxx(JsglModel model); /** * *@描述:删除角色分配用户信息 *@创建人:kangzhidong *@创建时间:2014-10-16上午09:26:19 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public void scJsyhfpxx(JsglModel model); /** *@描述:查询管理员的角色树形显示结果结果数据 *@创建人:kangzhidong *@创建时间:2015-1-20下午07:25:57 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<JsglModel> getAdminTreeGridModelList(JsglModel model); /** *@描述:查询角色树形显示结果结果数据 *@创建人:kangzhidong *@创建时间:2015-1-20下午07:25:57 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<JsglModel> getTreeGridModelList(JsglModel model); /** * *@描述:根据角色代码查询角色名称 *@创建人:kangzhidong *@创建时间:2015-1-9下午06:13:28 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public JsglModel cxJsmcByJsdm(JsglModel model); /** * *@描述:根据用户代码查询角色信息集合 *@创建人:kangzhidong *@创建时间:2015-1-9下午06:13:14 *@修改人: *@修改时间: *@修改描述: *@param yhm *@return */ public List<JsglModel> cxJsxxListByYhm(@Param("yhm")String yhm); /** * *@描述:根据操作人ID,用户代码查询获得当前操作人的角色集合与被操作人的角色集合的交集 *@创建人:kangzhidong *@创建时间:2015-1-9下午06:30:35 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<JsglModel> cxKczjsxxList(YhglModel model); /** * * @description: 查询指定角色的子角色信息列表 * @author : kangzhidong * @date : 2014-4-4 * @time : 上午09:17:08 * @param model * @return */ public List<JsglModel> cxSubJsxxList(JsglModel model); /** * *@描述:根据角色代码分页查询该角色未分配用户信息;并受到数据范围控制 *@创建人:kangzhidong *@创建时间:2015-1-15上午09:27:33 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<YhglModel> getPagedListWfpYhByScope(JsglModel model); /** * *@描述:根据角色代码分页查询该角色已分配用户信息;并受到数据范围控制 *@创建人:kangzhidong *@创建时间:2015-1-15上午09:26:43 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<YhglModel> getPagedListYfpYhByScope(JsglModel model); /** * *@描述:查询所有一级功能模块列表:增加,修改用户需要用到 *@创建人:kangzhidong *@创建时间:2015-1-15上午09:48:17 *@修改人: *@修改时间: *@修改描述: *@param model *@return */ public List<JsglModel> getGnmkYj(JsglModel model); /** * *@描述:根据角色代码查询角色是否具有二级授权功能; *@创建人:kangzhidong *@创建时间:2015-1-15上午09:48:39 *@修改人: *@修改时间: *@修改描述: *@param yhm *@return */ public String getYhEjsq(@Param(value="jsdm")String jsdm); }
16.162037
72
0.634775
ab26b4bb062bedfd00c42618e78d717b88343879
787
package com.jeiker.zk.demo; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Description: spring-boot-zk * User: jeikerxiao * Date: 2019/6/19 10:26 AM */ public class TestCountDownLatch { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(3); Worker w1 = new Worker(latch, "工人1"); Worker w2 = new Worker(latch, "工人2"); Worker w3 = new Worker(latch, "工人3"); Boss boss = new Boss(latch); executor.execute(w3); executor.execute(w2); executor.execute(w1); executor.execute(boss); executor.shutdown(); } }
23.147059
67
0.653113
2fa657c2ccf8cf9d9d90ea10919c2fba7e01a465
6,965
package no.sanchezrolfsen.framework.selenium; import lombok.extern.slf4j.Slf4j; import no.sanchezrolfsen.framework.selenium.config.BrowserConfig; import no.sanchezrolfsen.framework.selenium.config.BrowserType; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.InvalidArgumentException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.net.MalformedURLException; import java.net.URL; import java.security.InvalidParameterException; import java.time.Duration; import java.util.concurrent.TimeUnit; import static java.lang.String.format; @Slf4j public class Browser { public static final int DEFAULT_IMPLICIT_WAIT = 0; public static final int DEFAULT_SCRIPT_TIMEOUT = 8; public static final int DEFAULT_WAIT_TIMEOUT = 15; public static long globalWaitTimeout; private static boolean useRemoteDriver = false; private static WebDriver driver; private static JavascriptExecutor jsExecutor; private static WebDriverWait standardWait; private Browser() { } /** * Method to initialize the browser driver */ public static void init(BrowserConfig browserConfig) throws MalformedURLException { String seleniumGridUrl = browserConfig.getSeleniumGridAddress(); if (StringUtils.isNotBlank(seleniumGridUrl)) { for (int i = 0; i <= 5; i++) { try { createExternalBrowser(browserConfig.getBrowserType(), new URL(seleniumGridUrl)); break; } catch (org.openqa.selenium.remote.UnreachableBrowserException unreachableBrowserException) { log.debug(String.format("Didn't manage to start browser against %s on try nr %s. Waiting 10 s", seleniumGridUrl, i)); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } } else { createLocalBrowser(browserConfig.getBrowserType()); } setBrowserTimeouts(DEFAULT_SCRIPT_TIMEOUT, DEFAULT_IMPLICIT_WAIT, DEFAULT_WAIT_TIMEOUT); } /** * Method to create a local browser */ private static void createLocalBrowser(BrowserType browser) { switch (browser) { case CHROME -> { final ChromeOptions chromeOptions = new ChromeOptions(); driver = new ChromeDriver(chromeOptions); log.debug("Chrome selected as the desired browser."); } case CHROME_HEADLESS -> { final ChromeOptions chromeOptions2 = new ChromeOptions(); chromeOptions2.setHeadless(true); driver = new ChromeDriver(chromeOptions2); log.debug("Chrome Headless selected as the desired browser."); } case FIREFOX -> { driver = new FirefoxDriver(); log.debug("Firefox selected as the desired browser."); } case FIREFOX_HEADLESS -> { FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setHeadless(true); driver = new FirefoxDriver(firefoxOptions); log.debug("Firefox Headless selected as the desired browser."); } default -> throw new InvalidArgumentException(format("Browser '%s' is not implemented on the framework", browser.name())); } } /** * Method to create external browser (grid) */ private static void createExternalBrowser(BrowserType browser, URL seleniumGridUrl) { useRemoteDriver = true; RemoteWebDriver remoteWebDriver; switch (browser) { case CHROME -> { final ChromeOptions chromeOptions = new ChromeOptions(); remoteWebDriver = new RemoteWebDriver(seleniumGridUrl, chromeOptions); log.debug("Remote (Chrome) selected as the desired browser."); } case FIREFOX -> { remoteWebDriver = new RemoteWebDriver(seleniumGridUrl, new FirefoxOptions()); log.debug("Remote (Firefox) selected as the desired browser."); } default -> throw new InvalidParameterException(format("Browser %s for selenium grid is not implemented on the framework", browser.name())); } remoteWebDriver.setFileDetector(new LocalFileDetector()); // For uploading of files from local-path driver = remoteWebDriver; } /** * Method to set up browser timeouts */ public static void setBrowserTimeouts(int scriptTimeout, int implicitWait, int waitTimeout) { if (driver == null) { throw new NullPointerException("Browser.init() must be run before one can call the driver-instance"); } driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(scriptTimeout)); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(implicitWait)); globalWaitTimeout = waitTimeout; standardWait = new WebDriverWait(driver, Duration.ofSeconds(waitTimeout)); } /** * Method that returns WebDriver, to call this method Browser.init() must be run first */ public static WebDriver vanillaDriver() { if (driver == null) { throw new NullPointerException("Browser.init() must be run before one can call the driver-instance"); } return driver; } /** * Method to run javascript on browser when running tests */ public static JavascriptExecutor jsExecutor() { if (jsExecutor == null) { WebDriver jsDriver = vanillaDriver(); jsExecutor = (JavascriptExecutor) jsDriver; } return jsExecutor; } /** * Pause method, it waits by default 'waitTimeout' setup on method setBrowserTimeouts() */ public static WebDriverWait pause() { if (standardWait == null) { throw new NullPointerException("StandardWait is not set"); } return standardWait; } /** * Pause method a number of seconds */ public static WebDriverWait pause(long timeOutInSeconds) { return new WebDriverWait(vanillaDriver(), Duration.ofSeconds(timeOutInSeconds)); } /** * Method to check if the test are running remotely */ public static boolean isRemoteDriver() { return useRemoteDriver; } }
38.910615
151
0.646662
799563bdfa8b74dc1263b842be0938bf0cfce81b
3,806
package net.opendatadev.odensample; import android.content.res.Resources; import android.support.annotation.NonNull; import com.google.gson.Gson; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; public final class Manifest { private Manifest() { } public static ManifestEntry[] getManifestEntries(final int resourceId, @NonNull final Resources resources) throws IOException { final Gson gson; final InputStream resourceStream; gson = new Gson(); resourceStream = resources.openRawResource(resourceId); try(final Reader reader = new InputStreamReader(resourceStream)) { final ManifestEntry[] entries; entries = gson.fromJson(reader, ManifestEntry[].class); return (entries); } } public static ManifestEntry getManifestEntry(@NonNull final String id, @NonNull final String fileName) { throw new IllegalStateException("getManifestEntry"); } @NonNull public static File getLocalFolderFor(@NonNull final ManifestEntry entry, @NonNull final File rootFolder) { // Public Art/CA File folder; final String datasetName; final String countryName; datasetName = entry.getDatasetName(); countryName = entry.getCountry(); folder = new File(rootFolder, datasetName); if(countryName != null) { final String province; folder = new File(folder, countryName); province = entry.getProvince(); if(province != null) { final String region; final String city; // Public Art/CA/BC folder = new File(folder, province); region = entry.getRegion(); if(region != null) { // Public Art/CA/BC/Metro Vancouver folder = new File(folder, region); } city = entry.getCity(); // a city doesn't have to be in a region if(city != null) { // Public Art/CA/BC/Metro Vancouver/New Westminster // or Public Art/CA/BC/Lund folder = new File(folder, city); } } } return folder; } @NonNull public static File getLocalDatasetFileFor(@NonNull final ManifestEntry entry, @NonNull final File rootFolder) { final File localFolderFolder; final File providerFile; final String provider; localFolderFolder = getLocalFolderFor(entry, rootFolder); provider = entry.getProvider(); providerFile = new File(localFolderFolder, provider + ".json"); return (providerFile); } @NonNull public static File[] getLocalDatasetFilesFor(@NonNull final ManifestEntry[] entries, @NonNull final File rootFolder) { final List<File> datasetFilesList; final int fileCount; datasetFilesList = new ArrayList<>(); for(final ManifestEntry entry : entries) { final File providerDatasetFile; providerDatasetFile = getLocalDatasetFileFor(entry, rootFolder); datasetFilesList.add(providerDatasetFile); } fileCount = datasetFilesList.size(); return datasetFilesList.toArray(new File[fileCount]); } }
27.185714
120
0.56805
a31c663dfcd5ecbf620b8991caac190e01f6fed9
23,977
/* * 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.brooklyn.util.core.task; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import javax.annotation.Nullable; import org.apache.brooklyn.api.mgmt.ExecutionContext; import org.apache.brooklyn.api.mgmt.HasTaskChildren; import org.apache.brooklyn.api.mgmt.Task; import org.apache.brooklyn.api.mgmt.TaskAdaptable; import org.apache.brooklyn.api.mgmt.TaskFactory; import org.apache.brooklyn.api.mgmt.TaskQueueingContext; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.entity.Dumper; import org.apache.brooklyn.util.core.config.ConfigBag; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.exceptions.ReferenceWithError; import org.apache.brooklyn.util.repeat.Repeater; import org.apache.brooklyn.util.time.CountdownTimer; import org.apache.brooklyn.util.time.Duration; import org.apache.brooklyn.util.time.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; public class Tasks { private static final Logger log = LoggerFactory.getLogger(Tasks.class); /** convenience for setting "blocking details" on any task where the current thread is running; * typically invoked prior to a wait, for transparency to a user; * then invoked with 'null' just after the wait */ public static String setBlockingDetails(String description) { Task<?> current = current(); if (current instanceof TaskInternal) return ((TaskInternal<?>)current).setBlockingDetails(description); return null; } public static void resetBlockingDetails() { Task<?> current = current(); if (current instanceof TaskInternal) ((TaskInternal<?>)current).resetBlockingDetails(); } public static Task<?> setBlockingTask(Task<?> blocker) { Task<?> current = current(); if (current instanceof TaskInternal) return ((TaskInternal<?>)current).setBlockingTask(blocker); return null; } public static void resetBlockingTask() { Task<?> current = current(); if (current instanceof TaskInternal) ((TaskInternal<?>)current).resetBlockingTask(); } public static <T> Task<T> create(String name, Callable<T> job) { return Tasks.<T>builder().displayName(name).body(job).build(); } public static <T> Task<T> create(String name, Runnable job) { return Tasks.<T>builder().displayName(name).body(job).build(); } /** convenience for setting "blocking details" on any task where the current thread is running, * while the passed code is executed; often used from groovy as * <pre>{@code withBlockingDetails("sleeping 5s") { Thread.sleep(5000); } }</pre> * If code block is null, the description is set until further notice (not cleareed). */ @SuppressWarnings("rawtypes") public static <T> T withBlockingDetails(String description, Callable<T> code) throws Exception { Task current = current(); if (code==null) { log.warn("legacy invocation of withBlockingDetails with null code block, ignoring"); return null; } String prevBlockingDetails = null; if (current instanceof TaskInternal) { prevBlockingDetails = ((TaskInternal)current).setBlockingDetails(description); } try { return code.call(); } finally { if (current instanceof TaskInternal) ((TaskInternal)current).setBlockingDetails(prevBlockingDetails); } } /** the {@link Task} where the current thread is executing, if executing in a Task, otherwise null; * if the current task is a proxy, this returns the target of that proxy */ @SuppressWarnings("rawtypes") public static Task current() { return getFinalProxyTarget(BasicExecutionManager.getPerThreadCurrentTask().get()); } public static Task<?> getFinalProxyTarget(Task<?> task) { if (task==null) return null; Task<?> proxy = ((TaskInternal<?>)task).getProxyTarget(); if (proxy==null || proxy.equals(task)) return task; return getFinalProxyTarget(proxy); } /** creates a {@link ValueResolver} instance which allows significantly more customization than * the various {@link #resolveValue(Object, Class, ExecutionContext)} methods here */ public static <T> ValueResolver<T> resolving(Object v, Class<T> type) { return new ValueResolver<T>(v, type); } public static ValueResolver.ResolverBuilderPretype resolving(Object v) { return new ValueResolver.ResolverBuilderPretype(v); } @SuppressWarnings("unchecked") public static <T> ValueResolver<T> resolving(ConfigBag config, ConfigKey<T> key) { return new ValueResolver.ResolverBuilderPretype(config.getStringKey(key.getName())).as((Class<T>)key.getType()); } /** @see #resolveValue(Object, Class, ExecutionContext, String) */ public static <T> T resolveValue(Object v, Class<T> type, @Nullable ExecutionContext exec) throws ExecutionException, InterruptedException { return new ValueResolver<T>(v, type).context(exec).get(); } /** attempt to resolve the given value as the given type, waiting on futures, submitting if necessary, * and coercing as allowed by TypeCoercions; * contextMessage (optional) will be displayed in status reports while it waits (e.g. the name of the config key being looked up). * if no execution context supplied (null) this method will throw an exception if the object is an unsubmitted task */ public static <T> T resolveValue(Object v, Class<T> type, @Nullable ExecutionContext exec, String contextMessage) throws ExecutionException, InterruptedException { return new ValueResolver<T>(v, type).context(exec).description(contextMessage).get(); } /** * @see #resolveDeepValue(Object, Class, ExecutionContext, String) */ public static Object resolveDeepValue(Object v, Class<?> type, ExecutionContext exec) throws ExecutionException, InterruptedException { return resolveDeepValue(v, type, exec, null); } /** * Resolves the given object, blocking on futures and coercing it to the given type. If the object is a * map or iterable (or a list of map of maps, etc, etc) then walks these maps/iterables to convert all of * their values to the given type. For example, the following will return a list containing a map with "1"="true": * * {@code Object result = resolveDeepValue(ImmutableList.of(ImmutableMap.of(1, true)), String.class, exec)} * * To perform a deep conversion of futures contained within Iterables or Maps without coercion of each element, * the type should normally be Object, not the type of the collection. This differs from * {@link #resolveValue(Object, Class, ExecutionContext, String)} which will accept Map and Iterable * as the required type. */ public static <T> T resolveDeepValue(Object v, Class<T> type, ExecutionContext exec, String contextMessage) throws ExecutionException, InterruptedException { return new ValueResolver<T>(v, type).context(exec).deep(true).description(contextMessage).get(); } /** sets extra status details on the current task, if possible (otherwise does nothing). * the extra status is presented in Task.getStatusDetails(true) */ public static void setExtraStatusDetails(String notes) { Task<?> current = current(); if (current instanceof TaskInternal) ((TaskInternal<?>)current).setExtraStatusText(notes); } public static <T> TaskBuilder<T> builder() { return TaskBuilder.<T>builder(); } private static Task<?>[] asTasks(TaskAdaptable<?> ...tasks) { Task<?>[] result = new Task<?>[tasks.length]; for (int i=0; i<tasks.length; i++) result[i] = tasks[i].asTask(); return result; } public static Task<List<?>> parallel(TaskAdaptable<?> ...tasks) { return parallelInternal("parallelised tasks", asTasks(tasks)); } public static Task<List<?>> parallel(String name, TaskAdaptable<?> ...tasks) { return parallelInternal(name, asTasks(tasks)); } public static Task<List<?>> parallel(Iterable<? extends TaskAdaptable<?>> tasks) { return parallel(asTasks(Iterables.toArray(tasks, TaskAdaptable.class))); } public static Task<List<?>> parallel(String name, Iterable<? extends TaskAdaptable<?>> tasks) { return parallelInternal(name, asTasks(Iterables.toArray(tasks, TaskAdaptable.class))); } private static Task<List<?>> parallelInternal(String name, Task<?>[] tasks) { return Tasks.<List<?>>builder().displayName(name).parallel(true).add(tasks).build(); } public static Task<List<?>> sequential(TaskAdaptable<?> ...tasks) { return sequentialInternal("sequential tasks", asTasks(tasks)); } public static Task<List<?>> sequential(String name, TaskAdaptable<?> ...tasks) { return sequentialInternal(name, asTasks(tasks)); } public static TaskFactory<?> sequential(TaskFactory<?> ...taskFactories) { return sequentialInternal("sequential tasks", taskFactories); } public static TaskFactory<?> sequential(String name, TaskFactory<?> ...taskFactories) { return sequentialInternal(name, taskFactories); } public static Task<List<?>> sequential(List<? extends TaskAdaptable<?>> tasks) { return sequential(asTasks(Iterables.toArray(tasks, TaskAdaptable.class))); } public static Task<List<?>> sequential(String name, List<? extends TaskAdaptable<?>> tasks) { return sequential(name, asTasks(Iterables.toArray(tasks, TaskAdaptable.class))); } private static Task<List<?>> sequentialInternal(String name, Task<?>[] tasks) { return Tasks.<List<?>>builder().displayName(name).dynamic(false).parallel(false).add(tasks).build(); } private static TaskFactory<?> sequentialInternal(final String name, final TaskFactory<?> ...taskFactories) { return new TaskFactory<TaskAdaptable<?>>() { @Override public TaskAdaptable<?> newTask() { TaskBuilder<List<?>> tb = Tasks.<List<?>>builder().displayName(name).parallel(false); for (TaskFactory<?> tf: taskFactories) tb.add(tf.newTask().asTask()); return tb.build(); } }; } /** returns the first tag found on the given task which matches the given type, looking up the submission hierarachy if necessary */ @SuppressWarnings("unchecked") public static <T> T tag(@Nullable Task<?> task, Class<T> type, boolean recurseHierarchy) { // support null task to make it easier for callers to walk hierarchies if (task==null) return null; for (Object tag: TaskTags.getTagsFast(task)) if (type.isInstance(tag)) return (T)tag; if (!recurseHierarchy) return null; return tag(task.getSubmittedByTask(), type, true); } public static boolean isAncestorCancelled(Task<?> t) { if (t==null) return false; if (t.isCancelled()) return true; return isAncestorCancelled(t.getSubmittedByTask()); } public static boolean isQueued(TaskAdaptable<?> task) { return ((TaskInternal<?>)task.asTask()).isQueued(); } public static boolean isSubmitted(TaskAdaptable<?> task) { return ((TaskInternal<?>)task.asTask()).isSubmitted(); } public static boolean isQueuedOrSubmitted(TaskAdaptable<?> task) { return ((TaskInternal<?>)task.asTask()).isQueuedOrSubmitted(); } /** * Adds the given task to the given context. Does not throw an exception if the addition fails or would fail. * @return true if the task was added, false otherwise including if context is null or thread is interrupted. */ public static boolean tryQueueing(TaskQueueingContext adder, TaskAdaptable<?> task) { if (task==null || adder==null || isQueued(task) || Thread.currentThread().isInterrupted()) return false; try { adder.queue(task.asTask()); return true; } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Could not add task "+task+" at "+adder+": "+e); return false; } } /** see also {@link #resolving(Object)} which gives much more control about submission, timeout, etc */ public static <T> Supplier<T> supplier(final TaskAdaptable<T> task) { return new Supplier<T>() { @Override public T get() { return task.asTask().getUnchecked(); } }; } /** return all children tasks of the given tasks, if it has children, else empty list */ public static Iterable<Task<?>> children(Task<?> task) { if (task instanceof HasTaskChildren) return ((HasTaskChildren)task).getChildren(); return Collections.emptyList(); } /** returns failed tasks */ public static Iterable<Task<?>> failed(Iterable<Task<?>> subtasks) { return Iterables.filter(subtasks, new Predicate<Task<?>>() { @Override public boolean apply(Task<?> input) { return input.isError(); } }); } /** returns the task, its children, and all its children, and so on; * @param root task whose descendants should be iterated * @param parentFirst whether to put parents before children or after */ public static Iterable<Task<?>> descendants(Task<?> root, final boolean parentFirst) { Iterable<Task<?>> descs = Iterables.concat(Iterables.transform(Tasks.children(root), new Function<Task<?>,Iterable<Task<?>>>() { @Override public Iterable<Task<?>> apply(Task<?> input) { return descendants(input, parentFirst); } })); if (parentFirst) return Iterables.concat(Collections.singleton(root), descs); else return Iterables.concat(descs, Collections.singleton(root)); } /** returns the error thrown by the task if {@link Task#isError()}, or null if no error or not done */ public static Throwable getError(Task<?> t) { if (t==null) return null; if (!t.isDone()) return null; if (t.isCancelled()) return new CancellationException(); try { t.get(); return null; } catch (Throwable error) { // do not propagate as we are pretty much guaranteed above that it wasn't this // thread which originally threw the error return error; } } public static Task<Void> fail(final String name, final Throwable optionalError) { return Tasks.<Void>builder().dynamic(false).displayName(name).body(new Runnable() { @Override public void run() { if (optionalError!=null) throw Exceptions.propagate(optionalError); else throw new RuntimeException("Failed: "+name); } }).build(); } public static Task<Void> warning(final String message, final Throwable optionalError) { log.warn(message); return TaskTags.markInessential(fail(message, optionalError)); } /** marks the current task inessential; this mainly matters if the task is running in a parent * {@link TaskQueueingContext} and we don't want the parent to fail if this task fails * <p> * no-op (silently ignored) if not in a task */ public static void markInessential() { Task<?> task = Tasks.current(); if (task==null) { TaskQueueingContext qc = DynamicTasks.getTaskQueuingContext(); if (qc!=null) task = qc.asTask(); } if (task!=null) { TaskTags.markInessential(task); } } /** causes failures in subtasks of the current task not to fail the parent; * no-op if not in a {@link TaskQueueingContext}. * <p> * essentially like a {@link #markInessential()} on all tasks in the current * {@link TaskQueueingContext}, including tasks queued subsequently */ @Beta public static void swallowChildrenFailures() { Preconditions.checkNotNull(DynamicTasks.getTaskQueuingContext(), "Task queueing context required here"); TaskQueueingContext qc = DynamicTasks.getTaskQueuingContext(); if (qc!=null) { qc.swallowChildrenFailures(); } } /** as {@link TaskTags#addTagDynamically(TaskAdaptable, Object)} but for current task, skipping if no current task */ public static void addTagDynamically(Object tag) { Task<?> t = Tasks.current(); if (t!=null) TaskTags.addTagDynamically(t, tag); } /** * Workaround for limitation described at {@link Task#cancel(boolean)}; * internal method used to allow callers to wait for underlying tasks to finished in the case of cancellation. * <p> * It is irritating that {@link FutureTask} sync's object clears the runner thread, * so even if {@link BasicTask#getInternalFuture()} is used, there is no means of determining if the underlying object is done. * The {@link Task#getEndTimeUtc()} seems the only way. * * @return true if tasks ended; false if timed out **/ @Beta public static boolean blockUntilInternalTasksEnded(Task<?> t, Duration timeout) { CountdownTimer timer = timeout.countdownTimer(); if (t==null) return true; if (t instanceof ScheduledTask) { boolean result = ((ScheduledTask)t).blockUntilNextRunFinished(timer.getDurationRemaining()); if (!result) return false; } t.blockUntilEnded(timer.getDurationRemaining()); while (true) { if (t.getEndTimeUtc()>=0) return true; // above should be sufficient; but just in case, trying the below Thread tt = t.getThread(); if (t instanceof ScheduledTask) { ((ScheduledTask)t).blockUntilNextRunFinished(timer.getDurationRemaining()); return true; } else { if (tt==null || !tt.isAlive()) { if (!t.isCancelled()) { // may happen for a cancelled task, interrupted after submit but before start log.warn("Internal task thread is dead or null ("+tt+") but task not ended: "+t.getEndTimeUtc()+" ("+t+")"); } return true; } } if (timer.isExpired()) return false; Time.sleep(Repeater.DEFAULT_REAL_QUICK_PERIOD); } } /** returns true if either the current thread or the current task is interrupted/cancelled */ public static boolean isInterrupted() { if (Thread.currentThread().isInterrupted()) return true; Task<?> t = current(); if (t==null) return false; return t.isCancelled(); } private static class WaitForRepeaterCallable implements Callable<Boolean> { protected Repeater repeater; protected boolean requireTrue; public WaitForRepeaterCallable(Repeater repeater, boolean requireTrue) { this.repeater = repeater; this.requireTrue = requireTrue; } @Override public Boolean call() { ReferenceWithError<Boolean> result; Tasks.setBlockingDetails(repeater.getDescription()); try { result = repeater.runKeepingError(); } finally { Tasks.resetBlockingDetails(); } if (Boolean.TRUE.equals(result.getWithoutError())) return true; if (result.hasError()) throw Exceptions.propagate(result.getError()); if (requireTrue) throw new IllegalStateException("timeout - "+repeater.getDescription()); return false; } } /** @return a {@link TaskBuilder} which tests whether the repeater terminates with success in its configured timeframe, * returning true or false depending on whether repeater succeed */ public static TaskBuilder<Boolean> testing(Repeater repeater) { return Tasks.<Boolean>builder().body(new WaitForRepeaterCallable(repeater, false)) .displayName("waiting for condition") .description("Testing whether " + getTimeoutString(repeater) + ": "+repeater.getDescription()); } /** @return a {@link TaskBuilder} which requires that the repeater terminate with success in its configured timeframe, * throwing if it does not */ public static TaskBuilder<?> requiring(Repeater repeater) { return Tasks.<Boolean>builder().body(new WaitForRepeaterCallable(repeater, true)) .displayName("waiting for condition") .description("Requiring " + getTimeoutString(repeater) + ": " + repeater.getDescription()); } private static String getTimeoutString(Repeater repeater) { Duration timeout = repeater.getTimeLimit(); if (timeout==null || Duration.PRACTICALLY_FOREVER.equals(timeout)) return "eventually"; return "in "+timeout; } /** * @deprecated since 1.0.0; instead use {@link Dumper} methods */ @Deprecated public static void dumpInfo(Task<?> t) { Dumper.dumpInfo(t); } /** * @deprecated since 1.0.0; instead use {@link Dumper} methods */ @Deprecated public static void dumpInfo(Task<?> t, Writer out) throws IOException { Dumper.dumpInfo(t, out); } /** * @deprecated since 1.0.0; instead use {@link Dumper} methods */ @Deprecated public static void dumpInfo(Task<?> t, String currentIndentation, String tab) throws IOException { dumpInfo(t, new PrintWriter(System.out), currentIndentation, tab); } /** * @deprecated since 1.0.0; instead use {@link Dumper} methods */ @Deprecated public static void dumpInfo(Task<?> t, Writer out, String currentIndentation, String tab) throws IOException { out.append(currentIndentation+t+": "+t.getStatusDetail(false)+"\n"); if (t instanceof HasTaskChildren) { for (Task<?> child: ((HasTaskChildren)t).getChildren()) { dumpInfo(child, out, currentIndentation+tab, tab); } } out.flush(); } }
43.994495
167
0.652751
3673b948705461d50fe4e3ecc2732f9b944c9a90
4,445
/* * Copyright (C) 2017-2020 Samuel Audet * * Licensed either under the Apache License, Version 2.0, or (at your option) * under the terms of the GNU General Public License as published by * the Free Software Foundation (subject to the "Classpath" exception), * either version 2, or any later version (collectively, 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 * http://www.gnu.org/licenses/ * http://www.gnu.org/software/classpath/license.html * * or as provided in the LICENSE.txt file that accompanied this code. * 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.bytedeco.ale.presets; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.annotation.Platform; import org.bytedeco.javacpp.annotation.Properties; import org.bytedeco.javacpp.presets.javacpp; import org.bytedeco.javacpp.tools.Info; import org.bytedeco.javacpp.tools.InfoMap; import org.bytedeco.javacpp.tools.InfoMapper; /** * * @author Samuel Audet */ @Properties(inherit = javacpp.class, value = { @Platform(value = {"linux-x86", "macosx", "windows"}, compiler = "cpp11", define = "UNIQUE_PTR_NAMESPACE std", link = "ale", include = {"emucore/m6502/src/bspf/src/bspf.hxx", "emucore/m6502/src/Device.hxx", "emucore/Control.hxx", "emucore/Event.hxx", "emucore/Random.hxx", "common/Constants.h", "common/Array.hxx", "common/display_screen.h", "emucore/M6532.hxx", "emucore/Cart.hxx", "emucore/Console.hxx", "emucore/Sound.hxx", "emucore/Settings.hxx", "emucore/OSystem.hxx", "common/ColourPalette.hpp", "common/ScreenExporter.hpp", "environment/ale_ram.hpp", "environment/ale_screen.hpp", "environment/ale_state.hpp", "environment/stella_environment_wrapper.hpp", "environment/stella_environment.hpp", "ale_interface.hpp"}), @Platform(value = "linux-x86", preload = "[email protected]", preloadpath = {"/usr/lib32/", "/usr/lib/"}), @Platform(value = "linux-x86_64", preload = "[email protected]", preloadpath = {"/usr/lib64/", "/usr/lib/"}), @Platform(value = "macosx-x86_64", preload = "[email protected]", preloadpath = "/usr/local/lib/"), @Platform(value = "windows-x86", preload = {"SDL", "libale"}, preloadpath = "/mingw32/bin/"), @Platform(value = "windows-x86_64", preload = {"SDL", "libale"}, preloadpath = "/mingw64/bin")}, target = "org.bytedeco.ale", global = "org.bytedeco.ale.global.ale") public class ale implements InfoMapper { static { Loader.checkVersion("org.bytedeco", "ale"); } public void map(InfoMap infoMap) { infoMap.put(new Info("DEBUGGER_SUPPORT", "CHEATCODE_SUPPORT").define(false)) .put(new Info("BSPF_strcasecmp", "BSPF_strncasecmp", "BSPF_snprintf", "BSPF_vsnprintf").cppTypes()) .put(new Info("Common::Array<Resolution>").pointerTypes("ResolutionList").define()) .put(new Info("StellaEnvironmentWrapper::m_environment").javaText("public native @MemberGetter @ByRef StellaEnvironment m_environment();")) .put(new Info("StellaEnvironment::getWrapper").javaText("public native @Name(\"getWrapper().get\") StellaEnvironmentWrapper getWrapper();")) .put(new Info("ALEInterface::theOSystem").javaText("public native @Name(\"theOSystem.get\") OSystem theOSystem();")) .put(new Info("ALEInterface::theSettings").javaText("public native @Name(\"theSettings.get\") Settings theSettings();")) .put(new Info("ALEInterface::romSettings").javaText("public native @Name(\"romSettings.get\") RomSettings romSettings();")) .put(new Info("ALEInterface::environment").javaText("public native @Name(\"environment.get\") StellaEnvironment environment();")) .put(new Info("AtariVox", "Common::Array<Resolution>::contains", "ALEState::reset", "CheatManager", "CommandMenu", "Debugger", "GameController", "Launcher", "Menu", "Properties", "PropertiesSet", "VideoDialog").skip()); } }
65.367647
158
0.677165
375a717dec80d7684854b206c1bbf80c35039186
1,263
package jkanvas.examples; import java.io.IOException; import jkanvas.Canvas; import jkanvas.CanvasSetup; import jkanvas.animation.AnimatedPainter; import jkanvas.io.json.JSONElement; import jkanvas.io.json.JSONReader; import jkanvas.painter.SimpleTextHUD; import jkanvas.present.DefaultSlideMetrics; import jkanvas.present.Presentation; import jkanvas.present.SlideMetrics; import jkanvas.util.Resource; /** * A short example showing the presentation capabilities of Kanvas. * * @author Joschi <[email protected]> */ public final class PresentationMain { /** * Starts the example application. * * @param args No arguments. * @throws IOException I/O Exception. */ public static void main(final String[] args) throws IOException { final AnimatedPainter p = new AnimatedPainter(); final Canvas c = new Canvas(p, true, 1024, 768); final SimpleTextHUD info = CanvasSetup.setupCanvas("Presentation", c, p, true, true, true, false); final JSONElement el = new JSONReader(new Resource("test.json").reader()).get(); final SlideMetrics m = new DefaultSlideMetrics(); final Presentation present = Presentation.fromJSON(c, info, el, m); p.addPass(present); present.setPresentationMode(true); } }
28.704545
84
0.738717
ee06df626400bf4aa39633efacd60a8ad1a8358e
4,594
package net.varanus.sdncontroller.linkstats.sample; import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.Optional; import javax.annotation.ParametersAreNonnullByDefault; import javax.annotation.concurrent.Immutable; import net.varanus.mirroringprotocol.util.TimedPacketSummary; import net.varanus.sdncontroller.types.DatapathLink; import net.varanus.util.annotation.FieldsAreNonnullByDefault; import net.varanus.util.annotation.ReturnValuesAreNonnullByDefault; import net.varanus.util.functional.Possible; import net.varanus.util.lang.Comparables; import net.varanus.util.lang.MoreObjects; import net.varanus.util.openflow.types.BitMatch; import net.varanus.util.time.Timed; /** * */ @Immutable @FieldsAreNonnullByDefault @ParametersAreNonnullByDefault @ReturnValuesAreNonnullByDefault public final class SecureProbingSample implements LinkSampleBase<DatapathLink> { public static SecureProbingSample of( BitMatch bitMatch, DatapathLink link, Duration collDuration, Timed<Possible<TimedPacketSummary>> srcSumm, Timed<Possible<TimedPacketSummary>> destSumm ) { Instant collFinishTime = Comparables.max(srcSumm.timestamp(), destSumm.timestamp()); return of(bitMatch, link, collDuration, collFinishTime, srcSumm.value(), destSumm.value()); } public static SecureProbingSample of( BitMatch bitMatch, DatapathLink link, Duration collDuration, Instant collFinishTime, Possible<TimedPacketSummary> srcSumm, Possible<TimedPacketSummary> destSumm ) { MoreObjects.requireNonNull( bitMatch, "bitMatch", link, "link", collDuration, "collDuration", srcSumm, "srcSumm", destSumm, "destSumm"); return new SecureProbingSample(link, Optional.of(new Results( bitMatch, collDuration, collFinishTime, srcSumm, destSumm))); } public static SecureProbingSample noResults( DatapathLink link ) { Objects.requireNonNull(link); return new SecureProbingSample(link, Optional.empty()); } private final DatapathLink link; private final Optional<Results> results; private SecureProbingSample( DatapathLink link, Optional<Results> results ) { this.link = link; this.results = results; } @Override public DatapathLink getLink() { return link; } @Override public boolean hasResults() { return results.isPresent(); } public BitMatch getBitMatch() { return results.orElseThrow(SecureProbingSample::noResultsEx).bitMatch; } public Duration getCollectDuration() { return results.orElseThrow(SecureProbingSample::noResultsEx).collDuration; } public Instant getCollectFinishingTime() { return results.orElseThrow(SecureProbingSample::noResultsEx).collFinishTime; } public Possible<TimedPacketSummary> getSourceSummary() { return results.orElseThrow(SecureProbingSample::noResultsEx).srcSumm; } public Possible<TimedPacketSummary> getDestinationSummary() { return results.orElseThrow(SecureProbingSample::noResultsEx).destSumm; } private static UnsupportedOperationException noResultsEx() { return new UnsupportedOperationException("sample has no results"); } @Immutable @FieldsAreNonnullByDefault @ParametersAreNonnullByDefault private static final class Results { final BitMatch bitMatch; final Duration collDuration; final Instant collFinishTime; final Possible<TimedPacketSummary> srcSumm; final Possible<TimedPacketSummary> destSumm; Results( BitMatch bitMatch, Duration collDuration, Instant collFinishTime, Possible<TimedPacketSummary> srcSumm, Possible<TimedPacketSummary> destSumm ) { this.bitMatch = bitMatch; this.collDuration = collDuration; this.collFinishTime = collFinishTime; this.srcSumm = srcSumm; this.destSumm = destSumm; } } }
32.58156
99
0.642142
b658808ead4d2d20a7dc0a85c53035d41a7ef329
4,595
package org.eop.cassandra.json; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonStructure; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec; import static com.datastax.driver.core.querybuilder.QueryBuilder.*; /** * @author lixinjie * @since 2017-05-26 */ public class Jsr353JsonColumn { static String[] CONTACT_POINTS = {"127.0.0.1"}; static int PORT = 9042; public static void main(String[] args) { Cluster cluster = null; try { // A codec to convert JSON payloads into JsonObject instances; // this codec is declared in the driver-extras module Jsr353JsonCodec userCodec = new Jsr353JsonCodec(); cluster = Cluster.builder() .addContactPoints(CONTACT_POINTS).withPort(PORT) .withCodecRegistry(new CodecRegistry().register(userCodec)) .build(); Session session = cluster.connect(); createSchema(session); insertJsonColumn(session); selectJsonColumn(session); } finally { if (cluster != null) cluster.close(); } } private static void createSchema(Session session) { session.execute("CREATE KEYSPACE IF NOT EXISTS examples " + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); session.execute("CREATE TABLE IF NOT EXISTS examples.json_jsr353_column(" + "id int PRIMARY KEY, json text)"); } // Mapping a JSON object to a table column private static void insertJsonColumn(Session session) { JsonObject alice = Json.createObjectBuilder() .add("name", "alice") .add("age", 30) .build(); JsonObject bob = Json.createObjectBuilder() .add("name", "bob") .add("age", 35) .build(); // Build and execute a simple statement Statement stmt = insertInto("examples", "json_jsr353_column") .value("id", 1) // the JSON object will be converted into a String and persisted into the VARCHAR column "json" .value("json", alice); session.execute(stmt); // The JSON object can be a bound value if the statement is prepared // (we use a local variable here for the sake of example, but in a real application you would cache and reuse // the prepared statement) PreparedStatement pst = session.prepare( insertInto("examples", "json_jsr353_column") .value("id", bindMarker("id")) .value("json", bindMarker("json"))); session.execute(pst.bind() .setInt("id", 2) // note that the codec requires that the type passed to the set() method // be always JsonStructure, and not a subclass of it, such as JsonObject .set("json", bob, JsonStructure.class)); } // Retrieving JSON objects from a table column private static void selectJsonColumn(Session session) { Statement stmt = select() .from("examples", "json_jsr353_column") .where(in("id", 1, 2)); ResultSet rows = session.execute(stmt); for (Row row : rows) { int id = row.getInt("id"); // retrieve the JSON payload and convert it to a JsonObject instance // note that the codec requires that the type passed to the get() method // be always JsonStructure, and not a subclass of it, such as JsonObject, // hence the need to downcast to JsonObject manually JsonObject user = (JsonObject) row.get("json", JsonStructure.class); // it is also possible to retrieve the raw JSON payload String json = row.getString("json"); System.out.printf("Retrieved row:%n" + "id %d%n" + "user %s%n" + "user (raw) %s%n%n", id, user, json); } } }
39.612069
118
0.576061
11bccaf5444244f789d79f4aea46c98f59b00c56
874
package br.com.zupacademy.charles.proposta.criaCartaoAssociaProposta.carteiraDigital; import java.time.LocalDateTime; public class CarteiraDigitalResponse { private String id; private String email; private String associadaEm; private TipoCarteira emissor; public CarteiraDigitalResponse(String id, String email, String associadaEm, TipoCarteira emissor) { this.id = id; this.email = email; this.associadaEm = associadaEm; this.emissor = emissor; } public String getId() { return id; } public String getEmail() { return email; } public String getAssociadaEm() { return associadaEm; } public TipoCarteira getEmissor() { return emissor; } public CarteiraDigital toModel() { return new CarteiraDigital(this.id, this.email, LocalDateTime.parse(this.associadaEm), this.emissor); } }
28.193548
109
0.71167
0fbc300f821a53bccab3d3ceedd6d2cff0d00cb0
299
package com.github.opensharing.framework.springboot.view.freemarker.model; import lombok.AllArgsConstructor; import lombok.Data; /** * User * * @author jwen * Date 2020-09-17 */ @AllArgsConstructor @Data public class User { private int id; private String name; private int age; }
15.736842
74
0.722408
313008ec5c65f10272e7fc9704dbc3b659e37dd9
3,479
package cz.jcu.uai.javapract.mock.mock; import cz.jcu.uai.javapract.ITimetableDAO; import cz.jcu.uai.javapract.Subject; import cz.jcu.uai.javapract.TimeTable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * DAO mock TODO: smazat? * * Created by Drml on 4.7.2017. */ public class TimetableDAOMock implements ITimetableDAO { TimeTable stary; TimeTable novy; public TimetableDAOMock() { stary = createTimeTableStary(); novy = createTimeTableNovy(); } public TimeTable add(TimeTable timetable) { return null; } public TimeTable get(Date date) { SimpleDateFormat formater = new java.text.SimpleDateFormat("dd.MM.yyyy"); String dateInString = formater.format(date); if (dateInString.equals(formater.format(novy.getUpdate()))){ return novy; } else if (dateInString.equals(formater.format(stary.getUpdate()))) { return stary; } return null; } public boolean remove(Date date) { return false; } public TimeTable getLast() { return novy; } public TimeTable getOneBeforeLast() { return stary; } public void save() { } public boolean load() {return true; } //testovaci data - stary rozvrh private TimeTable createTimeTableStary(){ final String dateString = "04.07.2017"; SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy"); Date timetableDate = null; try { timetableDate = formater.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } ArrayList<Subject> testSubs = new ArrayList<>(); testSubs.add(new Subject("Př","Teoretická informatika",732,"UAI","08:00","09:30", Calendar.MONDAY, "BB", "1","3.10.2016","2.1.2017",true)); testSubs.add(new Subject("Př","Bakalářská angličtina NS 3",230,"OJZ","10:00","11:30", Calendar.TUESDAY, "BB", "4","3.10.2016","2.1.2017",true)); testSubs.add(new Subject("Cv","Teoretická informatika",732,"UAI","14:30","16:00", Calendar.TUESDAY, "AV", "Pč4","3.10.2016","2.1.2017",true)); return new TimeTable (timetableDate, testSubs); } //testovaci data - novy rozvrh private TimeTable createTimeTableNovy(){ final String dateString = "4.7.2017"; SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy"); Date timetableDate = null; try { timetableDate = formater.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } ArrayList<Subject> testSubs = new ArrayList<Subject>(); testSubs.add(new Subject("Př","Teoretická informatika",732,"UAI","08:00","09:30", Calendar.MONDAY, "BB", "1","3.10.2016","2.1.2017",true)); testSubs.add(new Subject("Př","Bakalářská angličtina NS 3",230,"OJZ","12:00","13:30", Calendar.TUESDAY, "BB", "4","3.10.2016","2.1.2017",true)); testSubs.add(new Subject("Cv","Teoretická informatika",732,"UAI","14:30","16:00", Calendar.TUESDAY, "AV", "Pč4","3.10.2016","2.1.2017",true)); testSubs.add(new Subject("Cv","Teoretická informatika",733,"UAI","14:30","16:00", Calendar.TUESDAY, "AV", "Pč4","3.10.2016","2.1.2017",true)); return new TimeTable(timetableDate, testSubs); } }
28.516393
152
0.623742
020b7ab7675aa0d958f8bb7a630efc2bfc3cb49a
1,747
package org.spring.cloud.service.user.controller; import org.apache.log4j.Logger; import org.spring.cloud.service.api.model.User; import org.spring.cloud.service.api.service.UserService; import org.spring.cloud.service.user.config.AppConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user/center") public class UserController { private final Logger logger = Logger.getLogger(UserController.class); @Autowired private AppConfig appConfig; @Autowired private UserService userService; @RequestMapping(value = "/byName", method = RequestMethod.GET) public User getByName(@RequestParam(value = "name") String name) { logger.info("===<call byName>==="); return userService.findByUserName(name); } @RequestMapping(value = "/byId", method = RequestMethod.GET) public User getByName(@RequestParam(value = "id") Integer id) { logger.info("===<call byId>==="); return userService.findById(id); } @RequestMapping(value = "/save", method = RequestMethod.POST) public String getByName(@RequestBody User user) { logger.info("===<call save>==="); userService.saveUser(user); return "OK"; } @RequestMapping(value = "/name", method = RequestMethod.GET) public String getName() { logger.info("===<call name>==="); return appConfig.getName(); } }
32.351852
73
0.713223
536ca860d4f560de7745e28f17706e21918ffedb
5,492
package com.boyarsky.apiservice.config; import com.boyarsky.apiservice.security.*; import com.boyarsky.apiservice.service.impl.CustomOAuth2UserService; import com.boyarsky.apiservice.service.impl.DefaultUserDetailsService; import com.boyarsky.apiservice.service.impl.TokenProvider; import org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @Import({OAuth2ClientAutoConfiguration.class}) public class SecurityConfig extends WebSecurityConfigurerAdapter { private final DefaultUserDetailsService customUserDetailsService; private final CustomOAuth2UserService customOAuth2UserService; private final OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler; private final OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler; private final TokenProvider tokenProvider; public SecurityConfig(DefaultUserDetailsService customUserDetailsService, CustomOAuth2UserService customOAuth2UserService, OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler, OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler, TokenProvider tokenProvider) { this.customUserDetailsService = customUserDetailsService; this.customOAuth2UserService = customOAuth2UserService; this.oAuth2AuthenticationSuccessHandler = oAuth2AuthenticationSuccessHandler; this.oAuth2AuthenticationFailureHandler = oAuth2AuthenticationFailureHandler; this.tokenProvider = tokenProvider; } @Bean public TokenAuthenticationFilter tokenAuthenticationFilter() { return new TokenAuthenticationFilter(tokenProvider, customUserDetailsService); } /* By default, Spring OAuth2 uses HttpSessionOAuth2AuthorizationRequestRepository to save the authorization request. But, since our service is stateless, we can't save it in the session. We'll save the request in a Base64 encoded cookie instead. */ @Bean public HttpCookieOAuth2AuthorizationRequestRepository cookieAuthorizationRequestRepository() { return new HttpCookieOAuth2AuthorizationRequestRepository(); } @Bean public PasswordEncoder createPasswordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(customUserDetailsService) .passwordEncoder(createPasswordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http .headers().frameOptions().sameOrigin() .and() .cors() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .csrf() .disable() .formLogin() .disable() .httpBasic() .disable() .exceptionHandling() .authenticationEntryPoint(new RestAuthenticationEntryPoint()) .and() .authorizeRequests() .antMatchers("/**/auth/**", "/oauth2/**", "/h2-console/**", "/swagger-ui**/**", "/api-docs/**", "/actuator/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .authorizationEndpoint() .baseUri("/oauth2/authorize") .authorizationRequestRepository(cookieAuthorizationRequestRepository()) .and() .redirectionEndpoint() .baseUri("/login/oauth2/code/google") .and() .userInfoEndpoint() .userService(customOAuth2UserService) .and() .successHandler(oAuth2AuthenticationSuccessHandler) .failureHandler(oAuth2AuthenticationFailureHandler); // Add custom Token based authentication filter http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } }
45.766667
299
0.727968
00c5b6e7636a53e87252171e71cac36ac53582f7
2,302
package de.oio.vaadin.uriactions; import com.google.common.eventbus.Subscribe; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.UI; import de.oio.vaadin.event.EventBus; import de.oio.vaadin.event.impl.navigation.NavigateToURIEvent; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.roklib.urifragmentrouting.UriActionMapperTree; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.vaadin.uriactions.UriFragmentActionNavigatorWrapper; import java.util.List; @Slf4j @UIScope @Component public class URIActionManager { private UriFragmentActionNavigatorWrapper uriActionNavigator; @Getter private UriActionMapperTree uriActionMapperTree; @Autowired public URIActionManager(EventBus eventBus) { eventBus.register(this); } public void initialize(UriActionMapperTree uriActionMapperTree, RoutingContextData routingContextData) { this.uriActionMapperTree = uriActionMapperTree; uriActionNavigator = new UriFragmentActionNavigatorWrapper(UI.getCurrent()); uriActionNavigator.setUriActionMapperTree(uriActionMapperTree); uriActionNavigator.setRoutingContext(routingContextData); logActionOverview(); } @Subscribe public void receiveNavigationEvent(final NavigateToURIEvent event) { if (log.isTraceEnabled()) { log.trace("Handling " + event); } uriActionNavigator.getNavigator().navigateTo(event.getNavigationTarget()); } /** * Prints an overview of all registered URI action handlers along with their respective parameters * as debug log statements. This looks like the following example: * <p> * <pre> * <blockquote> * /admin * /admin/users * /articles * /articles/show ? {SingleIntegerURIParameter : articleId} * /login * </blockquote> * </pre> */ public void logActionOverview() { if (!log.isDebugEnabled()) { return; } final List<String> uriOverview = uriActionMapperTree.getMapperOverview(); log.debug("Logging registered URI action handlers:"); final StringBuilder buf = new StringBuilder(); buf.append('\n'); for (final String url : uriOverview) { buf.append('\t').append(url).append('\n'); } log.debug(buf.toString()); } }
30.693333
106
0.746308
1a706ac03f78358cc39e7d6189c62ba70ee682b0
2,653
package org.joverseer.metadata.domain; import java.awt.Point; import java.io.Serializable; import org.joverseer.support.movement.MovementDirection; import org.joverseer.support.movement.MovementUtils; /** * Enumeration for the hex sides * * Values are according to the palantir data files. * * @author Marios Skounakis * */ public enum HexSideEnum implements Serializable { TopLeft (6), TopRight (1), Right (2), BottomRight (3), BottomLeft (4), Left (5); private final int side; HexSideEnum(int s) { this.side = s; } public int getSide() { return this.side; } public static HexSideEnum fromValue(int i) { for (HexSideEnum e : HexSideEnum.values()) { if (e.getSide() == i) return e; } return null; } public int getHexNoAtSide(int currentHexNo) { if (TopLeft.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.NorthWest); } else if (TopRight.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.NorthEast); } else if (Right.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.East); }else if (BottomRight.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.SouthEast); }else if (BottomLeft.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.SouthWest); } else if (Left.equals(this)) { return MovementUtils.getHexNoAtDir(currentHexNo, MovementDirection.West); } return -1; } public HexSideEnum getOppositeSide() { if (TopLeft.equals(this)) { return BottomRight; } else if (TopRight.equals(this)) { return BottomLeft; } else if (Right.equals(this)) { return Left; }else if (BottomRight.equals(this)) { return TopLeft; }else if (BottomLeft.equals(this)) { return TopRight; } else if (Left.equals(this)) { return Right; } return null; } public static HexSideEnum classifyPoint(Point p, Point hp,int hexHalfWidth,int hexOneThirdHeight) { final HexSideEnum lookup[] = { TopLeft,Left,BottomLeft, TopRight,Right,BottomRight}; boolean leftSide = p.x < hp.x + hexHalfWidth; int ySide = 0; if (p.y < hp.y + hexOneThirdHeight) { ySide = 0; } else if (p.y < hp.y + 2 * hexOneThirdHeight) { ySide = 1; } else { ySide = 2; } if (!leftSide) { ySide += 3; } return lookup[ySide]; } }
28.836957
104
0.63023
b0ce24a9b5d4aef2cafd2a5b85348d1139eeae2a
1,956
package com.young.mall.controller; import com.young.db.entity.YoungBrand; import com.young.mall.common.CommonPage; import com.young.mall.common.ResBean; import com.young.mall.service.BrandService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; /** * @Description: 品牌制造商 * @Author: yqz * @CreateDate: 2020/11/1 14:41 */ @Api(tags = "BrandController", description = "品牌") @RestController @RequestMapping("/admin/brand") public class BrandController extends BaseController { @Autowired private BrandService brandService; @ApiOperation("查询品牌list") @PreAuthorize("@pms.hasPermission('admin:brand:list')") @GetMapping("/list") public ResBean queryBrandList(String id, String name, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size, @RequestParam(defaultValue = "add_time") String sort, @RequestParam(defaultValue = "desc") String order) { logger.error("id:{},name:{},page:{},size:{},sort:{},order:{}", id, name, page, size, sort, order); Optional<List<YoungBrand>> listOptional = brandService.queryBrandList(id, name, page, size, sort, order); if (!listOptional.isPresent()) { return ResBean.failed("查询品牌失败"); } CommonPage<YoungBrand> restPage = CommonPage.restPage(listOptional.get()); return ResBean.success(restPage); } }
38.352941
113
0.692229
c0f886bc2a37fd8ddaf89571f42e5bc4639a79e9
8,348
/* * Copyright 2003-2017 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.bugs; import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; import com.intellij.psi.impl.source.PsiFieldImpl; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.fixes.EqualityToEqualsFix; import com.siyeh.ig.psiutils.*; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; import static com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil.isEffectivelyFinal; import static com.intellij.psi.JavaTokenType.*; import static com.intellij.psi.util.PsiUtil.skipParenthesizedExprDown; import static com.intellij.util.ObjectUtils.tryCast; public class NumberEqualityInspection extends BaseInspection { @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "number.comparison.problem.descriptor"); } @Override public boolean isEnabledByDefault() { return true; } @Override public BaseInspectionVisitor buildVisitor() { return new NumberEqualityVisitor(); } @Override protected InspectionGadgetsFix @NotNull [] buildFixes(Object... infos) { return EqualityToEqualsFix.buildEqualityFixes((PsiBinaryExpression)infos[0]); } private static class NumberEqualityVisitor extends BaseInspectionVisitor { @Override public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) { super.visitBinaryExpression(expression); if (!ComparisonUtils.isEqualityComparison(expression)) { return; } final PsiExpression rhs = expression.getROperand(); if (!hasNumberType(rhs)) { return; } final PsiExpression lhs = expression.getLOperand(); if (!hasNumberType(lhs)) { return; } if (isUniqueConstant(rhs) || isUniqueConstant(lhs)) return; final PsiElement element = PsiTreeUtil.findFirstParent(expression, new Filter(lhs, rhs)); final boolean isOneOfVariablesDefinitelyNull = element != null; if (isOneOfVariablesDefinitelyNull) return; registerError(expression.getOperationSign(), expression); } private static boolean isUniqueConstant(PsiExpression expression) { PsiReferenceExpression ref = tryCast(skipParenthesizedExprDown(expression), PsiReferenceExpression.class); if (ref == null) return false; PsiField target = tryCast(ref.resolve(), PsiField.class); if (target == null) return false; if (target instanceof PsiEnumConstant) return true; if (!(target instanceof PsiFieldImpl)) return false; if (!target.hasModifierProperty(PsiModifier.STATIC) || !target.hasModifierProperty(PsiModifier.FINAL)) return false; PsiExpression initializer = PsiFieldImpl.getDetachedInitializer(target); return ExpressionUtils.isNewObject(initializer); } private static boolean hasNumberType(PsiExpression expression) { return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_NUMBER); } } private static final class Filter implements Condition<PsiElement> { private final PsiExpression lhs; private final PsiExpression rhs; private Filter(final PsiExpression lhs, final PsiExpression rhs) { this.lhs = lhs; this.rhs = rhs; } @Override public boolean value(final PsiElement element) { PsiConditionalExpression ternary = tryCast(element, PsiConditionalExpression.class); if (ternary != null) { final PsiExpression condition = skipParenthesizedExprDown(ternary.getCondition()); final PsiElement then = skipParenthesizedExprDown(ternary.getThenExpression()); final PsiElement elze = skipParenthesizedExprDown(ternary.getElseExpression()); if (isOneOfVariablesDefinitelyNull(condition, then, elze)) return true; } final PsiIfStatement ifStatement = tryCast(element, PsiIfStatement.class); if (ifStatement == null) return false; final PsiExpression condition = skipParenthesizedExprDown(ifStatement.getCondition()); final PsiElement then = ifStatement.getThenBranch(); final PsiElement elze = ifStatement.getElseBranch(); return isOneOfVariablesDefinitelyNull(condition, then, elze); } private boolean isOneOfVariablesDefinitelyNull(PsiExpression condition, PsiElement then, PsiElement elze) { if (condition == null) return false; boolean isNegated = false; PsiBinaryExpression binOp = tryCast(condition, PsiBinaryExpression.class); if (binOp == null && BoolUtils.isNegation(condition)) { final PsiExpression operand = skipParenthesizedExprDown(((PsiPrefixExpression) condition).getOperand()); binOp = tryCast(operand, PsiBinaryExpression.class); isNegated = true; } if (binOp == null) return false; final IElementType tokenType = binOp.getOperationTokenType(); final PsiBinaryExpression lOperand = tryCast(skipParenthesizedExprDown(binOp.getLOperand()), PsiBinaryExpression.class); final PsiBinaryExpression rOperand = tryCast(skipParenthesizedExprDown(binOp.getROperand()), PsiBinaryExpression.class); if (lOperand == null || rOperand == null) return false; final PsiExpression lValue = ExpressionUtils.getValueComparedWithNull(lOperand); final PsiExpression rValue = ExpressionUtils.getValueComparedWithNull(rOperand); if (lValue == null || rValue == null) return false; final IElementType lTokenType = lOperand.getOperationTokenType(); final IElementType rTokenType = rOperand.getOperationTokenType(); boolean areBothOperandsComparedWithNull = lTokenType == EQEQ && rTokenType == EQEQ; boolean areBothOperandsComparedWithNotNull = lTokenType == NE && rTokenType == NE; if (areBothOperandsComparedWithNull == areBothOperandsComparedWithNotNull) return false; List<IElementType> targetTokenTypes = areBothOperandsComparedWithNull ? Arrays.asList(OROR, OR) : Arrays.asList(ANDAND, AND); if (!targetTokenTypes.contains(tokenType)) return false; final PsiElement branchContainsNumberEquality = isNegated ^ areBothOperandsComparedWithNull ? then : elze; if (!PsiTreeUtil.isAncestor(branchContainsNumberEquality, lhs, false)) return false; final EquivalenceChecker checker = EquivalenceChecker.getCanonicalPsiEquivalence(); final PsiReferenceExpression lReference = tryCast(skipParenthesizedExprDown(lhs), PsiReferenceExpression.class); if (lReference == null) return false; final PsiReferenceExpression rReference = tryCast(skipParenthesizedExprDown(rhs), PsiReferenceExpression.class); if (rReference == null) return false; final PsiVariable lVariable = tryCast(lReference.resolve(), PsiVariable.class); if (lVariable == null) return false; final PsiVariable rVariable = tryCast(rReference.resolve(), PsiVariable.class); if (rVariable == null) return false; final boolean isEffectivelyFinal = isEffectivelyFinal(lVariable, branchContainsNumberEquality, null) && isEffectivelyFinal(rVariable, branchContainsNumberEquality, null); if (!isEffectivelyFinal) return false; return (checker.expressionsMatch(lhs, lValue).isExactMatch() && checker.expressionsMatch(rhs, rValue).isExactMatch()) || (checker.expressionsMatch(lhs, rValue).isExactMatch() && checker.expressionsMatch(rhs, lValue).isExactMatch()); } } }
45.369565
131
0.747484
d3ac3ba079fbf1912c638889eafe76f48bbec2d6
916
package edu.fiuba.algo3.modelo.fases; import java.beans.PropertyChangeListener; import edu.fiuba.algo3.modelo.*; import edu.fiuba.algo3.modelo.Interfaces.*; import edu.fiuba.algo3.modelo.excepciones.*; public abstract class FaseAbstracta implements IFase { ITurno turno; Mazo mazo; IMapa mapa; ObjetivoManager objetivoManager; @Override public IFaseInicio obtenerFaseInicio() throws FaseErroneaException { throw new FaseErroneaException(null); } @Override public FaseAtacar obtenerFaseAtacar() throws FaseErroneaException { throw new FaseErroneaException(null); } @Override public FaseColocar obtenerFaseColocar() throws FaseErroneaException { throw new FaseErroneaException(null); } @Override public FaseReagrupar obtenerFaseReagrupar() throws FaseErroneaException { throw new FaseErroneaException(null); } }
26.941176
77
0.735808
f4b2c3df1d0ebbd6733a23f7c48bd26dce894a48
1,481
package edu.zieit.scheduler.schedule; import edu.zieit.scheduler.api.render.SheetRenderer; import edu.zieit.scheduler.api.schedule.ScheduleInfo; import edu.zieit.scheduler.api.schedule.ScheduleParseException; import edu.zieit.scheduler.api.schedule.ScheduleLoader; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.IOException; import java.io.InputStream; public abstract class AbstractScheduleLoader implements ScheduleLoader { protected final SheetRenderer renderer; public AbstractScheduleLoader(SheetRenderer renderer) { this.renderer = renderer; } protected Workbook loadWorkbook(ScheduleInfo info) throws ScheduleParseException { try (InputStream in = info.getUrl().openStream()) { String filename = info.getUrl().toString(); Workbook workbook = null; if (filename.endsWith(".xlsx")) { workbook = new XSSFWorkbook(in); } else if (filename.endsWith(".xls")) { workbook = new HSSFWorkbook(in); } return workbook; } catch (IOException e) { throw new ScheduleParseException("Cannot load " + info.getUrl().toString(), e); } } protected Cell getCell(Sheet sheet, int rowNum, int colNum) { Row row = sheet.getRow(rowNum); return row != null ? row.getCell(colNum) : null; } }
32.911111
91
0.681296
2f08886c907ff88e30e8fcc47e3390e8bf1d9344
25,514
// // Depot library - a Java relational persistence library // https://github.com/threerings/depot/blob/master/LICENSE package com.samskivert.depot; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import com.samskivert.depot.clause.*; import com.samskivert.depot.expression.ColumnExp; import com.samskivert.depot.expression.SQLExpression; import com.samskivert.depot.impl.FindAllQuery; import com.samskivert.depot.impl.Projector; import com.samskivert.depot.util.*; // TupleN import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; /** * The root of a fluent mechanism for constructing queries. Obtain an instance via {@link * DepotRepository#from}. For example: * <pre>{@code * List<Tuple2<Integer,String>> results = _repo.from(FooRecord.class). * where(FooRecord.NAME.like("%foo%")). * descending(FooRecord.NAME). * limit(25). * select(FooRecord.ID, FooRecord.NAME); * }</pre> * * <p> Note that each builder method returns a new builder instance so that partial queries can be * constructed and reused without interfering with one another: * <pre>{@code * Query<FooRecord> query = from(FooRecord.class).where(FooRecord.NAME.eq("foo")).limit(10); * List<Tuple2<Integer,String>> top = * query.ascending(FooRecord.NAME).select(FooRecord.ID, FooRecord.NAME); * List<Tuple2<Integer,String>> bot = * query.descending(FooRecord.NAME).select(FooRecord.ID, FooRecord.NAME); * }</pre> */ public class Query<T extends PersistentRecord> implements Cloneable { /** Disables the use of the cache for this query. */ public Query<T> noCache () { return cache(DepotRepository.CacheStrategy.NONE); } /** Configures the use of {@link DepotRepository.CacheStrategy#BEST} for this query. */ public Query<T> cacheBest () { return cache(DepotRepository.CacheStrategy.BEST); } /** Configures the use of {@link DepotRepository.CacheStrategy#RECORDS} for this query. */ public Query<T> cacheRecords () { return cache(DepotRepository.CacheStrategy.RECORDS); } /** Configures the use of {@link DepotRepository.CacheStrategy#SHORT_KEYS} for this query. */ public Query<T> cacheShortKeys () { return cache(DepotRepository.CacheStrategy.SHORT_KEYS); } /** Configures the use of {@link DepotRepository.CacheStrategy#LONG_KEYS} for this query. */ public Query<T> cacheLongKeys () { return cache(DepotRepository.CacheStrategy.LONG_KEYS); } /** Configures the use of {@link DepotRepository.CacheStrategy#CONTENTS} for this query. */ public Query<T> cacheContents () { return cache(DepotRepository.CacheStrategy.CONTENTS); } /** Configures the specified caching policy this query. */ public Query<T> cache (DepotRepository.CacheStrategy cache) { Query<T> query = clone(); query._cache = cache; return query; } /** * Configures a {@link Where} clause that matches all rows. For selections, a where clause can * simply be omitted, but for deletions, this method must be used if you intend to delete all * rows in the table. */ public Query<T> whereTrue () { return where(Exps.literal("true")); } /** * Configures a {@link Where} clause that ANDs together all of the supplied expressions. */ public Query<T> where (SQLExpression<?>... exprs) { return where(Arrays.asList(exprs)); } /** * Configures a {@link Where} clause that ANDs together all of the supplied expressions. */ public Query<T> where (Iterable<? extends SQLExpression<?>> exprs) { Iterator<? extends SQLExpression<?>> iter = exprs.iterator(); checkArgument(iter.hasNext(), "Must supply at least one expression."); SQLExpression<?> first = iter.next(); return where(iter.hasNext() ? new Where(Ops.and(exprs)) : new Where(first)); } /** * Configures a {@link Where} clause that selects rows where the supplied column equals the * supplied value. */ public <V extends Comparable<? super V>> Query<T> where (ColumnExp<V> column, V value) { return where(new Where(column, value)); } /** * Configures a {@link Where} clause that selects rows where both supplied columns equal both * supplied values. */ public <V1 extends Comparable<? super V1>, V2 extends Comparable<? super V2>> Query<T> where (ColumnExp<V1> index1, V1 value1, ColumnExp<V2> index2, V2 value2) { return where(new Where(index1, value1, index2, value2)); } /** * Configures a {@link Where} clause that selects rows where both supplied columns equal both * supplied values. */ public Query<T> where (WhereClause where) { checkState(_where == null, "Where clause is already configured."); Query<T> query = clone(); query._where = where; return query; } /** * Adds a {@link Join} clause configured with the supplied left and right columns. */ public Query<T> join (ColumnExp<?> left, ColumnExp<?> right) { return join(new Join(left, right)); } /** * Adds a {@link Join} clause configured with the join condition. */ public Query<T> join (Class<? extends PersistentRecord> joinClass, SQLExpression<?> joinCondition) { return join(new Join(joinClass, joinCondition)); } /** * Adds a {@link Join} clause configured with the supplied left and right columns and join * type. */ public Query<T> join (ColumnExp<?> left, ColumnExp<?> right, Join.Type type) { return join(new Join(left, right).setType(type)); } /** * Configures the query with the supplied {@link Join} clause. Multiple join clauses are * allowed. */ public Query<T> join (Join join) { Query<T> query = clone(); query._joins = cons(join, query._joins); return query; } /** * Configures the query to return only distinct rows. */ public Query<T> distinct () { return distinct(null); } /** * Configures the query to return rows for which the given expression evaluates distinctly. */ public Query<T> distinct (SQLExpression<?> distinctOn) { checkState(_distinct == null, "Distinct clause is already configured."); Query<T> query = clone(); query._distinct = new Distinct(distinctOn); return query; } /** * Configures a {@link GroupBy} clause on the supplied group expressions. */ public Query<T> groupBy (SQLExpression<?>... exprs) { checkState(_groupBy == null, "GroupBy clause is already configured."); Query<T> query = clone(); query._groupBy = new GroupBy(exprs); return query; } /** * Configures an {@link OrderBy} clause configured to randomly order the results. */ public Query<T> randomOrder () { return orderBy(OrderBy.random()); } /** * Configures an {@link OrderBy} clause that ascends on the supplied expression. */ public Query<T> ascending (SQLExpression<?> value) { return orderBy(OrderBy.ascending(value)); } /** * Configures an {@link OrderBy} clause that descends on the supplied expression. */ public Query<T> descending (SQLExpression<?> value) { return orderBy(OrderBy.descending(value)); } /** * Configures the query with the supplied {@link OrderBy} clause. */ public Query<T> orderBy (OrderBy orderBy) { checkState(_orderBy == null, "OrderBy clause is already configured."); Query<T> query = clone(); query._orderBy = orderBy; return query; } /** * Configures a {@link Limit} clause configured with the supplied count. */ public Query<T> limit (int count) { checkState(_limit == null, "Limit clause is already configured."); Query<T> query = clone(); query._limit = new Limit(0, count); return query; } /** * Configures a {@link Limit} clause configured with the supplied offset and count. */ public Query<T> limit (int offset, int count) { checkState(_limit == null, "Limit clause is already configured."); Query<T> query = clone(); query._limit = new Limit(offset, count); return query; } /** * Configures a {@link FromOverride} clause configured with the supplied override class. */ public Query<T> override (Class<? extends PersistentRecord> fromClass) { return override(new FromOverride(fromClass)); } /** * Configures a {@link FromOverride} clause configured with the supplied override classes. */ public Query<T> override (Class<? extends PersistentRecord> fromClass1, Class<? extends PersistentRecord> fromClass2) { return override(new FromOverride(fromClass1, fromClass2)); } /** * Configures the query with the supplied {@link FromOverride} clause. */ public Query<T> override (FromOverride fromOverride) { checkState(_fromOverride == null, "FromOverride clause is already configured."); Query<T> query = clone(); query._fromOverride = fromOverride; return query; } /** * Adds a {@link FieldDefinition} clause. */ public Query<T> fieldDef (String field, String value) { return fieldDef(new FieldDefinition(field, value)); } /** * Adds a {@link FieldDefinition} clause. */ public Query<T> fieldDef (String field, SQLExpression<?> override) { return fieldDef(new FieldDefinition(field, override)); } /** * Adds a {@link FieldDefinition} clause. */ public Query<T> fieldDef (ColumnExp<?> field, SQLExpression<?> override) { return fieldDef(new FieldDefinition(field, override)); } /** * Adds a {@link FieldDefinition} clause. */ public Query<T> fieldDef (FieldDefinition fieldDef) { Query<T> query = clone(); query._fieldDefs = cons(fieldDef, query._fieldDefs); return query; } /** * Configures a {@link ForUpdate} clause which marks this query as selecting for update. */ public Query<T> forUpdate () { checkState(_forUpdate == null, "ForUpdate clause is already configured."); Query<T> query = clone(); query._forUpdate = new ForUpdate(); return query; } /** * Loads the first persistent object that matches the configured query clauses. */ public T load () { return _repo.load(_pclass, _cache, getClauseArray()); } /** * Loads all persistent objects that match the configured query clauses. */ public List<T> select () throws DatabaseException { return _repo.findAll(_pclass, _cache, getClauses()); } /** * Loads the keys of all persistent objects that match the configured query clauses. Note that * cache configuration is ignored for key-only queries. * * @param useMaster if true, the query will be run using a read-write connection to ensure that * it talks to the master database, if false, the query will be run on a read-only connection * and may load keys from a slave. For performance reasons, you should always pass false unless * you know you will be modifying the database as a result of this query and absolutely need * the latest data. */ public List<Key<T>> selectKeys (boolean useMaster) throws DatabaseException { return _repo.findAllKeys(_pclass, useMaster, getClauses()); } /** * Returns the count of rows that match the configured query clauses. */ public int selectCount () { checkState(_groupBy == null, "Do you mean to select(Funcs.countStar())?"); return _repo.load(CountRecord.class, _cache, override(_pclass).getClauseArray()).count; } /** * Returns the value from the first row that matches the configured query clauses. This value * may be null if the query clauses match no rows. */ public <V> V load (SQLExpression<V> selexp) { return getLoaded(select(selexp)); // TODO: revamp FindOneQuery and use that } /** * Returns the value from the first row that matches the configured query clauses. This value * may be null if the query clauses match no rows. */ public <V1, V2> Tuple2<V1, V2> load (SQLExpression<V1> exp1, SQLExpression<V2> exp2) { return getLoaded(select(exp1, exp2)); // TODO: revamp FindOneQuery and use that } /** * Returns the value from the first row that matches the configured query clauses. This value * may be null if the query clauses match no rows. */ public <V1, V2, V3> Tuple3<V1, V2, V3> load ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3) { return getLoaded(select(exp1, exp2, exp3)); // TODO: revamp FindOneQuery and use that } /** * Returns the value from the first row that matches the configured query clauses. This value * may be null if the query clauses match no rows. */ public <V1, V2, V3, V4> Tuple4<V1, V2, V3, V4> load ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4) { return getLoaded(select(exp1, exp2, exp3, exp4)); // TODO: revamp FindOneQuery and use that } /** * Returns the value from the first row that matches the configured query clauses. This value * may be null if the query clauses match no rows. */ public <V1, V2, V3, V4, V5> Tuple5<V1, V2, V3, V4, V5> load ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4, SQLExpression<V5> exp5) { return getLoaded(select(exp1, exp2, exp3, exp4, exp5)); // TODO: use revamped FindOneQuery } /** * Returns just the supplied expression from the rows matching the query. */ public <V> List<V> select (SQLExpression<V> selexp) { return _ctx.invoke(new FindAllQuery.Projection<T,V>( _ctx, Projector.create(_pclass, selexp), getClauses())); } /** * Returns just the supplied expressions from the rows matching the query. */ public <V1, V2> List<Tuple2<V1,V2>> select (SQLExpression<V1> exp1, SQLExpression<V2> exp2) { Builder2<Tuple2<V1,V2>,V1,V2> builder = Tuple2.builder(); return select(builder, exp1, exp2); } /** * Returns just the supplied expressions from the rows matching the query. */ public <V1, V2, V3> List<Tuple3<V1,V2,V3>> select ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3) { Builder3<Tuple3<V1,V2,V3>,V1,V2,V3> builder = Tuple3.builder(); return select(builder, exp1, exp2, exp3); } /** * Returns just the supplied expressions from the rows matching the query. */ public <V1, V2, V3, V4> List<Tuple4<V1,V2,V3,V4>> select ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4) { Builder4<Tuple4<V1,V2,V3,V4>,V1,V2,V3,V4> builder = Tuple4.builder(); return select(builder, exp1, exp2, exp3, exp4); } /** * Returns just the supplied expressions from the rows matching the query. */ public <V1, V2, V3, V4, V5> List<Tuple5<V1,V2,V3,V4,V5>> select ( SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4, SQLExpression<V5> exp5) { Builder5<Tuple5<V1,V2,V3,V4,V5>,V1,V2,V3,V4,V5> builder = Tuple5.builder(); return select(builder, exp1, exp2, exp3, exp4, exp5); } /** * Selects the supplied expressions and writes their values into the supplied result class. The * result class must have exactly one constructor which takes arguments that are convertible * from the types of the selected expressions. Reflection will be used to find and invoke the * constructor; unboxing and widening will be performed by the reflective call. */ public <V> List<V> selectInto (Class<V> resultClass, SQLExpression<?>... selexps) { Projector<T,V> proj = Projector.create(_pclass, resultClass, selexps); return _ctx.invoke(new FindAllQuery.Projection<T,V>(_ctx, proj, getClauses())); } /** * Selects the supplied expressions and constructs a result record using their values using the * supplied record builder. */ public <R,V1,V2> List<R> select ( Builder2<R,? super V1,? super V2> builder, SQLExpression<V1> exp1, SQLExpression<V2> exp2) { Projector<T, R> proj = Projector.create(_pclass, builder, exp1, exp2); return _ctx.invoke(new FindAllQuery.Projection<T,R>(_ctx, proj, getClauses())); } /** * Selects the supplied expressions and constructs a result record using their values using the * supplied record builder. */ public <R, V1, V2, V3> List<R> select ( Builder3<R,? super V1,? super V2,? super V3> builder, SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3) { Projector<T, R> proj = Projector.create(_pclass, builder, exp1, exp2, exp3); return _ctx.invoke(new FindAllQuery.Projection<T,R>(_ctx, proj, getClauses())); } /** * Selects the supplied expressions and constructs a result record using their values using the * supplied record builder. */ public <R, V1, V2, V3, V4> List<R> select ( Builder4<R,? super V1,? super V2,? super V3,? super V4> builder, SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4) { Projector<T, R> proj = Projector.create(_pclass, builder, exp1, exp2, exp3, exp4); return _ctx.invoke(new FindAllQuery.Projection<T,R>(_ctx, proj, getClauses())); } /** * Selects the supplied expressions and constructs a result record using their values using the * supplied record builder. */ public <R, V1, V2, V3, V4, V5> List<R> select ( Builder5<R,? super V1,? super V2,? super V3,? super V4,? super V5> builder, SQLExpression<V1> exp1, SQLExpression<V2> exp2, SQLExpression<V3> exp3, SQLExpression<V4> exp4, SQLExpression<V5> exp5) { Projector<T, R> proj = Projector.create(_pclass, builder, exp1, exp2, exp3, exp4, exp5); return _ctx.invoke(new FindAllQuery.Projection<T,R>(_ctx, proj, getClauses())); } /** * Deletes the records that match the configured query clauses. Note that only the where and * limit clauses are used to evaluate a deletion. Attempts to use other clauses will result in * failure. * * @return the number of rows deleted by this action. * * @throws DatabaseException if any problem is encountered communicating with the database. */ public int delete () { assertValidDelete(); return _repo.deleteAll(_pclass, _where, _limit); } /** * Deletes the records that match the configured query clauses. Note that only the where and * limit clauses are used to evaluate a deletion. Attempts to use other clauses will result in * failure. * * @param invalidator if non-null, used to remove deleted records from the cache; if null, no * cache deletion will be performed. * * @return the number of rows deleted by this action. * * @throws DatabaseException if any problem is encountered communicating with the database. */ public int delete (CacheInvalidator invalidator) { assertValidDelete(); return _repo.deleteAll(_pclass, _where, _limit, invalidator); } /** * Clears the cache for the query configured by this instance. If the query would not result in * cache usage for whatever reason, this will NOOP. * * <p> Note: Depot uses numerous caches, so it is important to know what you are doing. If the * records fetched by this query have a primary key, Depot performs a two-phase query where the * primary keys for the records that satisify this query are first fetched and stored in a * <em>keyset</em> cache, then the actual records needed to satisfy the query are fetched using * the <em>by-primary-key</em> cache. This method will only clear the <em>keyset</em> cache. * That may be sufficient for your purposes, or you may need to call {@link * PersistenceContext#cacheClear(Class,boolean)} to clear the <em>by-primary-key</em> cache as * well. If the record in question does not define a primary key, Depot will use a * <em>contents</em> cache to store the entire records fetched as a result of executing this * query. In that case, calling this method is sufficient to ensure that no cached data will be * used to fulfill subsequent similarly configured queries. </p> * * <p> Finally, note that query configuration other than {@link #cache} (i.e. {@link #limit}, * {@link #groupBy}, {@link #join}, etc.) will have no influence on this operation. </p> * * @param localOnly if true, only the cache in this JVM will be cleared, no broadcast message * will be sent to instruct all distributed nodes to also clear this cache. */ public void clearCache (boolean localOnly) { String cacheId = FindAllQuery.newCachedFullRecordQuery( _ctx, _pclass, _cache, getClauses()).getCacheId(); if (cacheId != null) { _ctx.cacheClear(cacheId, localOnly); } } protected Query (PersistenceContext ctx, DepotRepository repo, Class<T> pclass) { _ctx = ctx; _repo = repo; _pclass = pclass; } @Override protected Query<T> clone () { try { @SuppressWarnings("unchecked") Query<T> qb = (Query<T>)super.clone(); return qb; } catch (Throwable t) { throw new AssertionError(t); } } protected List<QueryClause> getClauses () { List<QueryClause> clauses = Lists.newArrayList(); addIfNotNull(clauses, _where); addAll(clauses, _joins); addIfNotNull(clauses, _orderBy); addIfNotNull(clauses, _distinct); addIfNotNull(clauses, _groupBy); addIfNotNull(clauses, _limit); addIfNotNull(clauses, _fromOverride); addAll(clauses, _fieldDefs); addIfNotNull(clauses, _forUpdate); return clauses; } protected QueryClause[] getClauseArray () { List<QueryClause> clauses = getClauses(); return clauses.toArray(new QueryClause[clauses.size()]); } protected void addIfNotNull (List<QueryClause> clauses, QueryClause clause) { if (clause != null) { clauses.add(clause); } } protected void assertValidDelete () { checkState(_where != null, "Where clause must be specified for delete."); checkState(_joins == null, "Join clauses not supported by delete."); checkState(_orderBy == null, "OrderBy clause not applicable for delete."); checkState(_distinct == null, "Distinct clause not applicable for delete."); checkState(_groupBy == null, "GroupBy clause not applicable for delete."); checkState(_fromOverride == null, "FromOverride clause not applicable for delete."); checkState(_fieldDefs == null, "FieldDefinition clauses not applicable for delete."); checkState(_forUpdate == null, "ForUpdate clause not supported by delete."); } protected static <T> T getLoaded (List<T> selections) { return selections.isEmpty() ? null : selections.get(0); } protected static final class Cons<T> { public T head; public Cons<T> tail; public Cons (T head, Cons<T> tail) { this.head = head; this.tail = tail; } } protected static <T> Cons<T> cons (T head, Cons<T> tail) { return new Cons<T>(head, tail); } // note that because new elements are prepended to the cons list, we turn them into a Java list // in reverse order, which matches the original order in which they were "appended" protected static void addAll (List<QueryClause> toList, Cons<? extends QueryClause> cons) { if (cons != null) { addAll(toList, cons.tail); toList.add(cons.head); } } protected final PersistenceContext _ctx; protected final DepotRepository _repo; protected final Class<T> _pclass; protected DepotRepository.CacheStrategy _cache = DepotRepository.CacheStrategy.BEST; protected WhereClause _where; protected OrderBy _orderBy; protected Distinct _distinct; protected GroupBy _groupBy; protected Limit _limit; protected FromOverride _fromOverride; protected ForUpdate _forUpdate; protected Cons<Join> _joins; protected Cons<FieldDefinition> _fieldDefs; }
35.83427
99
0.644666
75fdca3119c6bcd710caddd273837cdda279761f
1,689
package com.ppdai.infrastructure.mq.biz.service.common; import com.ppdai.infrastructure.mq.biz.common.trace.Tracer; import com.ppdai.infrastructure.mq.biz.common.trace.spi.Transaction; import com.ppdai.infrastructure.mq.biz.common.util.SpringUtil; import com.ppdai.infrastructure.mq.biz.service.CacheUpdateService; import java.util.Map; /** * @Author:wanghe02 * @Date:2019/4/1 20:02 */ public class CacheUpdateHelper { public static void updateCache() { Transaction transaction = Tracer.newTransaction("Portal", "updateCache"); try { Map<String, CacheUpdateService> cacheUpdateServices = SpringUtil.getBeans(CacheUpdateService.class); if (cacheUpdateServices != null) { cacheUpdateServices.values().forEach(t1 -> { t1.updateCache(); }); } transaction.setStatus(Transaction.SUCCESS); } catch (Exception e) { transaction.setStatus(e); } finally { transaction.complete(); } } public static void forceUpdateCache() { Transaction transaction = Tracer.newTransaction("Portal", "updateCache"); try { Map<String, CacheUpdateService> cacheUpdateServices = SpringUtil.getBeans(CacheUpdateService.class); if (cacheUpdateServices != null) { cacheUpdateServices.values().forEach(t1 -> { t1.forceUpdateCache(); }); } transaction.setStatus(Transaction.SUCCESS); } catch (Exception e) { transaction.setStatus(e); } finally { transaction.complete(); } } }
35.1875
112
0.618709
01644d85d4485e383bfed4004975aff5704d3292
845
package com.oneidentity.safeguard.safeguardjava.event; import java.util.logging.Level; import java.util.logging.Logger; class EventHandlerRunnable implements Runnable { private final ISafeguardEventHandler handler; private final String eventName; private final String eventBody; EventHandlerRunnable(ISafeguardEventHandler handler, String eventName, String eventBody) { this.handler = handler; this.eventName = eventName; this.eventBody = eventBody; } @Override public void run() { try { handler.onEventReceived(eventName, eventBody); } catch (Exception ex) { Logger.getLogger(EventHandlerRegistry.class.getName()).log(Level.WARNING, "An error occured while calling onEventReceived"); } } }
27.258065
94
0.666272
c8c9b82d124ec5af502ccbaf6bcc5216d710b7da
2,372
package com.smalljava.core.test.l5_expression; import com.smalljava.core.analyse.l5_expression.ExpressionASTAnalyse; import com.smalljava.core.common.VarValue; import com.smalljava.core.commonvo.l5_expression.RootAST; import com.smalljava.core.eval.l5_expression.SmallJavaExpressionEval; import com.smalljava.core.l6_supportenv.l6_classsupport.SmallJavaClassSupportEnv; import com.smalljava.core.l6_supportenv.l6_oopsupport.SmallJavaOopSupportEnv; //import com.smalljava.core.l9_space.classtable.IClassTable; //import com.smalljava.core.l9_space.classtable.impl.ClassTableImpl; import com.smalljava.core.l9_space.vartable.IVarTable; import com.smalljava.core.l9_space.vartable.hashmapimpl.L2_HashMapClassInstanceVarTableImpl; import com.smalljava.core.l9_space.vartable.hashmapimpl.L2_HashMapClassStaticVarTableImpl; import com.smalljava.core.l9_space.vartable.hashmapimpl.L3_HashMapMethodInstanceVarTableImpl; import com.smalljava.core.l9_space.vartable.hashmapimpl.L4_HashMapBlockVarTableImpl; public class TestExpressionEval { @SuppressWarnings("static-access") public static void main(String args[]) { //String s1="{int i=0}"; //BasicBlock closedblock = new BasicBlock("",s1,null); //BlockAnalyse ba = new BlockAnalyse(); //boolean isok = ba.analyse(closedblock); //System.out.println("result:"+isok); ExpressionASTAnalyse eanlyse = new ExpressionASTAnalyse(); String s2="i=1+2"; RootAST root = eanlyse.analyse(s2); if(root == null) { System.out.println("ast fail."); return; }else { System.out.println("ast OK."); root.show(0); } L2_HashMapClassStaticVarTableImpl l2_static = new L2_HashMapClassStaticVarTableImpl(""); L2_HashMapClassInstanceVarTableImpl l2_instance = new L2_HashMapClassInstanceVarTableImpl("l2",l2_static); L3_HashMapMethodInstanceVarTableImpl l3 = new L3_HashMapMethodInstanceVarTableImpl("",l2_instance); L4_HashMapBlockVarTableImpl l4 = new L4_HashMapBlockVarTableImpl("",l3); //IClassTable classtable = new ClassTableImpl(); IVarTable vartable=l4; vartable.defineVar("i","int"); SmallJavaExpressionEval eval = new SmallJavaExpressionEval(); VarValue vv = eval.eval(root, vartable, new SmallJavaClassSupportEnv() , new SmallJavaOopSupportEnv()); if(vv == null) { System.out.println("[error]vv is null"); }else { System.out.println(vv.toString()); } } }
40.896552
108
0.786678
ab4dca6f02e9342f14e48afeab3eb37375a9d345
3,088
/************************************************************************* * * Compilation: javac Point.java * Execution: * Dependencies: StdDraw.java * * Description: An immutable data type for points in the plane. * *************************************************************************/ import java.util.Comparator; public class Point implements Comparable<Point> { // compare points by slope public final Comparator<Point> SLOPE_ORDER = new Comparator<Point>() { public int compare(Point o1, Point o2) { double slope1 = Point.this.slopeTo(o1); double slope2 = Point.this.slopeTo(o2); // return Double.compare(slope1+0.0, slope2+0.0); // avoid -0.0 if (slope1 < slope2) return -1; if (slope1 == slope2) return 0; return 1; } }; private final int x; private final int y; private int normalizeCompareTo(double val) { double delta = 1e-6; if (Math.abs(val) < delta) return 0; else if (val < 0) return -1; else return 1; } /** * create the point (x, y) * @param x * @param y */ public Point(int x, int y) { this.x = x; this.y = y; } /** * plot this point to standard drawing */ public void draw() { StdDraw.point(x, y); } /** * draw line between this point and that point to standard drawing * @param that */ public void drawTo(Point that) { StdDraw.line(this.x, this.y, that.x, that.y); } /** * slope between this point and that point * @param that * @return */ public double slopeTo(Point that) { int deltaY = this.y - that.y; int deltaX = this.x - that.x; if (deltaX == 0) if (deltaY == 0) return Double.NEGATIVE_INFINITY; // rather than using Integer.MIN_VALUE; else return Double.POSITIVE_INFINITY; double ret = deltaY/(double) (deltaX); return ret + 0.0; } /** * is this point lexicographically smaller than that one? * comparing y-coordinates and breaking ties by x-coordinates * @param that * @return */ public int compareTo(Point that) { int deltaY = this.y - that.y; if (deltaY < 0) return -1; else if (deltaY > 0) return 1; else return Integer.compare(this.x, that.x); } /** * return string representation of this point * @return */ public String toString() { return "(" + x + ", " + y + ")"; } /** * unit test * @param args */ public static void main(String[] args) { Point p = new Point(0, 9); Point q = new Point(0, 3); Point r = new Point(0, 3); System.out.println(p.SLOPE_ORDER.compare(q, r)); System.out.println(Double.compare(0.0, -0.0)); System.out.println(0.0 == -0.0); System.out.println(Double.POSITIVE_INFINITY+0.0); } }
25.733333
102
0.512953
f20570aefadd5c133a76a278034a929a665e3829
2,980
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat, Inc. and/or its affiliates, 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.arquillian.extension.governor.skipper.config; import org.arquillian.extension.governor.skipper.impl.SkipperReportHolder; import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured; import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor; import org.jboss.arquillian.config.descriptor.api.ExtensionDef; import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.InstanceProducer; import org.jboss.arquillian.core.api.annotation.ApplicationScoped; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.api.annotation.Observes; import org.jboss.arquillian.core.spi.ServiceLoader; import java.util.logging.Level; import java.util.logging.Logger; /** * @author <a href="mailto:[email protected]">Stefan Miklosovic</a> */ public class SkipperConfigurator { private static final Logger logger = Logger.getLogger(SkipperConfigurator.class.getName()); private static final String EXTENSION_NAME = "governor-skipper"; @Inject private Instance<ServiceLoader> serviceLoader; @Inject @ApplicationScoped private InstanceProducer<SkipperConfiguration> skipperConfiguration; @Inject @ApplicationScoped private InstanceProducer<SkipperReportHolder> skipperReportHolder; public void onGovernorExtensionConfigured(@Observes GovernorExtensionConfigured event, ArquillianDescriptor arquillianDescriptor) throws Exception { final SkipperConfiguration skipperConfiguration = new SkipperConfiguration(); for (final ExtensionDef extension : arquillianDescriptor.getExtensions()) { if (extension.getExtensionName().equals(EXTENSION_NAME)) { skipperConfiguration.setConfiguration(extension.getExtensionProperties()); skipperConfiguration.validate(); break; } } this.skipperReportHolder.set(new SkipperReportHolder()); this.skipperConfiguration.set(skipperConfiguration); logger.log(Level.CONFIG, "Configuration of Arquillian Skipper extension:"); logger.log(Level.CONFIG, skipperConfiguration.toString()); } }
41.971831
152
0.76745
8e6843764a3a703b52039641ac5d7427bdd417bd
33,873
/*** * Copyright (c) 1995-2009 Cycorp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Substantial portions of this code were developed by the Cyc project * and by Cycorp Inc, whose contribution is gratefully acknowledged. */ package com.cyc.cycjava_1.cycl; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.ConsesLow.*; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.*; import static com.cyc.tool.subl.util.SubLFiles.*; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.*; import com.cyc.tool.subl.jrtl.nativeCode.type.core.*; import com.cyc.tool.subl.jrtl.nativeCode.type.number.*; import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.*; import com.cyc.tool.subl.jrtl.translatedCode.sublisp.*; import com.cyc.tool.subl.util.*; //dm import com.cyc.cycjava_1.cycl.access_macros; //dm import com.cyc.cycjava_1.cycl.assertion_manager; //dm import com.cyc.cycjava_1.cycl.assertions_high; //dm import com.cyc.cycjava_1.cycl.cfasl_kb_methods; //dm import com.cyc.cycjava_1.cycl.clauses; //dm import com.cyc.cycjava_1.cycl.constant_handles; //dm import com.cyc.cycjava_1.cycl.control_vars; //dm import com.cyc.cycjava_1.cycl.czer_utilities; //dm import com.cyc.cycjava_1.cycl.id_index; //dm import com.cyc.cycjava_1.cycl.kb_macros; //dm import com.cyc.cycjava_1.cycl.subl_macro_promotions; //dm import com.cyc.cycjava_1.cycl.subl_macros; //dm import com.cyc.cycjava_1.cycl.utilities_macros; public final class assertion_handles extends SubLTranslatedFile { //// Constructor private assertion_handles() {} public static final SubLFile me = new assertion_handles(); public static final String myName = "com.cyc.cycjava_1.cycl.assertion_handles"; //// Definitions /** The ID -> ASSERTION mapping table. */ @SubL(source = "cycl/assertion-handles.lisp", position = 1231) private static SubLSymbol $assertion_from_id$ = null; @SubL(source = "cycl/assertion-handles.lisp", position = 2857) public static final SubLObject do_assertions_table() { return $assertion_from_id$.getGlobalValue(); } @SubL(source = "cycl/assertion-handles.lisp", position = 2956) public static final SubLObject setup_assertion_table(SubLObject size, SubLObject exactP) { if ((NIL != $assertion_from_id$.getGlobalValue())) { return NIL; } $assertion_from_id$.setGlobalValue(id_index.new_id_index(size, ZERO_INTEGER)); return T; } @SubL(source = "cycl/assertion-handles.lisp", position = 3174) public static final SubLObject finalize_assertions(SubLObject max_assertion_id) { if ((max_assertion_id == UNPROVIDED)) { max_assertion_id = NIL; } set_next_assertion_id(max_assertion_id); if ((NIL == max_assertion_id)) { Errors .handleMissingMethodError("This call was replaced for LarKC purposes. Originally a method was called. Refer to number 30896"); Errors .handleMissingMethodError("This call was replaced for LarKC purposes. Originally a method was called. Refer to number 32189"); } return NIL; } @SubL(source = "cycl/assertion-handles.lisp", position = 3660) public static final SubLObject clear_assertion_table() { return id_index.clear_id_index($assertion_from_id$.getGlobalValue()); } /** Return the total number of assertions. */ @SubL(source = "cycl/assertion-handles.lisp", position = 4004) public static final SubLObject assertion_count() { if ((NIL == $assertion_from_id$.getGlobalValue())) { return ZERO_INTEGER; } return id_index.id_index_count($assertion_from_id$.getGlobalValue()); } @SubL(source = "cycl/assertion-handles.lisp", position = 4210) public static final SubLObject lookup_assertion(SubLObject id) { return id_index.id_index_lookup($assertion_from_id$.getGlobalValue(), id, UNPROVIDED); } @SubL(source = "cycl/assertion-handles.lisp", position = 5033) public static final SubLObject set_next_assertion_id(SubLObject max_assertion_id) { if ((max_assertion_id == UNPROVIDED)) { max_assertion_id = NIL; } { final SubLThread thread = SubLProcess.currentSubLThread(); { SubLObject max = MINUS_ONE_INTEGER; if ((NIL != max_assertion_id)) { max = max_assertion_id; } else { { SubLObject idx = do_assertions_table(); SubLObject mess = $str22$Determining_maximum_assertion_ID; SubLObject total = id_index.id_index_count(idx); SubLObject sofar = ZERO_INTEGER; checkType(mess, $sym23$STRINGP); { SubLObject _prev_bind_0 = utilities_macros.$last_percent_progress_index$.currentBinding(thread); SubLObject _prev_bind_1 = utilities_macros.$last_percent_progress_prediction$.currentBinding(thread); SubLObject _prev_bind_2 = utilities_macros.$within_noting_percent_progress$.currentBinding(thread); SubLObject _prev_bind_3 = utilities_macros.$percent_progress_start_time$.currentBinding(thread); try { utilities_macros.$last_percent_progress_index$.bind(ZERO_INTEGER, thread); utilities_macros.$last_percent_progress_prediction$.bind(NIL, thread); utilities_macros.$within_noting_percent_progress$.bind(T, thread); utilities_macros.$percent_progress_start_time$.bind(Time.get_universal_time(), thread); utilities_macros.noting_percent_progress_preamble(mess); { SubLObject idx_4 = idx; if ((NIL == id_index.id_index_objects_empty_p(idx_4, $kw24$SKIP))) { { SubLObject idx_5 = idx_4; if ((NIL == id_index.id_index_old_objects_empty_p(idx_5, $kw24$SKIP))) { { SubLObject vector_var = id_index.id_index_old_objects(idx_5); SubLObject backwardP_var = NIL; SubLObject length = Sequences.length(vector_var); SubLObject v_iteration = NIL; for (v_iteration = ZERO_INTEGER; v_iteration.numL(length); v_iteration = Numbers.add(v_iteration, ONE_INTEGER)) { { SubLObject id = ((NIL != backwardP_var) ? ((SubLObject) Numbers.subtract(length, v_iteration, ONE_INTEGER)) : v_iteration); SubLObject assertion = Vectors.aref(vector_var, id); if ((!(((NIL != id_index.id_index_tombstone_p(assertion)) && (NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)))))) { if ((NIL != id_index.id_index_tombstone_p(assertion))) { assertion = $kw24$SKIP; } utilities_macros.note_percent_progress(sofar, total); sofar = Numbers.add(sofar, ONE_INTEGER); max = Numbers.max(max, assertion_id(assertion)); } } } } } } { SubLObject idx_6 = idx_4; if ((!(((NIL != id_index.id_index_new_objects_empty_p(idx_6)) && (NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)))))) { { SubLObject v_new = id_index.id_index_new_objects(idx_6); SubLObject id = id_index.id_index_new_id_threshold(idx_6); SubLObject end_id = id_index.id_index_next_id(idx_6); SubLObject v_default = ((NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)) ? ((SubLObject) NIL) : $kw24$SKIP); while (id.numL(end_id)) { { SubLObject assertion = Hashtables.gethash_without_values(id, v_new, v_default); if ((!(((NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)) && (NIL != id_index.id_index_tombstone_p(assertion)))))) { utilities_macros.note_percent_progress(sofar, total); sofar = Numbers.add(sofar, ONE_INTEGER); max = Numbers.max(max, assertion_id(assertion)); } } id = Numbers.add(id, ONE_INTEGER); } } } } } } utilities_macros.noting_percent_progress_postamble(); } finally { utilities_macros.$percent_progress_start_time$.rebind(_prev_bind_3, thread); utilities_macros.$within_noting_percent_progress$.rebind(_prev_bind_2, thread); utilities_macros.$last_percent_progress_prediction$.rebind(_prev_bind_1, thread); utilities_macros.$last_percent_progress_index$.rebind(_prev_bind_0, thread); } } } } { SubLObject next_id = Numbers.add(max, ONE_INTEGER); id_index.set_id_index_next_id($assertion_from_id$.getGlobalValue(), next_id); return next_id; } } } } /** Note that ID will be used as the id for ASSERTION. */ @SubL(source = "cycl/assertion-handles.lisp", position = 5420) public static final SubLObject register_assertion_id(SubLObject assertion, SubLObject id) { reset_assertion_id(assertion, id); id_index.id_index_enter($assertion_from_id$.getGlobalValue(), id, assertion); return assertion; } /** Note that ID is not in use as an assertion id. */ @SubL(source = "cycl/assertion-handles.lisp", position = 5636) public static final SubLObject deregister_assertion_id(SubLObject id) { return id_index.id_index_remove($assertion_from_id$.getGlobalValue(), id); } /** Return a new integer id for an assertion. */ @SubL(source = "cycl/assertion-handles.lisp", position = 5785) public static final SubLObject make_assertion_id() { return id_index.id_index_reserve($assertion_from_id$.getGlobalValue()); } public static final class $assertion_native extends SubLStructNative { public SubLStructDecl getStructDecl() { return structDecl; } public SubLObject getField2() { return $id; } public SubLObject setField2(SubLObject value) { return $id = value; } public SubLObject $id = NIL; public static final SubLStructDeclNative structDecl = Structures.makeStructDeclNative($assertion_native.class, $sym25$ASSERTION, $sym26$ASSERTION_P, $list28, $list29, new String[] {"$id"}, $list30, $list31, $sym32$PRINT_ASSERTION); } @SubL(source = "cycl/assertion-handles.lisp", position = 6239) public static SubLSymbol $dtp_assertion$ = null; @SubL(source = "cycl/assertion-handles.lisp", position = 6239) public static final SubLObject assertion_p(SubLObject object) { return ((object.getClass() == $assertion_native.class) ? ((SubLObject) T) : NIL); } public static final class $assertion_p$UnaryFunction extends UnaryFunction { public $assertion_p$UnaryFunction() { super(extractFunctionNamed("ASSERTION-P")); } public SubLObject processItem(SubLObject arg1) { return assertion_p(arg1); } } @SubL(source = "cycl/assertion-handles.lisp", position = 6239) public static final SubLObject as_id(SubLObject object) { checkType(object, $sym26$ASSERTION_P); return object.getField2(); } @SubL(source = "cycl/assertion-handles.lisp", position = 6239) public static final SubLObject _csetf_as_id(SubLObject object, SubLObject value) { checkType(object, $sym26$ASSERTION_P); return object.setField2(value); } @SubL(source = "cycl/assertion-handles.lisp", position = 6239) public static final SubLObject make_assertion(SubLObject arglist) { if ((arglist == UNPROVIDED)) { arglist = NIL; } { SubLObject v_new = new $assertion_native(); SubLObject next = NIL; for (next = arglist; (NIL != next); next = conses_high.cddr(next)) { { SubLObject current_arg = next.first(); SubLObject current_value = conses_high.cadr(next); SubLObject pcase_var = current_arg; if (pcase_var.eql($kw36$ID)) { _csetf_as_id(v_new, current_value); } else { Errors.error($str37$Invalid_slot__S_for_construction_, current_arg); } } } return v_new; } } @SubL(source = "cycl/assertion-handles.lisp", position = 6367) public static SubLSymbol $print_assertions_in_cnf$ = null; @SubL(source = "cycl/assertion-handles.lisp", position = 7238) public static final SubLObject sxhash_assertion_method(SubLObject object) { { SubLObject id = as_id(object); if (id.isInteger()) { return id; } } return $int41$23; } public static final class $sxhash_assertion_method$UnaryFunction extends UnaryFunction { public $sxhash_assertion_method$UnaryFunction() { super(extractFunctionNamed("SXHASH-ASSERTION-METHOD")); } public SubLObject processItem(SubLObject arg1) { return sxhash_assertion_method(arg1); } } /** Make a new assertion shell, potentially in static space. */ @SubL(source = "cycl/assertion-handles.lisp", position = 7366) public static final SubLObject get_assertion() { { SubLObject assertion = NIL; assertion = make_assertion(UNPROVIDED); return assertion; } } /** Invalidate ASSERTION. */ @SubL(source = "cycl/assertion-handles.lisp", position = 7594) public static final SubLObject free_assertion(SubLObject assertion) { _csetf_as_id(assertion, NIL); return assertion; } /** Return T iff OBJECT is a valid assertion handle. */ @SubL(source = "cycl/assertion-handles.lisp", position = 7886) public static final SubLObject valid_assertion_handleP(SubLObject object) { return makeBoolean(((NIL != assertion_p(object)) && (NIL != assertion_handle_validP(object)))); } /** Return T if ASSERTION is a valid assertion. */ @SubL(source = "cycl/assertion-handles.lisp", position = 8064) public static final SubLObject valid_assertionP(SubLObject assertion, SubLObject robustP) { if ((robustP == UNPROVIDED)) { robustP = NIL; } return valid_assertion_handleP(assertion); } @SubL(source = "cycl/assertion-handles.lisp", position = 8325) public static final SubLObject make_assertion_shell(SubLObject id) { if ((id == UNPROVIDED)) { id = NIL; } if ((NIL == id)) { id = make_assertion_id(); } checkType(id, $sym46$FIXNUMP); { SubLObject assertion = get_assertion(); register_assertion_id(assertion, id); return assertion; } } /** Create a sample invalid-assertion. */ @SubL(source = "cycl/assertion-handles.lisp", position = 8574) public static final SubLObject create_sample_invalid_assertion() { return get_assertion(); } @SubL(source = "cycl/assertion-handles.lisp", position = 8939) public static final SubLObject free_all_assertions() { { final SubLThread thread = SubLProcess.currentSubLThread(); { SubLObject idx = do_assertions_table(); SubLObject mess = $str47$Freeing_assertions; SubLObject total = id_index.id_index_count(idx); SubLObject sofar = ZERO_INTEGER; checkType(mess, $sym23$STRINGP); { SubLObject _prev_bind_0 = utilities_macros.$last_percent_progress_index$.currentBinding(thread); SubLObject _prev_bind_1 = utilities_macros.$last_percent_progress_prediction$.currentBinding(thread); SubLObject _prev_bind_2 = utilities_macros.$within_noting_percent_progress$.currentBinding(thread); SubLObject _prev_bind_3 = utilities_macros.$percent_progress_start_time$.currentBinding(thread); try { utilities_macros.$last_percent_progress_index$.bind(ZERO_INTEGER, thread); utilities_macros.$last_percent_progress_prediction$.bind(NIL, thread); utilities_macros.$within_noting_percent_progress$.bind(T, thread); utilities_macros.$percent_progress_start_time$.bind(Time.get_universal_time(), thread); utilities_macros.noting_percent_progress_preamble(mess); { SubLObject idx_7 = idx; if ((NIL == id_index.id_index_objects_empty_p(idx_7, $kw24$SKIP))) { { SubLObject idx_8 = idx_7; if ((NIL == id_index.id_index_old_objects_empty_p(idx_8, $kw24$SKIP))) { { SubLObject vector_var = id_index.id_index_old_objects(idx_8); SubLObject backwardP_var = NIL; SubLObject length = Sequences.length(vector_var); SubLObject v_iteration = NIL; for (v_iteration = ZERO_INTEGER; v_iteration.numL(length); v_iteration = Numbers.add(v_iteration, ONE_INTEGER)) { { SubLObject id = ((NIL != backwardP_var) ? ((SubLObject) Numbers.subtract(length, v_iteration, ONE_INTEGER)) : v_iteration); SubLObject assertion = Vectors.aref(vector_var, id); if ((!(((NIL != id_index.id_index_tombstone_p(assertion)) && (NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)))))) { if ((NIL != id_index.id_index_tombstone_p(assertion))) { assertion = $kw24$SKIP; } utilities_macros.note_percent_progress(sofar, total); sofar = Numbers.add(sofar, ONE_INTEGER); free_assertion(assertion); } } } } } } { SubLObject idx_9 = idx_7; if ((!(((NIL != id_index.id_index_new_objects_empty_p(idx_9)) && (NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)))))) { { SubLObject v_new = id_index.id_index_new_objects(idx_9); SubLObject id = id_index.id_index_new_id_threshold(idx_9); SubLObject end_id = id_index.id_index_next_id(idx_9); SubLObject v_default = ((NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)) ? ((SubLObject) NIL) : $kw24$SKIP); while (id.numL(end_id)) { { SubLObject assertion = Hashtables.gethash_without_values(id, v_new, v_default); if ((!(((NIL != id_index.id_index_skip_tombstones_p($kw24$SKIP)) && (NIL != id_index.id_index_tombstone_p(assertion)))))) { utilities_macros.note_percent_progress(sofar, total); sofar = Numbers.add(sofar, ONE_INTEGER); free_assertion(assertion); } } id = Numbers.add(id, ONE_INTEGER); } } } } } } utilities_macros.noting_percent_progress_postamble(); } finally { utilities_macros.$percent_progress_start_time$.rebind(_prev_bind_3, thread); utilities_macros.$within_noting_percent_progress$.rebind(_prev_bind_2, thread); utilities_macros.$last_percent_progress_prediction$.rebind(_prev_bind_1, thread); utilities_macros.$last_percent_progress_index$.rebind(_prev_bind_0, thread); } } } clear_assertion_table(); assertion_manager.clear_assertion_content_table(); return NIL; } } /** Return the id of this ASSERTION. */ @SubL(source = "cycl/assertion-handles.lisp", position = 9152) public static final SubLObject assertion_id(SubLObject assertion) { checkType(assertion, $sym26$ASSERTION_P); return as_id(assertion); } /** Primitively change the assertion id for ASSERTION to NEW-ID. */ @SubL(source = "cycl/assertion-handles.lisp", position = 9341) public static final SubLObject reset_assertion_id(SubLObject assertion, SubLObject new_id) { _csetf_as_id(assertion, new_id); return assertion; } @SubL(source = "cycl/assertion-handles.lisp", position = 9527) public static final SubLObject assertion_handle_validP(SubLObject assertion) { return Types.integerp(as_id(assertion)); } /** Return the assertion with ID, or NIL if not present. */ @SubL(source = "cycl/assertion-handles.lisp", position = 9631) public static final SubLObject find_assertion_by_id(SubLObject id) { checkType(id, $sym52$INTEGERP); return lookup_assertion(id); } public static final class $find_assertion_by_id$UnaryFunction extends UnaryFunction { public $find_assertion_by_id$UnaryFunction() { super(extractFunctionNamed("FIND-ASSERTION-BY-ID")); } public SubLObject processItem(SubLObject arg1) { return find_assertion_by_id(arg1); } } public static final SubLObject declare_assertion_handles_file() { declareFunction(myName, "new_assertions_iterator", "NEW-ASSERTIONS-ITERATOR", 0, 0, false); declareMacro(myName, "do_assertions", "DO-ASSERTIONS"); declareMacro(myName, "do_old_assertions", "DO-OLD-ASSERTIONS"); declareMacro(myName, "do_new_assertions", "DO-NEW-ASSERTIONS"); declareFunction(myName, "do_assertions_table", "DO-ASSERTIONS-TABLE", 0, 0, false); declareFunction(myName, "setup_assertion_table", "SETUP-ASSERTION-TABLE", 2, 0, false); declareFunction(myName, "finalize_assertions", "FINALIZE-ASSERTIONS", 0, 1, false); declareFunction(myName, "optimize_assertion_table", "OPTIMIZE-ASSERTION-TABLE", 0, 0, false); declareFunction(myName, "clear_assertion_table", "CLEAR-ASSERTION-TABLE", 0, 0, false); declareFunction(myName, "create_assertion_dump_id_table", "CREATE-ASSERTION-DUMP-ID-TABLE", 0, 0, false); declareFunction(myName, "new_dense_assertion_id_index", "NEW-DENSE-ASSERTION-ID-INDEX", 0, 0, false); declareFunction(myName, "assertion_count", "ASSERTION-COUNT", 0, 0, false); declareFunction(myName, "lookup_assertion", "LOOKUP-ASSERTION", 1, 0, false); declareFunction(myName, "next_assertion_id", "NEXT-ASSERTION-ID", 0, 0, false); declareFunction(myName, "new_assertion_id_threshold", "NEW-ASSERTION-ID-THRESHOLD", 0, 0, false); declareFunction(myName, "old_assertion_count", "OLD-ASSERTION-COUNT", 0, 0, false); declareFunction(myName, "new_assertion_count", "NEW-ASSERTION-COUNT", 0, 0, false); declareFunction(myName, "missing_old_assertion_ids", "MISSING-OLD-ASSERTION-IDS", 0, 0, false); declareFunction(myName, "set_next_assertion_id", "SET-NEXT-ASSERTION-ID", 0, 1, false); declareFunction(myName, "register_assertion_id", "REGISTER-ASSERTION-ID", 2, 0, false); declareFunction(myName, "deregister_assertion_id", "DEREGISTER-ASSERTION-ID", 1, 0, false); declareFunction(myName, "make_assertion_id", "MAKE-ASSERTION-ID", 0, 0, false); declareFunction(myName, "assertion_print_function_trampoline", "ASSERTION-PRINT-FUNCTION-TRAMPOLINE", 2, 0, false); declareFunction(myName, "assertion_p", "ASSERTION-P", 1, 0, false); new $assertion_p$UnaryFunction(); declareFunction(myName, "as_id", "AS-ID", 1, 0, false); declareFunction(myName, "_csetf_as_id", "_CSETF-AS-ID", 2, 0, false); declareFunction(myName, "make_assertion", "MAKE-ASSERTION", 0, 1, false); declareFunction(myName, "print_assertion", "PRINT-ASSERTION", 3, 0, false); declareFunction(myName, "sxhash_assertion_method", "SXHASH-ASSERTION-METHOD", 1, 0, false); new $sxhash_assertion_method$UnaryFunction(); declareFunction(myName, "get_assertion", "GET-ASSERTION", 0, 0, false); declareFunction(myName, "free_assertion", "FREE-ASSERTION", 1, 0, false); declareFunction(myName, "valid_assertion_handleP", "VALID-ASSERTION-HANDLE?", 1, 0, false); declareFunction(myName, "valid_assertionP", "VALID-ASSERTION?", 1, 1, false); declareFunction(myName, "assertion_id_p", "ASSERTION-ID-P", 1, 0, false); declareFunction(myName, "make_assertion_shell", "MAKE-ASSERTION-SHELL", 0, 1, false); declareFunction(myName, "create_sample_invalid_assertion", "CREATE-SAMPLE-INVALID-ASSERTION", 0, 0, false); declareFunction(myName, "partition_create_invalid_assertion", "PARTITION-CREATE-INVALID-ASSERTION", 0, 0, false); declareFunction(myName, "free_all_assertions", "FREE-ALL-ASSERTIONS", 0, 0, false); declareFunction(myName, "assertion_id", "ASSERTION-ID", 1, 0, false); declareFunction(myName, "reset_assertion_id", "RESET-ASSERTION-ID", 2, 0, false); declareFunction(myName, "assertion_handle_validP", "ASSERTION-HANDLE-VALID?", 1, 0, false); declareFunction(myName, "find_assertion_by_id", "FIND-ASSERTION-BY-ID", 1, 0, false); new $find_assertion_by_id$UnaryFunction(); return NIL; } public static final SubLObject init_assertion_handles_file() { $assertion_from_id$ = deflexical("*ASSERTION-FROM-ID*", maybeDefault( $sym0$_ASSERTION_FROM_ID_, $assertion_from_id$, NIL)); $dtp_assertion$ = defconstant("*DTP-ASSERTION*", $sym25$ASSERTION); $print_assertions_in_cnf$ = defparameter("*PRINT-ASSERTIONS-IN-CNF*", NIL); return NIL; } public static final SubLObject setup_assertion_handles_file() { subl_macro_promotions.declare_defglobal($sym0$_ASSERTION_FROM_ID_); utilities_macros.register_cyc_api_macro($sym9$DO_ASSERTIONS, $list1, $str10$Iterate_over_all_HL_assertion_dat); access_macros.register_macro_helper($sym15$DO_ASSERTIONS_TABLE, $sym9$DO_ASSERTIONS); access_macros.register_macro_helper($sym16$CREATE_ASSERTION_DUMP_ID_TABLE, $sym17$WITH_ASSERTION_DUMP_ID_TABLE); utilities_macros.register_cyc_api_function($sym18$ASSERTION_COUNT, NIL, $str19$Return_the_total_number_of_assert, NIL, $list20); Structures.register_method(print_high.$print_object_method_table$.getGlobalValue(), $dtp_assertion$.getGlobalValue(), Symbols.symbol_function($sym33$ASSERTION_PRINT_FUNCTION_TRAMPOLINE)); Structures.def_csetf($sym34$AS_ID, $sym35$_CSETF_AS_ID); Equality.identity($sym25$ASSERTION); Structures.register_method(Sxhash.$sxhash_method_table$.getGlobalValue(), $dtp_assertion$.getGlobalValue(), Symbols.symbol_function($sym42$SXHASH_ASSERTION_METHOD)); utilities_macros.register_cyc_api_function($sym26$ASSERTION_P, $list43, $str44$Return_T_iff_OBJECT_is_an_HL_asse, NIL, $list45); utilities_macros.register_cyc_api_function($sym48$ASSERTION_ID, $list49, $str50$Return_the_id_of_this_ASSERTION_, $list51, $list20); utilities_macros.register_cyc_api_function($sym53$FIND_ASSERTION_BY_ID, $list28, $str54$Return_the_assertion_with_ID__or_, $list55, $list56); return NIL; } //// Internal Constants public static final SubLSymbol $sym0$_ASSERTION_FROM_ID_ = makeSymbol("*ASSERTION-FROM-ID*"); public static final SubLList $list1 = list(list(makeSymbol("VAR"), makeSymbol("&OPTIONAL"), list(makeSymbol("PROGRESS-MESSAGE"), makeString("mapping Cyc assertions")), makeSymbol("&KEY"), makeSymbol("DONE")), makeSymbol("&BODY"), makeSymbol("BODY")); public static final SubLString $str2$mapping_Cyc_assertions = makeString("mapping Cyc assertions"); public static final SubLList $list3 = list(makeKeyword("DONE")); public static final SubLSymbol $kw4$ALLOW_OTHER_KEYS = makeKeyword("ALLOW-OTHER-KEYS"); public static final SubLSymbol $kw5$DONE = makeKeyword("DONE"); public static final SubLSymbol $sym6$DO_KB_SUID_TABLE = makeSymbol("DO-KB-SUID-TABLE"); public static final SubLList $list7 = list(makeSymbol("DO-ASSERTIONS-TABLE")); public static final SubLSymbol $kw8$PROGRESS_MESSAGE = makeKeyword("PROGRESS-MESSAGE"); public static final SubLSymbol $sym9$DO_ASSERTIONS = makeSymbol("DO-ASSERTIONS"); public static final SubLString $str10$Iterate_over_all_HL_assertion_dat = makeString("Iterate over all HL assertion datastructures, executing BODY within the scope of VAR.\n VAR is bound to the assertion.\n PROGRESS-MESSAGE is a progress message string.\n Iteration halts early as soon as DONE becomes non-nil."); public static final SubLList $list11 = list(list(makeSymbol("ASSERTION"), makeSymbol("&KEY"), makeSymbol("PROGRESS-MESSAGE"), makeSymbol("DONE")), makeSymbol("&BODY"), makeSymbol("BODY")); public static final SubLList $list12 = list(makeKeyword("PROGRESS-MESSAGE"), makeKeyword("DONE")); public static final SubLSymbol $sym13$DO_KB_SUID_TABLE_OLD_OBJECTS = makeSymbol("DO-KB-SUID-TABLE-OLD-OBJECTS"); public static final SubLSymbol $sym14$DO_KB_SUID_TABLE_NEW_OBJECTS = makeSymbol("DO-KB-SUID-TABLE-NEW-OBJECTS"); public static final SubLSymbol $sym15$DO_ASSERTIONS_TABLE = makeSymbol("DO-ASSERTIONS-TABLE"); public static final SubLSymbol $sym16$CREATE_ASSERTION_DUMP_ID_TABLE = makeSymbol("CREATE-ASSERTION-DUMP-ID-TABLE"); public static final SubLSymbol $sym17$WITH_ASSERTION_DUMP_ID_TABLE = makeSymbol("WITH-ASSERTION-DUMP-ID-TABLE"); public static final SubLSymbol $sym18$ASSERTION_COUNT = makeSymbol("ASSERTION-COUNT"); public static final SubLString $str19$Return_the_total_number_of_assert = makeString("Return the total number of assertions."); public static final SubLList $list20 = list(makeSymbol("INTEGERP")); public static final SubLSymbol $kw21$OLD = makeKeyword("OLD"); public static final SubLString $str22$Determining_maximum_assertion_ID = makeString("Determining maximum assertion ID"); public static final SubLSymbol $sym23$STRINGP = makeSymbol("STRINGP"); public static final SubLSymbol $kw24$SKIP = makeKeyword("SKIP"); public static final SubLSymbol $sym25$ASSERTION = makeSymbol("ASSERTION"); public static final SubLSymbol $sym26$ASSERTION_P = makeSymbol("ASSERTION-P"); public static final SubLInteger $int27$141 = makeInteger(141); public static final SubLList $list28 = list(makeSymbol("ID")); public static final SubLList $list29 = list(makeKeyword("ID")); public static final SubLList $list30 = list(makeSymbol("AS-ID")); public static final SubLList $list31 = list(makeSymbol("_CSETF-AS-ID")); public static final SubLSymbol $sym32$PRINT_ASSERTION = makeSymbol("PRINT-ASSERTION"); public static final SubLSymbol $sym33$ASSERTION_PRINT_FUNCTION_TRAMPOLINE = makeSymbol("ASSERTION-PRINT-FUNCTION-TRAMPOLINE"); public static final SubLSymbol $sym34$AS_ID = makeSymbol("AS-ID"); public static final SubLSymbol $sym35$_CSETF_AS_ID = makeSymbol("_CSETF-AS-ID"); public static final SubLSymbol $kw36$ID = makeKeyword("ID"); public static final SubLString $str37$Invalid_slot__S_for_construction_ = makeString("Invalid slot ~S for construction function"); public static final SubLString $str38$__AS__S__S_ = makeString("#<AS:~S:~S>"); public static final SubLString $str39$__AS__S_ = makeString("#<AS:~S>"); public static final SubLString $str40$_The_CFASL_invalid_assertion_ = makeString("<The CFASL invalid assertion>"); public static final SubLInteger $int41$23 = makeInteger(23); public static final SubLSymbol $sym42$SXHASH_ASSERTION_METHOD = makeSymbol("SXHASH-ASSERTION-METHOD"); public static final SubLList $list43 = list(makeSymbol("OBJECT")); public static final SubLString $str44$Return_T_iff_OBJECT_is_an_HL_asse = makeString("Return T iff OBJECT is an HL assertion"); public static final SubLList $list45 = list(makeSymbol("BOOLEANP")); public static final SubLSymbol $sym46$FIXNUMP = makeSymbol("FIXNUMP"); public static final SubLString $str47$Freeing_assertions = makeString("Freeing assertions"); public static final SubLSymbol $sym48$ASSERTION_ID = makeSymbol("ASSERTION-ID"); public static final SubLList $list49 = list(makeSymbol("ASSERTION")); public static final SubLString $str50$Return_the_id_of_this_ASSERTION_ = makeString("Return the id of this ASSERTION."); public static final SubLList $list51 = list(list(makeSymbol("ASSERTION"), makeSymbol("ASSERTION-P"))); public static final SubLSymbol $sym52$INTEGERP = makeSymbol("INTEGERP"); public static final SubLSymbol $sym53$FIND_ASSERTION_BY_ID = makeSymbol("FIND-ASSERTION-BY-ID"); public static final SubLString $str54$Return_the_assertion_with_ID__or_ = makeString("Return the assertion with ID, or NIL if not present."); public static final SubLList $list55 = list(list(makeSymbol("ID"), makeSymbol("INTEGERP"))); public static final SubLList $list56 = list(list(makeSymbol("NIL-OR"), makeSymbol("ASSERTION-P"))); //// Initializers public void declareFunctions() { declare_assertion_handles_file(); } public void initializeVariables() { init_assertion_handles_file(); } public void runTopLevelForms() { setup_assertion_handles_file(); } }
53.681458
321
0.676261
2ec93d85f0cc1b32ad087b734453820e3a43008b
723
package com.kimi.myshop.plus.cloud.feign; import com.kimi.myshop.plus.cloud.dto.AdminLoginLogDTO; import com.kimi.myshop.plus.cloud.feign.fallback.MessageFeignFallback; import com.kimi.myshop.plus.config.FeignRequestConfig; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; /** * @author 郭富城 */ @FeignClient(value = "cloud-message",path = "message",configuration = FeignRequestConfig.class,fallback = MessageFeignFallback.class) public interface MessageFeign { @PostMapping(value = "admin/login/log") public String sendAdminLoginLog(@RequestBody AdminLoginLogDTO adminLoginLogDTO); }
38.052632
133
0.811895
5a447073719db80a3747954520f42c7ec55f88eb
1,061
package com.sysu.guli.service.oss.controller.admin; import com.sysu.guli.service.base.result.R; import com.sysu.guli.service.oss.service.FileService; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Api(tags = "阿里云文件管理") //跨域 @RestController @Slf4j @RequestMapping("/admin/oss/file") public class FileController { @Autowired FileService fileService; @PostMapping("upload") public R uploadAvatar(MultipartFile file, String module){ String imgUrl = fileService.upload(file,module); return R.ok().data("imgUrl", imgUrl); } @DeleteMapping("delete") public R deleteA(@RequestParam String module, @RequestParam String imgUrl){ System.out.println("module = " + module); System.out.println("imgUrl = " + imgUrl); fileService.delete(module,imgUrl); return R.ok(); } }
31.205882
79
0.724788
a2df6752a327e8d874fc886a363ab563d86a5943
594
package org.kyojo.schemaorg.m3n5.doma.core.container; import java.math.BigDecimal; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n5.core.impl.MIN_VALUE; import org.kyojo.schemaorg.m3n5.core.Container.MinValue; @ExternalDomain public class MinValueConverter implements DomainConverter<MinValue, BigDecimal> { @Override public BigDecimal fromDomainToValue(MinValue domain) { return domain.getNativeValue(); } @Override public MinValue fromValueToDomain(BigDecimal value) { return new MIN_VALUE(value); } }
24.75
81
0.809764
0790660fcc87cf38d924d9176861fbb97cd0bd81
6,623
package com.ruoyi.web.controller.system; import java.util.List; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.service.ISysDeptService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import jdk.nashorn.internal.ir.annotations.Ignore; import org.apache.ibatis.annotations.Param; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.system.domain.TMember; import com.ruoyi.system.domain.TMemberType; import com.ruoyi.system.service.ITMemberTypeService; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.poi.ExcelUtil; import springfox.documentation.annotations.ApiIgnore; /** * 会员类型 信息操作处理 * * @author ruoyi * @date 2019-06-03 */ @Controller @RequestMapping("/system/tMemberType") public class TMemberTypeController extends BaseController { private String prefix = "system/tMemberType"; @Autowired private ITMemberTypeService tMemberTypeService; @Autowired private ISysDeptService deptService; @RequiresPermissions("system:tMemberType:view") @GetMapping() public String tMemberType() { return prefix + "/tMemberType"; } /** * 校验部门名称 */ @PostMapping("/checkTMemberTypeNameUnique") @ResponseBody public String checkDeptNameUnique(TMemberType tMemberType) { //System.out.println(tMemberType); return tMemberTypeService.checkDeptNameUnique(tMemberType); } /** * 选择部门树 */ @GetMapping("/selectDeptTree/{deptId}") public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) { mmap.put("dept" , deptService.selectDeptById(deptId)); return "system/tMember/tree"; } /** * 查询会员类型列表 */ @RequiresPermissions("system:tMemberType:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(TMemberType tMemberType, ModelMap mmap) { startPage(); List<TMemberType> list = tMemberTypeService.selectTMemberTypeList(tMemberType); return getDataTable(list); } /** * 查询会员类型列表 */ @PostMapping("/listTypeName") @ResponseBody public List<TMemberType> listTypeName(TMemberType tMemberType, ModelMap mmap) { return tMemberTypeService.selectTMemberTypeListAndMemberTypeName(tMemberType); } @PostMapping("/TypeName") @ResponseBody public List<TMemberType> listTypeNmae(@Param("id") Integer id, TMemberType tMemberType, ModelMap mmap) { // mmap.put("tMemberType", tMemberType); List<TMemberType> tMemberTypes = tMemberTypeService.selectTMemberTypeByCompanyId(id); /*for (TMemberType tt: tMemberTypes) { System.out.println(tt); }*/ return tMemberTypeService.selectTMemberTypeByCompanyId(id); } /** * 导出会员类型列表 */ @RequiresPermissions("system:tMemberType:export") @PostMapping("/export") @ResponseBody public AjaxResult export(TMemberType tMemberType) { List<TMemberType> list = tMemberTypeService.selectTMemberTypeList(tMemberType); ExcelUtil<TMemberType> util = new ExcelUtil<TMemberType>(TMemberType.class); return util.exportExcel(list, "tMemberType"); } /** * 新增会员类型 */ @GetMapping("/add/{id}") public String add(@PathVariable("id") Long id, ModelMap mmap) { mmap.put("dept" , deptService.selectDeptById(id)); return prefix + "/add"; } /** * 新增保存会员类型 */ @RequiresPermissions("system:tMemberType:add") @Log(title = "会员类型" , businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(TMemberType tMemberType) { if (tMemberType.getValidDays() == null) { tMemberType.setValidDays(3650); } return toAjax(tMemberTypeService.insertTMemberType(tMemberType)); } /** * 修改会员类型 */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") Integer id, ModelMap mmap) { TMemberType tMemberType = tMemberTypeService.selectTMemberTypeById(id); mmap.put("tMemberType" , tMemberType); return prefix + "/edit"; } /** * 修改保存会员类型 */ @RequiresPermissions("system:tMemberType:edit") @Log(title = "会员类型" , businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(TMemberType tMemberType) { return toAjax(tMemberTypeService.updateTMemberType(tMemberType)); } /** * 修改保存会员状态 */ @RequiresPermissions("system:tMemberType:update") @Log(title = "会员类型" , businessType = BusinessType.UPDATE) @PostMapping("/update") @ResponseBody public AjaxResult update(@Param("isMemberPrice") String isMemberPrice, @Param("isPoints") String isPoints, @Param("isRerurn") String isRerurn, @Param("isM1") String isM1, @Param("isEncourage") String isEncourage, @Param("isAllowother") String isAllowother, @Param("id") String id) { return toAjax(tMemberTypeService.updateTMemberTypeAndStatus(isMemberPrice, isPoints, isRerurn, isM1, isEncourage, isAllowother, id)); } /** * 删除会员类型 */ @RequiresPermissions("system:tMemberType:remove") @Log(title = "会员类型" , businessType = BusinessType.DELETE) @PostMapping("/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(tMemberTypeService.deleteTMemberTypeByIds(ids)); } /** * 挂失锁定(状态修改) */ @RequiresPermissions("system:tMemberType:replace") @Log(title = "会员类型" , businessType = BusinessType.UPDATE) @PostMapping("/replace") @ResponseBody public AjaxResult replace(TMemberType tMemberType) { return toAjax(tMemberTypeService.replaceTMemberType(tMemberType)); } /** * 注销会员卡 */ @RequiresPermissions("system:tMemberType:cancel") @Log(title = "会员类型" , businessType = BusinessType.UPDATE) @PostMapping("/cancelTMemberType") @ResponseBody public AjaxResult cancelTMemberType(TMemberType tMemberType) { return toAjax(tMemberTypeService.cancelTMemberType(tMemberType)); } }
30.804651
286
0.70074
d4893e9ef7f3a79270140e82c734d0eb59f076c7
1,213
package net.abcbook.learn.lombok; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * @author summer * @date 2018/4/12 下午6:39 * Lombok HelloWorld 测试类 */ @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class LombokHelloTest { /** * @author summer * @date 2018/4/14 上午10:30 * @return void * @description lombok 的 getter 和 setter 测试 */ @Test public void lombokHello(){ SimpleUser simpleUser = new SimpleUser(); simpleUser.setUsername("summer"); Assert.assertEquals(simpleUser.getUsername(), "summer"); log.info("username: " + simpleUser.getUsername()); } /** * @author summer * @date 2018/4/14 上午10:30 * @return void * @description lombok 的全参构造方法测试 */ @Test public void constructorTest(){ SimpleUser simpleUser = new SimpleUser("username", "password", 18); Assert.assertEquals("username", simpleUser.getUsername()); log.info("user: " + simpleUser.toString()); } }
23.784314
75
0.661171
ddae337692cb2693b1314194ab53040900db0d9c
1,544
/****************************************************************************** * * * Program: MyPane * * Programmer: Mariusz Derezinski-Choo * Date: 05/25/2018 * School: Northwest Guilford High School * * * Description: This class extends stackPane by allowing a pane to be constructed with instnace variables describing * the row and column it will be located in on the grid pane. * * Learned: I learned how to extend subclasses of Pane as needed for my programs * * * Difficulties: I initially tried to avoid creating this class, but i realized it was necessary to have the * row and column instance variables present in the panes since it is complicated * to access them from getChildren() * *********************************************************************************/ import javafx.application.*; import javafx.scene.*; import javafx.stage.*; import javafx.scene.paint.Color; import javafx.scene.layout.HBox; import javafx.scene.shape.Circle; import javafx.scene.layout.StackPane; public class MyPane extends StackPane { private int row, column; // instance variables /* * constructer of my pane. does everything a stack pane does plus stores the row and column as instance variables */ public MyPane(int r, int c) { super(); row = r; column = c; } /* * accessors */ public int getRow() { return row; } public int getColumn() { return column; } }
29.692308
117
0.584845
84b429c6dffc88dfd02c851090549a08f29a2ab7
1,365
package com.truthbean.debbie.jdbc.entity; import com.truthbean.debbie.jdbc.column.ColumnInfo; import java.util.Collection; import java.util.List; import java.util.function.Supplier; /** * @author TruthBean * @since 0.5.3 * Created on 2021/12/13 21:23. */ public class ResultMap<E> extends EntityInfo<E> { private final Supplier<E> initSupplier; public ResultMap(Supplier<E> initSupplier) { this.initSupplier = initSupplier; } public ResultMap(ResultMap<E> resultMap) { super(resultMap); this.initSupplier = resultMap.initSupplier; } public void addResult(Collection<ColumnInfo> columnInfos) { List<ColumnInfo> columnInfoList = super.getColumnInfoList(); for (ColumnInfo columnInfo : columnInfoList) { for (ColumnInfo info : columnInfos) { if (columnInfo.getColumn().equals(info.getColumn())) { columnInfo.setValue(info.getValue()); } } } } public E toEntity() { E e = initSupplier.get(); List<ColumnInfo> list = getColumnInfoList(); for (ColumnInfo columnInfo : list) { columnInfo.getPropertySetter().set(e, columnInfo.getValue()); } return e; } @Override public ResultMap<E> copy() { return new ResultMap<E>(this); } }
26.25
73
0.624176
e350e277bd83151025e214bcd7a6d1f1c94f7a58
2,066
// // Copyright (C) 2010-2016 Roger Rene Kommer & Micromata GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package de.micromata.genome.gwiki.page.impl.wiki; import de.micromata.genome.gwiki.model.AuthorizationFailedException; import de.micromata.genome.gwiki.page.GWikiContext; /** * Macros will be created for each instanceof of a macro node in the document. * * * @author Roger Rene Kommer ([email protected]) * */ public interface GWikiMacro { /** * * @return true if the macro expexts a body. */ public boolean hasBody(); /** * * @return true, if the body is not plain text, but itself should be parsed as wiki text. */ public boolean evalBody(); /** * Pages with this macro cannot be saved by current user. * * @param attrs the attrs * @param ctx the ctx * @return true, if is restricted */ public boolean isRestricted(MacroAttributes attrs, GWikiContext ctx); /** * Will be called if a wiki artefakt will be safed by the user. The implementation should throw * AuthorizationFailedException if the current user has not the right to make usage of this macro or use invalid * attributes. * * @param attrs the attributes of the macro. * @param ctx Context. * @throws AuthorizationFailedException */ public void ensureRight(MacroAttributes attrs, GWikiContext ctx) throws AuthorizationFailedException; /** * combination of GWikiMacroRenderFlags * * @return */ public int getRenderModes(); public GWikiMacroInfo getMacroInfo(); }
28.30137
114
0.714424
ad4d7d4a233f66b8324cc578ef989f4688098995
189
package uo270318.mp.tareaS9.collections_iterators.model; public class LinkedListTest extends ListTest { @Override protected List createList() { return new LinkedList(); } }
17.181818
56
0.740741
aa23af546bcf54d567aa43c7cfeba817c25cbf1f
1,217
package leetcode.datastructures.binarytree; import leetcode.models.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** Binary Tree Level Traversal */ public class BinaryTreeLevelTraversal { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); if (root != null) { q.offer(root); } TreeNode cur; while (!q.isEmpty()) { int size = q.size(); List<Integer> subAns = new LinkedList<Integer>(); for (int i = 0; i < size; ++i) { // traverse nodes in the same level cur = q.poll(); subAns.add(cur.val); // visit the root if (cur.left != null) { q.offer(cur.left); // push left child to queue if it is not null } if (cur.right != null) { q.offer(cur.right); // push right child to queue if it is not null } } ans.add(subAns); } return ans; } }
32.891892
98
0.510271
5c13ecd1b53339ce01c8635626bdeac88ea28d93
1,509
/* * Copyright 2002-2018 Jalal Kiswani. * E-mail: [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jk.web.mvc.api; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.jk.util.locale.JKMessage; // TODO: Auto-generated Javadoc /** * The Class MvcContextInitializer. */ @WebListener public class MvcContextInitializer implements ServletContextListener { /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent sce) { sce.getServletContext().setAttribute("msg", JKMessage.getInstance()); } /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ @Override public void contextDestroyed(ServletContextEvent sce) { } }
30.795918
100
0.744864
e2e6f1e2acf34092fb4eb09639d7a9bf2ee6a40e
1,027
package com.pyh.collection; /** * 类ListToStack的实现描述:自己实现的stack * * @author panyinghua 2020-7-29 20:41 */ public class ListToStack { // 1.直接使用java的链表结构,自己实现也比较简单 //private LinkedList<Integer> outList = new LinkedList<>(); // 2.自己的简单链表类 private JLinkedList outList = new JLinkedList(); public static void main(String[] args) { ListToStack stack = new ListToStack(); stack.push(1); stack.push(2); stack.push(3); System.out.println(stack.pull()); System.out.println(stack.pull()); stack.push(4); stack.push(5); System.out.println(stack.pull()); } /** * 入栈 * @param i * @return */ public void push(Integer i) { // 一个单链表实现即可,添加元素的时候添加到队列的首位置 outList.addFirst(i); } /** * 出栈 * @return */ public Integer pull() { // 出栈的时候先从出队列里边从头开始输出元素 if(!outList.isEmpty()) { return outList.removeFirst(); } return null; } }
20.959184
63
0.555988
e812bf396fb5eabe26ea20539f3330dd36cae673
494
package io.quarkus.it.jpa.configurationless; import static org.hamcrest.core.StringContains.containsString; import org.junit.jupiter.api.Test; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; /** * @author Emmanuel Bernard [email protected] */ @QuarkusTest public class JPALoadScriptTest { @Test public void testImportExecuted() { RestAssured.when().get("/jpa-test/import").then() .body(containsString("jpa=OK")); } }
22.454545
62
0.720648
a4667bbfd45d4abcf160ee4a49ae96cc40bb799f
857
package cn.wbnull.hellotlj.presenter; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import cn.wbnull.hellotlj.view.IBaseView; /** * Mvp BasePresenter * * @author dukunbiao(null) 2020-02-04 * https://github.com/dkbnull/HelloTlj */ public class BasePresenter<T extends IBaseView> { private Reference<T> mReference; protected T mView; public void attachView(T view) { mReference = new WeakReference<>(view); if (isViewAttached()) { mView = getView(); } } public void detachView() { if (mReference != null) { mReference.clear(); mReference = null; } } public boolean isViewAttached() { return mReference != null && mReference.get() != null; } public T getView() { return mReference.get(); } }
20.902439
62
0.610268
fccc74f878f8b59a3ac291784d24f958f37752e5
245
package com.basic; public class PowerOfNumber3 { public static void main (String[] args) { int number = 10, p = 3; double result = Math.pow(number, p); System.out.println(number+"^"+p+" = "+result); } }
24.5
55
0.563265
a81f8eee3faf45a9a157091e7fdf984cd5e600af
7,635
package nl.han.ica.oopg.dashboard; import nl.han.ica.oopg.objects.GameObject; import nl.han.ica.oopg.objects.Sprite; import nl.han.ica.oopg.view.PGraphicsCreator; import processing.core.PGraphics; import java.util.Vector; /** * Create or extend this class to create a new dashboard, a dashboard object * will be drawn above the ViewPort when added to the dashboard list inside the * GameEngine (addDashboard). */ public class Dashboard extends GameObject { private Integer backgroundR; private Integer backgroundG; private Integer backgroundB; private Sprite backgroundImage; private PGraphicsCreator pGraphicsCreator = new PGraphicsCreator(); private Vector<GameObject> gameObjects = new Vector<>(); public Dashboard(float x, float y, float width, float height) { super(x, y, width, height); } /** * Override this method to update the objects that need to be drawn. */ @Override public void update() { // Override this method to update the objects that need to be drawn. } /** * Draws all the GameObjects inside the dashboard on the given canvas. * * @param g PGraphics object will be given by the GameEngine. */ @Override public void draw(PGraphics g) { PGraphics canvas = drawCanvas(); g.image(canvas, this.getX(), this.getY()); } /** * Draws the canvas (dashboard). */ private PGraphics drawCanvas() { PGraphics canvas = pGraphicsCreator.createPGraphics( (int) this.getWidth(), (int) this.getHeight()); canvas.beginDraw(); canvas.noStroke(); setBackgroundFor(canvas); drawObjectsTo(canvas); canvas.endDraw(); return canvas; } /** * Draw the dashboardObjects from type nl.oopgame.supaplex.GameObject on the canvas which are set visible. * * @param canvas The Canvas as an PGraphics */ private void drawObjectsTo(PGraphics canvas) { for (int i = 0; i < gameObjects.size(); i++) { drawVisibleGameObjects(canvas, i); } } /** * Actually draws GameObjects that are set visible to the dashboard. * * @param canvas The Canvas * @param i The index of the nl.oopgame.supaplex.GameObject that should be mae visible */ private void drawVisibleGameObjects(PGraphics canvas, int i) { if (gameObjects.get(i).isVisible()) { gameObjects.get(i).draw(canvas); } } /** * Sets background for the dashboard. RGB when backgroundActive is false, * Image when backgroundActive is true. * * @param canvas The Canvas that should have a backgrund set */ private void setBackgroundFor(PGraphics canvas) { if (backgroundR != null && backgroundG != null && backgroundB != null) { canvas.background(backgroundR, backgroundG, backgroundB); } if (backgroundImage != null) { canvas.image(backgroundImage.getPImage(), 0, 0, width, height); } } /** * Add a nl.oopgame.supaplex.GameObject to the dashboard. * * @param gameObject The nl.oopgame.supaplex.GameObject that will be added to the canvas. Sets the X * and Y relatively to the canvas, so the GameObjects will move * with the dashboard. */ public void addGameObject(GameObject gameObject) { gameObject.setX(this.getX() + gameObject.getX()); gameObject.setY(this.getY() + gameObject.getY()); gameObjects.add(gameObject); } /** * Add a nl.oopgame.supaplex.GameObject to the dashboard. * * @param gameObject The nl.oopgame.supaplex.GameObject that should be added * @param x The x cooridinate on which the nl.oopgame.supaplex.GameObject should be added * @param y The y cooridinate on which the nl.oopgame.supaplex.GameObject should be added */ public void addGameObject(GameObject gameObject, int x, int y) { gameObjects.add(gameObject); gameObject.setX(this.getX() + (float) x); gameObject.setY(this.getY() + (float) y); } /** * Add a nl.oopgame.supaplex.GameObject to the dashboard. * * @param gameObject The nl.oopgame.supaplex.GameObject that should be added * @param x The x cooridinate on which the nl.oopgame.supaplex.GameObject should be added * @param y The y cooridinate on which the nl.oopgame.supaplex.GameObject should be added * @param layerposition The layer position on which the GameObjects should be created */ public void addGameObject(GameObject gameObject, int x, int y, float layerposition) { gameObjects.add(gameObject); gameObject.setX((float) x); gameObject.setY((float) y); gameObject.setZ(layerposition); } /** * Add a nl.oopgame.supaplex.GameObject to the dashboard. * * @param gameObject The nl.oopgame.supaplex.GameObject that should be added * @param layerposition The layer position on which the GameObjects should be created */ public void addGameObject(GameObject gameObject, float layerposition) { gameObjects.add(gameObject); gameObject.setZ(layerposition); } /** * Get a list of all the GameObjects inside the dashboard. * * @return All GameObjects */ public Vector<GameObject> getGameObjects() { return gameObjects; } /** * Delete a nl.oopgame.supaplex.GameObject from the dashboard. * * @param gameObject The nl.oopgame.supaplex.GameObject that should be deleted */ public void deleteGameObject(GameObject gameObject) { gameObjects.remove(gameObject); } /** * Deletes all GameObjects from the dashboard. */ public void deleteAllDashboardObjects() { gameObjects.removeAllElements(); } /** * Deletes all GameObjects with the given type from the dashboard. * <p> * Example paramater: nl.oopgame.supaplex.Player.class * * @param type The type of the gameobjects * @param <T> Generic type, should extend nl.oopgame.supaplex.GameObject */ public <T extends GameObject> void deleteAllGameObjectsOfType(Class<T> type) { gameObjects.removeIf(p -> type.equals(p.getClass())); } /** * Set the background of the dashboard with RGB-values. * * @param r Red value of the background * @param g Green value of the background * @param b Blue value of the background */ public void setBackground(Integer r, Integer g, Integer b) { backgroundR = r; backgroundG = g; backgroundB = b; } /** * Set the background of the dashboard with a Sprite object (image). * * @param sprite The Sprite that should be used as the background */ public void setBackgroundImage(Sprite sprite) { backgroundImage = sprite; } /** * Sets the PGraphicsCreator which can create the canvas where to draw on. * * @param pGraphicsCreator The PGraphicsCreator that should be used */ public void setPGraphicsCreator(PGraphicsCreator pGraphicsCreator) { this.pGraphicsCreator = pGraphicsCreator; } }
31.290984
111
0.620432
2155ddd7c5e5387833fcfd6f0d9332aeae90522e
1,753
package org.ticketbooking.core.domain.user; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import org.ticketbooking.core.domain.other.Locale; import org.ticketbooking.core.domain.other.LocaleImpl; @Entity @Table(name="TBS_COUNTRY") @NamedQueries(value={ @NamedQuery(name="CountryImpl.fetchByCountryName",query="from CountryImpl where name = :name") }) public class CountryImpl implements Country{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="TBS_COUNTRY_ID") private Long id; @Column(name="TBS_COUNTRY_NAME",unique=true) private String name; @OneToOne(mappedBy="country",cascade=CascadeType.ALL,targetEntity=LocaleImpl.class) private Locale locale; @OneToOne(mappedBy="country",cascade=CascadeType.ALL,targetEntity=StateImpl.class) private State state; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public State getState() { return state; } public void setState(State state) { this.state = state; } @Override public String toString() { return "CountryImpl [id=" + id + ", name=" + name + ", locale=" + locale + ", state=" + state + "]"; } }
21.120482
96
0.737593
921a150325e3b3400046110ad3064de124efda6d
4,167
package com.lesson.distributed.redis.sample; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * * 自写 jedis * * resp 协议 * * * * * @author zhengshijun * @version created on 2018/9/12. */ public class Zedis { private static final Logger log = LoggerFactory.getLogger(Zedis.class); private Socket socket; private String ip; private int port; private String auth; private final static String RN = StringUtils.CR.concat(StringUtils.LF); private byte[] bytes = null; public Zedis(String ip, int port, String auth) { this.ip = ip; this.port = port; this.auth = auth; try { socket = new Socket(ip, port); } catch (Exception e) { log.error(StringUtils.EMPTY, e); } init(); } private OutputStream getOutputStream() throws IOException { return socket.getOutputStream(); } private InputStream getInputStream() throws IOException { return socket.getInputStream(); } private void init() { try { sendCommand("AUTH",auth); String result = response(); log.info("result:{}",result); } catch (Exception e) { log.error(StringUtils.EMPTY,e); } } public String set(String key, String value) { try { sendCommand("SET",key,value); String result = response(); log.info("set result:{}",result); return result; } catch (Exception e) { log.error(StringUtils.EMPTY); } return null; } public String get(String key) { try { sendCommand("GET",key); String result = response(); log.info("get result:{}",result); return result; } catch (Exception e) { log.error(StringUtils.EMPTY); } return null; } /** * 发送命令 * @param command * @param args * @throws IOException */ public void sendCommand(String command,String...args) throws IOException{ StringBuilder stringBuilder = new StringBuilder(); // *多少组数据 stringBuilder.append("*").append(args.length+1).append(RN); stringBuilder.append("$").append(command.getBytes().length).append(RN); stringBuilder.append(command).append(RN); for (String arg : args) { stringBuilder.append("$").append(arg.getBytes().length).append(RN); stringBuilder.append(arg).append(RN); } log.info(StringUtils.LF+"command: \n{}",stringBuilder.toString()); OutputStream outputStream = getOutputStream(); outputStream.write(stringBuilder.toString().getBytes()); outputStream.flush(); } public String response() throws IOException{ InputStream inputStream = getInputStream(); byte[] response = new byte[2048]; int count = inputStream.read(response); if (count < 0){ return null; } byte flag = response[0]; bytes = new byte[count]; System.arraycopy(response, 0, bytes, 0, count); switch (flag){ case '+': break; case '$': break; } return new String(bytes); } public String mdel(String... keys) { try { sendCommand("DEL",keys); String result = response(); log.info("mdel result:{}",result); } catch (Exception e) { log.error(StringUtils.EMPTY); } return null; } public boolean isConnected() { return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } public void close() { try { socket.close(); } catch (Exception e) { log.error(StringUtils.EMPTY, e); } } }
23.948276
95
0.557715
7c8b054c8b1b8096e69c0fe50c869d94e03cf6b9
1,136
import java.util.Arrays; import java.util.stream.IntStream; class Check{ // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using Linear Search method boolean test = false; for (int element : arr) { if (element == toCheckValue) { test = true; break; } } // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); } }
26.418605
64
0.488556
5e3e12a811eb93149952c66c3d506db4ad983762
527
package com.threeq.dubbo.tracing; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @Date 2017/2/8 * @User three */ public class ApplicationContextAwareBean implements ApplicationContextAware { public static ApplicationContext CONTEXT; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { CONTEXT = applicationContext; } }
27.736842
100
0.798861
bfcd537dfdf935c6ea27e1b1c946215ea5477c3b
1,985
package de.techdev.trackr.domain.employee.login; import de.techdev.trackr.domain.AbstractDomainResourceTest; import org.junit.Test; import org.springframework.http.MediaType; import static de.techdev.trackr.domain.DomainResourceTestMatchers.isAccessible; import static de.techdev.trackr.domain.DomainResourceTestMatchers.isMethodNotAllowed; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * @author Moritz Schulze */ public class AuthorityResourceTest extends AbstractDomainResourceTest<Authority> { @Override protected String getResourceName() { return "authorities"; } @Test public void findAll() throws Exception { assertThat(root(employeeSession()), isAccessible()); } @Test public void findOne() throws Exception { assertThat(one(employeeSession()), isAccessible()); } @Test public void postDisabled() throws Exception { assertThat(create(employeeSession()), isMethodNotAllowed()); } @Test public void putDisabled() throws Exception { assertThat(update(employeeSession()), isMethodNotAllowed()); } @Test public void deleteDisabled() throws Exception { assertThat(remove(employeeSession()), isMethodNotAllowed()); } @Test public void findByAuthorityDisabled() throws Exception { Authority authority = dataOnDemand.getRandomObject(); mockMvc.perform( delete("/authorities/search/findByAuthority") .session(employeeSession()) .param("authority", authority.getAuthority())) .andExpect(status().isMethodNotAllowed()); } @Override protected String getJsonRepresentation(Authority item) { return "{}"; } }
31.015625
85
0.704282
a41622f1ffb27fc024b759a0e56207f2a7b912dd
19,267
package it.zenitlab.cordova.plugins.zbtprinter; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.os.Looper; import android.util.Base64; import android.util.Log; import it.zenitlab.cordova.plugins.zbtprinter.ZPLConverter; import com.zebra.sdk.comm.BluetoothConnectionInsecure; import com.zebra.sdk.comm.Connection; import com.zebra.sdk.comm.ConnectionException; import com.zebra.sdk.graphics.internal.ZebraImageAndroid; import com.zebra.sdk.printer.PrinterStatus; import com.zebra.sdk.printer.SGD; import com.zebra.sdk.printer.ZebraPrinter; import com.zebra.sdk.printer.ZebraPrinterFactory; import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException; import com.zebra.sdk.printer.ZebraPrinterLinkOs; import com.zebra.sdk.printer.discovery.BluetoothDiscoverer; import com.zebra.sdk.printer.discovery.DiscoveredPrinter; import com.zebra.sdk.printer.discovery.DiscoveryHandler; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.Set; public class ZebraBluetoothPrinter extends CordovaPlugin implements DiscoveryHandler { private static final String LOG_TAG = "ZebraBluetoothPrinter"; private CallbackContext callbackContext; private boolean printerFound; private Connection thePrinterConn; private PrinterStatus printerStatus; private ZebraPrinter printer; private final int MAX_PRINT_RETRIES = 1; public ZebraBluetoothPrinter() { } // @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("printImage")) { try { JSONArray labels = args.getJSONArray(0); String MACAddress = args.getString(1); sendImage(labels, MACAddress); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return true; } else if (action.equals("print")) { try { String MACAddress = args.getString(0); String msg = args.getString(1); sendData(callbackContext, MACAddress, msg); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return true; } else if (action.equals("discoverPrinters")) { discoverPrinters(); return true; } else if (action.equals("getPrinterName")) { String mac = args.getString(0); getPrinterName(mac); return true; } else if (action.equals("getStatus")) { try { String mac = args.getString(0); getPrinterStatus(callbackContext, mac); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return true; } else if(action.equals("getZPLfromImage")){ try { String base64String = args.getString(0); boolean addHeaderFooter = args.getBoolean(1); int blacknessPercentage = args.getInt(2); getZPLfromImage(callbackContext, base64String, blacknessPercentage, addHeaderFooter); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } } return false; } void getZPLfromImage(final CallbackContext callbackContext, final String base64Image, final int blacknessPercentage, final boolean addHeaderFooter) throws Exception { String zplCode = ""; byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); ZebraImageAndroid zebraimage = new ZebraImageAndroid(decodedByte); String base64Dithered = new String(zebraimage.getDitheredB64EncodedPng(), "UTF-8"); byte[] ditheredB64Png = Base64.decode(base64Dithered, Base64.DEFAULT); Bitmap ditheredPng = BitmapFactory.decodeByteArray(ditheredB64Png, 0, ditheredB64Png.length); if(ditheredPng.getHeight() > ditheredPng.getWidth()) ditheredPng = Bitmap.createScaledBitmap(ditheredPng, 300, 540, true); ZPLConverter zplConveter = new ZPLConverter(); zplConveter.setCompressHex(false); zplConveter.setBlacknessLimitPercentage(blacknessPercentage); //Bitmap grayBitmap = toGrayScale(decodedByte); try { zplCode = zplConveter.convertFromImage(ditheredPng, addHeaderFooter); callbackContext.success(zplCode); } catch (Exception e){ callbackContext.error(e.getMessage()); } } void getPrinterStatus(final CallbackContext callbackContext, final String mac) throws IOException { new Thread(new Runnable() { @Override public void run() { try { Connection thePrinterConn = new BluetoothConnectionInsecure(mac); Looper.prepare(); thePrinterConn.open(); ZebraPrinter zPrinter = ZebraPrinterFactory.getInstance(thePrinterConn); PrinterStatus printerStatus = zPrinter.getCurrentStatus(); if (printerStatus.isReadyToPrint){ callbackContext.success("Printer is ready for use"); } else if(printerStatus.isPaused){ callbackContext.error("Printer is currently paused"); } else if(printerStatus.isPaperOut){ callbackContext.error("Printer is out of paper"); } else if(printerStatus.isHeadOpen){ callbackContext.error("Printer head is open"); } else{ callbackContext.error("Cannot print, unknown error"); } thePrinterConn.close(); Looper.myLooper().quit(); } catch (Exception e){ callbackContext.error(e.getMessage()); } } }).start(); } /* * This will send data to be printed by the bluetooth printer */ void sendData(final CallbackContext callbackContext, final String mac, final String msg) throws IOException { new Thread(new Runnable() { @Override public void run() { try { // Instantiate insecure connection for given Bluetooth MAC Address. Connection thePrinterConn = new BluetoothConnectionInsecure(mac); // if (isPrinterReady(thePrinterConn)) { // Initialize Looper.prepare(); // Open the connection - physical connection is established here. thePrinterConn.open(); SGD.SET("device.languages", "zpl", thePrinterConn); thePrinterConn.write(msg.getBytes()); // Close the insecure connection to release resources. thePrinterConn.close(); Looper.myLooper().quit(); callbackContext.success("Done"); // } else { // callbackContext.error("Printer is not ready"); // } } catch (Exception e) { // Handle communications error here. callbackContext.error(e.getMessage()); } } }).start(); } private void sendImage(final JSONArray labels, final String MACAddress) throws IOException { new Thread(new Runnable() { @Override public void run() { printLabels(labels, MACAddress); } }).start(); } private void printLabels(JSONArray labels, String MACAddress) { try { boolean isConnected = openBluetoothConnection(MACAddress); if (isConnected) { initializePrinter(); boolean isPrinterReady = getPrinterStatus(0); if (isPrinterReady) { printLabel(labels); //Sufficient waiting for the label to print before we start a new printer operation. Thread.sleep(15000); thePrinterConn.close(); callbackContext.success(); } else { Log.e(LOG_TAG, "Printer not ready"); callbackContext.error("Printer is not yet ready."); } } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); //The connection between the printer & the device has been lost. if (e.getMessage().toLowerCase().contains("broken pipe")) { callbackContext.error("The connection between the device and the printer has been lost. Please try again."); //No printer found via Bluetooth, -1 return so that new printers are searched for. } else if (e.getMessage().toLowerCase().contains("socket might closed")) { int SEARCH_NEW_PRINTERS = -1; callbackContext.error(SEARCH_NEW_PRINTERS); } else { callbackContext.error("Unknown printer error occurred. Restart the printer and try again please."); } } catch (ZebraPrinterLanguageUnknownException e) { Log.e(LOG_TAG, "ZebraPrinterLanguageUnknown exception: " + e.getMessage()); callbackContext.error("Unknown printer error occurred. Restart the printer and try again please."); } catch (Exception e) { Log.e(LOG_TAG, "Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } } private void initializePrinter() throws ConnectionException, ZebraPrinterLanguageUnknownException { Log.d(LOG_TAG, "Initializing printer..."); printer = ZebraPrinterFactory.getInstance(thePrinterConn); String printerLanguage = SGD.GET("device.languages", thePrinterConn); if (!printerLanguage.contains("zpl")) { SGD.SET("device.languages", "hybrid_xml_zpl", thePrinterConn); Log.d(LOG_TAG, "printer language set..."); } } private boolean openBluetoothConnection(String MACAddress) throws ConnectionException { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Creating a bluetooth-connection for mac-address " + MACAddress); thePrinterConn = new BluetoothConnectionInsecure(MACAddress); Log.d(LOG_TAG, "Opening connection..."); thePrinterConn.open(); Log.d(LOG_TAG, "connection successfully opened..."); return true; } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not on."); } return false; } public static Bitmap toGrayScale(Bitmap bmpOriginal) { int width, height; height = bmpOriginal.getHeight(); width = bmpOriginal.getWidth(); Bitmap grayScale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(grayScale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmpOriginal, 0, 0, paint); return grayScale; } private void printLabel(JSONArray labels) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); for (int i = labels.length() - 1; i >= 0; i--) { String base64Image = labels.get(i).toString(); byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); ZebraImageAndroid zebraimage = new ZebraImageAndroid(decodedByte); //Lengte van het label eerst instellen om te kleine of te grote afdruk te voorkomen if (zebraPrinterLinkOs != null && i == labels.length() - 1) { setLabelLength(zebraimage); } if (zebraPrinterLinkOs != null) { printer.printImage(zebraimage, 150, 0, zebraimage.getWidth(), zebraimage.getHeight(), false); } else { Log.d(LOG_TAG, "Storing label on printer..."); printer.storeImage("wgkimage.pcx", zebraimage, -1, -1); printImageTheOldWay(zebraimage); } } } private void printImageTheOldWay(ZebraImageAndroid zebraimage) throws Exception { Log.d(LOG_TAG, "Printing image..."); String cpcl = "! 0 200 200 "; cpcl += zebraimage.getHeight(); cpcl += " 1\r\n"; cpcl += "PW 750\r\nTONE 0\r\nSPEED 6\r\nSETFF 203 5\r\nON - FEED FEED\r\nAUTO - PACE\r\nJOURNAL\r\n"; cpcl += "PCX 150 0 !<wgkimage.pcx\r\n"; cpcl += "FORM\r\n"; cpcl += "PRINT\r\n"; thePrinterConn.write(cpcl.getBytes()); } private boolean getPrinterStatus(int retryAttempt) throws Exception { try { printerStatus = printer.getCurrentStatus(); if (printerStatus.isReadyToPrint) { Log.d(LOG_TAG, "Printer is ready to print..."); return true; } else { if (printerStatus.isPaused) { throw new Exception("Printer is paused. Please activate it first."); } else if (printerStatus.isHeadOpen) { throw new Exception("Printer is open. Please close it first."); } else if (printerStatus.isPaperOut) { throw new Exception("Please complete the labels first."); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } catch (ConnectionException e) { if (retryAttempt < MAX_PRINT_RETRIES) { Thread.sleep(5000); return getPrinterStatus(++retryAttempt); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } /** * Use the Zebra Android SDK to determine the length if the printer supports LINK-OS * * @param zebraimage * @throws Exception */ private void setLabelLength(ZebraImageAndroid zebraimage) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); if (zebraPrinterLinkOs != null) { String currentLabelLength = zebraPrinterLinkOs.getSettingValue("zpl.label_length"); if (!currentLabelLength.equals(String.valueOf(zebraimage.getHeight()))) { zebraPrinterLinkOs.setSetting("zpl.label_length", zebraimage.getHeight() + ""); } } } private void discoverPrinters() { printerFound = false; new Thread(new Runnable() { public void run() { Looper.prepare(); try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Searching for printers..."); BluetoothDiscoverer.findPrinters(cordova.getActivity().getApplicationContext(), ZebraBluetoothPrinter.this); } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not on."); } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } finally { Looper.myLooper().quit(); } } }).start(); } private void getPrinterName(final String macAddress) { new Thread(new Runnable() { @Override public void run() { String printerName = searchPrinterNameForMacAddress(macAddress); if (printerName != null) { Log.d(LOG_TAG, "Successfully found connected printer with name " + printerName); callbackContext.success(printerName); } else { callbackContext.error("No printer found."); } } }).start(); } private String searchPrinterNameForMacAddress(String macAddress) { Log.d(LOG_TAG, "Connecting with printer " + macAddress + " over bluetooth..."); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { Log.d(LOG_TAG, "Paired device found: " + device.getName()); if (device.getAddress().equalsIgnoreCase(macAddress)) { return device.getName(); } } } return null; } @Override public void foundPrinter(DiscoveredPrinter discoveredPrinter) { Log.d(LOG_TAG, "Printer found: " + discoveredPrinter.address); if (!printerFound) { printerFound = true; callbackContext.success(discoveredPrinter.address); } } @Override public void discoveryFinished() { Log.d(LOG_TAG, "Finished searching for printers..."); if (!printerFound) { callbackContext.error("No printer found. If this problem persists, restart the printer."); } } @Override public void discoveryError(String s) { Log.e(LOG_TAG, "An error occurred while searching for printers. Message: " + s); callbackContext.error(s); } }
37.778431
170
0.589557
eda8fb47664a65953ebae2240b27e5989c5ff575
17,835
/* * 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.influxdata.nifi.processors.internal; import java.io.IOException; import java.io.OutputStream; import java.net.SocketTimeoutException; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CountDownLatch; import com.influxdb.Cancellable; import com.influxdb.client.domain.Dialect; import com.influxdb.client.domain.Query; import com.influxdb.exceptions.InfluxException; import com.influxdb.query.FluxRecord; import edu.umd.cs.findbugs.annotations.NonNull; import org.apache.nifi.annotation.lifecycle.OnScheduled; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.ValidationResult; import org.apache.nifi.expression.ExpressionLanguageScope; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.serialization.RecordSetWriter; import org.apache.nifi.serialization.RecordSetWriterFactory; import org.apache.nifi.serialization.SimpleRecordSchema; import org.apache.nifi.serialization.record.DataType; import org.apache.nifi.serialization.record.MapRecord; import org.apache.nifi.serialization.record.Record; import org.apache.nifi.serialization.record.RecordField; import org.apache.nifi.serialization.record.RecordFieldType; import org.apache.nifi.serialization.record.RecordSchema; import org.apache.nifi.serialization.record.util.DataTypeUtils; import org.apache.nifi.util.StopWatch; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.influxdata.nifi.processors.internal.AbstractInfluxDatabaseProcessor.INFLUX_DB_ERROR_MESSAGE; import static org.influxdata.nifi.processors.internal.AbstractInfluxDatabaseProcessor.INFLUX_DB_FAIL_TO_QUERY; /** * @author Jakub Bednar (bednar@github) (19/07/2019 10:23) */ public abstract class AbstractGetInfluxDatabase_2 extends AbstractInfluxDatabaseProcessor_2 { public static final PropertyDescriptor WRITER_FACTORY = new PropertyDescriptor.Builder() .name("influxdb-record-writer-factory") .displayName("Record Writer") .description("The record writer to use to write the result sets.") .identifiesControllerService(RecordSetWriterFactory.class) .required(true) .build(); public static final PropertyDescriptor ORG = new PropertyDescriptor.Builder() .name("influxdb-org") .displayName("Organization") .description("Specifies the source organization.") .required(true) .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final PropertyDescriptor QUERY = new PropertyDescriptor.Builder() .name("influxdb-flux") .displayName("Query") .description("A valid Flux query to use to execute against InfluxDB.") .required(true) .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final PropertyDescriptor DIALECT_HEADER = new PropertyDescriptor.Builder() .name("influxdb-dialect-header") .displayName("Dialect Header") .description("If true, the results will contain a header row.") .addValidator(StandardValidators.BOOLEAN_VALIDATOR) .allowableValues("false", "true") .defaultValue(Boolean.FALSE.toString()) .required(true) .build(); public static final PropertyDescriptor DIALECT_DELIMITER = new PropertyDescriptor.Builder() .name("influxdb-dialect-delimiter") .displayName("Dialect Delimiter") .description("Separator between cells; the default is ,") .required(true) .defaultValue(",") .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final PropertyDescriptor DIALECT_ANNOTATIONS = new PropertyDescriptor.Builder() .name("influxdb-dialect-annotations") .displayName("Dialect Annotations") .description("Describing properties about the columns of the table." + " More than one can be supplied if comma separated. " + "Allowable Values: group, datatype, default.") .required(false) .addValidator((subject, input, context) -> { if (input == null || input.isEmpty()) { return new ValidationResult.Builder().subject(subject).input(input).valid(true).build(); } Optional<ValidationResult> invalidAnnotation = Arrays.stream(input.split(",")) .filter(annotation -> annotation != null && !annotation.trim().isEmpty()) .map(String::trim) .filter((annotation) -> Dialect.AnnotationsEnum.fromValue(annotation) == null) .map((annotation) -> new ValidationResult.Builder().subject(subject).input(input).explanation("Not a valid annotation").valid(false).build()) .findFirst(); return invalidAnnotation.orElseGet(() -> new ValidationResult.Builder().subject(subject).input(input).explanation("Valid Annotation(s)").valid(true).build()); }) .build(); public static final PropertyDescriptor DIALECT_COMMENT_PREFIX = new PropertyDescriptor.Builder() .name("influxdb-dialect-commentPrefix") .displayName("Dialect Comment Prefix") .description("Character prefixed to comment strings.") .required(true) .defaultValue("#") .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final PropertyDescriptor DIALECT_DATE_TIME_FORMAT = new PropertyDescriptor.Builder() .name("influxdb-dialect-dateTimeFormat") .displayName("Dialect Date Time Format") .description("Format of timestamps.") .required(true) .defaultValue("#") .defaultValue("RFC3339") .allowableValues("RFC3339", "RFC3339Nano") .build(); public static PropertyDescriptor RECORDS_PER_FLOWFILE; public static final Relationship REL_SUCCESS = new Relationship.Builder().name("success") .description("Successful Flux queries are routed to this relationship").build(); public static final Relationship REL_FAILURE = new Relationship.Builder().name("failure") .description("Failed Flux queries are routed to this relationship").build(); public static final Relationship REL_RETRY = new Relationship.Builder().name("retry") .description("Failed queries that are retryable exception are routed to this relationship").build(); private volatile RecordSetWriterFactory writerFactory; @OnScheduled public void initWriterFactory(@NonNull final ProcessContext context) { Objects.requireNonNull(context, "ProcessContext is required"); if (getSupportedPropertyDescriptors().contains(WRITER_FACTORY)) { writerFactory = context.getProperty(WRITER_FACTORY).asControllerService(RecordSetWriterFactory.class); } } @Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { boolean createdFlowFile = false; FlowFile flowFile = session.get(); // If there aren't incoming connections. if (flowFile == null) { flowFile = session.create(); createdFlowFile = true; } String org = context.getProperty(ORG).evaluateAttributeExpressions(flowFile).getValue(); String flux = context.getProperty(QUERY).evaluateAttributeExpressions(flowFile).getValue(); Dialect dialect = prepareDialect(context); // // Records per Flowfile // long recordsPerFlowFile = -1; if (context.getProperty(RECORDS_PER_FLOWFILE).isSet()) { recordsPerFlowFile = context.getProperty(RECORDS_PER_FLOWFILE).evaluateAttributeExpressions().asLong(); } Query query = new Query() .query(flux) .dialect(dialect); try { QueryProcessor processor = new QueryProcessor(org, query, recordsPerFlowFile, flowFile, createdFlowFile, context, session); // CVS or Record based response? if (getSupportedPropertyDescriptors().contains(WRITER_FACTORY)) { processor.doQuery(); } else { processor.doQueryRaw(); } } catch (Exception e) { catchException(query, e, Collections.singletonList(flowFile), context, session); } } protected abstract Dialect prepareDialect(final ProcessContext context); private void catchException(final Query query, final Throwable e, final List<FlowFile> flowFiles, final ProcessContext context, final ProcessSession session) { String message = INFLUX_DB_FAIL_TO_QUERY; Object status = e.getClass().getSimpleName(); Relationship relationship = REL_FAILURE; if (e instanceof InfluxException) { InfluxException ie = (InfluxException) e; status = ie.status(); // Retryable if (Arrays.asList(429, 503).contains(ie.status()) || ie.getCause() instanceof SocketTimeoutException) { message += " ... retry"; relationship = REL_RETRY; } } for (FlowFile flowFile : flowFiles) { if (REL_RETRY.equals(relationship)) { session.penalize(flowFile); } session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, e.getMessage()); session.transfer(flowFile, relationship); } getLogger().error(message, new Object[]{status, query}, e); context.yield(); } private class QueryProcessor { private final List<FlowFile> flowFiles = new ArrayList<>(); private final String org; private final long recordsPerFlowFile; private final Query query; private final ProcessContext context; private final ProcessSession session; private final CountDownLatch countDownLatch = new CountDownLatch(1); private final StopWatch stopWatch = new StopWatch(); private long recordIndex = 0; private FlowFile flowFile; private RecordSetWriter writer; private OutputStream out; private QueryProcessor(final String org, final Query query, final long recordsPerFlowFile, final FlowFile flowFile, final boolean createdFlowFile, final ProcessContext context, final ProcessSession session) { this.flowFiles.add(flowFile); if (recordsPerFlowFile == -1 || createdFlowFile) { this.flowFile = flowFile; } else { this.flowFile = session.create(); this.flowFiles.add(this.flowFile); } this.org = org; this.recordsPerFlowFile = recordsPerFlowFile; this.query = query; this.context = context; this.session = session; this.stopWatch.start(); } void doQuery() { try { getInfluxDBClient(context) .getQueryApi() .query(query, org, this::onResponseRecord, this::onError, this::onComplete); countDownLatch.await(); } catch (Exception e) { catchException(query, e, flowFiles, context, session); } } void doQueryRaw() { try { getInfluxDBClient(context) .getQueryApi() .queryRaw(query, org, this::onResponseRaw, this::onError, this::onComplete); countDownLatch.await(); } catch (Exception e) { catchException(query, e, flowFiles, context, session); } } private void onResponseRecord(final Cancellable cancellable, final FluxRecord fluxRecord) { if (fluxRecord == null) { return; } beforeOnResponse(); Record record = toNifiRecord(fluxRecord); if (writer == null) { final RecordSchema recordSchema = record.getSchema(); try { out = session.write(flowFile); writer = writerFactory.createWriter(getLogger(), recordSchema, out, flowFile); writer.beginRecordSet(); } catch (Exception e) { cancellable.cancel(); onError(e); } } try { writer.write(record); } catch (IOException e) { cancellable.cancel(); onError(e); } } private void onResponseRaw(Cancellable cancellable, String record) { if (record == null || record.isEmpty()) { return; } beforeOnResponse(); session.append(flowFile, out -> { if (recordIndex > 1) { out.write('\n'); } out.write(record.getBytes()); }); } private void beforeOnResponse() { recordIndex++; if (recordsPerFlowFile != -1 && recordIndex > recordsPerFlowFile) { closeRecordWriter(); flowFile = session.create(); flowFiles.add(flowFile); recordIndex = 1; } } private void onError(Throwable throwable) { stopWatch.stop(); closeRecordWriter(); catchException(query, throwable, flowFiles, context, session); countDownLatch.countDown(); } private void onComplete() { stopWatch.stop(); closeRecordWriter(); session.transfer(flowFiles, REL_SUCCESS); for (FlowFile flowFile : flowFiles) { session.getProvenanceReporter() .send(flowFile, influxDatabaseService.getDatabaseURL(), stopWatch.getElapsed(MILLISECONDS)); } getLogger().debug("Query {} fetched in {}", new Object[]{query, stopWatch.getDuration()}); countDownLatch.countDown(); } private void closeRecordWriter() { if (writer != null) { try { writer.finishRecordSet(); writer.close(); out.close(); } catch (IOException e) { throw new RuntimeException(e); } } out = null; writer = null; } private Record toNifiRecord(final FluxRecord fluxRecord) { Map<String, Object> values = new LinkedHashMap<>(); List<RecordField> fields = new ArrayList<>(); fluxRecord.getValues().forEach((fieldName, fluxValue) -> { if (fluxValue == null) { return; } Object nifiValue = fluxValue; if (fluxValue instanceof Instant) { nifiValue = java.sql.Timestamp.from((Instant) fluxValue); } else if (fluxValue instanceof Duration) { nifiValue = ((Duration) fluxValue).get(ChronoUnit.NANOS); } DataType dataType = DataTypeUtils.inferDataType(nifiValue, RecordFieldType.STRING.getDataType()); if (fluxValue.getClass().isArray()) { dataType = RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.BYTE.getDataType()); } fields.add(new RecordField(fieldName, dataType)); values.put(fieldName, nifiValue); }); return new MapRecord(new SimpleRecordSchema(fields), values); } } }
39.284141
174
0.617382
60822de666309ffe933aef9e196ec29a779d7ec0
888
package ru.sftqa.pft.helmesframework.tests; import org.testng.annotations.Test; import ru.sftqa.pft.helmesframework.model.ClaimDescriptionData; import ru.sftqa.pft.helmesframework.model.NewCaseData; public class CreateNewCaseTest extends TestBase { @Test public void testClaimCreation() throws InterruptedException { app.getNewCaseHelper().initClaimCreation(); app.getNewCaseHelper().fillinRequiredFields(new NewCaseData("LPV CN 01022018-4", "LPVLP 02022018-4", "TRUZZZ8J991028634 ")); app.getNewCaseHelper().submitClaimCreation(); /* app.getNavigationHelper().clickNextButtonOnClaim(); app.getNewCaseHelper().fillInClaimDescriptionData(new ClaimDescriptionData("LPVPolicyCompany", "LPVInspectionCompany", "LPVRepairerCompany")); app.getNavigationHelper().clickNextButtonOnClaim(); */ app.getNavigationHelper().clickClaimManagerIcon(); } }
35.52
146
0.782658