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
fb01878079bf40f561bff976d90e52e99b146c9b
194
package com.arleex.wechat.miniprogram.api.urlscheme; /** * @author cat */ public class UrlSchemeServiceImpl implements UrlSchemeService { @Override public void generate() { } }
14.923077
63
0.706186
a414d01f00844d1297125907e0e02e508e3ac3da
580
package org.zstack.header.simulator; import org.zstack.header.host.AddHostMsg; public class AddSimulatorHostMsg extends AddHostMsg { private long memoryCapacity = 1000000000; private long cpuCapacity = 1000000000; public long getMemoryCapacity() { return memoryCapacity; } public void setMemoryCapacity(long memoryCapacity) { this.memoryCapacity = memoryCapacity; } public long getCpuCapacity() { return cpuCapacity; } public void setCpuCapacity(long cpuCapacity) { this.cpuCapacity = cpuCapacity; } }
23.2
56
0.706897
ac00e23a466d2ec9db6091e5351cba5ed17ce29a
3,731
package ru.pvg.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import ru.pvg.addressbook.model.GroupData; import ru.pvg.addressbook.model.Groups; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /* Created Владимир at 16:32 06.05.2019 */ public class GroupHelper extends HelperBase { public GroupHelper(WebDriver driver) { super(driver); } public void submitGroupCreation() { click(By.name("submit")); } public void fillGroupForm(GroupData groupData) { type(By.name("group_name"), groupData.getGroupName()); type(By.name("group_header"), groupData.getGroupHeader()); type(By.name("group_footer"), groupData.getGroupFooter()); } public void initGroupCreation() { click(By.name("new")); } public void deleteSelectedGroup() { click(By.name("delete")); } public void selectGroup(int index) { driver.findElements(By.name("selected[]")).get(index).click(); //выбор элемента с номером index на странице // click(By.name("selected[]")); //устарело - выбор первого элемента на странице } public void selectGroupById(int id) { driver.findElement(By.cssSelector("input[value='" + id + "']")).click(); //выбор элемента с идентификатором id на странице } public void initGroupModification() { click(By.name("edit")); } public void submitGroupModificarion() { click(By.name("update")); } public void create(GroupData groupData) { initGroupCreation(); fillGroupForm(groupData); submitGroupCreation(); groupCache = null; } public void deleteGroup(int index) { selectGroup(index); deleteSelectedGroup(); groupCache = null; } public void delete(GroupData groupToDelete) { selectGroupById(groupToDelete.getId()); deleteSelectedGroup(); groupCache = null; } public void modify(int index, GroupData group) { selectGroup(index); initGroupModification(); fillGroupForm(group); submitGroupModificarion(); groupCache = null; } public void modifyById(GroupData group) { selectGroupById(group.getId()); initGroupModification(); fillGroupForm(group); submitGroupModificarion(); groupCache = null; } public boolean isThereAnyGroup() { return isElementPresent(By.name("selected[]")); } public int getGroupCount() { return driver.findElements(By.name("selected[]")).size(); } public List<GroupData> list() { List<GroupData> groups = new ArrayList<>(); List<WebElement> elements = driver.findElements(By.cssSelector("span.group")); for (WebElement element : elements) { int id= Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); String name = element.getText(); String header = null; String footer= null; GroupData group = new GroupData().withId(id).withName(name).withHeader(header).withFooter(footer); groups.add(group); } return groups; } private Groups groupCache = null; public Groups all() { if (groupCache != null) { return new Groups(groupCache); } groupCache = new Groups(); List<WebElement> elements = driver.findElements(By.cssSelector("span.group")); for (WebElement element : elements) { int id= Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); String name = element.getText(); String header = null; String footer= null; GroupData group = new GroupData().withId(id).withName(name).withHeader(header).withFooter(footer); groupCache.add(group); } return new Groups(groupCache); } }
26.274648
126
0.686143
6f5627d75531057183519b5a6e84ef134d572e7f
1,367
package com.daaao.bid.policy.redis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import java.util.Arrays; /** * @author hao */ public class RedisIdWorker { private static final Logger LOGGER = LoggerFactory.getLogger(RedisIdWorker.class); @Autowired @Qualifier("bidStringRedisTemplate") private StringRedisTemplate redisTemplate; @Autowired @Qualifier("bidDefaultRedisScript") private DefaultRedisScript<Long> defaultRedisScript; public Long incr(String key, Integer increment, Long initial, long ttl) { increment = (increment == null || increment <= 0) ? 1 : increment; Long result = (Long) redisTemplate.execute(defaultRedisScript, Arrays.asList(key), String.valueOf(increment), String.valueOf(initial), String.valueOf(ttl)); return result; } public Long incr(String key, Long initial) { return incr(key, -1, initial, -1); } public Long incr(String key, Integer increment) { return incr(key, increment, -1L, -1); } public Long incr(String key) { return incr(key, -1); } }
29.717391
164
0.719824
8022fc6d767b6fcf67b5480d25d5d7d138beb779
3,491
/** * Copyright (C) 2016 Mehdi Bekioui (consulting@bekioui.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bekioui.maven.plugin.client.initializer; import static com.bekioui.maven.plugin.client.util.Constants.FULL_SRC_FOLDER; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import com.bekioui.maven.plugin.client.model.Project; import com.bekioui.maven.plugin.client.model.Properties; public class ProjectInitializer { @SuppressWarnings("unchecked") public static Project initialize(MavenProject mavenProject, Properties properties) throws MojoExecutionException { String clientPackagename = mavenProject.getParent().getGroupId() + ".client"; String contextPackageName = clientPackagename + ".context"; String apiPackageName = clientPackagename + ".api"; String implPackageName = clientPackagename + ".impl"; String resourceBasedirPath = mavenProject.getBasedir().getAbsolutePath(); String projectBasedirPath = resourceBasedirPath.substring(0, resourceBasedirPath.lastIndexOf(File.separator)); File clientDirectory = new File(projectBasedirPath + File.separator + properties.clientArtifactId()); if (clientDirectory.exists()) { try { FileUtils.deleteDirectory(clientDirectory); } catch (IOException e) { throw new MojoExecutionException("Failed to delete existing client directory.", e); } } clientDirectory.mkdir(); File javaSourceDirectory = new File(resourceBasedirPath + FULL_SRC_FOLDER + properties.resourcePackageName().replaceAll("\\.", File.separator)); if (!javaSourceDirectory.isDirectory()) { throw new MojoExecutionException("Java sources directory not found: " + javaSourceDirectory.getAbsolutePath()); } List<String> classpathElements; try { classpathElements = mavenProject.getCompileClasspathElements(); } catch (DependencyResolutionRequiredException e) { throw new MojoExecutionException("Failed to get compile classpath elements.", e); } List<URL> classpaths = new ArrayList<>(); for (String element : classpathElements) { try { classpaths.add(new File(element).toURI().toURL()); } catch (MalformedURLException e) { throw new MojoExecutionException(element + " is an invalid classpath element.", e); } } return Project.builder() // .mavenProject(mavenProject) // .properties(properties) // .clientPackageName(clientPackagename) // .contextPackageName(contextPackageName) // .apiPackageName(apiPackageName) // .implPackageName(implPackageName) // .clientDirectory(clientDirectory) // .javaSourceDirectory(javaSourceDirectory) // .classpaths(classpaths) // .build(); } }
38.362637
146
0.760527
2d28691b8f97ed5282a872802721ffe668895288
4,796
/** * * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.speedment.common.tuple.old_tests; import com.speedment.common.tuple.TuplesOfNullables; import com.speedment.common.tuple.nullable.Tuple2OfNullables; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * * @author pemi */ final class Tuple2NullableTest { private static final int FIRST = 8; private static final int SECOND = 16; private Tuple2OfNullables<Integer, Integer> instance; @BeforeEach void setUp() { instance = TuplesOfNullables.ofNullables(FIRST, SECOND); } @Test void testGet0() { assertEquals(FIRST, instance.get0().get().intValue()); } @Test void testGet1() { assertEquals(SECOND, instance.get1().get().intValue()); } @Test void testGet() { assertEquals(FIRST, instance.get(0).get()); assertEquals(SECOND, instance.get(1).get()); } @Test void testCasting() { Tuple2OfNullables<Integer, String> t2 = TuplesOfNullables.ofNullables(1, null); assertEquals(Optional.of(1), t2.get0()); assertEquals(Optional.empty(), t2.get1()); } // @Test // public void testSet0() { // System.out.println("set0"); // instance.set1(32); // assertEquals(32, instance.get1().get().intValue()); // } // // @Test // public void testSet1() { // System.out.println("set1"); // instance.set1(64); // assertEquals(64, instance.get1().get().intValue()); // } @Test void testDefConstructor() { final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(1, 2); assertTrue(newInstance.get0().isPresent()); assertTrue(newInstance.get1().isPresent()); } @Test void testHash() { int hashCodeInstance = instance.hashCode(); final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(FIRST, SECOND); int hashCodenewInstance = newInstance.hashCode(); assertEquals(hashCodeInstance, hashCodenewInstance); } @Test void testEquals() { final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(FIRST, SECOND); assertEquals(instance, newInstance); } @Test void testToString() { final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(null, null); } @Test void testStream() { final List<Object> content = instance.stream().collect(toList()); final List<Optional<Integer>> expected = Arrays.asList(Optional.of(FIRST), Optional.of(SECOND)); assertEquals(expected, content); final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(FIRST, null); final List<Object> content2 = newInstance.stream().collect(toList()); final List<Optional<Integer>> expected2 = Arrays.asList(Optional.of(FIRST), Optional.empty()); assertEquals(expected2, content2); } @Test void testStreamOf() { final Tuple2OfNullables<Integer, Integer> newInstance = TuplesOfNullables.ofNullables(FIRST, null); List<Integer> content = newInstance.streamOf(Integer.class).collect(toList()); List<Integer> expected = Collections.singletonList(FIRST); assertEquals(expected, content); } @Test void testStreamOf2() { final Tuple2OfNullables<Integer, String> newInstance = TuplesOfNullables.ofNullables(FIRST, "Tryggve"); List<Integer> content = newInstance.streamOf(Integer.class).collect(toList()); List<Integer> expected = Collections.singletonList(FIRST); assertEquals(expected, content); } }
33.075862
111
0.685154
0e429775a81f17841384081c674f122de426b90c
2,112
package com.mnaseri.cs.homework.ch24; import com.mmnaseri.cs.clrs.ch22.s1.*; import com.mmnaseri.cs.clrs.ch22.s4.DFSTopologicalSorter; import com.mmnaseri.cs.clrs.ch22.s4.TopologicalSorter; import com.mmnaseri.cs.clrs.ch23.s1.WeightedEdgeDetails; import java.util.List; public class DagSingleSourceShortestPathFinder<E extends WeightedEdgeDetails, V extends VertexDetails> { public Graph<E, V> find(Graph<E, V> graph, int start) { Graph<E, V> result = new AdjacencyListGraph<>(); List<Vertex<V>> vertices = graph.getVertices(); for (int i = 0, verticesSize = vertices.size(); i < verticesSize; i++) { result.add(); Vertex<V> node = result.get(i); node.setProperty("distance", Integer.MAX_VALUE); node.setProperty("predecessor", null); } for (Edge edge : graph.getEdges()) { result.connect(edge.getFrom().getIndex(), edge.getTo().getIndex()); } result.get(start).setProperty("distance", 0); TopologicalSorter topologicalSorter = new DFSTopologicalSorter(); List<Integer> sorted = topologicalSorter.sort(graph); for (Integer node : sorted) { Vertex<V> current = graph.get(node); Integer currentDistance = current.getProperty("distance", Integer.class); List<Vertex<V>> neighbors = graph.getNeighbors(current.getIndex()); for (Vertex<V> neighbor : neighbors) { Edge<E, V> edge = graph.edge(current.getIndex(), neighbor.getIndex()); int weight = weight(edge); int suggestedDistance = weight + currentDistance; if (neighbor.getProperty("distance", Integer.class) > suggestedDistance) { neighbor.setProperty("distance", suggestedDistance); neighbor.setProperty("predecessor", current); } } } return result; } protected int weight(Edge<E, V> edge) { final E details = edge.getDetails(); return details == null ? 0 : details.getWeight(); } }
39.111111
104
0.618371
d0a08c1a2f05edfcf7b0512d90e7dbe047c8e4fb
9,554
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 uk.co.flax.biosolr.ontology.search.solr; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.Group; import org.apache.solr.client.solrj.response.GroupCommand; import org.apache.solr.client.solrj.response.GroupResponse; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.params.DisMaxParams; import org.apache.solr.common.util.NamedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.biosolr.ontology.api.Document; import uk.co.flax.biosolr.ontology.api.FacetEntry; import uk.co.flax.biosolr.ontology.api.FacetStyle; import uk.co.flax.biosolr.ontology.api.HierarchicalFacetEntry; import uk.co.flax.biosolr.ontology.config.FacetTreeConfiguration; import uk.co.flax.biosolr.ontology.config.SolrConfiguration; import uk.co.flax.biosolr.ontology.search.DocumentSearch; import uk.co.flax.biosolr.ontology.search.ResultsList; import uk.co.flax.biosolr.ontology.search.SearchEngineException; /** * Solr-specific implementation of the {@link DocumentSearch} search engine. * * @author Matt Pearce */ public class SolrDocumentSearch extends SolrSearchEngine implements DocumentSearch { private static final Logger LOGGER = LoggerFactory.getLogger(SolrDocumentSearch.class); private static final String EFO_URI_FIELD = "efo_uri"; private static final String TITLE_FIELD = "title"; private static final String FIRST_AUTHOR_FIELD = "first_author"; private static final String PUBLICATION_FIELD = "publication"; private static final String EFO_LABELS_FIELD = "efo_labels"; private static final List<String> DEFAULT_SEARCH_FIELDS = new ArrayList<>(); static { DEFAULT_SEARCH_FIELDS.add(TITLE_FIELD); DEFAULT_SEARCH_FIELDS.add(FIRST_AUTHOR_FIELD); DEFAULT_SEARCH_FIELDS.add(PUBLICATION_FIELD); DEFAULT_SEARCH_FIELDS.add(EFO_LABELS_FIELD); } private final SolrConfiguration config; private final SolrServer server; public SolrDocumentSearch(SolrConfiguration config) { this.config = config; this.server = new HttpSolrServer(config.getDocumentUrl()); } @Override protected SolrServer getServer() { return server; } @Override protected Logger getLogger() { return LOGGER; } @Override public ResultsList<Document> searchDocuments(String term, int start, int rows, List<String> additionalFields, List<String> filters, FacetStyle facetStyle) throws SearchEngineException { ResultsList<Document> results = null; try { SolrQuery query = new SolrQuery(term); query.setStart(start); query.setRows(rows); query.setRequestHandler(config.getDocumentRequestHandler()); List<String> queryFields = new ArrayList<>(DEFAULT_SEARCH_FIELDS); if (additionalFields != null) { queryFields.addAll(additionalFields); } if (filters != null) { query.addFilterQuery(filters.toArray(new String[0])); } query.setParam(DisMaxParams.QF, queryFields.toArray(new String[queryFields.size()])); if (facetStyle == FacetStyle.NONE) { query.addFacetField(config.getFacetFields().toArray(new String[config.getFacetFields().size()])); } else { // Add the facet tree params query.setFacet(true); query.setParam("facet.tree", true); query.setParam("facet.tree.field", buildFacetTreeQueryParameter(facetStyle)); } LOGGER.debug("Query: {}", query); QueryResponse response = server.query(query); List<Document> docs; long total = 0; if (response.getGroupResponse() != null) { docs = new ArrayList<>(rows); GroupResponse gResponse = response.getGroupResponse(); for (GroupCommand gCommand : gResponse.getValues()) { total += gCommand.getNGroups(); for (Group group : gCommand.getValues()) { docs.addAll(server.getBinder().getBeans(Document.class, group.getResult())); } } } else if (response.getResults().getNumFound() == 0) { docs = new ArrayList<>(); } else { docs = response.getBeans(Document.class); total = response.getResults().getNumFound(); } results = new ResultsList<>(docs, start, (start / rows), total, extractFacets(response, facetStyle)); } catch (SolrServerException e) { throw new SearchEngineException(e); } return results; } private Map<String, List<FacetEntry>> extractFacets(QueryResponse response, FacetStyle facetStyle) { Map<String, List<FacetEntry>> facets = new HashMap<>(); for (String name : config.getFacetFields()) { FacetField fld = response.getFacetField(name); if (fld != null && !fld.getValues().isEmpty()) { List<FacetEntry> facetValues = new ArrayList<>(); for (Count count : fld.getValues()) { facetValues.add(new FacetEntry(count.getName(), count.getCount())); } facets.put(name, facetValues); } } // And extract the facet tree, if there is one if (facetStyle != FacetStyle.NONE) { List<Object> facetTree = findFacetTree(response, EFO_URI_FIELD); if (facetTree != null && !facetTree.isEmpty()) { facets.put(EFO_URI_FIELD + "_hierarchy", extractFacetTreeFromNamedList(facetTree)); } } return facets; } @SuppressWarnings("unchecked") private List<Object> findFacetTree(QueryResponse response, String field) { NamedList<Object> baseResponse = response.getResponse(); NamedList<Object> facetTrees = (NamedList<Object>) baseResponse.findRecursive("facet_counts", "facet_trees"); return facetTrees == null ? null : facetTrees.getAll(field); } @SuppressWarnings("unchecked") private List<FacetEntry> extractFacetTreeFromNamedList(List<Object> facetTree) { List<FacetEntry> entries; if (facetTree == null) { entries = null; } else { entries = new ArrayList<>(facetTree.size()); for (Object ftList : facetTree) { for (Object ft : (List<Object>)ftList) { NamedList<Object> nl = (NamedList<Object>)ft; String label = (String) nl.get("label"); String value = (String) nl.get("value"); long count = (long) nl.get("count"); long total = (long) nl.get("total"); List<FacetEntry> hierarchy = extractFacetTreeFromNamedList(nl.getAll("hierarchy")); entries.add(new HierarchicalFacetEntry(value, label, count, total, hierarchy)); } } } return entries; } private String buildFacetTreeQueryParameter(FacetStyle style) { FacetTreeConfiguration ftConfig = config.getDocumentFacetTree(); StringBuilder ftqParam = new StringBuilder("{!ftree"); ftqParam.append(" childField=").append(ftConfig.getChildField()); ftqParam.append(" nodeField=").append(ftConfig.getNodeField()); ftqParam.append(" collection=").append(ftConfig.getCollection()); if (StringUtils.isNotBlank(ftConfig.getLabelField())) { ftqParam.append(" labelField=").append(ftConfig.getLabelField()); } // Handle the pruning parameters, if required if (style == FacetStyle.SIMPLE_PRUNE) { ftqParam.append(" prune=simple"); } else if (style == FacetStyle.DATAPOINT_PRUNE) { ftqParam.append(" prune=datapoint datapoints=").append(ftConfig.getDatapoints()); } ftqParam.append("}").append(ftConfig.getBaseField()); return ftqParam.toString(); } @Override public ResultsList<Document> searchByEfoUri(int start, int rows, String term, String... uris) throws SearchEngineException { ResultsList<Document> results = null; try { SolrQuery query = new SolrQuery(term + " OR " + EFO_URI_FIELD + ":" + buildUriFilter(uris)); // query.addFilterQuery(EFO_URI_FIELD + ":" + buildUriFilter(uris)); query.setStart(start); query.setRows(rows); query.setRequestHandler(config.getDocumentUriRequestHandler()); LOGGER.debug("Solr query: {}", query); QueryResponse response = server.query(query); List<Document> docs = response.getBeans(Document.class); results = new ResultsList<>(docs, start, (start / rows), response.getResults().getNumFound()); } catch (SolrServerException e) { throw new SearchEngineException(e); } return results; } private String buildUriFilter(String... uris) { StringBuilder builder = new StringBuilder(); int count = 0; for (String uri : uris) { if (count > 0) { builder.append(" OR "); } builder.append('"').append(uri).append('"'); count ++; } return builder.toString(); } }
35.385185
126
0.707976
f7db82a40587e1a38a526bc0e65b31afc4d48d24
16,101
/** * Copyright (c) 2014 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.rigel.biplatform.ma.resource; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baidu.rigel.biplatform.ac.minicube.MiniCubeSchema; import com.baidu.rigel.biplatform.ac.model.Schema; import com.baidu.rigel.biplatform.ma.ds.exception.DataSourceOperationException; import com.baidu.rigel.biplatform.ma.ds.service.DataSourceService; import com.baidu.rigel.biplatform.ma.model.builder.Director; import com.baidu.rigel.biplatform.ma.model.ds.DataSourceDefine; import com.baidu.rigel.biplatform.ma.model.meta.CallbackDimTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.meta.ColumnInfo; import com.baidu.rigel.biplatform.ma.model.meta.DimTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.meta.FactTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.meta.StandardDimTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.meta.StandardDimType; import com.baidu.rigel.biplatform.ma.model.meta.StarModel; import com.baidu.rigel.biplatform.ma.model.meta.TimeDimTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.meta.TimeDimType; import com.baidu.rigel.biplatform.ma.model.meta.UserDefineDimTableMetaDefine; import com.baidu.rigel.biplatform.ma.model.service.CubeBuildService; import com.baidu.rigel.biplatform.ma.model.service.StarModelBuildService; import com.baidu.rigel.biplatform.ma.model.utils.DBInfoReader; import com.baidu.rigel.biplatform.ma.model.utils.DBUrlGeneratorUtils; import com.baidu.rigel.biplatform.ma.report.exception.CacheOperationException; import com.baidu.rigel.biplatform.ma.report.model.ReportDesignModel; import com.baidu.rigel.biplatform.ma.resource.cache.CacheManagerForResource; import com.baidu.rigel.biplatform.ma.resource.cache.ReportModelCacheManager; import com.baidu.rigel.biplatform.ma.resource.utils.ResourceUtils; import com.baidu.rigel.biplatform.ma.resource.view.CubeView; import com.baidu.rigel.biplatform.ma.resource.view.DateRelationTableView; import com.baidu.rigel.biplatform.ma.resource.view.DimBindConfigView; import com.baidu.rigel.biplatform.ma.resource.view.DimBindView; import com.baidu.rigel.biplatform.ma.resource.view.RelationTableView; import com.baidu.rigel.biplatform.ma.resource.view.dimdetail.CallbackDimDetail; import com.baidu.rigel.biplatform.ma.resource.view.dimdetail.CustDimDetail; import com.baidu.rigel.biplatform.ma.resource.view.dimdetail.DateDimDetail; import com.baidu.rigel.biplatform.ma.resource.view.dimdetail.NormalDimDetail; import com.baidu.rigel.biplatform.ma.resource.view.dimview.CallbackDimBindView; import com.baidu.rigel.biplatform.ma.resource.view.dimview.CustDimBindView; import com.baidu.rigel.biplatform.ma.resource.view.dimview.DateDimBindView; import com.baidu.rigel.biplatform.ma.resource.view.dimview.NormalDimBindView; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; /** * CubeTable的页面交互 * * @author zhongyi * * 2014-7-30 */ @RestController @RequestMapping("/silkroad/reports") public class DimConfigResource { /** * logger */ private Logger logger = LoggerFactory.getLogger(CacheManagerForResource.class); /** * gson */ private Gson gson = new GsonBuilder().create(); /** * reportModelCacheManager */ @Resource private ReportModelCacheManager reportModelCacheManager; /** * cubeBuildService */ @Resource private CubeBuildService cubeBuildService; /** * starModelBuildService */ @Resource private StarModelBuildService starModelBuildService; /** * director */ @Resource private Director director; /** * dsService */ @Resource private DataSourceService dsService; /** * * @param reportId * @param tableId * @return */ @RequestMapping(value = "/{reportId}/tables/{tableId}", method = { RequestMethod.GET }) public ResponseResult getTable(@PathVariable("reportId") String reportId, @PathVariable("tableId") String tableId) { // TODO 非内置时间以后实现 return null; } /** * * @param reportId * @param request * @return */ @RequestMapping(value = "/{id}/dim_config", method = { RequestMethod.GET }) public ResponseResult getDimConfig(@PathVariable("id") String reportId, HttpServletRequest request) { ReportDesignModel reportModel = getReportModel(reportId); if (reportModel == null) { String message = "can not get report model with id : " + reportId; logger.info(message); return ResourceUtils.getErrorResult(message, 1); } Schema schema = reportModel.getSchema(); StarModel[] starModels = director.getStarModel(schema); DimBindConfigView view = new DimBindConfigView(); List<RelationTableView> relationsTables = null; try { relationsTables = starModelBuildService.getAllTablesAndCols(reportModel.getDsId()); } catch (DataSourceOperationException e) { logger.error("Fail in get table info from ds. Ds Id: " + reportModel.getDsId(), e); return ResourceUtils.getErrorResult("获取数据源中的表格、列信息失败!请检查数据源配置。", 1); } view.setRelationTables(relationsTables); DimBindView dimBind = new DimBindView(); view.setDim(dimBind); Map<String, CubeView> cubes = Maps.newHashMap(); for (StarModel starModel : starModels) { NormalDimBindView normal = new NormalDimBindView(); normal.setCubeId(starModel.getCubeId()); CallbackDimBindView callback = new CallbackDimBindView(); callback.setCubeId(starModel.getCubeId()); CustDimBindView cust = new CustDimBindView(); cust.setCubeId(starModel.getCubeId()); DateDimBindView date = new DateDimBindView(); date.setCubeId(starModel.getCubeId()); dimBind.getCallback().add(callback); dimBind.getCustom().add(cust); dimBind.getNormal().add(normal); dimBind.getDate().add(date); for (DimTableMetaDefine dimTable : starModel.getDimTables()) { if (dimTable.getDimType() instanceof TimeDimType) { DateDimDetail dateDim = starModelBuildService.generateDateDimDetail( starModel.getCubeId(), (TimeDimTableMetaDefine) dimTable); date.getChildren().add(dateDim); } else if (dimTable.getDimType() == StandardDimType.CALLBACK) { CallbackDimDetail callbackDim = starModelBuildService .generateCallbackDimDetail((CallbackDimTableMetaDefine) dimTable); callback.getChildren().add(callbackDim); } else if (dimTable.getDimType() == StandardDimType.USERDEFINE) { CustDimDetail dateDim = starModelBuildService .generateCustDimDetail((UserDefineDimTableMetaDefine) dimTable); cust.getChildren().add(dateDim); } else { NormalDimDetail dateDim = starModelBuildService .generateNormalDimBindView((StandardDimTableMetaDefine) dimTable); if (dateDim != null) { normal.getChildren().add(dateDim); } } } FactTableMetaDefine cubeTable = starModel.getFactTable(); CubeView cubeView = new CubeView(); cubeView.setName(cubeTable.getName()); /** * 获取事实表的所有字段 */ DataSourceDefine ds; try { ds = dsService.getDsDefine(reportModel.getDsId()); } catch (DataSourceOperationException e) { String msg = "找不到数据源" + reportModel.getDsId(); logger.error(msg, e); return ResourceUtils.getErrorResult(msg, 1); } DBInfoReader reader = DBInfoReader.build(ds.getType(), ds.getDbUser(), ds.getDbPwd(), DBUrlGeneratorUtils.getConnUrl(ds)); String tableName = cubeTable.getName(); if (cubeTable.isMutilple() && CollectionUtils.isEmpty(cubeTable.getRegExpTables())) { tableName = cubeTable.getRegExpTables().get(0); } List<ColumnInfo> cols = null; try { cols = reader.getColumnInfos(tableName); } finally { reader.closeConn(); } if (CollectionUtils.isEmpty(cols)) { String msg = String.format("不能从表%s中获取字段!", tableName); logger.error(msg); return ResourceUtils.getErrorResult(msg, 1); } cubeView.setAllFields(cols); cubeView.setCurrDims(cols); cubes.put(cubeTable.getCubeId(), cubeView); } view.setCubes(cubes); List<DateRelationTableView> dateRelationTables = Lists.newArrayList(); // TODO 非内置时间以后实现 view.setDateRelationTables(dateRelationTables); ResponseResult rs = ResourceUtils.getCorrectResult("Success Getting Dim Config", view); logger.info("put operation rs is : " + rs.toString()); return rs; } /** * * @param reportId * @param request * @return */ @RequestMapping(value = "/{id}/dim_config", method = { RequestMethod.POST }) public ResponseResult saveDimConfig(@PathVariable("id") String reportId, HttpServletRequest request) { String normalStr = request.getParameter("normal"); String dateStr = request.getParameter("date"); String callbackStr = request.getParameter("callback"); String customStr = request.getParameter("custom"); List<NormalDimBindView> normalDims = gson.fromJson(normalStr, new TypeToken<List<NormalDimBindView>>() { }.getType()); List<CallbackDimBindView> callbackDims = gson.fromJson(callbackStr, new TypeToken<List<CallbackDimBindView>>() { }.getType()); List<CustDimBindView> custDims = gson.fromJson(customStr, new TypeToken<List<CustDimBindView>>() { }.getType()); List<DateDimBindView> dateDims = gson.fromJson(dateStr, new TypeToken<List<DateDimBindView>>() { }.getType()); /** * for efficiency */ Map<String, NormalDimBindView> normals = Maps.newHashMap(); Map<String, DateDimBindView> dates = Maps.newHashMap(); Map<String, CallbackDimBindView> callbacks = Maps.newHashMap(); Map<String, CustDimBindView> customs = Maps.newHashMap(); for (NormalDimBindView normalDim : normalDims) { normals.put(normalDim.getCubeId(), normalDim); } for (DateDimBindView dateDim : dateDims) { dates.put(dateDim.getCubeId(), dateDim); } for (CallbackDimBindView callbackDim : callbackDims) { callbacks.put(callbackDim.getCubeId(), callbackDim); } for (CustDimBindView custDim : custDims) { customs.put(custDim.getCubeId(), custDim); } ReportDesignModel reportModel = getReportModel(reportId); Schema schema = reportModel.getSchema(); StarModel[] starModels = director.getStarModel(schema); for (StarModel starModel : starModels) { List<DimTableMetaDefine> newDimTables = Lists.newArrayList(); Map<String, String> oldName = Maps.newHashMap(); for (DimTableMetaDefine dimMetaDefine : starModel.getDimTables()) { /** * 非用户自定义的维度,要保留原有的名字 */ if (dimMetaDefine.getDimType() != StandardDimType.USERDEFINE) { oldName.put(dimMetaDefine.getReference().getMajorColumn(), dimMetaDefine.getName()); } } NormalDimBindView normal = normals.get(starModel.getCubeId()); DateDimBindView date = dates.get(starModel.getCubeId()); CallbackDimBindView callback = callbacks.get(starModel.getCubeId()); CustDimBindView custom = customs.get(starModel.getCubeId()); try { newDimTables.addAll(starModelBuildService.generateMetaDefine(reportModel.getDsId(), normal, oldName)); } catch (DataSourceOperationException e) { logger.error("添加普通维度失败!", e); return ResourceUtils.getErrorResult("添加普通维度失败!", 1); } newDimTables.addAll(starModelBuildService.generateMetaDefine(date, oldName)); newDimTables.addAll(starModelBuildService.generateMetaDefine(callback, oldName)); newDimTables.addAll(starModelBuildService.generateMetaDefine(custom, oldName)); // 重置starModel的 starModel.setDimTables(newDimTables); } schema = director.modifySchemaWithNewModel(schema, starModels); ResponseResult rs = null; if (schema == null) { rs = ResourceUtils.getErrorResult("error when modify", 1); } else { reportModel.setSchema((MiniCubeSchema) schema); try { reportModelCacheManager.updateReportModelToCache(reportId, reportModel); } catch (CacheOperationException e) { logger.error("Fail in updating report model by id: " + reportId); return ResourceUtils.getErrorResult("更新报表模型失败!" , 1); } rs = ResourceUtils.getCorrectResult("Success modifying Starmodel! ", ""); } return rs; } /** * * @param reportId * @return */ private ReportDesignModel getReportModel(String reportId) { ReportDesignModel reportModel = null; try { reportModel = reportModelCacheManager.getReportModel(reportId); return reportModel; } catch (CacheOperationException e) { logger.debug("There is no such report model in cache. ", e); logger.info("Add report model into cache. "); } return reportModelCacheManager.loadReportModelToCache(reportId); } }
42.708223
100
0.632445
368dc71996c878669fac28b2827bdba68fbcbf04
4,978
/* * MIT License * * Copyright (c) 2021 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.terraforged.mod.biome.provider.analyser; import com.terraforged.mod.biome.context.TFBiomeContext; import net.minecraft.world.biome.Biome; import java.util.function.BiPredicate; public interface BiomePredicate { boolean test(int biome, TFBiomeContext context); default BiomePredicate and(BiomePredicate other) { return (b, c) -> this.test(b, c) && other.test(b, c); } default BiomePredicate not(BiomePredicate other) { return (b, c) -> this.test(b, c) && !other.test(b, c); } default BiomePredicate or(BiomePredicate other) { return (b, c) -> this.test(b, c) || other.test(b, c); } static BiomePredicate name(String... name) { return (b, c) -> anyMatch(c.getName(b), name, String::contains); } static BiomePredicate type(Biome.Category... categories) { return (b, c) -> anyMatch(c.getProperties().getProperty(b, Biome::getBiomeCategory), categories, (x, y) -> x == y); } static BiomePredicate rain(float min, float max) { return (b, c) -> testRange(c.getProperties().getMoisture(b), min, max); } static BiomePredicate rainType(Biome.RainType... rainTypes) { return (b, c) -> anyMatch(c.getProperties().getProperty(b, Biome::getPrecipitation), rainTypes, (x, y) -> x == y); } static BiomePredicate temp(float min, float max) { return (b, c) -> { float temp = c.getProperties().getTemperature(b); return testRange(temp, min, max); }; } static BiomePredicate depth(float min, float max) { return (b, c) -> testRange(c.getProperties().getDepth(b), min, max); } static <T> boolean anyMatch(T value, T[] test, BiPredicate<T, T> tester) { for (T t : test) { if (tester.test(value, t)) { return true; } } return false; } static boolean testRange(float value, float min, float max) { return value >= min && value <= max; } float ANY_MIN = -Float.MAX_VALUE; float ANY_MAX = Float.MAX_VALUE; // Temps float FROZEN = -0.4F; float COLD = 0.2F; float WARM = 1.4F; float HOT = 1.7F; // Rain float LIGHT = 0.2F; float MODERATE = 0.4F; float HEAVY = 0.8F; BiomePredicate OCEAN = type(Biome.Category.OCEAN); BiomePredicate BEACH = type(Biome.Category.BEACH).or(name("beach", "shore")); BiomePredicate COAST = type(Biome.Category.MUSHROOM).or(name("coast")); BiomePredicate COLD_STEPPE = name("steppe").and(temp(ANY_MIN, COLD)); BiomePredicate DESERT = type(Biome.Category.DESERT).or(temp(HOT, ANY_MAX).and(rain(ANY_MIN, LIGHT))); BiomePredicate GRASSLAND = type(Biome.Category.PLAINS); BiomePredicate LAKE = type(Biome.Category.RIVER).and(name("lake")).or(name("lake")); BiomePredicate MESA = type(Biome.Category.MESA); BiomePredicate MOUNTAIN = type(Biome.Category.EXTREME_HILLS).or(name("mountain")).or(name("cliff")); BiomePredicate VOLCANO = name("volcano").or(name("volcanic")); BiomePredicate RIVER = type(Biome.Category.RIVER).not(LAKE); BiomePredicate SAVANNA = type(Biome.Category.SAVANNA).or(temp(WARM, ANY_MAX).and(rain(ANY_MIN, MODERATE))); BiomePredicate STEPPE = name("steppe").and(temp(COLD, ANY_MAX)); BiomePredicate TAIGA = type(Biome.Category.TAIGA).or(temp(FROZEN, COLD)).not(rainType(Biome.RainType.SNOW)); BiomePredicate TEMPERATE_FOREST = type(Biome.Category.FOREST).and(rain(ANY_MIN, HEAVY)); BiomePredicate TEMPERATE_RAINFOREST = type(Biome.Category.FOREST).and(rain(HEAVY, ANY_MAX)); BiomePredicate TROPICAL_RAINFOREST = type(Biome.Category.JUNGLE); BiomePredicate TUNDRA = type(Biome.Category.ICY).or(temp(ANY_MIN, FROZEN).and(rainType(Biome.RainType.SNOW))); BiomePredicate WETLAND = type(Biome.Category.SWAMP); }
40.803279
123
0.681599
5dc524e0bf7563b19efb8ca92cec43daa75b30ec
1,550
/******************************************************************************* * Copyright (c) 2012, 2013 Arron Ferguson. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 05/17/2012-2.3.3 Arron Ferguson * - 379829: NPE Thrown with OneToOne Relationship ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.ddlgeneration; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = "sponsor") public class Sponsor implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(optional = false, cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) @PrimaryKeyJoinColumn private Address2 address; }
38.75
105
0.671613
0f12fa9e9a3313f71de252f033ae9fa04cd929d8
6,367
package nl.sense_os.service.ctrl; import nl.sense_os.service.DataTransmitter; import nl.sense_os.service.constants.SensePrefs; import nl.sense_os.service.constants.SensePrefs.Main; import android.app.AlarmManager; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.util.Log; /** * A singleton that includes all the intelligent methods of the sense-android-library that define * the function of specific sensors. The two different extensions, Default and Extended, implement * the default and the energy-saving behavior respectively. */ public abstract class Controller { private class Intervals { static final long ECO = AlarmManager.INTERVAL_HALF_HOUR; static final long RARELY = 1000 * 60 * 15; static final long NORMAL = 1000 * 60 * 5; static final long OFTEN = 1000 * 60 * 1; static final long BALANCED = 1000 * 60 * 3; } private static final String TAG = "Controller"; private static Controller sInstance; /** * Returns a controller instance * * @param context * Context of the Sense service * @return the existed controller if any, otherwise the one which has just been created */ public static synchronized Controller getController(Context context) { if (sInstance == null) { sInstance = new CtrlDefault(context); } return sInstance; } private Context mContext; protected Controller(Context context) { mContext = context; } /** * Retains the mode of Light sensor, and defines it as changed or idle, if the last light * measurement had a noticeable difference compared to the previous one or not, respectively * * @param value * Last light measurement, in lux. */ public abstract void checkLightSensor(float value); /** * Retains the mode of Noise sensor, and defines it as loud or idle, if the last noise * measurement had a noticeable difference compared to the previous one or not, respectively * * @param dB * Last noise measurement, in db. */ public abstract void checkNoiseSensor(double dB); /** * Checks to see if the sensor is still doing a useful job or whether it is better if we disable * it for a while. This method is a callback for a periodic alarm to check the sensor status. * * @param isGpsAllowed * True if Gps usage is allowed by the user. * @param isListeningNw * True if we currently listen for Network fix. * @param isListeningGps * True if we currently listen for Gps fix. * @param time * The time between location refresh attempts. * @param lastGpsFix * The last fix by Gps provider. * @param listenGpsStart * The last time the Gps provider was enabled. * @param lastNwFix * The last fix by Network provider. * @param listenNwStart * The last time the Network provider was enabled. * @param listenGpsStop * The last time the Gps provider was disabled. * @param listenNwStop * The last time the Network provider was disabled. * * @see #alarmReceiver */ public void checkSensorSettings(boolean isGpsAllowed, boolean isListeningNw, boolean isListeningGps, long time, Location lastGpsFix, long listenGpsStart, Location lastNwFix, long listenNwStart, long listenGpsStop, long listenNwStop) { } /** * Starts periodic transmission of the buffered sensor data. */ public void scheduleTransmissions() { Log.v(TAG, "Schedule transmissions"); SharedPreferences mainPrefs = mContext.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); int syncRate = Integer.parseInt(mainPrefs.getString(Main.SYNC_RATE, SensePrefs.Main.SyncRate.NORMAL)); int sampleRate = Integer.parseInt(mainPrefs.getString(Main.SAMPLE_RATE, SensePrefs.Main.SampleRate.NORMAL)); // pick transmission interval long txInterval; switch (syncRate) { case 2: // rarely, every 15 minutes txInterval = Intervals.RARELY; break; case 1: // eco-mode txInterval = Intervals.ECO; break; case 0: // 5 minute txInterval = Intervals.NORMAL; break; case -1: // 60 seconds txInterval = Intervals.OFTEN; break; case -2: // real-time: schedule transmission based on sample time switch (sampleRate) { case 2: // balanced txInterval = Intervals.BALANCED * 3; break; case 1: // rarely txInterval = Intervals.ECO * 3; break; case 0: // normal txInterval = Intervals.NORMAL * 3; break; case -1: // often txInterval = Intervals.OFTEN * 3; break; case -2: // real time txInterval = Intervals.OFTEN; break; default: Log.w(TAG, "Unexpected sample rate value: " + sampleRate); return; } break; default: Log.w(TAG, "Unexpected sync rate value: " + syncRate); return; } // pick transmitter task interval long txTaskInterval; switch (sampleRate) { case -2: // real time txTaskInterval = 0; break; case -1: // often txTaskInterval = 10 * 1000; break; case 0: // normal txTaskInterval = 60 * 1000; break; case 1: // rarely (15 minutes) txTaskInterval = 15 * 60 * 1000; break; case 2: // balanced (3 minutes) txTaskInterval = 3 * 60 * 1000; break; default: Log.w(TAG, "Unexpected sample rate value: " + sampleRate); return; } DataTransmitter transmitter = DataTransmitter.getInstance(mContext); transmitter.startTransmissions(txInterval, txTaskInterval); } }
35.372222
116
0.600911
e4ce71dad42c445cd1f9697d5498b01a3e5431fb
2,122
/** * The MIT License * * Copyright (C) 2021 Asterios Raptis * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.astrapi69.auth.api; import java.io.Serializable; /** * The interface {@link Permission}. */ public interface Permission extends Serializable { /** * Returns the field <code>description</code>. * * @return The field <code>description</code>. */ String getDescription(); /** * Sets the field <code>description</code>. * * @param description * The <code>description</code> to set */ void setDescription(final String description); /** * Returns the field <code>name</code>. * * @return The field <code>name</code>. */ String getPermissionName(); /** * Sets the field <code>name</code>. * * @param name * The <code>name</code> to set */ void setPermissionName(final String name); /** * Gets the shortcut. * * @return the shortcut */ String getShortcut(); /** * Sets the shortcut. * * @param shortcut * the new shortcut */ void setShortcut(final String shortcut); }
27.558442
100
0.698869
76f088345532193545fec4c7228b51036d4fd6cb
843
package cn.hust.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotBlank; /** * 用户信息VO * @author zz */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @ApiModel(description = "用户信息对象") public class UserInfoVO { /** * 用户昵称 */ @NotBlank(message = "昵称不能为空") @ApiModelProperty(name = "nickname", value = "昵称", dataType = "String") private String nickname; /** * 用户简介 */ @ApiModelProperty(name = "intro", value = "介绍", dataType = "String") private String intro; /** * 个人网站 */ @ApiModelProperty(name = "webSite", value = "个人网站", dataType = "String") private String webSite; }
21.075
76
0.673784
985d777abefd26ad80a6b394f2b2177011049287
403
package com.lives.platform.web.mapper; import com.lives.platform.web.entity.Register; public interface RegisterMapper { int deleteByPrimaryKey(Integer registerId); int insert(Register record); int insertSelective(Register record); Register selectByPrimaryKey(Integer registerId); int updateByPrimaryKeySelective(Register record); int updateByPrimaryKey(Register record); }
23.705882
53
0.781638
db15d02365635efb3251bf1e7afbcdc9a285f9ed
18,328
package seedu.inventory.model; import static java.util.Objects.requireNonNull; import static seedu.inventory.commons.util.CollectionUtil.requireAllNonNull; import java.nio.file.Path; import java.util.function.Predicate; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import seedu.inventory.commons.core.ComponentManager; import seedu.inventory.commons.core.LogsCenter; import seedu.inventory.commons.events.model.AccessItemEvent; import seedu.inventory.commons.events.model.AccessPurchaseOrderEvent; import seedu.inventory.commons.events.model.AccessSaleEvent; import seedu.inventory.commons.events.model.AccessStaffEvent; import seedu.inventory.commons.events.model.InventoryChangedEvent; import seedu.inventory.commons.events.model.ItemListExportEvent; import seedu.inventory.commons.events.model.ItemListImportEvent; import seedu.inventory.commons.events.model.PurchaseOrderListExportEvent; import seedu.inventory.commons.events.model.PurchaseOrderListImportEvent; import seedu.inventory.commons.events.model.SaleListChangedEvent; import seedu.inventory.commons.events.model.SaleListExportEvent; import seedu.inventory.commons.events.model.SaleListImportEvent; import seedu.inventory.commons.events.model.StaffListChangedEvent; import seedu.inventory.commons.events.model.StaffListExportEvent; import seedu.inventory.commons.events.model.StaffListImportEvent; import seedu.inventory.commons.events.storage.ItemListUpdateEvent; import seedu.inventory.commons.events.storage.PurchaseOrderListUpdateEvent; import seedu.inventory.commons.events.storage.SaleListUpdateEvent; import seedu.inventory.commons.events.storage.StaffListUpdateEvent; import seedu.inventory.commons.events.ui.ClearBrowserPanelEvent; import seedu.inventory.commons.events.ui.ShowDefaultPageEvent; import seedu.inventory.commons.events.ui.ShowItemTableViewEvent; import seedu.inventory.commons.events.ui.ShowPurchaseOrderTableViewEvent; import seedu.inventory.commons.events.ui.ShowSaleTableViewEvent; import seedu.inventory.commons.events.ui.ShowStaffTableViewEvent; import seedu.inventory.commons.events.ui.ToggleSidePanelVisibilityEvent; import seedu.inventory.model.item.Item; import seedu.inventory.model.purchaseorder.PurchaseOrder; import seedu.inventory.model.sale.Sale; import seedu.inventory.model.staff.Staff; /** * Represents the in-memory model of the inventory data. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private FilteredList accessedList; private final VersionedInventory versionedInventory; private final FilteredList<Item> filteredItems; private final FilteredList<PurchaseOrder> filteredPurchaseOrder; private final FilteredList<Staff> filteredStaffs; private UserSession session; /** * Initializes a ModelManager with the given inventory and userPrefs. */ public ModelManager(ReadOnlyInventory inventory, UserPrefs userPrefs, ReadOnlySaleList readOnlySaleList) { super(); requireAllNonNull(inventory, userPrefs, readOnlySaleList); logger.fine("Initializing with inventory: " + inventory + " and user prefs " + userPrefs); versionedInventory = new VersionedInventory(inventory); filteredItems = new FilteredList<>(versionedInventory.getItemList()); filteredPurchaseOrder = new FilteredList<>(versionedInventory.getPurchaseOrderList()); filteredStaffs = new FilteredList<>(versionedInventory.getStaffList()); accessedList = filteredItems; session = new UserSession(); } public ModelManager() { this(new Inventory(), new UserPrefs(), new SaleList()); } @Override public void resetData(ReadOnlyInventory newData) { versionedInventory.resetData(newData); indicateInventoryChanged(); } @Override public void resetItemList(ReadOnlyItemList newItemList) { versionedInventory.resetItemList(newItemList); indicateInventoryChanged(); } @Override public void resetSaleList(ReadOnlySaleList newSaleList) { versionedInventory.resetSaleList(newSaleList); indicateSaleListChanged(); } @Override public void resetStaffList(ReadOnlyStaffList newStaffList) { versionedInventory.resetStaffList(newStaffList); indicateInventoryChanged(); } @Override public void resetPurchaseOrderList(ReadOnlyPurchaseOrderList newPurchaseOrderList) { versionedInventory.resetPurchaseOrderList(newPurchaseOrderList); indicateInventoryChanged(); } @Override public ReadOnlyInventory getInventory() { return versionedInventory; } @Override public <T> FilteredList<T> getAccessedList() { return accessedList; } /** * Raises an event to indicate the model has changed */ private void indicateInventoryChanged() { raise(new InventoryChangedEvent(versionedInventory)); } /** * Raises an event to indicate accessing item */ private void indicateAccessItem() { raise(new AccessItemEvent()); } /** * Raises an event to indicate accessing purchase order */ private void indicatePurchaseOrder() { raise(new AccessPurchaseOrderEvent()); } //=========== Reporting =============================================================================== @Override public void showItemTableView() { raise(new ShowItemTableViewEvent()); } @Override public void showSaleTableView() { raise(new ShowSaleTableViewEvent()); } @Override public void showStaffTableView() { raise(new ShowStaffTableViewEvent()); } @Override public void showPurchaseOrderTableView() { raise(new ShowPurchaseOrderTableViewEvent()); } @Override public void exportItemList(Path filePath) { indicateAccessItem(); showItemTableView(); raise(new ItemListExportEvent(versionedInventory, filePath)); } @Override public void importItemList(Path filePath) { indicateAccessItem(); showItemTableView(); raise(new ItemListImportEvent(filePath)); } @Override public void exportSaleList(Path filePath) { indicateAccessSale(); showSaleTableView(); raise(new SaleListExportEvent(versionedInventory, filePath)); } @Override public void importSaleList(Path filePath) { indicateAccessSale(); showSaleTableView(); raise(new SaleListImportEvent(versionedInventory, filePath)); } @Override public void exportStaffList(Path filePath) { indicateAccessStaff(); showStaffTableView(); raise(new StaffListExportEvent(versionedInventory, filePath)); } @Override public void importStaffList(Path filePath) { indicateAccessStaff(); showStaffTableView(); raise(new StaffListImportEvent(filePath)); } @Override public void exportPurchaseOrderList(Path filePath) { indicatePurchaseOrder(); showPurchaseOrderTableView(); raise(new PurchaseOrderListExportEvent(versionedInventory, filePath)); } @Override public void importPurchaseOrderList(Path filePath) { indicatePurchaseOrder(); showPurchaseOrderTableView(); raise(new PurchaseOrderListImportEvent(versionedInventory, filePath)); } //=========== Item ==================================================================================== @Override public boolean hasItem(Item item) { requireNonNull(item); return versionedInventory.hasItem(item); } @Override public void viewItem() { updateFilteredItemList(PREDICATE_SHOW_ALL_ITEMS); accessedList = filteredItems; indicateAccessItem(); raise(new ClearBrowserPanelEvent()); } @Override public void viewLowQuantity() { updateFilteredItemList(PREDICATE_SHOW_ALL_LOW_QUANTITY); accessedList = filteredItems; indicateAccessItem(); raise(new ClearBrowserPanelEvent()); } @Override public void deleteItem(Item target) { versionedInventory.removeItem(target); indicateInventoryChanged(); } @Override public void addItem(Item item) { versionedInventory.addItem(item); updateFilteredItemList(PREDICATE_SHOW_ALL_ITEMS); indicateInventoryChanged(); } @Override public void updateItem(Item target, Item editedItem) { requireAllNonNull(target, editedItem); versionedInventory.updateItem(target, editedItem); indicateInventoryChanged(); } //=========== Filtered Item List Accessors ============================================================= /** * Returns an unmodifiable view of the list of {@code Item} backed by the internal list of * {@code versionedInventory} */ @Override public ObservableList<Item> getFilteredItemList() { return FXCollections.unmodifiableObservableList(filteredItems); } @Override public void updateFilteredItemList(Predicate<Item> predicate) { requireNonNull(predicate); filteredItems.setPredicate(predicate); } //=========== Purchase Order ========================================================================== @Override public boolean hasPurchaseOrder(PurchaseOrder po) { requireNonNull(po); return versionedInventory.hasPurchaseOrder(po); } @Override public boolean hasPurchaseOrder(Item item) { requireNonNull(item); return versionedInventory.hasPurchaseOrder(item); } @Override public void addPurchaseOrder(PurchaseOrder po) { versionedInventory.addPurchaseOrder(po); updateFilteredPurchaseOrderList(PREDICATE_SHOW_ALL_PURCHASE_ORDER); indicateInventoryChanged(); } @Override public void viewPurchaseOrder() { updateFilteredItemList(PREDICATE_SHOW_ALL_ITEMS); accessedList = filteredPurchaseOrder; indicatePurchaseOrder(); } @Override public void deletePurchaseOrder(int target) { versionedInventory.removePurchaseOrder(target); indicateInventoryChanged(); } @Override public void deletePurchaseOrder(Item target) { versionedInventory.removePurchaseOrder(target); indicateInventoryChanged(); } @Override public void updatePurchaseOrder(int target, PurchaseOrder editedPurchaseOrder) { requireNonNull(editedPurchaseOrder); versionedInventory.updatePurchaseOrder(target, editedPurchaseOrder); indicateInventoryChanged(); } @Override public void updatePurchaseOrder(Item target, Item editedItem) { requireAllNonNull(target, editedItem); versionedInventory.updatePurchaseOrder(target, editedItem); indicateInventoryChanged(); } @Override public void approvePurchaseOrder(int target, PurchaseOrder targetPo) { versionedInventory.approvePurchaseOrder(target, targetPo); indicateInventoryChanged(); } @Override public void rejectPurchaseOrder(int target, PurchaseOrder targetPo) { versionedInventory.rejectPurchaseOrder(target, targetPo); indicateInventoryChanged(); } //=========== User Management =========================================== @Override public boolean hasStaff(Staff staff) { requireNonNull(staff); return versionedInventory.hasStaff(staff); } @Override public boolean hasUsername(Staff staff) { requireNonNull(staff); return versionedInventory.hasUsername(staff); } @Override public void deleteStaff(Staff target) { requireNonNull(target); versionedInventory.removeStaff(target); indicateStaffListChanged(); } @Override public void addStaff(Staff staff) { requireNonNull(staff); versionedInventory.addStaff(staff); updateFilteredStaffList(PREDICATE_SHOW_ALL_STAFFS); indicateStaffListChanged(); } @Override public void updateStaff(Staff target, Staff editedStaff) { requireAllNonNull(target, editedStaff); versionedInventory.updateStaff(target, editedStaff); indicateStaffListChanged(); } @Override public void viewStaff() { updateFilteredStaffList(PREDICATE_SHOW_ALL_STAFFS); accessedList = filteredStaffs; indicateAccessStaff(); } /** * Raises an event to indicate accessing item */ private void indicateAccessStaff() { raise(new AccessStaffEvent()); } //=========== Filtered Purchase Order List Accessors ============================================================= /** * Returns an unmodifiable view of the list of {@code PurchaseOrder} backed by the internal list of * {@code versionedInventory} */ @Override public ObservableList<PurchaseOrder> getFilteredPurchaseOrderList() { return FXCollections.unmodifiableObservableList(filteredPurchaseOrder); } @Override public void updateFilteredPurchaseOrderList(Predicate<PurchaseOrder> predicate) { requireNonNull(predicate); filteredPurchaseOrder.setPredicate(predicate); } // ================ Filtered Staff list accessors============= /** * Returns an unmodifiable view of the list of {@code Item} backed by the internal list of * {@code versionedInventory} */ @Override public ObservableList<Staff> getFilteredStaffList() { return FXCollections.unmodifiableObservableList(filteredStaffs); } @Override public void updateFilteredStaffList(Predicate<Staff> predicate) { requireNonNull(predicate); filteredStaffs.setPredicate(predicate); } /** * Raises an event to indicate the model has changed */ private void indicateStaffListChanged() { raise(new StaffListChangedEvent(versionedInventory)); } //================ Authentication ======================== @Override public void authenticateUser(Staff toLogin) { requireNonNull(toLogin); session = new UserSession(toLogin); raise(new ToggleSidePanelVisibilityEvent(true)); } @Override public Staff retrieveStaff(Staff toRetrieve) { requireNonNull(toRetrieve); return versionedInventory.retrieveStaff(toRetrieve); } @Override public void updateUserSession(Staff staff) { session.updateUser(staff); } @Override public void logoutUser() { session.logout(); versionedInventory.reset(); raise(new ToggleSidePanelVisibilityEvent(false)); raise(new ShowDefaultPageEvent()); } @Override public boolean isUserLoggedIn() { return session.isLoggedIn(); } @Override public Staff getUser() { return this.session.getUser(); } //=========== Undo/Redo ================================================================================= @Override public boolean canUndoInventory() { return versionedInventory.canUndo(); } @Override public boolean canRedoInventory() { return versionedInventory.canRedo(); } @Override public void undoInventory() { versionedInventory.undo(); indicateInventoryChanged(); indicateSaleListChanged(); } @Override public void redoInventory() { versionedInventory.redo(); indicateInventoryChanged(); indicateSaleListChanged(); } @Override public void commitInventory() { versionedInventory.commit(); } @Override public boolean equals(Object obj) { // short circuit if same object if (obj == this) { return true; } // instanceof handles nulls if (!(obj instanceof ModelManager)) { return false; } // state check ModelManager other = (ModelManager) obj; return versionedInventory.equals(other.versionedInventory) && filteredItems.equals(other.filteredItems); } //=========== Sale ==================================================================================== @Override public ReadOnlySaleList getSaleList() { return versionedInventory; } @Override public ObservableList<Sale> getObservableSaleList() { return FXCollections.unmodifiableObservableList(versionedInventory.getSaleList()); } @Override public void addSale(Sale sale) { versionedInventory.addSale(sale); indicateSaleListChanged(); } @Override public void deleteSale(Sale sale) { versionedInventory.removeSale(sale); indicateSaleListChanged(); } @Override public void listSales() { indicateAccessSale(); } /** * Raises an event to indicate accessing sale */ private void indicateAccessSale() { raise(new AccessSaleEvent()); } /** * Raises an event to indicate the model has changed */ private void indicateSaleListChanged() { raise(new SaleListChangedEvent(versionedInventory)); } @Override @Subscribe public void handleItemListUpdateEvent(ItemListUpdateEvent event) { resetItemList(event.itemList); } @Override @Subscribe public void handleSaleListUpdateEvent(SaleListUpdateEvent event) { resetSaleList(event.saleList); } @Override @Subscribe public void handleStaffListUpdateEvent(StaffListUpdateEvent event) { StaffList staffList = new StaffList(event.staffList); if (!staffList.hasStaff(getUser())) { staffList.addStaff(getUser()); } resetStaffList(staffList); } @Override @Subscribe public void handlePurchaseOrderListUpdateEvent(PurchaseOrderListUpdateEvent event) { resetPurchaseOrderList(event.purchaseOrderList); } }
30.546667
118
0.674269
f76ece8664fc92a75e9e3fc3adf67984d2b702cc
14,369
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.arg.counterexamples; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.notNull; import static com.google.common.collect.FluentIterable.from; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import org.sosy_lab.common.Appender; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.FileOption; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.common.io.Files; import org.sosy_lab.common.io.Path; import org.sosy_lab.common.io.PathTemplate; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.core.CounterexampleInfo; import org.sosy_lab.cpachecker.core.counterexample.CFAEdgeWithAssumptions; import org.sosy_lab.cpachecker.core.counterexample.CFAMultiEdgeWithAssumptions; import org.sosy_lab.cpachecker.core.counterexample.CFAPathWithAssumptions; import org.sosy_lab.cpachecker.core.counterexample.RichModel; import org.sosy_lab.cpachecker.cpa.arg.ARGPath; import org.sosy_lab.cpachecker.cpa.arg.ARGPathExporter; import org.sosy_lab.cpachecker.cpa.arg.ARGState; import org.sosy_lab.cpachecker.cpa.arg.ARGToDotWriter; import org.sosy_lab.cpachecker.cpa.arg.ARGUtils; import org.sosy_lab.cpachecker.cpa.arg.ErrorPathShrinker; import org.sosy_lab.cpachecker.util.Pair; import org.sosy_lab.cpachecker.util.cwriter.PathToCTranslator; import org.sosy_lab.cpachecker.util.cwriter.PathToConcreteProgramTranslator; import org.sosy_lab.solver.AssignableTerm; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; @Options(prefix="cpa.arg.errorPath") public class CEXExporter { enum CounterexampleExportType { CBMC, CONCRETE_EXECUTION; } @Option(secure=true, name="export", description="export error path to file, if one is found") private boolean exportErrorPath = true; @Option(secure=true, name="file", description="export error path as text file") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathFile = PathTemplate.ofFormatString("ErrorPath.%d.txt"); @Option(secure=true, name="core", description="export error path core as text file") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathCoreFile = PathTemplate.ofFormatString("ErrorPath.%d.core.txt"); @Option(secure=true, name="source", description="export error path as source file") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathSourceFile = PathTemplate.ofFormatString("ErrorPath.%d.c"); @Option(secure=true, name="exportAsSource", description="export error path as source file") private boolean exportSource = true; @Option(secure=true, name="json", description="export error path as JSON file") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathJson = PathTemplate.ofFormatString("ErrorPath.%d.json"); @Option(secure=true, name="assignment", description="export one variable assignment for error path to file, if one is found") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathAssignment = PathTemplate.ofFormatString("ErrorPath.%d.assignment.txt"); @Option(secure=true, name="graph", description="export error path as graph") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathGraphFile = PathTemplate.ofFormatString("ErrorPath.%d.dot"); @Option(secure=true, name="automaton", description="export error path as automaton") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathAutomatonFile = PathTemplate.ofFormatString("ErrorPath.%d.spc"); @Option(secure=true, name="graphml", description="export error path to file as GraphML automaton") @FileOption(FileOption.Type.OUTPUT_FILE) private PathTemplate errorPathAutomatonGraphmlFile = null; @Option(secure=true, name="codeStyle", description="exports either CMBC format or a concrete path program") private CounterexampleExportType codeStyle = CounterexampleExportType.CBMC; private final LogManager logger; private final ARGPathExporter witnessExporter; public CEXExporter(Configuration config, LogManager logger, ARGPathExporter pARGPathExporter) throws InvalidConfigurationException { config.inject(this); this.logger = logger; this.witnessExporter = pARGPathExporter; if (!exportSource) { errorPathSourceFile = null; } if (errorPathAssignment == null && errorPathCoreFile == null && errorPathFile == null && errorPathGraphFile == null && errorPathJson == null && errorPathSourceFile == null && errorPathAutomatonFile == null && errorPathAutomatonGraphmlFile == null) { exportErrorPath = false; } } /** * Export an Error Trace in different formats, for example as C-file, dot-file or automaton. * * @param pTargetState state of an ARG, used as fallback, if pCounterexampleInfo contains no targetPath. * @param pCounterexampleInfo contains further information and the (optional) targetPath. * If the targetPath is available, it will be used for the output. * Otherwise we use backwards reachable states from pTargetState. * @param cexIndex should be a unique index for the CEX and will be used to enumerate files. */ public void exportCounterexample(final ARGState pTargetState, final CounterexampleInfo pCounterexampleInfo, int cexIndex) { checkNotNull(pTargetState); checkNotNull(pCounterexampleInfo); if (exportErrorPath) { exportCounterexample(pTargetState, cexIndex, pCounterexampleInfo); } } private void exportCounterexample(final ARGState lastState, final int cexIndex, final CounterexampleInfo counterexample) { final ARGPath targetPath = counterexample.getTargetPath(); final Predicate<Pair<ARGState, ARGState>> isTargetPathEdge = Predicates.in( new HashSet<>(targetPath.getStatePairs())); final ARGState rootState = targetPath.getFirstState(); writeErrorPathFile(errorPathFile, cexIndex, createErrorPathWithVariableAssignmentInformation(targetPath.getInnerEdges(), counterexample)); if (errorPathCoreFile != null) { // the shrinked errorPath only includes the nodes, // that are important for the error, it is not a complete path, // only some nodes of the targetPath are part of it ErrorPathShrinker pathShrinker = new ErrorPathShrinker(); List<CFAEdge> shrinkedErrorPath = pathShrinker.shrinkErrorPath(targetPath); writeErrorPathFile(errorPathCoreFile, cexIndex, createErrorPathWithVariableAssignmentInformation(shrinkedErrorPath, counterexample)); } writeErrorPathFile(errorPathJson, cexIndex, new Appender() { @Override public void appendTo(Appendable pAppendable) throws IOException { if (counterexample.getTargetPathModel() != null && counterexample.getTargetPathModel().getCFAPathWithAssignments() != null) { targetPath.toJSON(pAppendable, counterexample.getTargetPathModel().getCFAPathWithAssignments().asList()); } else { targetPath.toJSON(pAppendable, ImmutableList.<CFAEdgeWithAssumptions>of()); } } }); final Set<ARGState> pathElements; Appender pathProgram = null; if (counterexample.isPreciseCounterExample()) { pathElements = targetPath.getStateSet(); if (errorPathSourceFile != null) { switch(codeStyle) { case CONCRETE_EXECUTION: pathProgram = PathToConcreteProgramTranslator.translateSinglePath(targetPath, counterexample.getTargetPathModel()); break; case CBMC: pathProgram = PathToCTranslator.translateSinglePath(targetPath); break; default: throw new AssertionError("Unhandled case statement: " + codeStyle); } } } else { // Imprecise error path. // For the text export, we have no other chance, // but for the C code and graph export we use all existing paths // to avoid this problem. pathElements = ARGUtils.getAllStatesOnPathsTo(lastState); if (errorPathSourceFile != null) { switch(codeStyle) { case CONCRETE_EXECUTION: pathProgram = PathToConcreteProgramTranslator.translatePaths(rootState, pathElements, counterexample.getTargetPathModel()); break; case CBMC: pathProgram = PathToCTranslator.translatePaths(rootState, pathElements); break; default: throw new AssertionError("Unhandled case statement: " + codeStyle); } } } if (pathProgram != null) { writeErrorPathFile(errorPathSourceFile, cexIndex, pathProgram); } writeErrorPathFile(errorPathGraphFile, cexIndex, new Appender() { @Override public void appendTo(Appendable pAppendable) throws IOException { ARGToDotWriter.write(pAppendable, rootState, ARGUtils.CHILDREN_OF_STATE, Predicates.in(pathElements), isTargetPathEdge); } }); writeErrorPathFile(errorPathAutomatonFile, cexIndex, new Appender() { @Override public void appendTo(Appendable pAppendable) throws IOException { ARGUtils.producePathAutomaton(pAppendable, rootState, pathElements, "ErrorPath" + cexIndex, counterexample); } }); if (counterexample.getTargetPathModel() != null) { writeErrorPathFile(errorPathAssignment, cexIndex, counterexample.getTargetPathModel()); } for (Pair<Object, PathTemplate> info : counterexample.getAllFurtherInformation()) { if (info.getSecond() != null) { writeErrorPathFile(info.getSecond(), cexIndex, info.getFirst()); } } writeErrorPathFile(errorPathAutomatonGraphmlFile, cexIndex, new Appender() { @Override public void appendTo(Appendable pAppendable) throws IOException { witnessExporter.writeErrorWitness(pAppendable, rootState, Predicates.in(pathElements), isTargetPathEdge, counterexample); } }); } private Appender createErrorPathWithVariableAssignmentInformation( final List<CFAEdge> edgePath, final CounterexampleInfo counterexample) { final RichModel model = counterexample == null ? null : counterexample.getTargetPathModel(); return new Appender() { @Override public void appendTo(Appendable out) throws IOException { // Write edges mixed with assigned values. CFAPathWithAssumptions exactValuePath = model.getExactVariableValuePath(edgePath); if (exactValuePath != null) { printPreciseValues(out, exactValuePath); } else { printAllValues(out, edgePath); } } private void printAllValues(Appendable out, List<CFAEdge> pEdgePath) throws IOException { for (CFAEdge edge : from(pEdgePath).filter(notNull())) { out.append(edge.toString()); out.append(System.lineSeparator()); //TODO Erase, counterexample is supposed to be independent of Assignable terms for (AssignableTerm term : model.getAllAssignedTerms(edge)) { out.append('\t'); out.append(term.toString()); out.append(": "); out.append(model.get(term).toString()); out.append(System.lineSeparator()); } } } private void printPreciseValues(Appendable out, CFAPathWithAssumptions pExactValuePath) throws IOException { for (CFAEdgeWithAssumptions edgeWithAssignments : from(pExactValuePath).filter(notNull())) { if (edgeWithAssignments instanceof CFAMultiEdgeWithAssumptions) { for (CFAEdgeWithAssumptions singleEdge : (CFAMultiEdgeWithAssumptions) edgeWithAssignments) { printPreciseValues(out, singleEdge); } } else { printPreciseValues(out, edgeWithAssignments); } } } private void printPreciseValues(Appendable out, CFAEdgeWithAssumptions edgeWithAssignments) throws IOException { out.append(edgeWithAssignments.getCFAEdge().toString()); out.append(System.lineSeparator()); String cCode = edgeWithAssignments.prettyPrintCode(1); if (!cCode.isEmpty()) { out.append(cCode); } String comment = edgeWithAssignments.getComment(); if (!comment.isEmpty()) { out.append('\t'); out.append(comment); out.append(System.lineSeparator()); } } }; } private void writeErrorPathFile(PathTemplate template, int cexIndex, Object content) { if (template != null) { // fill in index in file name Path file = template.getPath(cexIndex); try { Files.writeFile(file, content); } catch (IOException e) { logger.logUserException(Level.WARNING, e, "Could not write information about the error path to file"); } } } }
39.584022
134
0.707565
5a036bda182b2817cc0e5c39e1fe2dbed00b6011
89
package lwjgui.geometry; public interface Resizable { public boolean isResizeable(); }
14.833333
31
0.786517
9d997b76fcf2f86aa12d6c4a5d90f4c19155e284
886
package io.stat.nabuproject.core.net.channel; import io.netty.channel.ChannelHandler; /** * Simply wraps an instance of a ChannelHandler, and returns that. * * @author Ilya Ostrovskiy (https://github.com/iostat/) */ final class SimpleHandlerWrapper<T extends ChannelHandler, U> implements FluentHandlerWrapper<T> { private final T theInstance; private final ChannelHandlerCallback<T, U> callback; private final U cbArgs; SimpleHandlerWrapper(T theInstance, ChannelHandlerCallback<T, U> callback, U args) { this.theInstance = theInstance; this.callback = callback; this.cbArgs = args; } @Override public T getHandler() throws Exception { return theInstance; } @Override public void runCallback(T instance) { if(callback != null) { callback.accept(instance, cbArgs); } } }
26.848485
98
0.67833
d086a9d5c079bc849f0145eddb2d3993d64afbf8
1,347
package com.skeqi.finance.service.asset; import com.skeqi.finance.domain.asset.TFaAssetTypeGroup; import com.skeqi.finance.pojo.vo.asset.TFaAssetTypeGroupVo; import com.skeqi.finance.pojo.bo.asset.TFaAssetTypeGroupQueryBo; import com.skeqi.finance.pojo.bo.asset.TFaAssetTypeGroupAddBo; import com.skeqi.finance.pojo.bo.asset.TFaAssetTypeGroupEditBo; import com.skeqi.common.core.mybatisplus.core.IServicePlus; import com.skeqi.common.core.page.TableDataInfo; import java.util.Collection; import java.util.List; /** * 资产类别组Service接口 * * @author toms * @date 2021-07-09 */ public interface ITFaAssetTypeGroupService extends IServicePlus<TFaAssetTypeGroup> { /** * 查询单个 * @return */ TFaAssetTypeGroupVo queryById(Integer fId); /** * 查询列表 */ TableDataInfo<TFaAssetTypeGroupVo> queryPageList(TFaAssetTypeGroupQueryBo bo); /** * 查询列表 */ List<TFaAssetTypeGroupVo> queryList(TFaAssetTypeGroupQueryBo bo); /** * 根据新增业务对象插入资产类别组 * @param bo 资产类别组新增业务对象 * @return */ Boolean insertByAddBo(TFaAssetTypeGroupAddBo bo); /** * 根据编辑业务对象修改资产类别组 * @param bo 资产类别组编辑业务对象 * @return */ Boolean updateByEditBo(TFaAssetTypeGroupEditBo bo); /** * 校验并删除数据 * @param ids 主键集合 * @param isValid 是否校验,true-删除前校验,false-不校验 * @return */ Boolean deleteWithValidByIds(Collection<Integer> ids, Boolean isValid); }
22.830508
84
0.755011
b6616c275670a60ef56d0ec1704878078ef597a1
10,105
package synergynet3.apps.numbernet.controller.numbernettable; import java.util.UUID; import java.util.logging.Logger; import multiplicity3.csys.MultiplicityEnvironment; import multiplicity3.csys.factory.ContentTypeNotBoundException; import multiplicity3.csys.items.container.IContainer; import multiplicity3.csys.items.image.IImage; import multiplicity3.csys.stage.IStage; import multiplicity3.input.MultiTouchInputComponent; import synergynet3.apps.numbernet.graphing.builders.SpringGraphBuilder; import synergynet3.apps.numbernet.model.ExpressionSession; import synergynet3.apps.numbernet.network.CalculatorCollectionSync; import synergynet3.apps.numbernet.network.CalculatorKeySynchronizer; import synergynet3.apps.numbernet.network.ExpressionDisplaySync; import synergynet3.apps.numbernet.network.ExpressionPositionSync; import synergynet3.apps.numbernet.network.MultiTouchEnabledSync; import synergynet3.apps.numbernet.ui.expression.ExpressionDisplay; import synergynet3.apps.numbernet.validation.DefaultValidationChecker; import synergynet3.cluster.SynergyNetCluster; import synergynet3.cluster.sharedmemory.DistributedPropertyChangedAction; import synergynet3.web.apps.numbernet.comms.table.NumberNetStudentTableClusteredData; import com.hazelcast.core.Member; /** * The Class NumberNetController. */ public class NumberNetController { /** The Constant log. */ private static final Logger log = Logger.getLogger(NumberNetController.class.getName()); /** The calculator collection manager. */ private CalculatorCollectionManager calculatorCollectionManager; /** The calculator collection synchronizer. */ private CalculatorCollectionSync calculatorCollectionSynchronizer; /** The calculator event processor. */ private CalculatorEventProcessor calculatorEventProcessor; /** The calculator key synchronizer. */ private CalculatorKeySynchronizer calculatorKeySynchronizer; /** The calculators and expressions container. */ private IContainer calculatorsAndExpressionsContainer; /** The current target set. */ private Double currentTargetSet = 10.0; /** The expression display. */ private ExpressionDisplay expressionDisplay; /** The expression display synchronizer. */ private ExpressionDisplaySync expressionDisplaySynchronizer; /** The expression position synchronizer. */ private ExpressionPositionSync expressionPositionSynchronizer; /** The expression session. */ private ExpressionSession expressionSession; /** The graphing lines container. */ private IContainer graphingLinesContainer; /** The multi touch enabled synchronizer. */ private MultiTouchEnabledSync multiTouchEnabledSynchronizer; /** The spring graph builder. */ private SpringGraphBuilder springGraphBuilder; /** The stage. */ private IStage stage; /** The student table data cluster. */ private NumberNetStudentTableClusteredData studentTableDataCluster; /** The table identity. */ private String tableIdentity; /** The validation checker. */ private DefaultValidationChecker validationChecker; /** * Instantiates a new number net controller. * * @param input * the input * @throws ContentTypeNotBoundException * the content type not bound exception */ public NumberNetController(MultiTouchInputComponent input) throws ContentTypeNotBoundException { try { this.tableIdentity = SynergyNetCluster.get().getIdentity(); log.info("Starting controller for numbernet"); initDisplay(); validationChecker = new DefaultValidationChecker(); studentTableDataCluster = new NumberNetStudentTableClusteredData(tableIdentity); expressionSession = new ExpressionSession(studentTableDataCluster); calculatorEventProcessor = new CalculatorEventProcessor(tableIdentity, validationChecker); log.info("private inits"); initCalculatorCollection(); initCalculatorSync(); initMultiTouchInputSync(input); initExpressionDisplay(); initExpressionDisplaySync(); setExpressionSession(expressionSession); // Adds a dummy to avoid java error calculatorCollectionManager.addCalculator("dummy", -100, 0); log.info("Populating from network"); expressionSession.addAllExpressionsFromDistributedMap(); log.info("Creating SGB"); springGraphBuilder = new SpringGraphBuilder(stage, 70, 300, 100); log.info("Done"); // enterTestMode(); studentTableDataCluster.getGraphingModeControl().registerChangeListener(new DistributedPropertyChangedAction<Boolean>() { @Override public void distributedPropertyDidChange(Member member, Boolean oldValue, Boolean newValue) { log.fine("Graphing mode control change to " + newValue); setGraphingModeEnabled(newValue); } }); Boolean graphModeEnabled = studentTableDataCluster.getGraphingModeControl().getValue(); if ((graphModeEnabled != null) && (graphModeEnabled == true)) { setGraphingModeEnabled(true); } calculatorCollectionManager.removeCalculator("dummy"); } catch (Exception ex) { ex.printStackTrace(); } } /** * Gets the current target set. * * @return the current target set */ public Double getCurrentTargetSet() { return currentTargetSet; } /** * Sets the current target set. * * @param currentTargetSet * the new current target set */ public void setCurrentTargetSet(Double currentTargetSet) { this.currentTargetSet = currentTargetSet; } /** * Sets the expression session. * * @param session * the new expression session */ public void setExpressionSession(ExpressionSession session) { expressionDisplay.setExpressionSession(session); calculatorEventProcessor.setExpressionSession(session); validationChecker.setCurrentExpressionSession(session); } /** * Shutdown. */ public void shutdown() { expressionPositionSynchronizer.stop(); calculatorCollectionSynchronizer.stop(); multiTouchEnabledSynchronizer.stop(); } /** * Inits the calculator collection. */ private void initCalculatorCollection() { calculatorCollectionManager = new CalculatorCollectionManager(calculatorsAndExpressionsContainer, calculatorEventProcessor); } // ******* private ******** /** * Inits the calculator sync. */ private void initCalculatorSync() { calculatorCollectionSynchronizer = new CalculatorCollectionSync(calculatorCollectionManager, studentTableDataCluster); calculatorCollectionSynchronizer.start(); calculatorKeySynchronizer = new CalculatorKeySynchronizer(calculatorCollectionManager, studentTableDataCluster); calculatorKeySynchronizer.start(); } /** * Inits the display. * * @throws ContentTypeNotBoundException * the content type not bound exception */ private void initDisplay() throws ContentTypeNotBoundException { stage = MultiplicityEnvironment.get().getLocalStages().get(0); IImage background = stage.getContentFactory().create(IImage.class, "bg", UUID.randomUUID()); stage.addItem(background); background.setImage("/synergynet3/apps/numbernet/backgrounds/blue.png"); background.setSize(stage.getDisplayWidth(), stage.getDisplayHeight()); float wrapScale = 100f; background.setWrapping(wrapScale, wrapScale); graphingLinesContainer = stage.getContentFactory().create(IContainer.class, "glines", UUID.randomUUID()); stage.addItem(graphingLinesContainer); stage.getZOrderManager().ignoreItemClickedBehaviour(background); calculatorsAndExpressionsContainer = stage.getContentFactory().create(IContainer.class, "calcexpr", UUID.randomUUID()); stage.addItem(calculatorsAndExpressionsContainer); stage.getZOrderManager().setAutoBringToTop(false); stage.getZOrderManager().bringToTop(calculatorsAndExpressionsContainer); } /** * Inits the expression display. * * @throws ContentTypeNotBoundException * the content type not bound exception */ private void initExpressionDisplay() throws ContentTypeNotBoundException { expressionDisplay = new ExpressionDisplay(tableIdentity, stage, calculatorsAndExpressionsContainer, calculatorCollectionManager); } /** * Inits the expression display sync. */ private void initExpressionDisplaySync() { expressionPositionSynchronizer = new ExpressionPositionSync(expressionDisplay, studentTableDataCluster); expressionPositionSynchronizer.start(); expressionDisplaySynchronizer = new ExpressionDisplaySync(expressionDisplay, studentTableDataCluster); expressionDisplaySynchronizer.start(); } /** * Inits the multi touch input sync. * * @param input * the input */ private void initMultiTouchInputSync(MultiTouchInputComponent input) { multiTouchEnabledSynchronizer = new MultiTouchEnabledSync(studentTableDataCluster, input); multiTouchEnabledSynchronizer.start(); } /** * Enter test mode. */ protected void enterTestMode() { log.info("Entering test mode"); // calculatorCollectionManager.addCalculator("iyad", -300, 0); calculatorCollectionManager.addCalculator("andrew", -100, 0); // calculatorCollectionManager.addCalculator("steve", 100, 0); // calculatorCollectionManager.addCalculator("phyo", 300, 0); expressionSession.setTarget(35); springGraphBuilder.setExpressionSessionAndDisplay(expressionSession, expressionDisplay, graphingLinesContainer); this.setGraphingModeEnabled(true); calculatorCollectionManager.setAllCalculatorsVisible(true); } /** * Sets the graphing mode enabled. * * @param enabled * the new graphing mode enabled */ protected void setGraphingModeEnabled(boolean enabled) { if (enabled) { log.fine("Setting graph builder up"); calculatorCollectionManager.setAllCalculatorsVisible(false); springGraphBuilder.setExpressionSessionAndDisplay(expressionSession, expressionDisplay, graphingLinesContainer); try { springGraphBuilder.setActive(true, expressionSession.getTargetValue()); } catch (Exception e) { } } else { log.fine("Shutting down graphbuilder"); calculatorCollectionManager.setAllCalculatorsVisible(true); springGraphBuilder.setActive(false, 0); } } }
30.345345
131
0.774666
617e691b1a493757117ab67239ec10f4426ca9d3
1,003
package vop.groep7.vop7backend.database.mongodb; import com.mongodb.MongoClient; /** * * @author Backend Team */ public class EventDataAccessContext { private final MongoClient client; private EventDAO eventDAO; /** * The constructor of a EventDataAccessContext needs a connection to a * database. * * @param client A client to the mongoDB database */ public EventDataAccessContext(MongoClient client) { this.client = client; } /** * Get the EventDAO object * * @return The EventDAO object to execute mongoDB queries on the database */ public EventDAO getEventDAO() { if (eventDAO == null) { eventDAO = new EventDAO(client); } return eventDAO; } /** * Called when Spring wants to close the server. Will make sure all * connections are closed. */ public void destroy() { if (client != null) { client.close(); } } }
21.804348
77
0.60319
d67696db13d4acf3e32fbfe388a197e028cc8379
8,328
/* * Copyright 2010 DTO Labs, Inc. (http://dtolabs.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.core.common; import com.dtolabs.rundeck.core.tools.AbstractBaseTest; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.tools.ant.Project; import java.io.File; /** * TestFramework */ public class TestFramework extends AbstractBaseTest { /** * Constructor for test * * @param name name of test */ public TestFramework(final String name) { super(name); } /** * main method * * @param args cli args */ public static void main(final String[] args) { junit.textui.TestRunner.run(suite()); } /** * Junit suite * * @return test suite */ public static Test suite() { return new TestSuite(TestFramework.class); } protected void setUp() { super.setUp(); } /** * Test creation */ public void testConstruction() { try { Framework.getInstance(getBaseDir()+"/test", getFrameworkProjectsBase()); fail("Framework.getInstance should have thrown an exception for missing framework.properties"); } catch (Exception e) { assertNotNull(e); } final Framework framework = Framework.getInstance(getBaseDir(), getFrameworkProjectsBase()); assertNotNull("Framework.getInstance returned null", framework); assertTrue("framework.node.hostname property was not set", framework.hasProperty("framework.node.hostname")); assertEquals("basedir did not match: " + framework.getBaseDir().getAbsolutePath(), new File( getBaseDir()).getAbsolutePath(), framework.getBaseDir().getAbsolutePath()); assertNotNull("authorization manager was null", framework.getAuthorizationMgr()); assertNotNull("authentication manager was null", framework.getAuthenticationMgr()); assertNotNull("FrameworkProjectMgr was null", framework.getFrameworkProjectMgr()); } public void testServices() { final Framework fw = Framework.getInstance(getBaseDir(), getFrameworkProjectsBase()); //test default service implementations assertNotNull(fw.services); assertNotNull(fw.getService("CommandInterpreter")); assertNotNull(fw.getService("NodeExecutor")); assertNotNull(fw.getService("FileCopier")); assertNotNull(fw.getService("NodeDispatcher")); } public void testSetService() { final Framework fw = Framework.getInstance(getBaseDir(), getFrameworkProjectsBase()); //test removing services assertNotNull(fw.services); final FrameworkSupportService commandInterpreter = fw.getService("CommandInterpreter"); assertNotNull(commandInterpreter); fw.setService("CommandInterpreter", null); assertNull(fw.getService("CommandInterpreter")); fw.setService("CommandInterpreter", commandInterpreter); assertNotNull(fw.getService("CommandInterpreter")); final FrameworkSupportService commandInterpreter2 = fw.getService("CommandInterpreter"); assertEquals(commandInterpreter, commandInterpreter2); } /** * Test the allowUserInput property of Framework class */ public void testAllowUserInput() { final Framework newfw = Framework.getInstance(getBaseDir()); assertTrue("User input should be enabled by default", newfw.isAllowUserInput()); newfw.setAllowUserInput(false); assertFalse("User input should be disabled", newfw.isAllowUserInput()); { final Project p = new Project(); assertNull("property should not be set", p.getProperty("framework.userinput.disabled")); newfw.configureProject(p); assertEquals("Ant property not set to disable user input", "true", p.getProperty("framework.userinput.disabled")); assertNotNull("Input Handler should be configured", p.getInputHandler()); assertEquals("Input Handler isn't expected type", Framework.FailInputHandler.class, p.getInputHandler().getClass()); newfw.setAllowUserInput(true); newfw.configureProject(p); assertTrue("Ant property not set to enable user input", "false".equals(p.getProperty("framework.userinput.disabled")) || null == p.getProperty( "framework.userinput.disabled")); assertTrue("Input Handler shouldn't be configured", null == p.getInputHandler() || !(p.getInputHandler() instanceof Framework.FailInputHandler)); } { final Project p = new Project(); p.setProperty("framework.userinput.disabled", "true"); p.setProperty("rdeck.base", getBaseDir()); final Framework ftest1 = Framework.getInstanceOrCreate(p); assertNotNull("instance should be found from PRoject", ftest1); assertFalse("framework input should be disabled", ftest1.isAllowUserInput()); assertNotNull("Input Handler should be configured", p.getInputHandler()); assertEquals("Input Handler isn't expected type", Framework.FailInputHandler.class, p.getInputHandler().getClass()); } { final Project p = new Project(); p.setProperty("framework.userinput.disabled", "false"); p.setProperty("rdeck.base", getBaseDir()); final Framework ftest1 = Framework.getInstanceOrCreate(p); assertNotNull("instance should be found from PRoject", ftest1); assertTrue("framework input should be enabled", ftest1.isAllowUserInput()); assertTrue("Input Handler shouldn't be configured", null == p.getInputHandler() || !(p.getInputHandler() instanceof Framework.FailInputHandler)); } { final Project p = new Project(); // p.setResultproperty("framework.userinput.disabled", "false"); p.setProperty("rdeck.base", getBaseDir()); final Framework ftest1 = Framework.getInstanceOrCreate(p); assertNotNull("instance should be found from PRoject", ftest1); assertTrue("framework input should be enabled", ftest1.isAllowUserInput()); assertTrue("Input Handler shouldn't be configured", null == p.getInputHandler() || !(p.getInputHandler() instanceof Framework.FailInputHandler)); } } public void testIsLocal() { final Project p = new Project(); p.setProperty("rdeck.base", getBaseDir()); final Framework framework = Framework.getInstanceOrCreate(p); assertTrue("framework node self-comparison should be true", framework.isLocalNode(framework.getNodeDesc())); final String frameworkNodename = framework.getFrameworkNodeName(); final String frameworkHostname = framework.getFrameworkNodeHostname(); assertTrue("framework node should be local", framework.isLocalNode(NodeEntryImpl.create( frameworkHostname, frameworkNodename))); assertFalse("incorrect local node result", framework.isLocalNode(NodeEntryImpl.create( frameworkHostname, "blahanode"))); assertTrue("should have matched based on the common node name value", framework.isLocalNode(NodeEntryImpl.create( "blahahostname", frameworkNodename))); } }
39.098592
117
0.639769
2e91db6ab1226254b149d5b8c3b2fe044ce9019f
382
package de.martinspielmann.wicket.chartjs.data.dataset.property.spangaps; import de.martinspielmann.wicket.chartjs.core.internal.JsonAware; public enum BooleanSpanGaps implements SpanGaps, JsonAware { TRUE(true), FALSE(false); private boolean json; BooleanSpanGaps(boolean json) { this.json = json; } @Override public Object getJson() { return json; } }
19.1
73
0.743455
c84f92a5a10f2c902241d1a62e3f1982728669b6
12,690
/* * Copyright (c) 2018-2019 ActionTech. * License: http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 or higher. */ package org.apache.servicecomb.saga.alpha.server.accidenthandling; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.servicecomb.saga.alpha.core.TxEvent; import org.apache.servicecomb.saga.alpha.core.TxEventRepository; import org.apache.servicecomb.saga.alpha.core.TxleMetrics; import org.apache.servicecomb.saga.alpha.core.accidenthandling.AccidentHandleStatus; import org.apache.servicecomb.saga.alpha.core.accidenthandling.AccidentHandleType; import org.apache.servicecomb.saga.alpha.core.accidenthandling.AccidentHandling; import org.apache.servicecomb.saga.alpha.core.accidenthandling.IAccidentHandlingService; import org.apache.servicecomb.saga.alpha.core.datadictionary.DataDictionaryItem; import org.apache.servicecomb.saga.alpha.core.datadictionary.IDataDictionaryService; import org.apache.servicecomb.saga.common.TxleConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; import java.lang.invoke.MethodHandles; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class AccidentHandlingService implements IAccidentHandlingService { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final PageRequest PAGEREQUEST = new PageRequest(0, 100); private final String accidentPlatformAddress; private final int retries; // default is 1s private final RestTemplate restTemplate; private final int interval; @Autowired private TxEventRepository eventRepository; @Autowired private TxleMetrics txleMetrics; @Autowired private IDataDictionaryService dataDictionaryService; private AccidentHandlingEntityRepository accidentHandlingEntityRepository; public AccidentHandlingService(AccidentHandlingEntityRepository accidentHandlingEntityRepository, String accidentPlatformAddress, int retries, int interval, RestTemplate restTemplate) { this.accidentHandlingEntityRepository = accidentHandlingEntityRepository; this.accidentPlatformAddress = accidentPlatformAddress; this.retries = retries < 0 ? 0 : retries; this.interval = interval < 1 ? 1 : interval; this.restTemplate = restTemplate; } @Override public boolean save(AccidentHandling accidentHandling) { try { AccidentHandling savedAccident = accidentHandlingEntityRepository.save(accidentHandling); if (savedAccident != null) { // 设置保存后的id accidentHandling.setId(savedAccident.getId()); } return true; } catch (Exception e) { LOG.error("Failed to save accident handling.", e); } return false; } @Override public List<AccidentHandling> findAccidentHandlingList() { return accidentHandlingEntityRepository.findAccidentHandlingList(PAGEREQUEST); } @Override public List<AccidentHandling> findAccidentHandlingList(AccidentHandleStatus status) { return accidentHandlingEntityRepository.findAccidentListByStatus(status.toInteger()); } @Override public boolean updateAccidentStatusByIdList(List<Long> idList, AccidentHandleStatus status) { return accidentHandlingEntityRepository.updateAccidentStatusByIdList(idList, status.toInteger()) > 0; } @Override public boolean reportMsgToAccidentPlatform(String jsonParams) { long a = System.currentTimeMillis(); LOG.debug(TxleConstants.logDebugPrefixWithTime() + "Message [[{}]] will send to Accident Platform [" + this.accidentPlatformAddress + "].", jsonParams); AtomicBoolean result = new AtomicBoolean(); AtomicInteger invokeTimes = new AtomicInteger(); try { AccidentHandling savedAccident = parseAccidentJson(jsonParams); // To save accident to db. saveAccidentHandling(savedAccident); final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleWithFixedDelay(() -> { if (result.get()) { accidentHandlingEntityRepository.updateAccidentStatusByIdList(Arrays.asList(savedAccident.getId()), AccidentHandleStatus.SEND_OK.toInteger()); scheduler.shutdownNow(); // TODO prometheus内部方法持续循环,无法该行代码后的代码 txleMetrics.countSuccessfulNumber(); } else if (invokeTimes.incrementAndGet() > 1 + this.retries) { accidentHandlingEntityRepository.updateAccidentStatusByIdList(Arrays.asList(savedAccident.getId()), AccidentHandleStatus.SEND_FAIL.toInteger()); LOG.error(TxleConstants.LOG_ERROR_PREFIX + "Failed to report msg to Accident Platform."); scheduler.shutdownNow(); txleMetrics.countFailedNumber(); } else { // To report accident to Accident Platform. result.set(reportTask(jsonParams)); } // 下一次执行会在本次任务完全执行后的interval时间后执行,如本次任务花费5s,interval为1s,那么将在6s后执行下次任务,而非1s后执行 }, 0, interval, TimeUnit.SECONDS); } catch (Exception e) { LOG.error(TxleConstants.LOG_ERROR_PREFIX + "Failed to report msg to Accident Platform."); txleMetrics.countFailedNumber(); } LOG.info("Method 'AccidentPlatformService.reportMsgToAccidentPlatform' took {} milliseconds.", System.currentTimeMillis() - a); return result.get(); } @Override public List<Map<String, Object>> findAccidentList(int pageIndex, int pageSize, String orderName, String direction, String searchText) { List<AccidentHandling> accidentList = this.searchAccidentList(pageIndex, pageSize, orderName, direction, searchText); if (accidentList != null && !accidentList.isEmpty()) { List<Map<String, Object>> resultAccidentList = new LinkedList<>(); Map<String, String> typeValueName = new HashMap<>(8); List<DataDictionaryItem> dataDictionaryItemList = dataDictionaryService.selectDataDictionaryList("accident-handle-type"); if (dataDictionaryItemList != null && !dataDictionaryItemList.isEmpty()) { dataDictionaryItemList.forEach(dd -> typeValueName.put(dd.getValue(), dd.getName())); } Map<String, String> statusValueName = new HashMap<>(8); dataDictionaryItemList = dataDictionaryService.selectDataDictionaryList("accident-handle-status"); if (dataDictionaryItemList != null && !dataDictionaryItemList.isEmpty()) { dataDictionaryItemList.forEach(dd -> statusValueName.put(dd.getValue(), dd.getName())); } accidentList.forEach(accident -> resultAccidentList.add(accident.toMap(typeValueName.get(String.valueOf(accident.getType())), statusValueName.get(String.valueOf(accident.getStatus()))))); return resultAccidentList; } return null; } private List<AccidentHandling> searchAccidentList(int pageIndex, int pageSize, String orderName, String direction, String searchText) { try { pageIndex = pageIndex < 1 ? 0 : pageIndex; pageSize = pageSize < 1 ? 100 : pageSize; Sort.Direction sd = Sort.Direction.DESC; if (orderName == null || orderName.length() == 0) { orderName = "completetime"; } if ("asc".equalsIgnoreCase(direction)) { sd = Sort.Direction.ASC; } PageRequest pageRequest = new PageRequest(pageIndex, pageSize, sd, orderName); if (searchText == null || searchText.length() == 0) { return accidentHandlingEntityRepository.findAccidentList(pageRequest); } return accidentHandlingEntityRepository.findAccidentList(pageRequest, searchText); } catch (Exception e) { LOG.error("Failed to find the list of Accident Handling. params {pageIndex: [{}], pageSize: [{}], orderName: [{}], direction: [{}], searchText: [{}]}.", pageIndex, pageSize, orderName, direction, searchText, e); } return null; } @Override public long findAccidentCount(String searchText) { if (searchText == null || searchText.length() == 0) { return accidentHandlingEntityRepository.findAccidentCount(); } return accidentHandlingEntityRepository.findAccidentCount(searchText); } private AccidentHandling parseAccidentJson(String jsonParams) { JsonObject jsonObject = new JsonParser().parse(jsonParams).getAsJsonObject(); String serviceName = "", instanceId = "", globalTxId = "", localTxId = "", bizinfo = "", remark = ""; int type = 1; JsonElement jsonElement = jsonObject.get("servicename"); if (jsonElement != null) { serviceName = jsonElement.getAsString(); } jsonElement = jsonObject.get("instanceid"); if (jsonElement != null) { instanceId = jsonElement.getAsString(); } jsonElement = jsonObject.get("globaltxid"); if (jsonElement != null) { globalTxId = jsonElement.getAsString(); } jsonElement = jsonObject.get("localtxid"); if (jsonElement != null) { localTxId = jsonElement.getAsString(); } jsonElement = jsonObject.get("type"); if (jsonElement != null) { type = jsonElement.getAsInt(); } jsonElement = jsonObject.get("bizinfo"); if (jsonElement != null) { bizinfo = jsonElement.getAsString(); } jsonElement = jsonObject.get("remark"); if (jsonElement != null) { remark = jsonElement.getAsString(); } return new AccidentHandling(serviceName, instanceId, globalTxId, localTxId, AccidentHandleType.convertTypeFromValue(type), bizinfo, remark); } private boolean saveAccidentHandling(AccidentHandling accident) { boolean result = false; try { if (accident.getServicename() == null || accident.getInstanceid() == null || "".equals(accident.getServicename()) || "".equals(accident.getInstanceid())) { Optional<TxEvent> event = eventRepository.findTxStartedEvent(accident.getGlobaltxid(), accident.getLocaltxid()); if (event != null && event.get() != null) { accident.setServicename(event.get().serviceName()); accident.setInstanceid(event.get().instanceId()); } } result = accidentHandlingEntityRepository.save(accident) != null; } catch (Exception e) { // That's not too important for main business to throw an exception. LOG.error("Failed to save accident to db, accident [{}].", accident, e); } finally { LOG.error("Saved accident to db, result [{}] and accident [{}].", result, accident); } return result; } private boolean reportTask(String jsonParams) { boolean result = false; try { HttpHeaders headers = new HttpHeaders(); MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(mediaType); HttpEntity<String> entity = new HttpEntity<>(jsonParams, headers); String reportResponse = restTemplate.postForObject(this.accidentPlatformAddress, entity, String.class); result = TxleConstants.OK.equals(reportResponse); } catch (Exception e) { LOG.error("Failed to report msg [{}] to Accident Platform [{}].", jsonParams, this.accidentPlatformAddress, e); } finally { LOG.error("Reported accident to platform, result [{}], platform address [{}] and accident [{}].", result, this.accidentPlatformAddress, jsonParams); } return result; } }
47.886792
223
0.674941
ac8fbadbacdcf1696bc92391cc697f110d82c31e
169
package specs; public enum Symbol { ADD, SUB, MUL, DIV, REM, EQ, LT, LE, AND, OR, NOT, HEAD, TAIL, CONS, BOOL, INT, LIST, OBJECT, }
7.347826
20
0.508876
cc25454bac8d236d37235c0398965dba4d5d020b
2,322
/* Copyright 2020 Twitter, Inc. SPDX-License-Identifier: Apache-2.0 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. NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). https://openapi-generator.tech Do not edit the class manually. */ package com.twitter.clientlib.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.twitter.clientlib.model.Error; import com.twitter.clientlib.model.Problem; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * Model tests for ProblemOrError */ public class ProblemOrErrorTest { private final ProblemOrError model = new ProblemOrError(); /** * Model tests for ProblemOrError */ @Test public void testProblemOrError() { // TODO: test ProblemOrError } /** * Test the property 'code' */ @Test public void codeTest() { // TODO: test code } /** * Test the property 'message' */ @Test public void messageTest() { // TODO: test message } /** * Test the property 'detail' */ @Test public void detailTest() { // TODO: test detail } /** * Test the property 'status' */ @Test public void statusTest() { // TODO: test status } /** * Test the property 'title' */ @Test public void titleTest() { // TODO: test title } /** * Test the property 'type' */ @Test public void typeTest() { // TODO: test type } }
22.764706
89
0.673127
3030dd7f2a581ee9037a0a34ee166a492720f72e
15,750
package net.osdn.aoiro.report; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import net.osdn.aoiro.AccountSettlement; import net.osdn.aoiro.Util; import net.osdn.aoiro.model.Creditor; import net.osdn.aoiro.model.Debtor; import net.osdn.aoiro.model.JournalEntry; import net.osdn.pdf_brewer.BrewerData; import net.osdn.pdf_brewer.FontLoader; import net.osdn.pdf_brewer.PdfBrewer; /** 仕訳帳 * */ public class GeneralJournal { private static final int ROWS = 50; private static final double ROW_HEIGHT = 5.0; private List<JournalEntry> entries; int financialYear; boolean isFromNewYearsDay; private List<String> pageData = new ArrayList<String>(); private List<String> printData; private FontLoader fontLoader; private boolean bindingMarginEnabled = true; private boolean pageNumberEnabled = true; public GeneralJournal(List<JournalEntry> journalEntries, boolean isSoloProprietorship) throws IOException { this.entries = journalEntries; InputStream in = getClass().getResourceAsStream("/templates/仕訳帳.pb"); BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); String line; while((line = r.readLine()) != null) { pageData.add(line); } r.close(); LocalDate closing = AccountSettlement.getClosingDate(entries, isSoloProprietorship); if(closing.getMonthValue() == 12 && closing.getDayOfMonth() == 31) { //決算日が 12月31日の場合は会計年度の「年」は決算日の「年」と同じになります。 financialYear = closing.getYear(); isFromNewYearsDay = true; } else { //決算日が 12月31日ではない場合は会計年度の「年」は決算日の前年になります。 financialYear = closing.getYear() - 1; isFromNewYearsDay = false; } //総勘定元帳と相互にページ番号を印字するために //writeToを呼び出してPDFを作成する前にprepareを呼び出しておく必要があります。 prepare(); } public List<JournalEntry> getJournalEntries() { return entries; } protected void prepare() { int pageNumber = 0; int restOfRows = 0; int currentRow = 0; long debtorTotal = 0; long creditorTotal = 0; printData = new ArrayList<String>(); if(bindingMarginEnabled) { printData.add("\\media A4"); //穴あけパンチの位置を合わせるための中心線を先頭ページのみ印字します。 printData.add("\\line-style thin dot"); printData.add("\\line 0 148.5 5 148.5"); } else { // 綴じ代なしの場合は15mm分だけ横幅を短くして195mmとします。(A4本来の横幅は210mm) // 穴あけパンチ用の中心線も出力しません。 printData.add("\\media 195 297"); } // 摘要が2行折り返しで印字されても枠内に収まるように行の高さを 1.15 に変更しています。(デフォルトは 1.8) printData.add("\\line-height 1.15"); for(int i = 0; i < entries.size(); i++) { JournalEntry entry = entries.get(i); int month = entry.getDate().getMonthValue(); int day = entry.getDate().getDayOfMonth(); //この仕訳の後で改ページが必要かどうか boolean isCarriedForward = false; //仕訳の印字に必要な行数を求めます。 int rowsRequired = getRowsRequired(entry); //最後の明細の場合は締切行を追加するために 1行加算します。 if(i == entries.size() - 1) { rowsRequired++; } else if(currentRow != 0) { if(rowsRequired <= restOfRows) { //最後の明細ではない場合、次の仕訳の印字必要行数を調べて改ページが発生する有無を求めます。 JournalEntry nextEntry = entries.get(i + 1); int nextEntryRowsRequired = getRowsRequired(nextEntry); //次の仕訳の印字必要行数を含めると超過する場合は改ページが必要になります。 if(rowsRequired + nextEntryRowsRequired + 1 > restOfRows) { isCarriedForward = true; rowsRequired++; //次頁繰越を印字するために必要行数を加算します。 } } } //仕訳の印字に必要な行数が残り行数を超えているときに改ページします。 if(rowsRequired > restOfRows) { if(++pageNumber >= 2) { printData.add("\\new-page"); } if(!bindingMarginEnabled) { //綴じ代なし printData.add("\\box 10 0 -10 -10"); //テンプレート printData.addAll(pageData); if(pageNumberEnabled) { if(pageNumber % 2 == 1) { //ページ番号(奇数ページ) printData.add("\t\\box 0 0 -3 22"); printData.add("\t\\font serif 10.5"); printData.add("\t\\align bottom right"); printData.add("\t\\text " + pageNumber); } else { //ページ番号(偶数ページ) printData.add("\t\\box 3 0 10 22"); printData.add("\t\\font serif 10.5"); printData.add("\t\\align bottom left"); printData.add("\t\\text " + pageNumber); } } } else if(pageNumber % 2 == 1) { //綴じ代(奇数ページ) printData.add("\\box 15 0 0 0"); printData.add("\\line-style thin dot"); printData.add("\\line 0 0 0 -0"); printData.add("\\box 25 0 -10 -10"); //テンプレート printData.addAll(pageData); if(pageNumberEnabled) { //ページ番号(奇数ページ) printData.add("\t\\box 0 0 -3 22"); printData.add("\t\\font serif 10.5"); printData.add("\t\\align bottom right"); printData.add("\t\\text " + pageNumber); } } else { //綴じ代(偶数ページ) printData.add("\\box 0 0 -15 0"); printData.add("\\line-style thin dot"); printData.add("\\line -0 0 -0 -0"); printData.add("\\box 10 0 -25 -10"); //テンプレート printData.addAll(pageData); if(pageNumberEnabled) { //ページ番号(偶数ページ) printData.add("\t\\box 3 0 10 22"); printData.add("\t\\font serif 10.5"); printData.add("\t\\align bottom left"); printData.add("\t\\text " + pageNumber); } } //年 if(isFromNewYearsDay) { printData.add("\t\\box 0 25 14.5 6"); printData.add("\t\\align center right"); printData.add("\t\\font sans-serif 8"); printData.add("\t\\text 年"); printData.add("\t\\box 0 25 10.5 6"); printData.add("\t\\font serif 10"); printData.add("\t\\align center right"); printData.add("\t\\text " + financialYear); } else { printData.add("\t\\box 0 25 14.7 6"); printData.add("\t\\align center right"); printData.add("\t\\font sans-serif 8"); printData.add("\t\\text 年度"); printData.add("\t\\box 0 25 8.6 6"); printData.add("\t\\font serif 10"); printData.add("\t\\align center right"); printData.add("\t\\text " + financialYear); } //明細印字領域 printData.add("\t\\box 0 37 -0 -0"); restOfRows = ROWS; currentRow = 0; //2ページ目以降は前頁繰越を印字します。 if(pageNumber >= 2) { printData.add("\t\t\\box " + String.format("0 %.2f -0 %.2f", currentRow * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\t\\box " + String.format("16 0 75 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\font serif 10"); printData.add("\t\t\t\\text 前頁繰越"); printData.add("\t\t\t\\box " + String.format("101 0 32 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\text " + String.format("%,d", debtorTotal)); printData.add("\t\t\t\\box " + String.format("138 0 32 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\text " + String.format("%,d", creditorTotal)); currentRow++; restOfRows--; } } //総勘定元帳に記載する仕訳帳ページ(仕丁)を設定します。 for(Debtor debtor : entry.getDebtors()) { debtor.setJournalPageNumber(pageNumber); } for(Creditor creditor : entry.getCreditors()) { creditor.setJournalPageNumber(pageNumber); } //日付 printData.add("\t\t\\box " + String.format("0 %.2f -0 %.2f", currentRow * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\font serif 10"); printData.add("\t\t\t\\box " + String.format("0 0 6 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + month); printData.add("\t\t\t\\box " + String.format("8 0 6.2 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + day); double y = 0.0; //借方 if(entry.getDebtors().size() >= 2) { printData.add("\t\t\t\\box " + String.format("18 0 34 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center left"); printData.add("\t\t\t\\text 諸口"); y += ROW_HEIGHT; } for(int j = 0; j < entry.getDebtors().size(); j++) { Debtor debtor = entry.getDebtors().get(j); debtorTotal += debtor.getAmount(); printData.add("\t\t\t\\box " + String.format("16 %.2f 77 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center left"); printData.add("\t\t\t\\text " + "(" + debtor.getAccountTitle().getDisplayName() + ")"); printData.add("\t\t\t\\box " + String.format("101 %.2f 32 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + String.format("%,d", debtor.getAmount())); //元丁 if(debtor.getLedgerPageNumber() >= 1) { printData.add("\t\t\t\\box " + String.format("93 %.2f 8 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center"); printData.add("\t\t\t\\text " + debtor.getLedgerPageNumber()); } y += ROW_HEIGHT; } //貸方 if(entry.getDebtors().size() >= 2 && entry.getCreditors().size() == 1) { //借方が諸口で貸方が1行しかない場合は借方の諸口行に貸方を記入します。 Creditor creditor = entry.getCreditors().get(0); creditorTotal += creditor.getAmount(); printData.add("\t\t\t\\box " + String.format("16 0 77 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + "(" + creditor.getAccountTitle().getDisplayName() + ")"); printData.add("\t\t\t\\box " + String.format("138 0 32 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + String.format("%,d", creditor.getAmount())); //元丁 if(creditor.getLedgerPageNumber() >= 1) { printData.add("\t\t\t\\box " + String.format("93 0 8 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center"); printData.add("\t\t\t\\text " + creditor.getLedgerPageNumber()); } } else { if(entry.getCreditors().size() >= 2) { printData.add("\t\t\t\\box " + String.format("54.5 0 36.5 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text 諸口"); } for(int j = 0; j < entry.getCreditors().size(); j++) { Creditor creditor = entry.getCreditors().get(j); creditorTotal += creditor.getAmount(); printData.add("\t\t\t\\box " + String.format("16 %.2f 77 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + "(" + creditor.getAccountTitle().getDisplayName() + ")"); printData.add("\t\t\t\\box " + String.format("138 %.2f 32 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\text " + String.format("%,d", creditor.getAmount())); //元丁 if(creditor.getLedgerPageNumber() >= 1) { printData.add("\t\t\t\\box " + String.format("93 %.2f 8 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\align center"); printData.add("\t\t\t\\text " + creditor.getLedgerPageNumber()); } y += ROW_HEIGHT; } } //摘要 printData.add("\t\t\t\\box " + String.format("18 %.2f 75 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\font serif 8"); printData.add("\t\t\t\\align center left"); printData.add("\t\t\t\\text " + entry.getDescription()); //締切線 (改ページ前および最終明細の摘要欄には締切線を引きません) if(!isCarriedForward && (i + 1 < entries.size())) { printData.add("\t\t\t\\box " + String.format("16 %.2f 77 %.2f", y, ROW_HEIGHT)); printData.add("\t\t\t\\line-style medium solid"); printData.add("\t\t\t\\line 0.325 -0 -0.325 -0"); } //次頁繰越の印字が必要な場合 if(isCarriedForward) { if((ROWS - currentRow - rowsRequired) * ROW_HEIGHT > 0) { printData.add("\t\t\t\\box " + String.format("16 %.2f 77 %.2f", y + ROW_HEIGHT, (ROWS - currentRow - rowsRequired) * ROW_HEIGHT)); printData.add("\t\t\t\\line-style medium solid"); printData.add("\t\t\t\\line -0.325 0.15 0.325 -0.15"); } printData.add("\t\t\\line-style medium solid"); printData.add("\t\t\\box " + String.format("16 %.2f 77 %.2f", (ROWS - 1) * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\line 0.325 0 -0.325 0"); printData.add("\t\t\\box " + String.format("101 %.2f -0 %.2f", (ROWS - 1) * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\line 0.325 0 -0.125 0"); printData.add("\t\t\\box " + String.format("16 %.2f 75 %.2f", (ROWS - 1) * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\align center right"); printData.add("\t\t\\font serif 10"); printData.add("\t\t\\text 次頁繰越"); printData.add("\t\t\\box " + String.format("101 %.2f 32 %.2f", (ROWS - 1) * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\text " + String.format("%,d", debtorTotal)); printData.add("\t\t\\box " + String.format("138 %.2f 32 %.2f", (ROWS - 1) * ROW_HEIGHT, ROW_HEIGHT)); printData.add("\t\t\\text " + String.format("%,d", creditorTotal)); } currentRow += rowsRequired; restOfRows -= rowsRequired; //期末締切線 if(i == entries.size() - 1) { printData.add("\t\t\\box " + String.format("0 %.2f -0 %.2f", (currentRow - 1) * ROW_HEIGHT, ROW_HEIGHT + 0.5)); printData.add("\t\t\\line-style medium solid"); printData.add("\t\t\\line 101.325 0 -0.125 0"); printData.add("\t\t\\line 0.125 -0.5 15.675 -0.5"); printData.add("\t\t\\line 0.125 -0.0 15.675 -0.0"); printData.add("\t\t\\line 101.325 -0.5 -0.125 -0.5"); printData.add("\t\t\\line 101.325 -0.0 -0.125 -0.0"); printData.add("\t\t\t\\align center right"); printData.add("\t\t\t\\font serif 10"); printData.add("\t\t\t\\box " + String.format("101 0 32 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\text " + String.format("%,d", debtorTotal)); printData.add("\t\t\t\\box " + String.format("138 0 32 %.2f", ROW_HEIGHT)); printData.add("\t\t\t\\text " + String.format("%,d", creditorTotal)); } } } /** 指定した仕訳を印字するのに必要な行数を取得します。 * * @param entry 仕訳 * @return 指定した仕訳を印字するのに必要な行数を返します。 */ public int getRowsRequired(JournalEntry entry) { int rowsRequired = 0; //借方が2つ以上ある場合は「諸口」のために1行加算します。 if(entry.getDebtors().size() >= 2) { rowsRequired++; } //借方件数を加算します。 rowsRequired += entry.getDebtors().size(); //借方が2つ以上かつ貸方も2つ以上ある場合は貸方件数を加算します。 if(entry.getDebtors().size() >= 2 && entry.getCreditors().size() == 1) { //借方が2つ以上で貸方が1つの場合は借方の「諸口」行に貸方を印字するので行を加算する必要がありません。 } else { rowsRequired += entry.getCreditors().size(); } //摘要のために1行加算します。 rowsRequired++; return rowsRequired; } public void setFontLoader(FontLoader fontLoader) { this.fontLoader = fontLoader; } public void setBindingMarginEnabled(boolean enabled) { this.bindingMarginEnabled = enabled; } public void setPageNumberEnabled(boolean enabled) { this.pageNumberEnabled = enabled; } public void writeTo(Path path) throws IOException { prepare(); PdfBrewer brewer; if(fontLoader != null) { brewer = new PdfBrewer(fontLoader); } else { brewer = new PdfBrewer(); } brewer.setCreator(Util.getPdfCreator()); BrewerData pb = new BrewerData(printData, brewer.getFontLoader()); brewer.setTitle("仕訳帳"); brewer.process(pb); brewer.save(path); brewer.close(); } public void writeTo(OutputStream out) throws IOException { prepare(); PdfBrewer brewer; if(fontLoader != null) { brewer = new PdfBrewer(fontLoader); } else { brewer = new PdfBrewer(); } brewer.setCreator(Util.getPdfCreator()); BrewerData pb = new BrewerData(printData, brewer.getFontLoader()); brewer.setTitle("仕訳帳"); brewer.process(pb); brewer.save(out); brewer.close(); } }
35.958904
136
0.609524
67939ea61497952559118afbaf80cf49109725b5
1,186
package org.openstreetmap.atlas.geography.geojson.parser.domain.geometry; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.openstreetmap.atlas.geography.geojson.parser.GeoJsonParser; import org.openstreetmap.atlas.geography.geojson.parser.domain.foreign.DefaultForeignFieldsImpl; /** * {@link GeometryCollection} nesting inside other {@link GeometryCollection}(s) is NOT allowed. * * @author Yazad Khambata */ public class GeometryCollection extends AbstractGeometry { private List<Geometry> geometries; public GeometryCollection(final GeoJsonParser goeJsonParser, final Map<String, Object> map) { super(map, new DefaultForeignFieldsImpl(extractForeignFields(map, new HashSet<>(Arrays.asList("type", "bbox", "geometries", "properties"))))); this.geometries = ((List<Map<String, Object>>) map.get("geometries")).stream() .map(goeJsonParser::deserialize).map(item -> (Geometry) item) .collect(Collectors.toList()); } public List<Geometry> getGeometries() { return this.geometries; } }
33.885714
96
0.720067
c4913bd7e3568fffe3cf47b36bbc76e6e6ec25ff
1,528
/* * Copyright (c) 2021 Hanbings / hanbings Cynops Toolbox. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hanbings.cynops.auth.oauth.interfaces; import lombok.AllArgsConstructor; import lombok.Data; import java.io.IOException; import java.util.List; @Data @AllArgsConstructor public abstract class OAuthClient { // 密钥与回调地址 OAuthConfig client; // 需要申请的权限 List<String> scope; // state 保护密钥 用于预防中间人攻击 建议使用 OAuthState state; // state 保护密钥开关 默认为 false 即使用 state boolean notUseState; // 授权类型 String grantType; // 授权地址 String authorizationUrl; // 使用授权码获取 token 的地址 String tokenUrl; // 使用 token 获取资源的地址 String resourceUrl; // http client 设置 OAuthRequest request; public abstract String authorize(); public abstract String token(String code) throws IOException; public abstract String resource(String token) throws IOException; public abstract String resource(String token, String url) throws IOException; }
28.296296
81
0.723822
c0bb298158efc323bb986d82aa7af0615ba98b2d
4,752
package org.twak.viewTrace.facades; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.twak.tweed.Tweed; import org.twak.tweed.TweedSettings; import org.twak.tweed.gen.FeatureCache; import org.twak.tweed.gen.FeatureCache.ImageFeatures; import org.twak.tweed.gen.FeatureCache.MegaFeatures; import org.twak.utils.Line; import org.twak.utils.ui.ListDownLayout; import org.twak.utils.ui.Plot; import org.twak.utils.ui.WindowManager; import com.thoughtworks.xstream.XStream; public class AlignStandalone2d extends JPanel { Plot plot = new Plot(); String folder; JSlider imageSlide, facadeSlide;//, massSlide; List<ImageFeatures> features; List<File> facadeFolders; public AlignStandalone2d( String folder ) { super (new BorderLayout()); // TweedSettings.load( new File(folder).getParentFile() ); this.folder = folder; add(plot, BorderLayout.CENTER); JPanel controls = new JPanel(new ListDownLayout()); add(controls, BorderLayout.EAST); facadeFolders = new ArrayList ( Arrays.asList( new File (folder).listFiles() ) ); Collections.sort(facadeFolders, FILE_COMPARATOR); facadeSlide = new JSlider(0, facadeFolders.size()-1, 0); controls.add(facadeSlide); facadeSlide.addChangeListener( new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { setFolder( facadeFolders.get ( facadeSlide.getValue() )); } } ); imageSlide = new JSlider(-1, 1); controls.add(imageSlide); imageSlide.addChangeListener( new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { plot(); } } ); // JButton dump = new JButton("dump"); // controls.add(dump); // dump.addActionListener( new ActionListener() { // // @Override // public void actionPerformed( ActionEvent e ) { // for (int i = facadeSlide.getMinimum(); i <= facadeSlide.getMaximum(); i++) { // facadeSlide.setValue( i ); // // for (int j = imageSlide.getMinimum(); j < imageSlide.getMaximum(); j++) { // imageSlide.setValue( j ); // plot(); // plot.writeImage(Tweed.SCRATCH+i+"_"+(j==-1? "all":("image_"+j) )+"_align"); // } // } // } // } ); // setFolder( facadeFolders.get ( facadeSlide.getValue() )); } private void setFolder( File folder ) { if (!folder.exists()) return; MegaFeatures mf = new MegaFeatures((Line) new XStream().fromXML( new File (folder, "line.xml") )); features = new ArrayList<>(); File[] files = folder.listFiles(); Arrays.sort( files, FILE_COMPARATOR ); for ( File f : files ) if (f.isDirectory() ) { System.out.println(features.size()+" :: " + f.getName()); ImageFeatures imf = FeatureCache.readFeatures (f, mf); if (imf != null) features.add( imf ); } imageSlide.setMaximum( features.size() - 1 ); imageSlide.setValue( 0 ); plot(); } private void plot() { if (features == null) return; plot.toPaint.clear(); for (int i = 0; i < features.size(); i++) if (imageSlide.getValue() == -1 || imageSlide.getValue() == i) { ImageFeatures f = features.get(i); // plot.toPaint.add( f ); } for (int i = 0; i < features.size(); i++) if (imageSlide.getValue() == -1 || imageSlide.getValue() == i) { ImageFeatures f = features.get(i); for (MiniFacade mf : f.miniFacades) plot.toPaint.add(mf); } plot.toPaint.add( facadeFolders.get ( facadeSlide.getValue() ).getName() + "/" + imageSlide.getValue() ); plot.repaint(); } Comparator<File> FILE_COMPARATOR = new Comparator<File>() { @Override public int compare( File o1, File o2 ) { String a = o1.getName(), b = o2.getName(); try { return Integer.compare( Integer.parseInt(a), Integer.parseInt( b ) ); } catch (Throwable th) { return a.compareTo( b ); } } }; public static JFrame show (String file ) { JFrame go = new JFrame("2D align"); go.add( new AlignStandalone2d( file ) ); go.setExtendedState( go.getExtendedState() | JFrame.MAXIMIZED_BOTH); go.pack(); go.setVisible( true ); WindowManager.register( go ); return go; } public static void main (String[] args) { show ( "/home/twak/data/regent/features/652.9836272423689_-455.4482046683377").setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }
24.75
130
0.661195
9b99bab95b78d62586c7f9d3c603fafe211d8d34
3,333
/** * Copyright (C) 2014 Xillio (support@xillio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.xillio.xill.plugins.collection.constructs; import nl.xillio.xill.TestUtils; import nl.xillio.xill.api.components.MetaExpression; import nl.xillio.xill.api.components.MetaExpressionIterator; import nl.xillio.xill.api.errors.InvalidUserInputException; import nl.xillio.xill.plugins.collection.data.range.RangeIteratorFactory; import org.testng.annotations.Test; import java.util.Iterator; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * The test class for {@link RangeConstruct}. * * @author Pieter Soels */ public class RangeConstructTest extends TestUtils { @Test public void testProcessWithoutStep() throws Exception { // Mock RangeIteratorFactory rangeIteratorFactory = mock(RangeIteratorFactory.class); Iterator<Number> rangeIterator = mock(Iterator.class); when(rangeIteratorFactory.createIterator(any(), any(), any())).thenReturn(rangeIterator); // Initialize RangeConstruct construct = new RangeConstruct(rangeIteratorFactory); // Run MetaExpression result = process(construct, fromValue(1), fromValue(10)); // Assert assertTrue(result.hasMeta(MetaExpressionIterator.class)); assertEquals(result.getStringValue(), "[Ranged iterator]"); } @Test public void testProcessWithStep() throws Exception { // Mock RangeIteratorFactory rangeIteratorFactory = mock(RangeIteratorFactory.class); Iterator<Number> rangeIterator = mock(Iterator.class); when(rangeIteratorFactory.createIterator(any(), any(), any())).thenReturn(rangeIterator); // Initialize RangeConstruct construct = new RangeConstruct(rangeIteratorFactory); // Run MetaExpression result = process(construct, fromValue(1), fromValue(10), fromValue(1)); // Assert assertTrue(result.hasMeta(MetaExpressionIterator.class)); assertEquals(result.getStringValue(), "[Ranged iterator]"); } @Test(expectedExceptions = InvalidUserInputException.class, expectedExceptionsMessageRegExp = ".*Test.*") public void testProcessExceptionHandling() throws Exception { // Mock RangeIteratorFactory rangeIteratorFactory = mock(RangeIteratorFactory.class); when(rangeIteratorFactory.createIterator(any(), any(), any())).thenThrow(new IllegalArgumentException("Test")); // Initialize RangeConstruct construct = new RangeConstruct(rangeIteratorFactory); // Run process(construct, fromValue(0), fromValue(0)); } }
38.310345
119
0.725173
2a437a5394cb28087ba80b8ebd0e6bd6deb75905
1,562
/* * Copyright 2018-2021 Pranav Pandey * * 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.pranavpandey.android.dynamic.support.graphics; import android.graphics.Paint; import com.pranavpandey.android.dynamic.support.Defaults; import com.pranavpandey.android.dynamic.support.theme.DynamicTheme; /** * A {@link Paint} to apply the {@link Paint.Cap} according ot the {@link DynamicTheme}. * * @see Paint.Cap#BUTT * @see Paint.Cap#ROUND */ public class DynamicPaint extends Paint { public DynamicPaint() { super(); initialize(); } public DynamicPaint(int flags) { super(flags); initialize(); } public DynamicPaint(Paint paint) { super(paint); initialize(); } /** * Apply the {@link Paint.Cap} according ot the {@link DynamicTheme}. */ private void initialize() { setStrokeCap(DynamicTheme.getInstance().get().getCornerSizeDp() >= Defaults.ADS_CORNER_MIN_THEME_ROUND ? Paint.Cap.ROUND : Paint.Cap.BUTT); } }
26.931034
91
0.684379
0d1a11cbe88b9571f829998207d78134e5328e4d
3,088
/* * Copyright 2014-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaoslemur.infrastructure; import io.pivotal.strepsirrhini.chaoslemur.Member; import java.util.Properties; import java.util.Set; import org.jclouds.Constants; import org.jclouds.ContextBuilder; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.features.ServerApi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import com.google.inject.Module; final class JCloudsComputeInfrastructure extends AbstractDirectorUtilsInfrastructure { private final static Logger logger=LoggerFactory.getLogger(JCloudsComputeInfrastructure.class.getName()); private final NovaApi novaApi; private final Set<String> regions; public JCloudsComputeInfrastructure(DirectorUtils directorUtils,String endpoint, String tenant, String username, String password, String proxyhost, String proxyport) { super(directorUtils); Iterable<Module> modules = ImmutableSet.<Module>of(new SLF4JLoggingModule()); logger.debug("initialize jclouds compute API"); String provider = "openstack-nova"; String identity = tenant+":"+username; // tenantName:userName String credential = password; logger.debug("logging as {}",identity); // see https://issues.apache.org/jira/browse/JCLOUDS-816 Properties props = new Properties(); props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true"); novaApi = ContextBuilder.newBuilder(provider) .endpoint(endpoint) .credentials(identity, credential) .modules(modules) .overrides(props) .buildApi(NovaApi.class); regions = novaApi.getConfiguredRegions(); } @Override public void destroy(Member member) throws DestructionException { try { logger.debug("destroy vm {}",member); String vmId=member.getId(); ServerApi serverApi = novaApi.getServerApi(regions.iterator().next()); //FIXME: multi az ? logger.debug("found member {}",vmId); serverApi.stop(vmId); //serverApi.delete(vmId); } catch (Exception e) { throw new DestructionException(String.format("Unable to destroy %s", member), e); } } }
35.090909
106
0.702073
7683ea3c95cd9ab76329b81292fbd794d4e0b51f
12,610
/* * Copyright 2020 Red Hat, Inc. and/or 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 org.kie.dmn.core.internal.utils; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.drools.util.io.ResourceConfigurationImpl; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.util.io.ClassPathResource; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieRuntimeFactory; import org.kie.dmn.api.core.DMNCompiler; import org.kie.dmn.api.core.DMNCompilerConfiguration; import org.kie.dmn.api.core.DMNModel; import org.kie.dmn.api.core.DMNRuntime; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.api.marshalling.DMNMarshaller; import org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory; import org.kie.dmn.core.assembler.DMNAssemblerService; import org.kie.dmn.core.assembler.DMNResource; import org.kie.dmn.core.assembler.DMNResourceDependenciesSorter; import org.kie.dmn.core.compiler.DMNCompilerConfigurationImpl; import org.kie.dmn.core.compiler.DMNCompilerImpl; import org.kie.dmn.core.compiler.DMNDecisionLogicCompilerFactory; import org.kie.dmn.core.compiler.DMNProfile; import org.kie.dmn.core.compiler.RuntimeTypeCheckOption; import org.kie.dmn.core.compiler.profiles.ExtendedDMNProfile; import org.kie.dmn.core.impl.DMNRuntimeImpl; import org.kie.dmn.core.impl.DMNRuntimeKB; import org.kie.dmn.feel.util.Either; import org.kie.dmn.model.api.Definitions; import org.kie.internal.io.ResourceWithConfigurationImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Internal Utility class. */ public class DMNRuntimeBuilder { private static final Logger LOG = LoggerFactory.getLogger(DMNRuntimeBuilder.class); private final DMNRuntimeBuilderCtx ctx; private DMNRuntimeBuilder() { this.ctx = new DMNRuntimeBuilderCtx(); } private static class DMNRuntimeBuilderCtx { public final DMNCompilerConfigurationImpl cc; public final List<DMNProfile> dmnProfiles = new ArrayList<>(); private RelativeImportResolver relativeResolver; private Function<String, KieRuntimeFactory> kieRuntimeFactoryFunction; public DMNRuntimeBuilderCtx() { this.cc = new DMNCompilerConfigurationImpl(); } public void setRelativeResolver(RelativeImportResolver relativeResolver) { this.relativeResolver = relativeResolver; } public void setKieRuntimeFactoryFunction(Function<String, KieRuntimeFactory> kieRuntimeFactoryFunction) { this.kieRuntimeFactoryFunction = kieRuntimeFactoryFunction; } } @FunctionalInterface public static interface RelativeImportResolver { Reader resolve(String modelNamespace, String modelName, String locationURI); } /** * Internal Utility class. */ public static DMNRuntimeBuilder fromDefaults() { DMNRuntimeBuilder dmnRuntimeBuilder = new DMNRuntimeBuilder(); dmnRuntimeBuilder.addProfile(new ExtendedDMNProfile()); return dmnRuntimeBuilder; } public DMNRuntimeBuilder addProfile(DMNProfile dmnProfile) { ctx.dmnProfiles.add(dmnProfile); ctx.cc.addExtensions(dmnProfile.getExtensionRegisters()); ctx.cc.addDRGElementCompilers(dmnProfile.getDRGElementCompilers()); ctx.cc.addFEELProfile(dmnProfile); return this; } public DMNRuntimeBuilder setOption(RuntimeTypeCheckOption option) { ctx.cc.setProperty(option.getPropertyName(), "" + option.isRuntimeTypeCheck()); return this; } public DMNRuntimeBuilder setRootClassLoader(ClassLoader classLoader) { ctx.cc.setRootClassLoader(classLoader); return this; } public DMNRuntimeBuilder setRelativeImportResolver(RelativeImportResolver relativeResolver) { ctx.setRelativeResolver(relativeResolver); return this; } public DMNRuntimeBuilder setKieRuntimeFactoryFunction(Function<String, KieRuntimeFactory> kieRuntimeFactoryFunction) { ctx.setKieRuntimeFactoryFunction(kieRuntimeFactoryFunction); return this; } public DMNRuntimeBuilder setDecisionLogicCompilerFactory(DMNDecisionLogicCompilerFactory factory) { ctx.cc.setProperty(DMNAssemblerService.DMN_DECISION_LOGIC_COMPILER, factory.getClass().getCanonicalName()); ctx.cc.setDecisionLogicCompilerFactory(factory); return this; } /** * Internal Utility class. */ public static DMNRuntimeBuilderConfigured usingStrict() { DMNRuntimeBuilder dmnRuntimeBuilder = new DMNRuntimeBuilder(); dmnRuntimeBuilder.setRootClassLoader(null); dmnRuntimeBuilder.setOption(new RuntimeTypeCheckOption(true)); return dmnRuntimeBuilder.buildConfiguration(); } public DMNRuntimeBuilderConfigured buildConfiguration() { return buildConfigurationUsingCustomCompiler(DMNCompilerImpl::new); } public DMNRuntimeBuilderConfigured buildConfigurationUsingCustomCompiler(Function<DMNCompilerConfiguration, DMNCompiler> dmnCompilerFn) { return new DMNRuntimeBuilderConfigured(ctx, dmnCompilerFn.apply(ctx.cc)); } public static class DMNRuntimeBuilderConfigured { private static final Logger LOG = LoggerFactory.getLogger(DMNRuntimeBuilderConfigured.class); private final DMNRuntimeBuilderCtx ctx; private final DMNCompiler dmnCompiler; private DMNRuntimeBuilderConfigured(DMNRuntimeBuilderCtx ctx, DMNCompiler dmnCompiler) { this.ctx = ctx; this.dmnCompiler = dmnCompiler; } public Either<Exception, DMNRuntime> fromClasspathResource(final String resourceName, final Class<?> testClass) { return fromResources(Arrays.asList(new ClassPathResource(resourceName, testClass))); } public Either<Exception, DMNRuntime> fromClasspathResources(final String resourceName, final Class<?> testClass, final String... additionalResources) { List<Resource> resources = new ArrayList<>(); resources.add(new ClassPathResource(resourceName, testClass)); for (String ar : additionalResources) { resources.add(new ClassPathResource(ar, testClass)); } return fromResources(resources); } public Either<Exception, DMNRuntime> fromResources(Collection<Resource> resources) { List<DMNResource> dmnResources = new ArrayList<>(); for (Resource r : resources) { Definitions definitions; try { definitions = getMarshaller().unmarshal(r.getReader()); } catch (IOException e) { return Either.ofLeft(e); } ResourceConfigurationImpl rc = new ResourceConfigurationImpl(); rc.setResourceType(ResourceType.DMN); DMNResource dmnResource = new DMNResource(definitions, new ResourceWithConfigurationImpl(r, rc, b -> { }, a -> { })); dmnResources.add(dmnResource); } DMNAssemblerService.enrichDMNResourcesWithImportsDependencies(dmnResources, Collections.emptyList()); List<DMNResource> sortedDmnResources = DMNResourceDependenciesSorter.sort(dmnResources); List<DMNModel> dmnModels = new ArrayList<>(); for (DMNResource dmnRes : sortedDmnResources) { DMNModel dmnModel = null; if (ctx.relativeResolver != null) { if (dmnCompiler instanceof DMNCompilerImpl) { dmnModel = ((DMNCompilerImpl) dmnCompiler).compile(dmnRes.getDefinitions(), dmnModels, dmnRes.getResAndConfig().getResource(), relativeURI -> ctx.relativeResolver.resolve(dmnRes.getDefinitions().getNamespace(), dmnRes.getDefinitions().getName(), relativeURI)); } else { throw new IllegalStateException("specified a RelativeImportResolver but the compiler is not org.kie.dmn.core.compiler.DMNCompilerImpl"); } } else { dmnModel = dmnCompiler.compile(dmnRes.getDefinitions(), dmnRes.getResAndConfig().getResource(), dmnModels); } if (dmnModel != null) { dmnModels.add(dmnModel); } else { LOG.error("Unable to compile DMN model for the resource {}", dmnRes.getResAndConfig().getResource()); return Either.ofLeft(new IllegalStateException("Unable to compile DMN model for the resource " + dmnRes.getResAndConfig().getResource())); } } return Either.ofRight(new DMNRuntimeImpl(new DMNRuntimeKBStatic(ctx.cc.getRootClassLoader(), dmnModels, ctx.dmnProfiles, ctx.kieRuntimeFactoryFunction))); } private DMNMarshaller getMarshaller() { if (!ctx.cc.getRegisteredExtensions().isEmpty()) { return DMNMarshallerFactory.newMarshallerWithExtensions(ctx.cc.getRegisteredExtensions()); } else { return DMNMarshallerFactory.newDefaultMarshaller(); } } } private static class DMNRuntimeKBStatic implements DMNRuntimeKB { private final ClassLoader rootClassLoader; private final List<DMNProfile> dmnProfiles; private final List<DMNModel> models; private final Function<String, KieRuntimeFactory> kieRuntimeFactoryFunction; private DMNRuntimeKBStatic(ClassLoader rootClassLoader, Collection<DMNModel> models, Collection<DMNProfile> dmnProfiles, Function<String, KieRuntimeFactory> kieRuntimeFactoryFunction) { this.rootClassLoader = rootClassLoader; LOG.trace("DMNRuntimeKBStatic rootClassLoader is set to {}", rootClassLoader); this.models = Collections.unmodifiableList(new ArrayList<>(models)); this.dmnProfiles = Collections.unmodifiableList(new ArrayList<>(dmnProfiles)); this.kieRuntimeFactoryFunction = kieRuntimeFactoryFunction; } @Override public List<DMNModel> getModels() { return models; } @Override public DMNModel getModel(String namespace, String modelName) { return models.stream().filter(m -> m.getNamespace().equals(namespace) && m.getName().equals(modelName)).findFirst().orElse(null); } @Override public DMNModel getModelById(String namespace, String modelId) { return models.stream().filter(m -> m.getNamespace().equals(namespace) && m.getDefinitions().getId().equals(modelId)).findFirst().orElse(null); } @Override public List<DMNProfile> getProfiles() { return dmnProfiles; } @Override public List<DMNRuntimeEventListener> getListeners() { return Collections.emptyList(); } @Override public ClassLoader getRootClassLoader() { return rootClassLoader; } @Override public InternalKnowledgeBase getInternalKnowledgeBase() { throw new UnsupportedOperationException(); } @Override public KieRuntimeFactory getKieRuntimeFactory(String kieBaseName) { return kieRuntimeFactoryFunction.apply(kieBaseName); } } }
42.891156
193
0.671134
3569b59cd060831f98884b72a2c633f24f5eb450
4,045
/* * Copyright 2000-2017 Holon TDCN. * * 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.holonplatform.vaadin7.components; import com.holonplatform.core.property.Property; import com.holonplatform.core.property.PropertyRenderer; import com.holonplatform.vaadin7.internal.components.InputFieldWrapper; import com.vaadin.ui.Component; import com.vaadin.ui.Field; /** * Input component representation, i.e. a UI component that has a user-editable value. * <p> * Extends {@link ValueHolder} since handles a value, supporting {@link ValueChangeListener}s registration. * </p> * <p> * The actual UI {@link Component} which represents the input component can be obtained through {@link #getComponent()}. * </p> * * @param <V> Value type * * @since 5.0.0 */ public interface Input<V> extends ValueHolder<V>, ValueComponent<V> { /** * Sets the read-only mode of this input component. The user can't change the value when in read-only mode. * @param readOnly the read-only mode of this input component */ void setReadOnly(boolean readOnly); /** * Returns whether this input component is in read-only mode or not. * @return <code>false</code> if the user can modify the value, <code>true</code> if not */ boolean isReadOnly(); /** * Gets whether the field is <em>required</em>. * @return <code>true</code> if the field as required, <code>false</code> otherwise */ public boolean isRequired(); /** * Sets the field as <em>required</em>. * <p> * Required fields should show a <em>required indicator</em> symbol in UI and the default non-empty validator is * setted up. * </p> * @param required <code>true</code> to set the field as required, <code>false</code> otherwise */ void setRequired(boolean required); /** * Sets the focus for this input component, if supported by concrete component implementation. */ void focus(); /** * Create a {@link Input} component type from given {@link Field} instance. * @param <T> Value type * @param field The field instance (not null) * @return A new {@link Input} component which wraps the given <code>field</code> */ static <T> Input<T> from(Field<T> field) { return new InputFieldWrapper<>(field); } /** * A convenience interface with a fixed {@link Input} rendering type to use a {@link Input} {@link PropertyRenderer} * as a functional interface. * @param <T> Property type */ @FunctionalInterface public interface InputPropertyRenderer<T> extends PropertyRenderer<Input<T>, T> { /* * (non-Javadoc) * @see com.holonplatform.core.property.PropertyRenderer#getRenderType() */ @SuppressWarnings("unchecked") @Override default Class<? extends Input<T>> getRenderType() { return (Class<? extends Input<T>>) (Class<?>) Input.class; } } /** * A convenience interface to render a {@link Property} as a {@link Input} using a {@link Field}. * @param <T> Property type */ public interface InputFieldPropertyRenderer<T> extends InputPropertyRenderer<T> { /** * Render given <code>property</code> as consistent value type {@link Field} to handle the property value. * @param property Property to render * @return property {@link Field} */ Field<T> renderField(Property<? extends T> property); /* * (non-Javadoc) * @see com.holonplatform.core.property.PropertyRenderer#render(com.holonplatform.core.property.Property) */ @Override default Input<T> render(Property<? extends T> property) { return Input.from(renderField(property)); } } }
31.850394
120
0.70754
076eb08f873f01beee19caecf5f14d620a1e71f5
499
package com.wlgdo.avatar.activiti.task.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.wlgdo.avatar.activiti.task.entity.LeaveBill; import com.wlgdo.avatar.activiti.task.mapper.LeaveBillMapper; import com.wlgdo.avatar.activiti.task.service.LeaveBillService; import org.springframework.stereotype.Service; @Service("leaveBillService") public class LeaveBillServiceImpl extends ServiceImpl<LeaveBillMapper, LeaveBill> implements LeaveBillService { }
31.1875
111
0.843687
948b20cb593704f7d61c182ed850fb01217cc2b1
1,693
package org.ywb.ono.toolkit; import java.util.Random; /** * @author yuwenbo1 * @date 2020/10/20 7:50 下午 星期二 * @since 1.0.0 */ public class RandomUtils { /** * 随机数种子 */ private static final Random RAND = new Random(); /** * 生成随机整数数 * * @param bound 整数范围 * @param containZero 是否包含0 * @return randomInt */ public static int randomInt(int bound, boolean containZero) { int num = RAND.nextInt(bound); if (containZero) { return num; } while (num == 0) { num = randomInt(bound, false); } return num; } /** * 生成随机数,不包含0 * * @param bound 随机数范围 * @return randomInt */ public static int randomInt(int bound) { return randomInt(bound, false); } /** * 生成随机数low-height之间 * * @param low low * @param height height * @return [low, height) */ public static int randomInt(int low, int height) { int bound = height - low; return randomInt(bound, true) + low; } /** * 生成0-1内的浮点数 * eg: * 0.2961418、0.031211853、0.7102669、etc * * @return float */ public static float randomFloat() { return RAND.nextFloat(); } /** * 生成验证码 * * @param len 验证码长度 * @return verify code */ public static String verifyCode(int len) { char[] cell = new char[len]; for (int i = 0; i < len; i++) { cell[i] = (char) (randomInt(10, true) + 48); } return new String(cell); } }
20.646341
66
0.484347
8421950d31188cac23410b44e1730b22545003d6
11,000
// (c) Copyright 2010 Cloudera, Inc. All Rights Reserved. package com.cloudera.sqoop.netezza; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import com.cloudera.sqoop.manager.EnterpriseManagerFactory; import org.apache.sqoop.ConnFactory; import org.apache.sqoop.SqoopOptions; import org.apache.sqoop.manager.ConnManager; import org.apache.sqoop.metastore.JobData; import org.apache.sqoop.tool.ImportTool; import org.apache.sqoop.util.AsyncSink; /** * Utilities for testing Netezza. */ public class NzTestUtil { private static final Log LOG = LogFactory.getLog(NzTestUtil.class.getName()); /** Hostname in /etc/hosts for the Netezza test database. */ public static final String NETEZZA_HOST = System.getProperty("sqoop.netezza.host", "ve0326.halxg.cloudera.com:5480"); /** DB schema to use on the host. */ public static final String NETEZZA_DB = System.getProperty("sqoop.netezza.db", "sqooptestdb"); /** Netezza DB username. */ public static final String NETEZZA_USER = System.getProperty("sqoop.netezza.user", "SQOOPTEST"); /** Netezza DB password. */ public static final String NETEZZA_PASS = System.getProperty("sqoop.netezza.password", "sqooptest"); // Due to a bug holding connections open within the same process, we need to // login as admin and clear state between tests using the 'nzsession' // executable. public static final String ADMIN_USER = "admin"; public static final String ADMIN_PASS = "password"; // System property setting the path to the nzsession executable. public static final String NZ_SESSION_PATH_KEY = "nz.session.path"; public static final String DEFAULT_NZ_SESSION_PATH = "/usr/local/nz/bin/nzsession"; public static String getConnectString() { return "jdbc:netezza://" + NzTestUtil.NETEZZA_HOST + "/" + NzTestUtil.NETEZZA_DB; } /** * Use the 'nzsession' program to clear out any persistent sessions. * This is a hack; somehow, the Connection.close() call occurring in * tearDown() is not actually closing the open netezza sessions. After * 32 connections open like this, subsequent tests will deadlock. * This method terminates the sessions forcefully. */ public void clearNzSessions() throws IOException, InterruptedException { String pathToNzSession = System.getProperty( NZ_SESSION_PATH_KEY, DEFAULT_NZ_SESSION_PATH); // Run nzsession and capture a list of open transactions. ArrayList<String> args = new ArrayList<String>(); args.add(pathToNzSession); args.add("-host"); args.add(NETEZZA_HOST); args.add("-u"); args.add(ADMIN_USER); args.add("-pw"); args.add(ADMIN_PASS); Process p = Runtime.getRuntime().exec(args.toArray(new String[0])); InputStream is = p.getInputStream(); LineBufferingAsyncSink sink = new LineBufferingAsyncSink(); sink.processStream(is); // Wait for the process to end. int result = p.waitFor(); if (0 != result) { throw new IOException("Session list command terminated with " + result); } // Collect all the stdout, and parse the output. // If the third whitespace-delimited token is the sqooptest user, // the the first token is the nzsession id. We should kill that id. sink.join(); List<String> processList = sink.getLines(); for (String processLine : processList) { if (null == processLine || processLine.length() == 0) { continue; // Ignore empty lines. } String [] tokens = processLine.split(" +"); if (tokens.length < 3) { continue; // Not enough tokens on this line. } if (tokens[2].equalsIgnoreCase(NETEZZA_USER)) { // Found a match. killSession(tokens[0]); } } } private void killSession(String sessionIdStr) throws IOException, InterruptedException { String pathToNzSession = System.getProperty( NZ_SESSION_PATH_KEY, DEFAULT_NZ_SESSION_PATH); // Run nzsession and capture a list of open transactions. ArrayList<String> args = new ArrayList<String>(); args.add(pathToNzSession); args.add("abort"); args.add("-host"); args.add(NETEZZA_HOST); args.add("-u"); args.add(ADMIN_USER); args.add("-pw"); args.add(ADMIN_PASS); args.add("-force"); args.add("-id"); args.add(sessionIdStr); Process p = Runtime.getRuntime().exec(args.toArray(new String[0])); int result = p.waitFor(); if (0 != result) { LOG.error("Could not kill session; exit status " + result); } } /** * An AsyncSink that takes the contents of a stream and stores the * retrieved lines in an array. */ public class LineBufferingAsyncSink extends AsyncSink { private final Log log = LogFactory.getLog( LineBufferingAsyncSink.class.getName()); public LineBufferingAsyncSink() { this.lines = new ArrayList<String>(); } private Thread child; private List<String> lines; public void processStream(InputStream is) { child = new BufferThread(is); child.start(); } public int join() throws InterruptedException { child.join(); return 0; // always successful. } public List<String> getLines() { return this.lines; } /** * Run a background thread that copies the contents of the stream * to the array buffer. */ private class BufferThread extends Thread { private InputStream stream; BufferThread(final InputStream is) { this.stream = is; } public void run() { InputStreamReader isr = new InputStreamReader(this.stream); BufferedReader r = new BufferedReader(isr); try { while (true) { String line = r.readLine(); if (null == line) { break; // stream was closed by remote end. } LineBufferingAsyncSink.this.lines.add(line); } } catch (IOException ioe) { log.error("IOException reading from stream: " + ioe.toString()); } try { r.close(); } catch (IOException ioe) { log.warn("Error closing stream in LineBufferingAsyncSink: " + ioe.toString()); } } } } public static Configuration initConf(Configuration conf) { conf.set("sqoop.connection.factories", EnterpriseManagerFactory.class.getName()); return conf; } public static SqoopOptions initSqoopOptions(SqoopOptions options) { options.setConnectString(NzTestUtil.getConnectString()); options.setUsername(NzTestUtil.NETEZZA_USER); options.setPassword(NzTestUtil.NETEZZA_PASS); return options; } public static ConnManager getNzManager(SqoopOptions options) throws IOException { initSqoopOptions(options); ConnFactory cf = new ConnFactory(options.getConf()); return cf.getManager(new JobData(options, new ImportTool())); } public static void dropTableIfExists(Connection conn, String tableName) throws SQLException { PreparedStatement s = null; try { s = conn.prepareStatement("DROP TABLE " + tableName); s.executeUpdate(); conn.commit(); } catch (SQLException sqlE) { // DROP TABLE may not succeed; the table might not exist. Just continue. LOG.warn("Ignoring SQL Exception dropping table " + tableName + " : " + sqlE); // Clear current query state. conn.rollback(); } finally { if (null != s) { s.close(); } } } public static void dropSchemaIfExists(Connection conn, String schema) throws SQLException { PreparedStatement s = null; try { s = conn.prepareStatement("DROP SCHEMA " + schema + " CASCADE"); s.executeUpdate(); conn.commit(); } catch (SQLException sqlE) { // DROP TABLE may not succeed; the table might not exist. Just continue. LOG.warn("Ignoring SQL Exception dropping schema " + schema + " : " + sqlE); // Clear current query state. conn.rollback(); } finally { if (null != s) { s.close(); } } } public static void dropViewIfExists(Connection conn, String viewName) throws SQLException { PreparedStatement s = null; try { s = conn.prepareStatement("DROP VIEW " + viewName); s.executeUpdate(); conn.commit(); } catch (SQLException sqlE) { // DROP TABLE may not succeed; the table might not exist. Just continue. LOG.warn("Ignoring SQL Exception dropping view " + viewName + " : " + sqlE); // Clear current query state. conn.rollback(); } finally { if (null != s) { s.close(); } } } /** * Check if version is at least 7.0.3. * @param conn * @return true if version is newer than 7.0.3. * @throws SQLException */ public static boolean supportsMultipleSchema(Connection conn) throws SQLException { Statement s = null; try { s = conn.createStatement(); boolean hasResultSet = s.execute("SELECT VERSION()"); conn.commit(); if (hasResultSet) { ResultSet rs = s.getResultSet(); rs.next(); int[] version = interpretVersion(rs.getString(1)); if (version != null) { return version[0] > 7 || (version[0] == 7 && (version[1] > 0 || (version[2] >= 3))); } } else { LOG.warn("Could not find Netezza version. `SELECT VERSION()` has no results."); } } catch (SQLException sqlE) { // DROP TABLE may not succeed; the table might not exist. Just continue. LOG.warn("Could not find Netezza version.", sqlE); // Clear current query state. conn.rollback(); } finally { if (null != s) { s.close(); } } return false; } /** * Interprets a version string. * @param version * @return triplet of version */ public static int[] interpretVersion(String version) { if (version == null) { LOG.warn("Could not find Netezza version. `SELECT VERSION()` results could not be interpreted."); return null; } Pattern p = Pattern.compile("Release (\\d+)\\.(\\d+)\\.(\\d+).*"); Matcher m = p.matcher(version); if (m.matches()) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); int fix = Integer.parseInt(m.group(3)); return new int[]{ major, minor, fix }; } else { return null; } } }
29.810298
119
0.644182
713e74455b0c2c9416b69dd36a4fa13cbe172a1d
4,610
/* * Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 David Berkman * * This file is part of the SmallMind Code Project. * * The SmallMind Code Project is free software, you can redistribute * it and/or modify it under either, at your discretion... * * 1) The terms of GNU Affero General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * ...or... * * 2) The terms of the Apache License, Version 2.0. * * The SmallMind Code Project is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License or Apache License for more details. * * You should have received a copy of the GNU Affero General Public License * and the Apache License along with the SmallMind Code Project. If not, see * <http://www.gnu.org/licenses/> or <http://www.apache.org/licenses/LICENSE-2.0>. * * Additional permission under the GNU Affero GPL version 3 section 7 * ------------------------------------------------------------------ * If you modify this Program, or any covered work, by linking or * combining it with other code, such other code is not for that reason * alone subject to any of the requirements of the GNU Affero GPL * version 3. */ package org.smallmind.phalanx.wire.transport.rest; import java.util.concurrent.atomic.AtomicReference; import javax.ws.rs.Consumes; import javax.ws.rs.ForbiddenException; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.smallmind.claxon.registry.Instrument; import org.smallmind.claxon.registry.Tag; import org.smallmind.claxon.registry.meter.LazyBuilder; import org.smallmind.claxon.registry.meter.SpeedometerBuilder; import org.smallmind.nutsnbolts.util.SnowflakeId; import org.smallmind.phalanx.wire.signal.InvocationSignal; import org.smallmind.phalanx.wire.signal.SignalCodec; import org.smallmind.phalanx.wire.transport.ResponseTransport; import org.smallmind.phalanx.wire.transport.TransportState; import org.smallmind.phalanx.wire.transport.WireInvocationCircuit; import org.smallmind.phalanx.wire.transport.WiredService; import org.smallmind.web.jersey.aop.Validated; @Path("/org/smallmind/wire/transport/response") public class RestResponseTransport implements ResponseTransport { private final AtomicReference<TransportState> stateRef = new AtomicReference<>(TransportState.PLAYING); private final WireInvocationCircuit invocationCircuit = new WireInvocationCircuit(); private final String instanceId = SnowflakeId.newInstance().generateDottedString(); private SignalCodec signalCodec; public void setSignalCodec (SignalCodec signalCodec) { this.signalCodec = signalCodec; } @Override public String getInstanceId () { return instanceId; } @Override public String register (Class<?> serviceInterface, WiredService targetService) throws Exception { invocationCircuit.register(serviceInterface, targetService); return instanceId; } @Override public TransportState getState () { return stateRef.get(); } @Override public void play () { } @Override public void pause () throws Exception { throw new UnsupportedOperationException(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Validated public Response invoke (@HeaderParam("X-SMALLMIND-WIRE-CALLER-ID") String callerId, @HeaderParam("X-SMALLMIND-WIRE-MESSAGE-ID") String messageId, InvocationSignal invocationSignal) throws Throwable { if (TransportState.PLAYING.equals(stateRef.get())) { return Instrument.with(RestResponseTransport.class, LazyBuilder.instance(SpeedometerBuilder::new), new Tag("operation", "invoke"), new Tag("service", invocationSignal.getRoute().getService()), new Tag("method", invocationSignal.getRoute().getFunction().getName())).on( () -> { RestResponseTransmitter responseTransmitter; invocationCircuit.handle(responseTransmitter = new RestResponseTransmitter(), signalCodec, callerId, messageId, invocationSignal); return responseTransmitter.getResultSignal(); } ); } else { throw new ForbiddenException("The resource has been closed"); } } @Override public void close () { stateRef.set(TransportState.CLOSED); } }
35.19084
274
0.745987
766688952509c41daef2741e99d8229c8868fe57
5,476
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.file.config; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.concurrent.PriorityBlockingQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.integration.channel.AbstractMessageChannel; import org.springframework.integration.file.DefaultDirectoryScanner; import org.springframework.integration.file.FileReadingMessageSource; import org.springframework.integration.file.filters.AcceptOnceFileListFilter; import org.springframework.integration.file.filters.FileListFilter; import org.springframework.integration.file.filters.IgnoreHiddenFileListFilter; import org.springframework.integration.test.util.TestUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Iwein Fuld * @author Mark Fisher * @author Gary Russell * @author Gunnar Hillert * @author Artem Bilan */ @SpringJUnitConfig @DirtiesContext public class FileInboundChannelAdapterParserTests { @Autowired private ApplicationContext context; @Autowired @Qualifier("inputDirPoller.adapter.source") private FileReadingMessageSource inputDirPollerSource; @Autowired @Qualifier("inboundWithJustFilter.adapter.source") private FileReadingMessageSource inboundWithJustFilterSource; @Autowired private FileListFilter<File> filter; private DirectFieldAccessor accessor; @BeforeEach public void init() { this.accessor = new DirectFieldAccessor(inputDirPollerSource); } @Test public void channelName() { AbstractMessageChannel channel = context.getBean("inputDirPoller", AbstractMessageChannel.class); assertThat(channel.getComponentName()).as("Channel should be available under specified id") .isEqualTo("inputDirPoller"); } @Test public void justFilter() { Iterator<?> filterIterator = TestUtils .getPropertyValue(this.inboundWithJustFilterSource, "scanner.filter.fileFilters", Set.class).iterator(); assertThat(filterIterator.next()).isInstanceOf(IgnoreHiddenFileListFilter.class); assertThat(filterIterator.next()).isSameAs(this.filter); } @Test public void inputDirectory() { File expected = new File(System.getProperty("java.io.tmpdir")); File actual = (File) this.accessor.getPropertyValue("directory"); assertThat(actual).as("'directory' should be set").isEqualTo(expected); assertThat(this.accessor.getPropertyValue("scanEachPoll")).isEqualTo(Boolean.TRUE); assertThat(this.inputDirPollerSource.getComponentName()).isEqualTo("inputDirPoller.adapter.source"); } @Test public void filter() { DefaultDirectoryScanner scanner = (DefaultDirectoryScanner) accessor.getPropertyValue("scanner"); DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(scanner); Object filter = scannerAccessor.getPropertyValue("filter"); assertThat(filter instanceof AcceptOnceFileListFilter) .as("'filter' should be set and be of instance AcceptOnceFileListFilter but got " + filter.getClass().getSimpleName()).isTrue(); assertThat(scanner.getClass().getName()).contains("FileReadingMessageSource$WatchServiceDirectoryScanner"); FileReadingMessageSource.WatchEventType[] watchEvents = (FileReadingMessageSource.WatchEventType[]) this.accessor.getPropertyValue("watchEvents"); assertThat(watchEvents.length).isEqualTo(2); for (FileReadingMessageSource.WatchEventType watchEvent : watchEvents) { assertThat(watchEvent).isNotEqualTo(FileReadingMessageSource.WatchEventType.CREATE); assertThat(watchEvent) .isIn(FileReadingMessageSource.WatchEventType.MODIFY, FileReadingMessageSource.WatchEventType.DELETE); } } @Test public void comparator() { Object priorityQueue = accessor.getPropertyValue("toBeReceived"); assertThat(priorityQueue).isInstanceOf(PriorityBlockingQueue.class); Object expected = context.getBean("testComparator"); DirectFieldAccessor queueAccessor = new DirectFieldAccessor(priorityQueue); Object innerQueue = queueAccessor.getPropertyValue("q"); Object actual; if (innerQueue != null) { actual = new DirectFieldAccessor(innerQueue).getPropertyValue("comparator"); } else { // probably running under JDK 7 actual = queueAccessor.getPropertyValue("comparator"); } assertThat(actual).as("comparator reference not set, ").isSameAs(expected); } static class TestComparator implements Comparator<File> { @Override public int compare(File f1, File f2) { return 0; } } }
36.506667
109
0.794375
0ea4ea30cad152d2970c07fcfbbf8d1015a00c05
1,688
package org.moparscape.msc.ls.packethandler.loginserver; import org.apache.mina.common.IoSession; import org.moparscape.msc.ls.Server; import org.moparscape.msc.ls.model.World; import org.moparscape.msc.ls.net.LSPacket; import org.moparscape.msc.ls.net.Packet; import org.moparscape.msc.ls.packetbuilder.loginserver.ReplyPacketBuilder; import org.moparscape.msc.ls.packethandler.PacketHandler; import org.moparscape.msc.ls.util.DataConversions; public class BanHandler implements PacketHandler { private ReplyPacketBuilder builder = new ReplyPacketBuilder(); public void handlePacket(Packet p, IoSession session) throws Exception { final long uID = ((LSPacket) p).getUID(); boolean setBanned = ((LSPacket) p).getID() == 4; long user = p.readLong(); long modhash = p.readLong(); if (!Server.storage.playerExists(user)) { builder.setSuccess(false); builder.setReply("There is not an account by that username"); } else if (setBanned && Server.storage.getGroupID(user) < 3) { builder.setSuccess(false); builder.setReply("You cannot ban a (p)mod or admin!"); } else if (Server.storage.ban(setBanned, user)) { builder.setSuccess(false); builder.setReply("There is not an account by that username"); } else { World w = Server.getServer().findWorld(user); if (w != null) { w.getActionSender().logoutUser(user); } if (setBanned) Server.storage.logBan(user, modhash); builder.setSuccess(true); builder.setReply(DataConversions.hashToUsername(user) + " has been " + (setBanned ? "banned" : "unbanned")); } builder.setUID(uID); LSPacket temp = builder.getPacket(); if (temp != null) { session.write(temp); } } }
33.098039
74
0.723341
fddbe0eab2666746004db7b34eef92988bd3c8be
1,402
package org.ovirt.engine.ui.webadmin.section.main.view.tab.virtualMachine; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.ui.uicommonweb.models.vms.VmAppListModel; import org.ovirt.engine.ui.uicommonweb.models.vms.VmListModel; import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.virtualMachine.SubTabVirtualMachineApplicationPresenter; import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabTableView; import org.ovirt.engine.ui.webadmin.uicommon.model.SearchableDetailModelProvider; import org.ovirt.engine.ui.webadmin.widget.table.column.TextColumnWithTooltip; import com.google.inject.Inject; public class SubTabVirtualMachineApplicationView extends AbstractSubTabTableView<VM, String, VmListModel, VmAppListModel> implements SubTabVirtualMachineApplicationPresenter.ViewDef { @Inject public SubTabVirtualMachineApplicationView(SearchableDetailModelProvider<String, VmListModel, VmAppListModel> modelProvider) { super(modelProvider); initTable(); initWidget(getTable()); } void initTable() { TextColumnWithTooltip<String> appNameColumn = new TextColumnWithTooltip<String>() { @Override public String getValue(String appName) { return appName; } }; getTable().addColumn(appNameColumn, "Installed Applications"); } }
42.484848
183
0.771041
90c33ff5c5d4e7a7265fba032ffcc45f24a17fc8
3,824
/* * 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.sysml.runtime.instructions.mr; import java.util.ArrayList; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.instructions.InstructionUtils; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.MatrixIndexes; import org.apache.sysml.runtime.matrix.data.MatrixValue; import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues; import org.apache.sysml.runtime.matrix.mapred.CachedValueMap; import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue; import org.apache.sysml.runtime.matrix.operators.AggregateUnaryOperator; import org.apache.sysml.runtime.matrix.operators.BinaryOperator; public class BinUaggChainInstruction extends UnaryInstruction { // operators private BinaryOperator _bOp = null; private AggregateUnaryOperator _uaggOp = null; // reused intermediates private MatrixIndexes _tmpIx = null; private MatrixValue _tmpVal = null; private BinUaggChainInstruction(BinaryOperator bop, AggregateUnaryOperator uaggop, byte in1, byte out, String istr) { super(MRType.BinUaggChain, null, in1, out, istr); _bOp = bop; _uaggOp = uaggop; _tmpIx = new MatrixIndexes(); _tmpVal = new MatrixBlock(); instString = istr; } public static BinUaggChainInstruction parseInstruction( String str ) throws DMLRuntimeException { //check number of fields (2/3 inputs, output, type) InstructionUtils.checkNumFields ( str, 4 ); //parse instruction parts (without exec type) String[] parts = InstructionUtils.getInstructionParts( str ); BinaryOperator bop = InstructionUtils.parseBinaryOperator(parts[1]); AggregateUnaryOperator uaggop = InstructionUtils.parseBasicAggregateUnaryOperator(parts[2]); byte in1 = Byte.parseByte(parts[3]); byte out = Byte.parseByte(parts[4]); return new BinUaggChainInstruction(bop, uaggop, in1, out, str); } @Override public void processInstruction(Class<? extends MatrixValue> valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput, int blockRowFactor, int blockColFactor) throws DMLRuntimeException { ArrayList<IndexedMatrixValue> blkList = cachedValues.get( input ); if( blkList == null ) return; for(IndexedMatrixValue imv : blkList) { if(imv == null) continue; MatrixIndexes inIx = imv.getIndexes(); MatrixValue inVal = imv.getValue(); //allocate space for the intermediate and output value IndexedMatrixValue iout = cachedValues.holdPlace(output, valueClass); MatrixIndexes outIx = iout.getIndexes(); MatrixValue outVal = iout.getValue(); //process instruction OperationsOnMatrixValues.performAggregateUnary( inIx, inVal, _tmpIx, _tmpVal, _uaggOp, blockRowFactor, blockColFactor); ((MatrixBlock)_tmpVal).dropLastRowsOrColumns(_uaggOp.aggOp.correctionLocation); OperationsOnMatrixValues.performBinaryIgnoreIndexes(inVal, _tmpVal, outVal, _bOp); outIx.setIndexes(inIx); } } }
38.24
122
0.771444
bd22bc15c95615ff7ef0fe2337a6af4bbfb9c524
3,982
package br.com.sistema.rotinas.produtos; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Transient; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import br.com.sistema.enuns.TipoPlataformaProduto; import br.com.sistema.jsf.Mensagens; @Entity public class Produto implements Serializable { private static final long serialVersionUID = -4627023780267375102L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "nome", nullable = false, length = 100) private String nome; @Column(name = "descricao", nullable = false, length = 300) private String descricao; @Column(name = "codigoDeBarras", nullable = false, length = 300) private String codigoDeBarras; @Column(name = "preco", nullable = false, length = 30) private double preco; @Column(name = "quantidade", nullable = false, length = 10) private int quantidade; @Enumerated @Column(name = "plataforma", nullable = false) private TipoPlataformaProduto plataforma; @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true) @Cascade(CascadeType.ALL) @JoinColumn(name = "produto_id", nullable = true) private List<PerguntasERespostas> perguntasERespostas; @Transient private ImagemProduto imagemPrincipal; public boolean equals(Object o) { if (o instanceof Produto) return this.getId() == ((Produto) o).getId(); else return false; } public Produto() { this.perguntasERespostas = new ArrayList<>(); } public Produto(String nome) { this.nome = nome; } public Produto(String nome, String descricao, String codigoDeBarras, double preco, int quantidade, TipoPlataformaProduto plataforma) { super(); this.nome = nome; this.descricao = descricao; this.codigoDeBarras = codigoDeBarras; this.preco = preco; this.quantidade = quantidade; this.plataforma = plataforma; } public TipoPlataformaProduto getPlataforma() { return plataforma; } public void setPlataforma(TipoPlataformaProduto plataforma) { this.plataforma = plataforma; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getCodigoDeBarras() { return codigoDeBarras; } public void setCodigoDeBarras(String codigoDeBarras) { this.codigoDeBarras = codigoDeBarras; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public List<PerguntasERespostas> getPerguntasERespostas() { return perguntasERespostas; } public void setPerguntasERespostas(List<PerguntasERespostas> perguntasERespostas) { this.perguntasERespostas = perguntasERespostas; } public ImagemProduto getImagemPrincipal() { return imagemPrincipal; } public void setImagemPrincipal(ImagemProduto imagemPrincipal) { this.imagemPrincipal = imagemPrincipal; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public void adicionarProduto() { try { new ProdutosDAO().save(this); } catch (Exception e) { Mensagens.gerarMensagemException(e); } } public static long getSerialversionuid() { return serialVersionUID; } }
23.28655
100
0.718734
28472ae8158721a9e83e9469738ec19c34e5b2bc
91
package org.lasencinas.interfaces; public interface Adder { int add(int n1, int n2); }
11.375
34
0.725275
6cc701b5fba94547a794a6c9e1dcb5c427043b8c
3,514
package ua.com.fielden.platform.dao.dynamic; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.MapEntityTo; import ua.com.fielden.platform.entity.annotation.MapTo; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.types.Money; /** * Entity for "dynamic query" testing. * * @author TG Team * */ @KeyType(String.class) @MapEntityTo("MASTER_ENTITY") public class MasterEntity extends AbstractEntity<String> { private static final long serialVersionUID = 1L; ////////// Range types ////////// @IsProperty @MapTo("INTEGER_PROP") private Integer integerProp = null; @IsProperty @MapTo("DOUBLE_PROP") private Double doubleProp = 0.0; @IsProperty @MapTo("DOUBLE_PROP") private BigDecimal bigDecimalProp = new BigDecimal(0.0); @IsProperty @MapTo("MONEY_PROP") private Money moneyProp; @IsProperty @MapTo("DATE_PROP") private Date dateProp; ////////// boolean type ////////// @IsProperty @MapTo("BOOLEAN_PROP") private boolean booleanProp = false; ////////// String type ////////// @IsProperty @MapTo("STRING_PROP") private String stringProp; ////////// Entity type ////////// @IsProperty @MapTo("ENTITY_PROP") private SlaveEntity entityProp; ///////// Collections ///////// @IsProperty(SlaveEntity.class) private List<SlaveEntity> collection = new ArrayList<SlaveEntity>(); public Integer getIntegerProp() { return integerProp; } @Observable public void setIntegerProp(final Integer integerProp) { this.integerProp = integerProp; } public Double getDoubleProp() { return doubleProp; } @Observable public void setDoubleProp(final Double doubleProp) { this.doubleProp = doubleProp; } public BigDecimal getBigDecimalProp() { return bigDecimalProp; } @Observable public void setBigDecimalProp(final BigDecimal bigDecimalProp) { this.bigDecimalProp = bigDecimalProp; } public Money getMoneyProp() { return moneyProp; } @Observable public void setMoneyProp(final Money moneyProp) { this.moneyProp = moneyProp; } public Date getDateProp() { return dateProp; } @Observable public void setDateProp(final Date dateProp) { this.dateProp = dateProp; } public boolean isBooleanProp() { return booleanProp; } @Observable public void setBooleanProp(final boolean booleanProp) { this.booleanProp = booleanProp; } public String getStringProp() { return stringProp; } @Observable public void setStringProp(final String stringProp) { this.stringProp = stringProp; } public SlaveEntity getEntityProp() { return entityProp; } @Observable public void setEntityProp(final SlaveEntity entityProp) { this.entityProp = entityProp; } public List<SlaveEntity> getCollection() { return collection; } @Observable public void setCollection(final List<SlaveEntity> collection) { this.collection.clear(); this.collection.addAll(collection); } }
24.068493
72
0.664485
58fc9eed48131a94d5698b0e59352a11abf0c0af
863
package io.github.edwinmindcraft.apoli.common.condition.block; import io.github.edwinmindcraft.apoli.api.power.factory.BlockCondition; import io.github.edwinmindcraft.apoli.common.condition.configuration.AdjacentConfiguration; import java.util.Arrays; import net.minecraft.core.Direction; import net.minecraft.world.level.block.state.pattern.BlockInWorld; public class AdjacentCondition extends BlockCondition<AdjacentConfiguration> { public AdjacentCondition() { super(AdjacentConfiguration.CODEC); } @Override protected boolean check(AdjacentConfiguration configuration, BlockInWorld block) { int count = Math.toIntExact(Arrays.stream(Direction.values()) .map(x -> new BlockInWorld(block.getLevel(), block.getPos().relative(x), true)) .filter(configuration.condition()::check).count()); return configuration.comparison().check(count); } }
39.227273
91
0.801854
11009bff4b44be9e56432a4886ada47addfcfa98
367
package tk.gushizone.distributed.seata.api; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; /** * @author gushizone@gmail.com * @date 2021/8/20 3:25 下午 */ @FeignClient("demo-seata-client-producer") public interface SeataProducerApi { @PostMapping("/seata/stock/save") String save(); }
22.9375
59
0.754768
882b0dcb767e978236f4e237fd7367a58cb38554
658
package io.jenkins.plugins.pipelinegraphview.consoleview; import hudson.Extension; import hudson.model.Action; import java.util.Collection; import java.util.Collections; import jenkins.model.TransientActionFactory; import org.jenkinsci.plugins.workflow.job.WorkflowRun; @Extension public class PipelineConsoleViewActionFactory extends TransientActionFactory<WorkflowRun> { @Override public Class<WorkflowRun> type() { return WorkflowRun.class; } @Override public Collection<? extends Action> createFor(WorkflowRun target) { PipelineConsoleViewAction a = new PipelineConsoleViewAction(target); return Collections.singleton(a); } }
27.416667
91
0.803951
b3b582aa4315e0b2ef16530b509105ec3f4751c9
4,252
package openmods.inventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import openmods.inventory.StackEqualityTesterBuilder.IEqualityTester; import org.junit.Assert; import org.junit.Test; public class EqualTest { private static void assertSymmetricEquals(IEqualityTester tester, ItemStack left, ItemStack right) { Assert.assertTrue(tester.isEqual(left, right)); Assert.assertTrue(tester.isEqual(right, left)); } private static void assertSymmetricNotEquals(IEqualityTester tester, ItemStack left, ItemStack right) { Assert.assertFalse(tester.isEqual(left, right)); Assert.assertFalse(tester.isEqual(right, left)); } @Test public void testEmptyIdentity() { ItemStack stack = new ItemStack(Utils.ITEM_A); StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); IEqualityTester tester = builder.build(); Assert.assertTrue(tester.isEqual(null, null)); Assert.assertFalse(tester.isEqual(stack, null)); Assert.assertFalse(tester.isEqual(null, stack)); Assert.assertTrue(tester.isEqual(stack, stack)); } @Test public void testEmpty() { StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); IEqualityTester tester = builder.build(); ItemStack stackA = new ItemStack(Utils.ITEM_A); ItemStack stackB = new ItemStack(Utils.ITEM_A); Assert.assertTrue(tester.isEqual(stackA, stackB)); } @Test public void testCompositeIdentity() { ItemStack stack = new ItemStack(Utils.ITEM_A); StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); builder.useItem(); IEqualityTester tester = builder.build(); Assert.assertTrue(tester.isEqual(null, null)); Assert.assertFalse(tester.isEqual(stack, null)); Assert.assertFalse(tester.isEqual(null, stack)); Assert.assertTrue(tester.isEqual(stack, stack)); } @Test public void testItemComparator() { ItemStack stackA1 = new ItemStack(Utils.ITEM_A, 1); ItemStack stackA2 = new ItemStack(Utils.ITEM_A, 2); ItemStack stackB = new ItemStack(Utils.ITEM_B, 2); StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); builder.useItem(); IEqualityTester tester = builder.build(); assertSymmetricEquals(tester, stackA1, stackA2); assertSymmetricNotEquals(tester, stackA1, stackB); assertSymmetricNotEquals(tester, stackA2, stackB); } @Test public void testNBTComparator() { ItemStack stackAa1 = new ItemStack(Utils.ITEM_A, 1); stackAa1.stackTagCompound = new NBTTagCompound(); stackAa1.stackTagCompound.setBoolean("test", true); ItemStack stackAa2 = new ItemStack(Utils.ITEM_A, 2); stackAa2.stackTagCompound = new NBTTagCompound(); stackAa2.stackTagCompound.setBoolean("test", true); ItemStack stackAb = new ItemStack(Utils.ITEM_A); stackAb.stackTagCompound = new NBTTagCompound(); stackAb.stackTagCompound.setBoolean("test", false); ItemStack stackAn = new ItemStack(Utils.ITEM_A); ItemStack stackBn = new ItemStack(Utils.ITEM_B); StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); builder.useNBT(); IEqualityTester tester = builder.build(); assertSymmetricEquals(tester, stackAa1, stackAa2); assertSymmetricEquals(tester, stackAn, stackBn); assertSymmetricNotEquals(tester, stackAa1, stackAb); assertSymmetricNotEquals(tester, stackAa1, stackAn); assertSymmetricNotEquals(tester, stackAa1, stackBn); } @Test public void testCompositeComparator() { ItemStack stackA = new ItemStack(Utils.ITEM_A, 1, 10); ItemStack stackA1 = new ItemStack(Utils.ITEM_A, 1, 2); ItemStack stackA2 = new ItemStack(Utils.ITEM_A, 2, 1); ItemStack stackB = new ItemStack(Utils.ITEM_B, 1, 10); ItemStack stackB1 = new ItemStack(Utils.ITEM_B, 1, 2); ItemStack stackB2 = new ItemStack(Utils.ITEM_B, 2, 1); StackEqualityTesterBuilder builder = new StackEqualityTesterBuilder(); builder.useItem(); builder.useSize(); IEqualityTester tester = builder.build(); assertSymmetricEquals(tester, stackA, stackA1); assertSymmetricEquals(tester, stackB, stackB1); assertSymmetricNotEquals(tester, stackA1, stackA2); assertSymmetricNotEquals(tester, stackA1, stackB1); assertSymmetricNotEquals(tester, stackA2, stackB1); assertSymmetricNotEquals(tester, stackA2, stackB2); } }
33.746032
104
0.771872
fc2bb24e1512697d1e80c7d35ae9afeb857bdff4
977
package liquibase.snapshot; import liquibase.database.Database; import liquibase.structure.DatabaseObject; /** * Listener interface to be called during the snapshot process. Attach instances to {@link liquibase.snapshot.SnapshotControl} */ public interface SnapshotListener { /** * Called before a snapshot is done. * @param example Example of object to be created * @param database Database to be read from */ public void willSnapshot(DatabaseObject example, Database database); /** * Called after an object is fully loaded from the database. Dependent objects may have their willSnapshot and finishSnapshot methods called before this method is called for a given example. * @param example Original example object used for the snapshot * @param snapshot Final snapshot object * @param database Database read from */ void finishedSnapshot(DatabaseObject example, DatabaseObject snapshot, Database database); }
37.576923
194
0.750256
7d73a22cd4da0fd8fa477d8ce5e39c444d47eb32
2,733
/* ************************************************************************************ * Copyright (C) 2001-2017 Openbravo S.L.U. * Licensed under the Apache Software License version 2.0 * 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.openbravo.data; import java.util.Enumeration; import java.util.Vector; import org.apache.log4j.Logger; class Sql { String sqlName; String sqlReturn; String sqlDefaultReturn; String sqlStatic; String sqlConnection; String executeType; String sqlType; String strSQL; String strSqlComments; String sqlObject; String sqlClass; String sqlImport; boolean useQueryProfile; Vector<Parameter> vecParameter; // vector of Parameter's Vector<Object> vecFieldAdded; // vector of fields added to the Class String strSequenceName = null; boolean boolOptional = false; boolean saveContextInfo = true; static Logger log4j = Logger.getLogger(Sql.class); // log4j public Sql() { vecParameter = new Vector<Parameter>(); vecFieldAdded = new Vector<Object>(); } public Parameter addParameter(boolean sequence, String strName, String strDefault, String strInOut, String strOptional, String strAfter, String strText, String strIgnoreValue) { if (log4j.isDebugEnabled()) log4j.debug("addParameter sequence: " + sequence + " name: " + strName); if (strOptional != null) boolOptional = true; if (log4j.isDebugEnabled()) log4j.debug("previous new Parameter"); Parameter parameterNew = new Parameter(sequence, strName, strDefault, strInOut, strOptional, strAfter, strText, strIgnoreValue); if (log4j.isDebugEnabled()) log4j.debug("called new Parameter"); for (Enumeration<Parameter> e = vecParameter.elements(); e.hasMoreElements();) { Parameter parameter = e.nextElement(); if (log4j.isDebugEnabled()) log4j.debug("parameter: " + parameter.strName); if (parameter.strName.equals(strName)) { parameterNew.boolRepeated = true; } } if (log4j.isDebugEnabled()) log4j.debug("previous new vecParameter.addElement"); vecParameter.addElement(parameterNew); if (log4j.isDebugEnabled()) log4j.debug("called new vecParameter.addElement"); return parameterNew; } }
37.438356
100
0.670692
26004863a40a2eaaf0652ef5045840bb4d30de27
3,466
package com.xcynice.XMvp.module.register; import android.text.TextUtils; import com.xcynice.XMvp.api.TestApi; import com.xcynice.XMvp.bean.User; import com.xmvp.xcynice.base.XBaseBean; import com.xmvp.xcynice.base.XBaseObserver; import com.xmvp.xcynice.base.XBasePresenter; import com.xmvp.xcynice.util.XUtil; /** * Description : RegisterPresenter * * @author XuCanyou666 * @date 2020/2/8 */ class RegisterPresenter extends XBasePresenter<IRegisterView> { RegisterPresenter(IRegisterView baseView) { super(baseView); } void register(String username, String password, String rePassword, int usernameCountMax, int passwordCountMax, int rePasswordCountMax) { XUtil.closeSoftKeyboard(); //判断输入是否合规 if (checkIsValid(username, password, rePassword, usernameCountMax, passwordCountMax, rePasswordCountMax)) { //判断两次密码输入是否一致 if (password.equals(rePassword)) { addDisposable(retrofitService.createRs(TestApi.class).register(username, password, rePassword), new XBaseObserver<XBaseBean<User>>(baseView, true) { @Override public void onSuccess(XBaseBean<User> bean) { baseView.showRegisterSuccess("注册成功( ̄▽ ̄)"); baseView.doSuccess(bean); } @Override public void onError(String msg) { baseView.showRegisterFailed(msg + "(°∀°)ノ"); } }); } else { baseView.showRegisterFailed("两次密码不一样( ⊙ o ⊙ ) "); } } else { baseView.showRegisterFailed("填写错误 (°∀°)ノ"); } } /** * 整体判断输入的内容是否合规 * * @param username 账号 * @param password 密码 * @param rePassword 再次输入的密码 * @param usernameCountMax 账号最大输入字数 * @param passwordCountMax 密码最大输入字数 * @param rePasswordCountMax 再次输入密码最大输入字数 * @return 是否合规 */ private boolean checkIsValid(String username, String password, String rePassword, int usernameCountMax, int passwordCountMax, int rePasswordCountMax) { return isUsernameValid(username, usernameCountMax) && isPasswordValid(password, passwordCountMax) && isRePasswordValid(rePassword, rePasswordCountMax); } /** * 判断username输入是否合规 * * @param username username * @param usernameCountMax 账号规定输入字符最大值 * @return 是否合规 */ private boolean isUsernameValid(String username, int usernameCountMax) { return !TextUtils.isEmpty(username) && username.length() <= usernameCountMax && username.length() >= usernameCountMax / 2; } /** * 判断password输入是否合规 * * @param password password * @param passwordCountMax 密码规定输入字符最大值 * @return 是否合规 */ private boolean isPasswordValid(String password, int passwordCountMax) { return !TextUtils.isEmpty(password) && password.length() <= passwordCountMax && password.length() >= passwordCountMax / 2; } /** * 判断rePassword输入是否合规 * * @param rePassword 确认密码 * @param rePasswordCountMax 确认密码的规定输入字符最大值 * @return 是否合规 */ private boolean isRePasswordValid(String rePassword, int rePasswordCountMax) { return !TextUtils.isEmpty(rePassword) && rePassword.length() <= rePasswordCountMax && rePassword.length() >= rePasswordCountMax / 2; } }
34.66
164
0.631852
e0383858f8cf4e6d0e625f80931ed5b42db3af42
1,338
package org.kafka.etl.load; import com.google.inject.Inject; import org.apache.kafka.clients.producer.KafkaProducer; import org.kafka.etl.kafka.IPartitionKeyCalculator; import org.kafka.etl.kafka.IProducerCallback; import org.kafka.etl.kafka.IProducerManager; import javax.inject.Named; import java.util.Properties; import static org.kafka.etl.ioc.BindedConstants.OUTPUT_TOPIC; public class KafkaLoader implements ILoad { @Inject private IProducerManager producerManager; @Inject private IPartitionKeyCalculator partitionKeyCalculator; @Inject private IProducerCallback callback; @Inject @Named(OUTPUT_TOPIC) private String outputTopic; private KafkaProducer<String, String> producer; @Override public ILoad init(Properties properties) { return this; } @Override public void loadEvent(String originalKey, String event) { if (null == producer) { producer = producerManager.getProducer(); } producerManager.sendEvent(producer, partitionKeyCalculator.generatePartitionKey(originalKey, event), event, outputTopic, callback); } @Override public void close() { if (null != producer) { producer.close(); } } public KafkaLoader setOutputTopic(String outputTopic) { this.outputTopic = outputTopic; return this; } }
21.934426
72
0.736921
f9dce75e20b87e1dd333e00aec87c910e44b19af
225
package me.leiho.blog.services; import me.leiho.blog.services.impls.IndexSettingServiceImpl; import java.util.Map; public interface IndexSettingService { IndexSettingServiceImpl getValueMap(Map<String, Object> map); }
22.5
65
0.808889
fdf83c2e1787a6a512854de421fdacf4f4d863df
9,103
package com.highjet.common.base.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 日期处理 * * @author jiangyin * @email * @date 2016年12月21日 下午12:53:33 */ public class DateUtils { /** 时间格式(yyyy-MM-dd) */ public final static String DATE_PATTERN = "yyyy-MM-dd"; /** 时间格式(yyyy-MM-dd HH:mm:ss) */ public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; /** * 日期格式化 日期格式为:yyyy-MM-dd * @param date 日期 * @return 返回yyyy-MM-dd格式日期 */ public static String format(Date date) { return format(date, DATE_PATTERN); } /** * 日期格式化 日期格式为:yyyy-MM-dd * @param date 日期 * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN * @return 返回yyyy-MM-dd格式日期 */ public static String format(Date date, String pattern) { if(date != null){ SimpleDateFormat df = new SimpleDateFormat(pattern); return df.format(date); } return null; } /** * 日期解析 * @param date 日期 * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN * @return 返回Date */ public static Date parse(String date, String pattern) { try { return new SimpleDateFormat(pattern).parse(date); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 字符串转换成日期 * @param strDate 日期字符串 * @param pattern 日期的格式,如:DateUtils.DATE_TIME_PATTERN */ public static Date stringToDate(String strDate, String pattern) { if (StringUtils.isBlank(strDate)){ return null; } DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern); return fmt.parseLocalDateTime(strDate).toDate(); } /** * 根据周数,获取开始日期、结束日期 * @param week 周期 0本周,-1上周,-2上上周,1下周,2下下周 * @return 返回date[0]开始日期、date[1]结束日期 */ public static Date[] getWeekStartAndEnd(int week) { DateTime dateTime = new DateTime(); LocalDate date = new LocalDate(dateTime.plusWeeks(week)); date = date.dayOfWeek().withMinimumValue(); Date beginDate = date.toDate(); Date endDate = date.plusDays(6).toDate(); return new Date[]{beginDate, endDate}; } /** * 对日期的【秒】进行加/减 * * @param date 日期 * @param seconds 秒数,负数为减 * @return 加/减几秒后的日期 */ public static Date addDateSeconds(Date date, int seconds) { DateTime dateTime = new DateTime(date); return dateTime.plusSeconds(seconds).toDate(); } /** * 对日期的【分钟】进行加/减 * * @param date 日期 * @param minutes 分钟数,负数为减 * @return 加/减几分钟后的日期 */ public static Date addDateMinutes(Date date, int minutes) { DateTime dateTime = new DateTime(date); return dateTime.plusMinutes(minutes).toDate(); } /** * 对日期的【小时】进行加/减 * * @param date 日期 * @param hours 小时数,负数为减 * @return 加/减几小时后的日期 */ public static Date addDateHours(Date date, int hours) { DateTime dateTime = new DateTime(date); return dateTime.plusHours(hours).toDate(); } /** * 对日期的【天】进行加/减 * * @param date 日期 * @param days 天数,负数为减 * @return 加/减几天后的日期 */ public static Date addDateDays(Date date, int days) { DateTime dateTime = new DateTime(date); return dateTime.plusDays(days).toDate(); } /** * 对日期的【周】进行加/减 * * @param date 日期 * @param weeks 周数,负数为减 * @return 加/减几周后的日期 */ public static Date addDateWeeks(Date date, int weeks) { DateTime dateTime = new DateTime(date); return dateTime.plusWeeks(weeks).toDate(); } /** * 对日期的【月】进行加/减 * * @param date 日期 * @param months 月数,负数为减 * @return 加/减几月后的日期 */ public static Date addDateMonths(Date date, int months) { DateTime dateTime = new DateTime(date); return dateTime.plusMonths(months).toDate(); } /** * 对日期的【年】进行加/减 * * @param date 日期 * @param years 年数,负数为减 * @return 加/减几年后的日期 */ public static Date addDateYears(Date date, int years) { DateTime dateTime = new DateTime(date); return dateTime.plusYears(years).toDate(); } private static Logger log = LoggerFactory.getLogger(DateUtils.class); private static Calendar calendar = Calendar.getInstance(); /** * * @描述 date to str * * @date 2018/9/15 20:49 */ public static String DateToSTr(Date date) { SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = aDate.format(date); return format; } /** * 转换为年月日字符窜 */ public static String DateToSTr2(Date date) { SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd"); String format = aDate.format(date); return format; } /** * * @描述: 字符窜转日期 * * @params: * @return: * @date: 2018/9/29 11:28 */ public static Date StrToDate(String date) { SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date parse = null; try { parse = aDate.parse(date); } catch (ParseException e) { log.error("日期格式化出错=[{}]", date); } return parse; } /** * 获取上一个月 * * @param date 当前日期的上一个月 */ public static Date getPreMoth(Date date) { //获取上个月日期 Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.MONTH, -1); Date pre = c.getTime(); return pre; } /** * 获取周几 */ public static String getTodayWeek() { //获取当前时间 calendar.setTime(new Date()); int week = calendar.get(Calendar.DAY_OF_WEEK) - 1; if (week < 0) { week = 7; } return weekToStr(week); } public static String weekToStr(int week) { String w = ""; switch (week) { case 7: w = "日"; break; case 6: w = "六"; break; case 5: w = "五"; break; case 4: w = "四"; break; case 3: w = "三"; break; case 2: w = "二"; break; case 1: w = "一"; break; default: w = ""; break; } return w; } /** * 获取 时 分 秒 字符窜 */ public static String getTimeShort(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); String dateString = formatter.format(date); return dateString.equals("00:00:00") ? "12:00:00" : dateString; } /** * 计算时间戳的时间差 * * @param start 减数 * @param end 被减数 * * @return 分钟 */ public static long getTimeRang(long start, long end) { long l = (end - start) / (1000 * 60); return l; } /** * 获取当前月的天数 */ public static int getDayOfMonth(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); int day = c.getActualMaximum(Calendar.DATE); return day; } /** * 获取个月的第一天 */ public static Date getFirstDayDateOfMonth(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMinimum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last); return cal.getTime(); } /** * 获取月的最后一天 */ public static Date getLastDayOfMonth(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last); return cal.getTime(); } /** * 获取小时 * @param date * @return */ public static int getHours(Date date) { Calendar c=Calendar.getInstance(); c.setTime(date); return c.get(Calendar.HOUR_OF_DAY); } /** * 获取分钟 * @param date * @return */ public static int getMinute(Date date) { Calendar c=Calendar.getInstance(); c.setTime(date); return c.get(Calendar.MINUTE); } /** * 获取秒 * @param date * @return */ public static int getSecend(Date date) { Calendar c=Calendar.getInstance(); c.setTime(date); return c.get(Calendar.SECOND); } }
22.588089
77
0.543996
147dd8c3d117d48902bc588777ea303ebe582df9
526
/* * Copyright (C) 2016-2020 Lightbend Inc. <https://www.lightbend.com> */ package docs.home.serialization.v2d; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; import com.lightbend.lagom.serialization.Jsonable; import org.immutables.value.Value; // #rename-class @Value.Immutable @ImmutableStyle @JsonDeserialize(as = OrderPlaced.class) public interface AbstractOrderPlaced extends Jsonable { String getShoppingCartId(); } // #rename-class
26.3
69
0.798479
ce60f3e65debb1b35860b98187c9ad0d93953972
1,979
package io.stargate.graphql.schema; import static org.assertj.core.api.Assertions.assertThat; import graphql.schema.GraphQLInputObjectType; import io.stargate.db.schema.Column; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class FieldFilterInputTypeCacheTest { @Mock private NameMapping nameMapping; private FieldFilterInputTypeCache fieldFilterInputTypes; private List<String> warnings = new ArrayList<>(); @BeforeEach public void setup() { FieldInputTypeCache fieldInputTypes = new FieldInputTypeCache(nameMapping, warnings); fieldFilterInputTypes = new FieldFilterInputTypeCache(fieldInputTypes, nameMapping); } /** * The goal of this test is to ensure that our naming rules don't generate colliding GraphQL type * names for different CQL types. FilterInput types are particularly sensitive to that because we * generate custom types not only for CQL maps, but also for sets and lists. * * <p>TODO we might have to update this test when tuples get added */ @Test @DisplayName("Should generate unique type names") public void collisionsTest() { // This example would fail if we didn't add "Entry" at the beginning of entry types Column.ColumnType cqlType1 = Column.Type.List.of(Column.Type.Map.of(Column.Type.Int, Column.Type.Text)); Column.ColumnType cqlType2 = Column.Type.Map.of(Column.Type.List.of(Column.Type.Int), Column.Type.Text); GraphQLInputObjectType type1 = (GraphQLInputObjectType) fieldFilterInputTypes.get(cqlType1); GraphQLInputObjectType type2 = (GraphQLInputObjectType) fieldFilterInputTypes.get(cqlType2); assertThat(type1.getName()).isNotEqualTo(type2.getName()); } }
38.803922
99
0.774128
86ef3bdf35c552afe4d44407f55103dca20edb28
2,295
package zes.core.utils; /** * 캐릭터 관련 유틸 클래스 * * @author wisepms * @version 23 2011-07-13 05:20:04Z */ public class CharUtil { /** * 캐릭터 배열을 바이트 배열로 변환한다. * * @param carr 변환할 캐릭터 배열 * @return 변환된 바이트 배열 */ public static byte[] toByteArray(char[] carr) { if(carr == null) { return null; } byte[] barr = new byte[carr.length]; for(int i = 0 ; i < carr.length ; i++) { barr[i] = (byte) carr[i]; } return barr; } /** * 바이트 배열을 캐릭터 배열로 변환한다. * * @param barr 변환할 바이트 배열 * @return 변환된 캐릭터 배열 */ public static char[] toCharArray(byte[] barr) { if(barr == null) { return null; } char[] carr = new char[barr.length]; for(int i = 0 ; i < barr.length ; i++) { carr[i] = (char) barr[i]; } return carr; } /** * 지정한 캐릭터가 지정한 캐릭터배열에 속해있는지 여부를 확인한다. * * @param c 확인할 대상 캐릭터 * @param match 캐릭터 배열 * @return 속해있다면 <code>true</code>, 아니면 <code>false</code> */ public static boolean equals(char c, char[] match) { for(int i = 0 ; i < match.length ; i++) { if(c == match[i]) { return true; } } return false; } /** * 주어진 2개의 캐릭터 배열에 대해 지정 인덱스로부터 매치되는 값에 대한 첫번째 인덱스를 얻는다. * * @param source 소스 캐릭터 배열 * @param index 시작 인덱스 * @param match 매칭 대상 캐릭터 배열 * @return 매칭되는 캐릭터가 있다면 해당 인덱스 값, 아니면 -1 */ public static int findFirstAny(char[] source, int index, char[] match) { for(int i = index ; i < source.length ; i++) { if(equals(source[i], match) == true) { return i; } } return -1; } /** * 주어진 2개의 캐릭터 배열에 대해 지정 인덱스로부터 매치되지 않는 값에 대한 첫번째 인덱스를 얻는다. * * @param source 소스 캐릭터 배열 * @param index 시작 인덱스 * @param match 매칭 대상 캐릭터 배열 * @return 매칭되는 캐릭터가 없다면 해당 인덱스 값, 아니면 -1 */ public static int findFirstDiff(char[] source, int index, char[] match) { for(int i = index ; i < source.length ; i++) { if(equals(source[i], match) == false) { return i; } } return -1; } }
24.157895
77
0.475381
d8dab82204e6cd3aef74da3077373ada964590fa
1,404
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.largeFilesEditor; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class UtilsTest { @Test public void calculateProgressValue_firstOf10() { assertEquals(0, Utils.calculatePagePositionPercent(0, 10)); } @Test public void calculateProgressValue_lastOf10() { assertEquals(100, Utils.calculatePagePositionPercent(9, 10)); } @Test public void calculateProgressValue_firstOf1000() { assertEquals(0, Utils.calculatePagePositionPercent(0, 1000)); } @Test public void calculateProgressValue_lastOf1000() { assertEquals(100, Utils.calculatePagePositionPercent(999, 1000)); } @Test public void calculateProgressValue_penultimateOf1000() { int result = Utils.calculatePagePositionPercent(998, 1000); assertTrue(result == 99 || result == 100); } @Test public void calculateProgressValue_secondOf1000() { int result = Utils.calculatePagePositionPercent(1, 1000); assertTrue(result == 0 || result == 1); } @Test public void calculateProgressValue_midOf1000() { int progress = Utils.calculatePagePositionPercent(500, 1000); assertTrue("progress=" + progress, progress >= 49 && progress <= 51); } }
29.25
140
0.740028
3631d61365a49b3fa0346e3d61fd94e8e031ddd4
884
package com.hui.common.dao.core; /** * <code>BaseDaoStrategy</code> * <desc> * 描述: * <desc/> * Creation Time: 2019/12/10 1:17. * * @author Gary.Hu */ public enum BaseDaoStrategy { /** * INIT SINGLE */ MYSQL { @Override public BaseDao createBaseDao(RunnerDao runnerDao, String tableName, String primaryKey) { return new MySqlDao(runnerDao, tableName, primaryKey); } }, ORACLE { @Override public BaseDao createBaseDao(RunnerDao runnerDao, String tableName, String primaryKey) { return null; } }, POSTGRESQL { @Override public BaseDao createBaseDao(RunnerDao runnerDao, String tableName, String primaryKey) { return null; } }; public abstract BaseDao createBaseDao(RunnerDao runnerDao, String tableName, String primaryKey); }
23.263158
100
0.618778
903475caea63a5bb70f9b5fca6159bc0442951e6
1,454
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; /** * */ public final class RpcBrokerImplModule extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractRpcBrokerImplModule { public RpcBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { super(identifier, dependencyResolver); } public RpcBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, RpcBrokerImplModule oldModule, java.lang.AutoCloseable oldInstance) { super(identifier, dependencyResolver, oldModule, oldInstance); } @Override public void validate() { super.validate(); // Add custom validation for module attributes here. } @Override public java.lang.AutoCloseable createInstance() { // TODO:implement throw new java.lang.UnsupportedOperationException("Unimplemented stub method"); } }
37.282051
98
0.73934
44fa2214a697b30aac1069935d678d8fd9ab187c
1,032
package com.caliven.config.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; // @RefreshScope,如果代码中需要动态刷新配置,在需要的类上加上该注解 //(更改配置文件后提交到git,使用curl -X POST http://localhost:8086/refresh 接口刷新配置,/refresh接口是actuator模块的接口) @RefreshScope @RestController public class TestController { // 读取git配置文件中的属性值 @Value("${from}") private String from; @Value("${my-name}") private String name; @Autowired private Environment environment; @GetMapping("/from1") public String from1() { return this.from + "-" + this.name; } @GetMapping("/from2") public String from2() { // 通过 Environment 获取属性 return environment.getProperty("from", "未定义"); } }
26.461538
95
0.731589
f3887d0dc8a2aa2b06a65a7ddf69c4639a844be4
575
package com.github.aites.framework.dbcomponent; public class DBForeignKey { private String fkTableName; private String fkColumnName; private int fkSequence; public DBForeignKey(String fkTableName, String fkColumnName, int fkSequence){ this.fkColumnName = fkColumnName; this.fkTableName = fkTableName; this.fkSequence =fkSequence; } public String getFkColumnName(){ return fkColumnName; } public String getFkTableName(){ return fkTableName; } public int getFkSequence(){ return fkSequence; } }
23.958333
81
0.70087
c1bcc146db47d0ca406833b820a05e9b51965978
7,827
/* * All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP). * * Please see LICENSE.txt for details. */ package gov.gtas.services.udr; import gov.gtas.constant.CommonErrorConstants; import gov.gtas.constant.RuleConstants; import gov.gtas.enumtype.YesNoEnum; import gov.gtas.error.ErrorHandler; import gov.gtas.error.ErrorHandlerFactory; import gov.gtas.model.BaseEntity; import gov.gtas.model.User; import gov.gtas.model.udr.KnowledgeBase; import gov.gtas.model.udr.Rule; import gov.gtas.model.udr.RuleMeta; import gov.gtas.model.udr.UdrRule; import gov.gtas.repository.udr.UdrRuleRepository; import gov.gtas.services.security.UserService; import gov.gtas.util.DateCalendarUtils; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.transaction.Transactional.TxType; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; /** * The back-end service for persisting rules. */ @Service public class RulePersistenceServiceImpl implements RulePersistenceService { /* * The logger for the RulePersistenceService. */ private static final Logger logger = LoggerFactory.getLogger(RulePersistenceServiceImpl.class); private static final int UPDATE_BATCH_SIZE = 100; @PersistenceContext private EntityManager entityManager; @Resource private UdrRuleRepository udrRuleRepository; @Autowired private UserService userService; @Override @Transactional public UdrRule create(UdrRule r, String userId) { final User user = userService.fetchUser(userId); // remove meta for now, since its ID is the same as the parent UdrRule // ID. // we will add it after saving the UDR rule and the ID has been // generated. RuleMeta savedMeta = r.getMetaData(); r.setMetaData(null); if (savedMeta == null) { ErrorHandler errorHandler = ErrorHandlerFactory.getErrorHandler(); throw errorHandler.createException(CommonErrorConstants.NULL_ARGUMENT_ERROR_CODE, "UDR metatdata", "RulePersistenceServiceImpl.create()"); } // set the audit fields r.setEditDt(new Date()); r.setAuthor(user); r.setEditedBy(user); // save the rule with the meta data stripped. // Once the rule id is generated we will add back the meta data // and set its key to the rule ID. UdrRule rule = udrRuleRepository.save(r); // now add back the meta and conditions and update the rule. long ruleid = rule.getId(); savedMeta.setId(ruleid); rule.setMetaData(savedMeta); savedMeta.setParent(rule); rule = udrRuleRepository.save(rule); return rule; } @Override @Transactional public UdrRule delete(Long id, String userId) { final User user = userService.fetchUser(userId); UdrRule ruleToDelete = udrRuleRepository.findById(id).orElse(null); if (ruleToDelete != null && ruleToDelete.getDeleted() == YesNoEnum.N) { ruleToDelete.setDeleted(YesNoEnum.Y); ruleToDelete.setDeleteId(ruleToDelete.getId()); RuleMeta meta = ruleToDelete.getMetaData(); meta.setEnabled(YesNoEnum.N); ruleToDelete.setEditedBy(user); ruleToDelete.setEditDt(new Date()); // remove references to the Knowledge Base if (ruleToDelete.getEngineRules() != null) { for (Rule rl : ruleToDelete.getEngineRules()) { rl.setKnowledgeBase(null); } } udrRuleRepository.save(ruleToDelete); } else { ruleToDelete = null; // in case delete flag was Y logger.warn( "RulePersistenceServiceImpl.delete() - object does not exist or has already been deleted:" + id); } return ruleToDelete; } @Override @Transactional(value = TxType.SUPPORTS) public List<UdrRule> findAll() { return udrRuleRepository.findByDeletedAndEnabled(YesNoEnum.N, YesNoEnum.Y); } @Override public List<UdrRule> findAllUdrSummary(String userId) { if (StringUtils.isEmpty(userId)) { return udrRuleRepository.findAllUdrRuleSummary(); } else { return udrRuleRepository.findAllUdrRuleSummaryByAuthor(userId); } } @Override public Collection<? extends BaseEntity> batchUpdate(Collection<? extends BaseEntity> entities) { /* * Note: this method is only used for Knowledge base maintenance. Hence there is * no need for logging the updates in this method. */ List<BaseEntity> ret = new LinkedList<>(); int count = 0; for (BaseEntity ent : entities) { BaseEntity upd = entityManager.merge(ent); ret.add(upd); ++count; if (count > UPDATE_BATCH_SIZE) { entityManager.flush(); entityManager.clear(); } } return ret; } @Override @Transactional public UdrRule update(UdrRule rule, String userId) { final User user = userService.fetchUser(userId); if (rule.getId() == null) { ErrorHandler errorHandler = ErrorHandlerFactory.getErrorHandler(); throw errorHandler.createException(CommonErrorConstants.NULL_ARGUMENT_ERROR_CODE, "id", "Update UDR"); } rule.setEditDt(new Date()); rule.setEditedBy(user); return udrRuleRepository.save(rule); } @Override @Transactional public UdrRule update(UdrRule rule, User user) { if (rule.getId() == null) { ErrorHandler errorHandler = ErrorHandlerFactory.getErrorHandler(); throw errorHandler.createException(CommonErrorConstants.NULL_ARGUMENT_ERROR_CODE, "id", "Update UDR"); } rule.setEditDt(new Date()); rule.setEditedBy(user); return udrRuleRepository.save(rule); } @Override @Transactional(TxType.SUPPORTS) public UdrRule findById(Long id) { return udrRuleRepository.findById(id).orElse(null); } @Override @Transactional(TxType.SUPPORTS) public UdrRule findByTitleAndAuthor(String title, String authorUserId) { return udrRuleRepository.getUdrRuleByTitleAndAuthor(title, authorUserId); } @Override public List<UdrRule> findByAuthor(String authorUserId) { return udrRuleRepository.findUdrRuleByAuthor(authorUserId); } @Override public List<UdrRule> findValidUdrOnDate(Date targetDate) { List<UdrRule> ret = null; try { // remove the time portion of the date Date tDate = DateCalendarUtils.parseJsonDate(DateCalendarUtils.formatJsonDate(targetDate)); ret = udrRuleRepository.findValidUdrRuleByDate(tDate); } catch (ParseException ex) { throw ErrorHandlerFactory.getErrorHandler().createException( CommonErrorConstants.INVALID_ARGUMENT_ERROR_CODE, ex, "targetDate", "RulePersistenceServiceImpl.findValidUdrOnDate"); } return ret; } @Override public KnowledgeBase findUdrKnowledgeBase() { return this.findUdrKnowledgeBase(RuleConstants.UDR_KNOWLEDGE_BASE_NAME); } @Override public KnowledgeBase findUdrKnowledgeBase(String kbName) { return udrRuleRepository.getKnowledgeBaseByName(kbName); } @Override public KnowledgeBase saveKnowledgeBase(KnowledgeBase kb) { kb.setCreationDt(new Date()); if (kb.getId() == null) { entityManager.persist(kb); } else { entityManager.merge(kb); } return kb; } @Override public KnowledgeBase deleteKnowledgeBase(String kbName) { KnowledgeBase kb = findUdrKnowledgeBase(kbName); if (kb != null) { entityManager.remove(kb); } return kb; } @Override public List<Rule> findRulesByKnowledgeBaseId(Long id) { return udrRuleRepository.getRuleByKbId(id); } /** * @return the entityManager */ @Override public EntityManager getEntityManager() { return entityManager; } }
28.988889
120
0.757762
78da94f537cfe9c32db5b2fa34b7184df761150c
2,560
package sm.vpc.graficos; import java.awt.Point; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; /** * Clase que hereda de Geometrix para la representación de * un trazo libre con sus propios atributos. * @author Víctor Padilla */ public class Trazo extends Geometrix { /** * Constructor que inicializa el objeto Shape figura a un * GeneralPath y le asigna el punto dado como el punto de inicio. * @param p El punto de inicio del GeneralPath. */ public Trazo(Point p){ this.figura = new GeneralPath(); addPoint(p); } /** * Para documentación detallada ver: GeneralPath.lineTo() * @param p Punto final de la nueva línea. */ public void addLine(Point p){ ((GeneralPath) figura).lineTo(p.getX(), p.getY()); } /** * Para documentación detallada ver: GeneralPath.lineTo() * * @param x Coordenada X en punto flotante del punto final de la nueva linea. * @param y Coordenada Y en punto flotante del punto final de la nueva linea. */ public void addLine(float x, float y){ ((GeneralPath) figura).lineTo(x, y); } /** * Para documentación detallada ver: GeneralPath.moveTo() * * @param x Coordenada X del nuevo punto en el recorrido. * @param y Coordenada Y del nuevo punto en el recorrido. */ public void addPoint(float x, float y){ ((GeneralPath) figura).moveTo(x, y); } /** * Para documentación detallada ver: GeneralPath.moveTo() * @param p Nuevo punto en el recorrido. */ public void addPoint(Point p){ ((GeneralPath) figura).moveTo(p.getX(), p.getY()); } /** * Actualiza la posición de una figura tomando como referencia la boundingBox de la * figura y un punto que será el nuevo origen de la figura. Calcula la diferencia * de distancia que hay entre las coordenadas y le aplica una AffineTransform del tipo * Translation a la figura. * @param p El nuevo punto de origen de la figura. A donde se va a mover. */ @Override public void updateLocation(Point p) { double tx = p.getX()-figura.getBounds().getCenterX(); double ty = p.getY()-figura.getBounds().getCenterY(); AffineTransform at = AffineTransform.getTranslateInstance(tx ,ty); ((GeneralPath) figura).transform(at); } }
30.843373
91
0.605859
d6280462a5acfcc4ebc1aa752ba1a4f6f8a6646c
1,186
package pl.pawelirla.pbd.web; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebAssert; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.*; import com.sun.webkit.WebPage; import dagger.multibindings.ElementsIntoSet; import javax.inject.Inject; import javax.inject.Named; import java.io.IOException; import java.util.List; /** * Created by irla on 2016-09-23. */ public class LoggingIn { @Inject WebClient client; @Inject @Named("url.login") String loginUrl; @Inject public LoggingIn() {} public boolean logIn(String username, String password) throws IOException, InterruptedException { HtmlPage page = client.getPage(loginUrl); HtmlInput usernameInput = (HtmlInput) page.getElementById("j_username"); usernameInput.type(username); HtmlInput passwordInput = (HtmlInput) page.getElementById("j_password"); passwordInput.type(password); HtmlButton submit = (HtmlButton) page.getElementById("submit"); page = submit.click(); return !page.asText().contains("Incorrect email or password. Please try again."); } }
29.65
101
0.726813
3f94d5590fd9d3baedcd55f6a0e599d6af555162
502
package learning.messages; /** * It is an annotation based interface which indicates that * the implementing class is a message i.e. it can be sent * through the network.<br/> * There is one very important, non-syntactical requirement for the * implementation: each piece of data in the message has to be a * <b>deep copy</b> of the original one. Breaking this requirement * the simulation could not be performed realistically! * * @author Róbert Ormándi * */ public interface Message { }
29.529412
67
0.739044
9be8e08cb261971ea0a29a7c9430e9c2be27bb35
83
public void printlnArray(long[] arr) { printArray(arr); writer.println(); }
20.75
38
0.662651
2cd4382f99cabc4109778e14156c16572e5710a5
196
package io.bootique.linkrest.demo.cayenne; import io.bootique.linkrest.demo.cayenne.auto._Domain; public class Domain extends _Domain { private static final long serialVersionUID = 1L; }
19.6
54
0.780612
0a1cc9b84d9831fc04488e703e92e1cb539cf88f
727
package org.prosolo.web.lti.json.data; import java.util.List; import com.google.gson.annotations.SerializedName; public class ToolService { @SerializedName("@type") private String type; //must match the "@id" from service offered in Tool Consumer Profile private String service; //subset of actions from Tool Consumer Profile private List<String> action; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getService() { return service; } public void setService(String service) { this.service = service; } public List<String> getAction() { return action; } public void setAction(List<String> action) { this.action = action; } }
19.648649
69
0.723521
d5361435d00b4636a54c48e131cca1d355f76c1b
331
package com.eu.habbo.plugin.events.rooms; import com.eu.habbo.habbohotel.rooms.Room; public class RoomLoadedEvent extends RoomEvent { /** * Triggered whenever a room is fully loaded. * * @param room The room that has been loaded. */ public RoomLoadedEvent(Room room) { super(room); } }
20.6875
49
0.655589
3a0aed6019a499b182b61aa2112f831b56c8304c
10,997
package eu.cosbi.qspcc.ast; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import eu.cosbi.qspcc.ast.attrs.NodeAttr; import eu.cosbi.qspcc.expressions.complextype.StructDefinition; import eu.cosbi.qspcc.expressions.type.GType; import eu.cosbi.qspcc.expressions.type.TypeDefinition.BType; import eu.cosbi.qspcc.interfaces.CompilerFrontend.FunctionType; import eu.cosbi.qspcc.interfaces.CompilerFrontend.IFunction; import eu.cosbi.utils.Tuple; /** * A program is a DAG of compilation units where a compilation unit is an AAST * coming from the Frontend, and a directed edge between compilation units can * be interpreted as "the parent compilation unit calls the child compilation * unit" * * @author tomasoni * */ public class Program implements ProgramRoot { Logger logger = LogManager.getLogger(Program.class); // root of the DAG AAST mainCompilationUnit; // global functions table protected Map<String, AASTNode> globalFunctions; private Set<String> envFunctions; // global variables table private Map<String, List<AASTNode>> globalVariables; private Set<String> envVariables; protected Set<AAST> nGlobalIncompleteFunction; private int nGlobalIncompleteStatements; // used to decide type of undefined nodes private Function<AASTNode, List<GType>> undefInputTypeAlgorithm; private Set<String> userFunctions; public Program(IFunction[] coreFuns, List<Tuple<GType, String>> gvars) { nGlobalIncompleteStatements = 0; nGlobalIncompleteFunction = new HashSet<AAST>(); globalFunctions = new HashMap<String, AASTNode>(); globalVariables = new HashMap<String, List<AASTNode>>(); envFunctions = new HashSet<String>(); envVariables = new HashSet<String>(); userFunctions = new HashSet<String>(); undefInputTypeAlgorithm = null; fillcoreFuns(coreFuns); fillVars(gvars); } private void fillVars(List<Tuple<GType, String>> gvars) { for (Tuple<GType, String> var : gvars) { envVariables.add(var.second()); List<AASTNode> lst = new ArrayList<AASTNode>(); lst.add(iVariableToAASTNode(var.first(), var.second())); globalVariables.put(var.second(), lst); } } private void fillcoreFuns(IFunction[] coreFuns) { for (IFunction fun : coreFuns) { if (fun.type().equals(FunctionType.VARIABLE)) { envVariables.add(fun.getName()); List<AASTNode> lst = new ArrayList<AASTNode>(); lst.add(iVariableToAASTNode(fun)); globalVariables.put(fun.getName(), lst); } else { envFunctions.add(fun.getName().toLowerCase()); globalFunctions.put(fun.getName().toLowerCase(), iFunctionToAASTNode(fun)); } } } /** * create from IFunction an AAST so that from an AAST perspective a core * variable is like an user-defined global variable. * * @param fun * @return */ private AASTNode iVariableToAASTNode(IFunction fun) { AAST main = null; Map<BType, GType> retType = fun.getOutType(); GType varType = retType.get(BType.UNKNOWN); AASTNode id = new AASTNode(main, NodeType.ID, fun.getName(), 0, 0, null); id.expr(varType, true); return id; } private AASTNode iVariableToAASTNode(GType type, String name) { AAST main = null; AASTNode id = new AASTNode(main, NodeType.ID, name, 0, 0, null); id.expr(type, true); return id; } /** * create from IFunction an AAST so that from an AAST perspective a core * function is as an user-defined function * * @param fun * @return */ private AASTNode iFunctionToAASTNode(IFunction fun) { AAST main = null; Map<BType, GType> retType = fun.getOutType(); List<GType> params = fun.getParamTypes(); List<String> paramNames = new ArrayList<String>(); String fun_out = fun.getName() + "_out"; for (int i = 0; i < params.size(); ++i) paramNames.add("p" + Integer.toString(i)); AASTNode fundef = new AASTNode(main, NodeType.FUNCTION, "function " + fun.getName() + "(" + String.join(", ", paramNames) + ") returns " + fun_out, 0, 0, null); fundef.attr(NodeAttr.CORE_FUNCTION, fun); // fun name AASTNode id = new AASTNode(main, NodeType.ID, fun.getName(), 0, 0, fundef); fundef.addChild(id); // function return values AASTNode funret = new AASTNode(main, NodeType.FUNCTION_RETURN, fun_out, 0, 0, fundef); fundef.addChild(funret); AASTNode idret = new AASTNode(main, NodeType.ID, fun_out, 0, 0, funret); funret.addChild(idret); // function parameters AASTNode funpara = new AASTNode(main, NodeType.PARAMETER_LIST, "(" + String.join(", ", paramNames) + ")", 0, 0, fundef); fundef.addChild(funpara); if (retType.size() == 1) { GType[] inputs = new GType[params.size()]; for (int i = 0; i < params.size(); ++i) { GType param = params.get(i); id = new AASTNode(main, NodeType.ID, paramNames.get(i), 0, 0, funpara); id.expr(param, false); funpara.addChild(id); inputs[i] = param; } GType[] outputs = new GType[retType.size()]; int k = 0; for (Map.Entry<BType, GType> entry : retType.entrySet()) { BType inType = entry.getKey(); GType rType = entry.getValue(); idret.expr(rType, false); outputs[k++] = rType; } fundef.expr(GType.get(BType.FUNCTION, inputs, outputs), false); } else { // the key of the map is the input that causes this output // add input parameter id = new AASTNode(main, NodeType.ID, paramNames.get(0), 0, 0, funpara); funpara.addChild(id); for (Map.Entry<BType, GType> entry : retType.entrySet()) { BType inType = entry.getKey(); GType iType = GType.get(inType); GType rType = entry.getValue(); // expr for input parameter id.expr(iType, false); idret.expr(rType, false); fundef.expr(GType.get(BType.FUNCTION, new GType[] { iType }, new GType[] { rType }), false); } } return fundef; } public void mainCompilationUnit(AAST root) { if (this.mainCompilationUnit == null) this.mainCompilationUnit = root; } public AAST mainCompilationUnit() { return mainCompilationUnit; } public boolean functionExists(String id) { return globalFunctions.containsKey(id.toLowerCase()); } public boolean symbolExists(String nodeText) { return globalVariables.containsKey(nodeText); } protected List<AASTNode> variables(AASTNode node) { return globalVariables.get(node.name()); } public Map<String, AASTNode> functions() { return globalFunctions; } public Set<String> userFunctionNames() { return userFunctions; } public Set<StructDefinition> userStructures() { return StructDefinition.structures(); } protected void delFunction(AAST aast, String nodeText, AASTNode parent) { if (!globalFunctions.containsKey(nodeText.toLowerCase())) // nothing to remove return; userFunctions.remove(nodeText); globalFunctions.remove(nodeText.toLowerCase()); } protected void newFunction(AAST aast, String name, AASTNode functionNode) { if (globalFunctions.containsKey(name.toLowerCase())) { // case insensitive AASTNode programNode = globalFunctions.get(name.toLowerCase()); AAST subProgram = programNode.compilationUnit(); String subprogramName = null; if (subProgram == null) subprogramName = "global environment"; else subprogramName = subProgram.sourcePath(); if (!aast.sourcePath().equals(subprogramName)) logger.warn("Overriding function definition '" + name + "' in '" + aast.sourcePath() + "' was previously defined in '" + subprogramName + "' line " + programNode.lineNumber()); } // preserve case here userFunctions.add(name); globalFunctions.put(name.toLowerCase(), functionNode); } /** * returns the function definition of the function named 'functionName' or * null if it doesn't exist (yet). * * @param functionName * @return */ public AASTNode functionNode(String functionName) { return globalFunctions.get(functionName.toLowerCase()); } /** * remove this node from global variables * @param aastNode * @param nodeText */ public void delVariable(AASTNode aastNode, String nodeText) { if (!globalVariables.containsKey(nodeText)) // nothing to delete return; List<AASTNode> nodes = variables(aastNode); if (!nodes.contains(aastNode)) // nothing to delete return; nodes.remove(aastNode); } /** * new node that represents a global variable * * @param aastNode * @param nodeText */ protected void newVariable(AASTNode aastNode, String nodeText) { if (!globalVariables.containsKey(nodeText)) globalVariables.put(nodeText, new ArrayList<AASTNode>()); List<AASTNode> nodes = variables(aastNode); if (!nodes.contains(aastNode)) { List<GType> types; if (!nodes.isEmpty()) types = nodes.get(0).exprs(); else { types = new LinkedList<GType>(); types.add(GType.get(BType.UNKNOWN)); } // they should have the same type aastNode.exprs(types, false); // remember that this comes from global env aastNode.attr(NodeAttr.ETYPE_FROM_EXTERNAL_ENV, true); nodes.add(aastNode); } } @Override public List<AAST> incompleteFunctions() { return new LinkedList<AAST>(nGlobalIncompleteFunction); } @Override public void pushWalk(AAST name) { nGlobalIncompleteFunction.add(name); } @Override public void popWalk(AAST name) { nGlobalIncompleteFunction.remove(name); } @Override public boolean walkNeeded() { return nGlobalIncompleteFunction.size() > 0; } public void popStatementWalk() { nGlobalIncompleteStatements--; } public void pushStatementWalk() { nGlobalIncompleteStatements++; } @Override public boolean statementWalkNeeded() { return nGlobalIncompleteStatements > 0; } public void undefinedType(Function<AASTNode, List<GType>> fun) { undefInputTypeAlgorithm = fun; } public boolean hasCustomUndefinedType() { return undefInputTypeAlgorithm != null; } public List<GType> undefinedType(AASTNode node) { if (undefInputTypeAlgorithm == null) { List<GType> ret = new LinkedList<GType>(); if (node.parentExists(NodeType.FIELDACCESS, 2)) { AASTNode fieldaccess = node.parent(NodeType.FIELDACCESS); if (fieldaccess.childs().get(0).equals(node)) { node.attr(NodeAttr.IMPLICITLY_DEFINED, node); // if this is the first part of a fieldaccess, this is a struct ret.add(GType.get(BType.STRUCT).name(node.name())); return ret; } else { // subelements of structures are unknown ret.add(GType.get(BType.UNKNOWN)); return ret; } } ret.add(GType.get(BType.UNDEFINED)); return ret; } else return undefInputTypeAlgorithm.apply(node); } }
30.211538
112
0.688824
764905c73160a7db571e297f78861492268cd3a0
20,818
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugins.ide.idea; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.gradle.api.Action; import org.gradle.api.DomainObjectCollection; import org.gradle.api.JavaVersion; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.artifacts.component.ProjectComponentIdentifier; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.ConventionMapping; import org.gradle.api.internal.IConventionAware; import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectLocalComponentProvider; import org.gradle.api.internal.artifacts.publish.DefaultPublishArtifact; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.invocation.Gradle; import org.gradle.api.plugins.JavaBasePlugin; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.plugins.scala.ScalaBasePlugin; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.internal.component.local.model.LocalComponentArtifactMetadata; import org.gradle.internal.component.local.model.PublishArtifactLocalArtifactMetadata; import org.gradle.internal.reflect.Instantiator; import org.gradle.language.scala.plugins.ScalaLanguagePlugin; import org.gradle.plugins.ide.api.XmlFileContentMerger; import org.gradle.plugins.ide.idea.internal.IdeaNameDeduper; import org.gradle.plugins.ide.idea.internal.IdeaScalaConfigurer; import org.gradle.plugins.ide.idea.model.IdeaLanguageLevel; import org.gradle.plugins.ide.idea.model.IdeaModel; import org.gradle.plugins.ide.idea.model.IdeaModule; import org.gradle.plugins.ide.idea.model.IdeaModuleIml; import org.gradle.plugins.ide.idea.model.IdeaProject; import org.gradle.plugins.ide.idea.model.IdeaWorkspace; import org.gradle.plugins.ide.idea.model.PathFactory; import org.gradle.plugins.ide.idea.model.internal.PathInterner; import org.gradle.plugins.ide.internal.IdePlugin; import javax.inject.Inject; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import static org.gradle.internal.component.local.model.DefaultProjectComponentIdentifier.newProjectId; /** * Adds a GenerateIdeaModule task. When applied to a root project, also adds a GenerateIdeaProject task. For projects that have the Java plugin applied, the tasks receive additional Java-specific * configuration. */ public class IdeaPlugin extends IdePlugin { private static final String EXT_KEY_IDEA_PATH_INTERNER = "ideaPathInterner"; private static final Predicate<Project> HAS_IDEA_AND_JAVA_PLUGINS = new Predicate<Project>() { @Override public boolean apply(Project project) { return project.getPlugins().hasPlugin(IdeaPlugin.class) && project.getPlugins().hasPlugin(JavaBasePlugin.class); } }; public static final Function<Project, JavaVersion> SOURCE_COMPATIBILITY = new Function<Project, JavaVersion>() { @Override public JavaVersion apply(Project p) { return p.getConvention().getPlugin(JavaPluginConvention.class).getSourceCompatibility(); } }; public static final Function<Project, JavaVersion> TARGET_COMPATIBILITY = new Function<Project, JavaVersion>() { @Override public JavaVersion apply(Project p) { return p.getConvention().getPlugin(JavaPluginConvention.class).getTargetCompatibility(); } }; private final Instantiator instantiator; private final PathInterner pathInterner; private IdeaModel ideaModel; private List<Project> allJavaProjects; @Inject public IdeaPlugin(Instantiator instantiator, PathInterner pathInterner) { this.instantiator = instantiator; this.pathInterner = pathInterner; } public IdeaModel getModel() { return ideaModel; } @Override protected String getLifecycleTaskName() { return "idea"; } @Override protected void onApply(Project project) { getLifecycleTask().setDescription("Generates IDEA project files (IML, IPR, IWS)"); getCleanTask().setDescription("Cleans IDEA project files (IML, IPR)"); ideaModel = project.getExtensions().create("idea", IdeaModel.class); configureIdeaWorkspace(project); configureIdeaProject(project); configureIdeaModule(project); configureForJavaPlugin(project); configureForScalaPlugin(); postProcess("idea", new Action<Gradle>() { @Override public void execute(Gradle gradle) { performPostEvaluationActions(); } }); } public void performPostEvaluationActions() { makeSureModuleNamesAreUnique(); // This needs to happen after de-duplication registerImlArtifacts(); } private void makeSureModuleNamesAreUnique() { new IdeaNameDeduper().configureRoot(project.getRootProject()); } private void registerImlArtifacts() { Set<Project> projectsWithIml = Sets.filter(project.getRootProject().getAllprojects(), new Predicate<Project>() { @Override public boolean apply(Project project) { return project.getPlugins().hasPlugin(IdeaPlugin.class); } }); for (Project project : projectsWithIml) { ProjectLocalComponentProvider projectComponentProvider = ((ProjectInternal) project).getServices().get(ProjectLocalComponentProvider.class); ProjectComponentIdentifier projectId = newProjectId(project); projectComponentProvider.registerAdditionalArtifact(projectId, createImlArtifact(projectId, project)); } } private static LocalComponentArtifactMetadata createImlArtifact(ProjectComponentIdentifier projectId, Project project) { String moduleName = project.getExtensions().getByType(IdeaModel.class).getModule().getName(); File imlFile = new File(project.getProjectDir(), moduleName + ".iml"); Task byName = project.getTasks().getByName("ideaModule"); PublishArtifact publishArtifact = new DefaultPublishArtifact(moduleName, "iml", "iml", null, null, imlFile, byName); return new PublishArtifactLocalArtifactMetadata(projectId, "idea.iml", publishArtifact); } private void configureIdeaWorkspace(final Project project) { if (isRoot(project)) { GenerateIdeaWorkspace task = project.getTasks().create("ideaWorkspace", GenerateIdeaWorkspace.class); task.setDescription("Generates an IDEA workspace file (IWS)"); IdeaWorkspace workspace = new IdeaWorkspace(); workspace.setIws(new XmlFileContentMerger(task.getXmlTransformer())); task.setWorkspace(workspace); ideaModel.setWorkspace(task.getWorkspace()); task.setOutputFile(new File(project.getProjectDir(), project.getName() + ".iws")); addWorker(task, false); } } private void configureIdeaProject(final Project project) { if (isRoot(project)) { final GenerateIdeaProject task = project.getTasks().create("ideaProject", GenerateIdeaProject.class); task.setDescription("Generates IDEA project file (IPR)"); XmlFileContentMerger ipr = new XmlFileContentMerger(task.getXmlTransformer()); IdeaProject ideaProject = instantiator.newInstance(IdeaProject.class, project, ipr); task.setIdeaProject(ideaProject); ideaModel.setProject(ideaProject); ideaProject.setOutputFile(new File(project.getProjectDir(), project.getName() + ".ipr")); ConventionMapping conventionMapping = ((IConventionAware) ideaProject).getConventionMapping(); conventionMapping.map("jdkName", new Callable<String>() { @Override public String call() throws Exception { return JavaVersion.current().toString(); } }); conventionMapping.map("languageLevel", new Callable<IdeaLanguageLevel>() { @Override public IdeaLanguageLevel call() throws Exception { JavaVersion maxSourceCompatibility = getMaxJavaModuleCompatibilityVersionFor(SOURCE_COMPATIBILITY); return new IdeaLanguageLevel(maxSourceCompatibility); } }); conventionMapping.map("targetBytecodeVersion", new Callable<JavaVersion>() { @Override public JavaVersion call() throws Exception { return getMaxJavaModuleCompatibilityVersionFor(TARGET_COMPATIBILITY); } }); ideaProject.setWildcards(Sets.newHashSet("!?*.class", "!?*.scala", "!?*.groovy", "!?*.java")); conventionMapping.map("modules", new Callable<List<IdeaModule>>() { @Override public List<IdeaModule> call() throws Exception { return Lists.newArrayList(Iterables.transform(Sets.filter(project.getRootProject().getAllprojects(), new Predicate<Project>() { @Override public boolean apply(Project p) { return p.getPlugins().hasPlugin(IdeaPlugin.class); } }), new Function<Project, IdeaModule>() { @Override public IdeaModule apply(Project p) { return ideaModelFor(p).getModule(); } })); } }); conventionMapping.map("pathFactory", new Callable<PathFactory>() { @Override public PathFactory call() throws Exception { return new PathFactory(pathInterner).addPathVariable("PROJECT_DIR", task.getOutputFile().getParentFile()); } }); addWorker(task); } } private static IdeaModel ideaModelFor(Project project) { return project.getExtensions().getByType(IdeaModel.class); } private JavaVersion getMaxJavaModuleCompatibilityVersionFor(Function<Project, JavaVersion> toJavaVersion) { List<Project> allJavaProjects = getAllJavaProjects(); if (allJavaProjects.isEmpty()) { return JavaVersion.VERSION_1_6; } else { return Collections.max(Lists.transform(allJavaProjects, toJavaVersion)); } } private List<Project> getAllJavaProjects() { if (allJavaProjects != null) { // cache result because it is pretty expensive to compute return allJavaProjects; } allJavaProjects = Lists.newArrayList(Iterables.filter(project.getRootProject().getAllprojects(), HAS_IDEA_AND_JAVA_PLUGINS)); return allJavaProjects; } private void configureIdeaModule(final Project project) { final GenerateIdeaModule task = project.getTasks().create("ideaModule", GenerateIdeaModule.class); task.setDescription("Generates IDEA module files (IML)"); IdeaModuleIml iml = new IdeaModuleIml(task.getXmlTransformer(), project.getProjectDir()); final IdeaModule module = instantiator.newInstance(IdeaModule.class, project, iml); task.setModule(module); ideaModel.setModule(module); ConventionMapping conventionMapping = ((IConventionAware) module).getConventionMapping(); conventionMapping.map("sourceDirs", new Callable<Set<File>>() { @Override public Set<File> call() throws Exception { return Sets.newHashSet(); } }); conventionMapping.map("name", new Callable<String>() { @Override public String call() throws Exception { return project.getName(); } }); conventionMapping.map("contentRoot", new Callable<File>() { @Override public File call() throws Exception { return project.getProjectDir(); } }); conventionMapping.map("testSourceDirs", new Callable<Set<File>>() { @Override public Set<File> call() throws Exception { return Sets.newHashSet(); } }); conventionMapping.map("excludeDirs", new Callable<Set<File>>() { @Override public Set<File> call() throws Exception { return Sets.newHashSet(project.getBuildDir(), project.file(".gradle")); } }); conventionMapping.map("pathFactory", new Callable<PathFactory>() { @Override public PathFactory call() throws Exception { final PathFactory factory = new PathFactory(pathInterner); factory.addPathVariable("MODULE_DIR", task.getOutputFile().getParentFile()); for (Map.Entry<String, File> entry : module.getPathVariables().entrySet()) { factory.addPathVariable(entry.getKey(), entry.getValue()); } return factory; } }); addWorker(task); } private DomainObjectCollection<JavaPlugin> configureForJavaPlugin(final Project project) { return project.getPlugins().withType(JavaPlugin.class, new Action<JavaPlugin>() { @Override public void execute(JavaPlugin javaPlugin) { configureIdeaModuleForJava(project); } }); } private void configureIdeaModuleForJava(final Project project) { project.getTasks().withType(GenerateIdeaModule.class, new Action<GenerateIdeaModule>() { @Override public void execute(GenerateIdeaModule ideaModule) { // Defaults LinkedHashMap<String, Map<String, Collection<Configuration>>> scopes = Maps.newLinkedHashMap(); addScope("PROVIDED", scopes); addScope("COMPILE", scopes); addScope("RUNTIME", scopes); addScope("TEST", scopes); ideaModule.getModule().setScopes(scopes); // Convention ConventionMapping convention = ((IConventionAware) ideaModule.getModule()).getConventionMapping(); convention.map("sourceDirs", new Callable<Set<File>>() { @Override public Set<File> call() throws Exception { SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets(); return sourceSets.getByName("main").getAllSource().getSrcDirs(); } }); convention.map("testSourceDirs", new Callable<Set<File>>() { @Override public Set<File> call() throws Exception { SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets(); return sourceSets.getByName("test").getAllSource().getSrcDirs(); } }); convention.map("singleEntryLibraries", new Callable<Map<String, FileCollection>>() { @Override public Map<String, FileCollection> call() throws Exception { SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets(); LinkedHashMap<String, FileCollection> map = new LinkedHashMap<String, FileCollection>(2); map.put("RUNTIME", sourceSets.getByName("main").getOutput().getDirs()); map.put("TEST", sourceSets.getByName("test").getOutput().getDirs()); return map; } }); convention.map("targetBytecodeVersion", new Callable<JavaVersion>() { @Override public JavaVersion call() throws Exception { JavaVersion moduleTargetBytecodeLevel = project.getConvention().getPlugin(JavaPluginConvention.class).getTargetCompatibility(); return includeModuleBytecodeLevelOverride(project.getRootProject(), moduleTargetBytecodeLevel) ? moduleTargetBytecodeLevel : null; } }); convention.map("languageLevel", new Callable<IdeaLanguageLevel>() { @Override public IdeaLanguageLevel call() throws Exception { IdeaLanguageLevel moduleLanguageLevel = new IdeaLanguageLevel(project.getConvention().getPlugin(JavaPluginConvention.class).getSourceCompatibility()); return includeModuleLanguageLevelOverride(project.getRootProject(), moduleLanguageLevel) ? moduleLanguageLevel : null; } }); // Dependencies ideaModule.dependsOn(new Callable<FileCollection>() { @Override public FileCollection call() throws Exception { SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets(); return sourceSets.getByName("main").getOutput().getDirs().plus(sourceSets.getByName("test").getOutput().getDirs()); } }); } private void addScope(String name, LinkedHashMap<String, Map<String, Collection<Configuration>>> scopes) { LinkedHashMap<String, Collection<Configuration>> scope = Maps.newLinkedHashMap(); scope.put("plus", Lists.<Configuration>newArrayList()); scope.put("minus", Lists.<Configuration>newArrayList()); scopes.put(name, scope); } }); } private static boolean includeModuleBytecodeLevelOverride(Project rootProject, JavaVersion moduleTargetBytecodeLevel) { if (!rootProject.getPlugins().hasPlugin(IdeaPlugin.class)) { return true; } IdeaProject ideaProject = ideaModelFor(rootProject).getProject(); return !moduleTargetBytecodeLevel.equals(ideaProject.getTargetBytecodeVersion()); } private static boolean includeModuleLanguageLevelOverride(Project rootProject, IdeaLanguageLevel moduleLanguageLevel) { if (!rootProject.getPlugins().hasPlugin(IdeaPlugin.class)) { return true; } IdeaProject ideaProject = ideaModelFor(rootProject).getProject(); return !moduleLanguageLevel.equals(ideaProject.getLanguageLevel()); } private void configureForScalaPlugin() { project.getPlugins().withType(ScalaBasePlugin.class, new Action<ScalaBasePlugin>() { @Override public void execute(ScalaBasePlugin scalaBasePlugin) { ideaModuleDependsOnRoot(); } }); project.getPlugins().withType(ScalaLanguagePlugin.class, new Action<ScalaLanguagePlugin>() { @Override public void execute(ScalaLanguagePlugin scalaLanguagePlugin) { ideaModuleDependsOnRoot(); } }); if (isRoot(project)) { new IdeaScalaConfigurer(project).configure(); } } private void ideaModuleDependsOnRoot() { // see IdeaScalaConfigurer which requires the ipr to be generated first project.getTasks().findByName("ideaModule").dependsOn(project.getRootProject().getTasks().findByName("ideaProject")); } private static boolean isRoot(Project project) { return project.getParent() == null; } }
45.653509
195
0.652128
c01a491f8c96c81b224eb29d64f7ee7a813f57a7
583
package Lotto649_Package; public class lotto649_Predict { public int get_x4(int x1,int x2) { System.out.println(x1+"*"+x2+"="+(x1*x2)); return x1*x2; } public int rollLotto(int s) { System.out.println(s); return s; } public static void main(String[] args) { // TODO Auto-generated method stub lotto649_Predict dump = new lotto649_Predict(); int s = 5; System.out.println(dump.get_x4(5, 6)); // dump.numLotto(s); String []nar = {"22","31","34","9","12","15"}; lotto649_Sqlite QQQ = new lotto649_Sqlite(nar); QQQ.detect(); } }
20.103448
49
0.626072
42ae102de7f2d318fc6ba30793895dbdf6975ea5
1,736
/* * Copyright © 2019 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package co.cask.cdap.etl.api.validation; import java.util.ArrayList; import java.util.List; /** * Thrown when a pipeline stage is invalid for any reason. If there are multiple reasons that the stage is invalid, * they should all be specified. */ public class InvalidStageException extends RuntimeException { private final List<? extends InvalidStageException> reasons; /** * Used when there is a single reason that the pipeline stage is invalid. * * @param message message indicating what is invalid */ public InvalidStageException(String message) { super(message); reasons = new ArrayList<>(); } public InvalidStageException(String s, Throwable throwable) { super(s, throwable); this.reasons = new ArrayList<>(); } /** * Used when there are multiple reasons that the pipeline stage is invalid. * * @param reasons the reasons that the stage is invalid */ public InvalidStageException(List<? extends InvalidStageException> reasons) { this.reasons = new ArrayList<>(reasons); } public List<? extends InvalidStageException> getReasons() { return reasons; } }
29.931034
115
0.722926
ed197cbe322df40d1960c7aa4cd2cfa7ae9504cd
3,319
package com.grolinger.java.service.adapter.exportdata; import com.grolinger.java.controller.templatemodel.DiagramType; import com.grolinger.java.service.data.ApplicationDefinition; import com.grolinger.java.service.data.InterfaceDefinition; import com.grolinger.java.service.data.ServiceDefinition; import com.grolinger.java.service.data.exportdata.ComponentFile; import com.grolinger.java.service.data.exportdata.ExampleFile; import org.thymeleaf.context.Context; import java.io.IOException; public interface LocalExportAdapter { /** * Creates a directory for a service * * @param basePath the path from where the repository is starting * @param applicationDefinition the definition for the application * @param serviceDefinition the service definition * @return returns the path of the created directory * @throws IOException the reason why creating the directory didn't work */ String createServiceDirectory(final String basePath, final ApplicationDefinition applicationDefinition, final ServiceDefinition serviceDefinition) throws IOException; /** * Writes the example file after all interface files are exported * * @param basePath the common base path * @param currentApplication the current application for which the example file should be written * @param exampleFile the content */ void writeExampleFile(final String basePath, final ApplicationDefinition currentApplication, final String exampleFile); /** * Writes a iuml file that represents an interface * * @param currentPath the current root path for this application * @param currentApplication the current application * @param serviceDefinition the current service * @param currentInterface the current interface * @param context the context for the application, service, interface * @param exampleFile the current example file for this application * @return the example file with all interfaces for later export */ ExampleFile writeInterfaceFile(final String currentPath, final ApplicationDefinition currentApplication, final ServiceDefinition serviceDefinition, final InterfaceDefinition currentInterface, Context context, ExampleFile exampleFile); /** * Method that creates a directory in the local file system. * * @param fullPath Path to the directory to be created */ void createParentDir(final String fullPath); /** * Creates a specified directory * * @param basePath The absolute base path from which the repository is created * @param path which * @param application for which application the directory should be created * @return path to the newly created directory */ String createDirectory(final String basePath, String path, final ApplicationDefinition application); /** * Writes a single file for an application_service_interface * * @param diagramType either component|sequence * @param componentFile the content of the file * @throws IOException the reason why the component file couldn't be written */ void writeComponentFile(final DiagramType diagramType, ComponentFile componentFile) throws IOException; }
45.465753
238
0.741187
0f66d1e01bd267e3ac795dce96cd241ddc5ee675
6,930
/* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jdi.ClassObjectReference.toString; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; import com.sun.jdi.*; import com.sun.jdi.request.*; import com.sun.jdi.event.*; import com.sun.jdi.connect.*; import java.io.*; import java.util.*; /** * The debugger application of the test. */ public class tostring001 { //------------------------------------------------------- immutable common fields final static String SIGNAL_READY = "ready"; final static String SIGNAL_GO = "go"; final static String SIGNAL_QUIT = "quit"; private static int waitTime; private static int exitStatus; private static ArgumentHandler argHandler; private static Log log; private static Debugee debuggee; private static ReferenceType debuggeeClass; //------------------------------------------------------- mutable common fields private final static String prefix = "nsk.jdi.ClassObjectReference.toString."; private final static String className = "tostring001"; private final static String debuggerName = prefix + className; private final static String debuggeeName = debuggerName + "a"; //------------------------------------------------------- test specific fields /** debuggee's methods for check **/ private final static String checkedClasses[] = { "java.lang.Boolean" , "java.lang.Byte" , "java.lang.Character", "java.lang.Double" , "java.lang.Float" , "java.lang.Integer" , "java.lang.Long" , "java.lang.Short" , "java.lang.String" , "java.lang.Object" , debuggeeName + "$innerClass", debuggeeName + "$innerInterf", prefix + "tostring001aClass", prefix + "tostring001aInterf" }; //------------------------------------------------------- immutable common methods public static void main(String argv[]) { System.exit(Consts.JCK_STATUS_BASE + run(argv, System.out)); } private static void display(String msg) { log.display("debugger > " + msg); } private static void complain(String msg) { log.complain("debugger FAILURE > " + msg); } public static int run(String argv[], PrintStream out) { exitStatus = Consts.TEST_PASSED; argHandler = new ArgumentHandler(argv); log = new Log(out, argHandler); waitTime = argHandler.getWaitTime() * 60000; debuggee = Debugee.prepareDebugee(argHandler, log, debuggeeName); debuggeeClass = debuggee.classByName(debuggeeName); if ( debuggeeClass == null ) { complain("Class '" + debuggeeName + "' not found."); exitStatus = Consts.TEST_FAILED; } execTest(); debuggee.quit(); return exitStatus; } //------------------------------------------------------ mutable common method private static void execTest() { BreakpointRequest brkp = debuggee.setBreakpoint(debuggeeClass, tostring001a.brkpMethodName, tostring001a.brkpLineNumber); debuggee.resume(); debuggee.sendSignal(SIGNAL_GO); Event event = null; // waiting the breakpoint event try { event = debuggee.waitingEvent(brkp, waitTime); } catch (InterruptedException e) { throw new Failure("unexpected InterruptedException while waiting for Breakpoint event"); } if (!(event instanceof BreakpointEvent)) { debuggee.resume(); throw new Failure("BreakpointEvent didn't arrive"); } ThreadReference thread = ((BreakpointEvent)event).thread(); List params = new Vector(); ClassType testedClass = (ClassType)debuggeeClass; display("Checking toString() method for ClassObjectReferences of debuggee's fields..."); String brackets[] = {"", "[]", "[][]"}; for (int i=0; i < checkedClasses.length; i++) { String basicName = checkedClasses[i]; for (int dim = 0; dim<3; dim++) { String className = basicName + brackets[dim]; ReferenceType refType = debuggee.classByName(className); if (refType == null) { complain("Could NOT FIND class: " + className); exitStatus = Consts.TEST_FAILED; continue; } try { ClassObjectReference classObjRef = refType.classObject(); String str = classObjRef.toString(); if (str == null) { complain("toString() returns null for ClassObjectReferences of debugges's field: " + className); exitStatus = Consts.TEST_FAILED; } else if (str.length() == 0) { complain("toString() returns empty string for ClassObjectReferences of debugges's field: " + className); exitStatus = Consts.TEST_FAILED; } else { display("toString() method returns for " + className + " : " + str); } } catch(Exception e) { complain("unexpected " + e + " while taking ClassObjectReferences of debugges's field: " + className); exitStatus = Consts.TEST_FAILED; } } } display("Checking completed!"); debuggee.resume(); } //--------------------------------------------------------- test specific methods } //--------------------------------------------------------- test specific classes
36.282723
128
0.563348
6e010db1955f3c93d6634e8ef9873d3e4afd1d27
5,554
package observatorio.utils; //JAVA import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.List; //HTMLUNIT "http://htmlunit.sourceforge.net"; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; //VRODDON import java.lang.String; import java.util.ArrayList; import org.apache.log4j.Logger; import vroddon.web.utils.Downloader; /** * This class implements some methods to analyze the license of dumped RDFs etc. * @author vroddon */ public class WebLicenseAnalyzer { //Lista con las palabras clave para reconocer licencias en el texto public static List<String> key; public static void init(){ key=new ArrayList(); key.add("http://creativecommons.org/licenses/by/3.0/"); key.add("licensing"); key.add("license"); key.add("terms of use"); key.add("policy"); } /** * @param args the command line arguments */ public static void main(String[] args) { final String PAGINA = "http://creativecommons.org/ns"; System.out.println(checkForLicenseHint(PAGINA)); // WebLicenseAnalyzer.downloadRDFfromHTML(PAGINA); } /** * Determines whether there is or not a hint to have a licenses clause */ public static String checkForLicenseHint(String PAGINA) { init(); String salida="No license hint found"; final WebClient webClient = new WebClient(); try { final HtmlPage page = webClient.getPage(PAGINA); String s=page.asText(); for(String ss : WebLicenseAnalyzer.key) { int indice=s.toLowerCase().lastIndexOf(ss.toLowerCase()); if (indice!=-1) return "Found " + ss; } }catch(Exception e) { return "Error parsing webpage"; } return salida; } /** * Gets the URIs in a web page with RDF files */ public static List<String> getLinkedRDF(String PAGINA) { List<String> ls = new ArrayList(); final WebClient webClient = new WebClient(); try { final HtmlPage page = webClient.getPage(PAGINA); List<HtmlAnchor> enlaces = page.getAnchors(); for (HtmlAnchor a : enlaces) { URL url = WebLicenseAnalyzer.isRDF(a); if (url!=null) ls.add(url.toString()); } } catch (Exception ex) { Logger.getLogger("licenser").error("Error " + ex); }; return ls; } /** * Downloads all the RDF in a web page into the data folder */ public static boolean downloadRDFfromHTML(String PAGINA) { final WebClient webClient = new WebClient(); try { final HtmlPage page = webClient.getPage(PAGINA); List<HtmlAnchor> enlaces = page.getAnchors(); for (HtmlAnchor a : enlaces) { URL url = WebLicenseAnalyzer.isRDF(a); if (url != null) { File f = null; Logger.getLogger("licenser").info("Downloading " + url); try { f = new File(url.getFile()); String sf = "./data/" + f.getName(); boolean ok = Downloader.Descargar(url.toString(), sf); if (ok == true) { Logger.getLogger("licenser").info("Downloaded as " + sf); } } catch (Exception e) { Logger.getLogger("licenser").error("Error"); if (f != null) { f.delete(); } Logger.getLogger("licenser").error("Error"); return false; } } } } catch (Exception ex) { Logger.getLogger("licenser").error("Error " + ex); System.err.println(ex.getMessage()); return false; }; return true; } /** * Gets the file extension of a given file name */ private static String getExtension(String fileName) { String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); return extension; } return ""; } /** * Decides */ private static URL isRDF(HtmlAnchor a) { if (!a.hasAttribute("href")) { return null; } String s = a.getHrefAttribute(); if (s.startsWith("#")) { return null; } URL url = null; try { url = new URL(s); } catch (MalformedURLException ex) { return null; // System.out.println(s); // Logger.getLogger(RascaWeb.class.getName()).log(Level.SEVERE, null, ex); } String sf = url.getFile(); if (WebLicenseAnalyzer.getExtension(s).equals("tgz")) { return url; } if (WebLicenseAnalyzer.getExtension(s).equals("rdf")) { return url; } if (WebLicenseAnalyzer.getExtension(s).equals("gz")) { return url; } if (WebLicenseAnalyzer.getExtension(s).equals("owl")) { return url; } return null; } }
30.685083
85
0.527368
800d7c07c0b6fb60c8f36d10cf875aaab404125e
7,707
package org.onebillion.onecourse.mainui.oc_countmore; import android.graphics.Color; import android.graphics.PointF; import android.graphics.RectF; import android.view.View; import org.onebillion.onecourse.controls.OBControl; import org.onebillion.onecourse.controls.OBGroup; import org.onebillion.onecourse.controls.OBLabel; import org.onebillion.onecourse.mainui.OC_SectionController; import org.onebillion.onecourse.utils.OBMisc; import org.onebillion.onecourse.utils.OBUtils; import org.onebillion.onecourse.utils.OB_Maths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by michal on 20/02/2017. */ public class OC_CountMore_S3 extends OC_SectionController { List<OBGroup> numbers; List<OBControl> sceneObjs; int hilitecolour; int correct; public void prepare() { setStatus(STATUS_BUSY); super.prepare(); loadFingers(); loadEvent("master"); loadNumbers(); sceneObjs = new ArrayList<>(); hilitecolour = OBUtils.colorFromRGBString(eventAttributes.get("colour_highlight")); events = Arrays.asList(eventAttributes.get("scenes").split(",")); setSceneXX(currentEvent()); } public void start() { OBUtils.runOnOtherThread(new OBUtils.RunLambda() { public void run() throws Exception { demo3a(); } }); } public void setSceneXX(String scene) { super.setSceneXX(scene); correct = Integer.valueOf(eventAttributes.get("correct")); if(eventAttributes.get("reload") != null) { for(OBControl con : sceneObjs) detachControl(con); sceneObjs.clear(); String[] vals = eventAttributes.get("reload").split(","); int val1 = Integer.valueOf(vals[0]); int val2 = Integer.valueOf(vals[1]); OBGroup obj = (OBGroup)objectDict.get("obj"); obj.show(); OBGroup group = new OBGroup(Arrays.asList(obj.copy())); obj.hide(); group.highlight(); group.lowlight(); PointF rloc = OB_Maths.relativePointInRectForLocation(obj.position(), objectDict.get("workrect").frame()); float distance = (1.0f-(rloc.x*2.0f))/(val1-1); for(int i=0;i<val2;i++) { OBGroup screenObj = (OBGroup)group.copy(); PointF objLoc = new PointF(rloc.x + (i%val1) *distance, rloc.y); screenObj.setPosition ( OB_Maths.locationForRect(objLoc.x,objLoc.y,objectDict.get("workrect").frame())); if(i>=val1) { screenObj.setTop (sceneObjs.get(0).bottom()+0.3f*screenObj.height()); } attachControl(screenObj); sceneObjs.add(screenObj); } } for(int i=0;i<sceneObjs.size();i++) sceneObjs.get(i).hide(); for(int i=0;i<correct;i++) sceneObjs.get(i).show(); for(OBGroup con : numbers) con.objectDict.get("box").setBackgroundColor(Color.WHITE); } public void doMainXX() throws Exception { startScene(); } public void touchDownAtPoint(final PointF pt,View v) { if(status() == STATUS_AWAITING_CLICK) { final OBGroup box = (OBGroup)finger(-1,-1,(List<OBControl>)(Object)numbers, pt); if(box != null) { setStatus(STATUS_BUSY); OBUtils.runOnOtherThread(new OBUtils.RunLambda() { public void run() throws Exception { checkTarget(box); } }); } } } public void checkTarget(OBGroup box) throws Exception { playAudio(null); box.objectDict.get("box").setBackgroundColor(hilitecolour); if((int)box.settings.get("num_val") == correct) { gotItRightBigTick(true); waitForSecs(0.3f); playAudioQueuedScene("FINAL",0.3f,true); waitForSecs(0.5f); nextScene(); } else { gotItWrongWithSfx(); long time = setStatus(STATUS_AWAITING_CLICK); waitSFX(); box.objectDict.get("box").setBackgroundColor(Color.WHITE); if(time == statusTime) playAudioQueuedScene("INCORRECT",0.3f,false); } } public void startScene() throws Exception { demoCount(); OBMisc.doSceneAudio(4,setStatus(STATUS_AWAITING_CLICK),this); } public void loadNumbers() { numbers = new ArrayList<>(); OBControl numbox = objectDict.get("numbox"); float fontSize = 65.0f*numbox.height()/85.0f; for(int i = 0;i<10;i++) { OBControl box = new OBControl(); box.setFrame(new RectF(0, 0, numbox.width()/10.0f, numbox.height())); box.setBackgroundColor(Color.WHITE); box.setBorderColor(Color.BLACK); box.setBorderWidth(applyGraphicScale(2)); box.setPosition(OB_Maths.locationForRect(1/10.0f * i,0.5f,numbox.frame())); box.setLeft(numbox.position().x - (5-i)*(box.width() - box.borderWidth)); OBLabel label = new OBLabel(String.format("%d",(i+1)*2),OBUtils.standardTypeFace(), fontSize); label.setColour(Color.BLACK); label.setPosition(box.position()); OBGroup group = new OBGroup(Arrays.asList(box,label)); group.objectDict.put("label",label); group.objectDict.put("box",box); attachControl(group); group.setProperty("num_val",i+1); numbers.add(group); } } public void demoCount() throws Exception { playAudioQueuedScene("DEMO",0.3f,true); waitForSecs(0.3f); if(getAudioForScene(currentEvent(),"DEMO2") != null) { for(int i=0;i<correct;i++) { OBGroup cont = (OBGroup)sceneObjs.get(i); cont.highlight(); playAudioScene("DEMO2",i,true); waitForSecs(0.3f); cont.lowlight(); } waitForSecs(0.3f); } } public void demo3a() throws Exception { loadPointer(POINTER_LEFT); moveScenePointer(OB_Maths.locationForRect(0.5f,0.8f,this.bounds()),-20,0.5f,"DEMO",0,0.3f); moveScenePointer(OB_Maths.locationForRect(0.3f,0.8f,this.bounds()),-30,0.5f,"DEMO",1,0.3f); for(int i=0;i<5;i++) { OBGroup cont = (OBGroup)sceneObjs.get(i); movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,cont.frame()) ,-30+(i*4),0.5f,true); cont.highlight(); playAudioScene("DEMO2",i,true); waitForSecs(0.3f); cont.lowlight(); } OBGroup targetBox = numbers.get(4); movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,targetBox.frame()) ,-20,0.5f,true); movePointerToPoint(OB_Maths.locationForRect(0.55f,0.7f,targetBox.frame()) ,-20,0.2f,true); targetBox.objectDict.get("box").setBackgroundColor(hilitecolour); playAudio("correct"); waitAudio(); movePointerToPoint(OB_Maths.locationForRect(0.55f,1.05f,targetBox.frame()) ,-20,0.2f,true); moveScenePointer(OB_Maths.locationForRect(0.5f,0.8f,this.bounds()),-15,0.5f,"DEMO3",0,0.5f); thePointer.hide(); waitForSecs(0.3f); nextScene(); } }
32.382353
120
0.572726
8140bf1be90544a0f2563666ed79d9ba30a7885b
188
package com.qthegamep.pattern.project2.model.container; public enum IoStrategy { SAME_IO_STRATEGY, WORKER_IO_STRATEGY, LEADER_FOLLOWER_IO_STRATEGY, DYNAMIC_IO_STRATEGY }
18.8
55
0.787234
e213eb5a5875ea37cf0e07f48b64190cf07c7b8e
478
package org.openestate.io.is24_xml.xml; import java.math.BigDecimal; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Adapter36 extends XmlAdapter<String, BigDecimal> { public BigDecimal unmarshal(String value) { return (org.openestate.io.is24_xml.Is24XmlUtils.parsePreisAufAnfrage(value)); } public String marshal(BigDecimal value) { return (org.openestate.io.is24_xml.Is24XmlUtils.printPreisAufAnfrage(value)); } }
22.761905
85
0.748954
fdb77d45278500558c4663c6e47c26102a403d8e
5,725
package org.vcell.sbml; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.xml.stream.XMLStreamException; import org.junit.Ignore; import org.junit.Test; import org.vcell.sbml.vcell.SBMLImporter; import cbit.util.xml.VCLogger; import cbit.vcell.biomodel.BioModel; @Ignore public class SBMLImporterTest { public static void main(String[] args) { try { VCLogger vcl = new TLogger(); SBMLImporter imp = new SBMLImporter("samp.sbml", vcl,false); for (;;) { /* JFileChooser jfc = new JFileChooser( new File(System.getProperty("user.dir"))); int returnVal = jfc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { File f= jfc.getSelectedFile(); BioModel bm = sa.importSBML(f); System.out.println(bm.getName()); } */ BioModel bm = imp.getBioModel(); System.out.println(bm.getName()); } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } public enum FAULT { RESERVED_WORD, DELAY, NONINTEGER_STOICH, INCONSISTENT_UNIT_SYSTEM, EXPRESSION_BINDING_EXCEPTION, XOR_MISSING, JSBML_ERROR // seems like a bug in jsbml RenderParser.processEndDocument() ... line 403 ... wrong constant for extension name }; @Test public void testImport() throws XMLStreamException, IOException{ HashMap<Integer,FAULT> faults = new HashMap(); faults.put(6, FAULT.RESERVED_WORD); faults.put(15, FAULT.RESERVED_WORD); faults.put(92, FAULT.RESERVED_WORD); faults.put(114, FAULT.RESERVED_WORD); faults.put(115, FAULT.RESERVED_WORD); faults.put(117, FAULT.RESERVED_WORD); faults.put(148, FAULT.RESERVED_WORD); faults.put(154, FAULT.RESERVED_WORD); faults.put(155, FAULT.RESERVED_WORD); faults.put(154, FAULT.RESERVED_WORD); faults.put(155, FAULT.RESERVED_WORD); faults.put(156, FAULT.RESERVED_WORD); faults.put(157, FAULT.RESERVED_WORD); faults.put(158, FAULT.RESERVED_WORD); faults.put(159, FAULT.RESERVED_WORD); faults.put(274, FAULT.RESERVED_WORD); faults.put(279, FAULT.RESERVED_WORD); faults.put(282, FAULT.RESERVED_WORD); faults.put(288, FAULT.RESERVED_WORD); faults.put(346, FAULT.RESERVED_WORD); faults.put(24, FAULT.DELAY); faults.put(25, FAULT.DELAY); faults.put(34, FAULT.DELAY); faults.put(196, FAULT.DELAY); faults.put(39, FAULT.NONINTEGER_STOICH); faults.put(59, FAULT.NONINTEGER_STOICH); faults.put(63, FAULT.NONINTEGER_STOICH); faults.put(81, FAULT.NONINTEGER_STOICH); faults.put(145, FAULT.NONINTEGER_STOICH); faults.put(151, FAULT.NONINTEGER_STOICH); faults.put(199, FAULT.NONINTEGER_STOICH); faults.put(206, FAULT.NONINTEGER_STOICH); faults.put(232, FAULT.NONINTEGER_STOICH); faults.put(244, FAULT.NONINTEGER_STOICH); faults.put(246, FAULT.NONINTEGER_STOICH); faults.put(110, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(178, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(228, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(245, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(252, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(262, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(263, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(264, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(267, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(283, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(300, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(316, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(317, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(319, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(322, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(323, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(337, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(327, FAULT.EXPRESSION_BINDING_EXCEPTION); faults.put(340, FAULT.XOR_MISSING); faults.put(248, FAULT.EXPRESSION_BINDING_EXCEPTION); faults.put(305, FAULT.EXPRESSION_BINDING_EXCEPTION); faults.put(353, FAULT.NONINTEGER_STOICH); faults.put(367, FAULT.RESERVED_WORD); faults.put(382, FAULT.RESERVED_WORD); faults.put(383, FAULT.NONINTEGER_STOICH); faults.put(384, FAULT.NONINTEGER_STOICH); faults.put(385, FAULT.NONINTEGER_STOICH); faults.put(386, FAULT.NONINTEGER_STOICH); faults.put(387, FAULT.NONINTEGER_STOICH); faults.put(388, FAULT.NONINTEGER_STOICH); faults.put(392, FAULT.NONINTEGER_STOICH); faults.put(401, FAULT.NONINTEGER_STOICH); faults.put(402, FAULT.RESERVED_WORD); faults.put(403, FAULT.RESERVED_WORD); faults.put(405, FAULT.INCONSISTENT_UNIT_SYSTEM); faults.put(539, FAULT.JSBML_ERROR); File[] sbmlFiles = SBMLUnitTranslatorTest.getBiomodelsCuratedSBMLFiles(); // File[] sbmlFiles = new File[] { // new File("/Users/schaff/Documents/workspace-maven/BioModels_Database-r30_pub-sbml_files/curated/BIOMD0000000001.xml"), // new File("/Users/schaff/Documents/workspace-maven/BioModels_Database-r30_pub-sbml_files/curated/BIOMD0000000101.xml"), // new File("/Users/schaff/Documents/workspace-maven/sbml-test-suite/cases/semantic/00001/00001-sbml-l3v1.xml") // }; VCLogger vcl = new TLogger(); int start = 401; for (int index=start; index<sbmlFiles.length; index++){ File sbmlFile = sbmlFiles[index]; int sbmlNumber = Integer.parseInt(sbmlFile.getName().substring(6).replace(".xml", "")); if (faults.containsKey(sbmlNumber)){ System.err.println("skipping this model, "+faults.get(sbmlNumber).name()); continue; } System.out.println("testing "+sbmlFile); SBMLImporter importer = new SBMLImporter(sbmlFile.getAbsolutePath(), vcl, false); BioModel bioModel = importer.getBioModel(); } } }
36.935484
130
0.726812
3c6143843af218b72e60b714a1b925ad27cbf164
31,244
/* * Copyright 2016, Yahoo Inc. * Licensed under the terms of the Apache License, Version 2.0. * See the LICENSE file associated with the project for terms. */ package com.yahoo.bullet.storm; import com.yahoo.bullet.common.BulletConfig; import com.yahoo.bullet.common.Config; import com.yahoo.bullet.common.Utilities; import com.yahoo.bullet.common.Validator; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.yahoo.bullet.storm.TopologyConstants.BUILT_IN_METRICS; @Slf4j public class BulletStormConfig extends BulletConfig implements Serializable { private static final long serialVersionUID = -1778598395631221122L; // Settings public static final String TOPOLOGY_NAME = "bullet.topology.name"; public static final String TOPOLOGY_METRICS_ENABLE = "bullet.topology.metrics.enable"; public static final String TOPOLOGY_METRICS_BUILT_IN_ENABLE = "bullet.topology.metrics.built.in.enable"; public static final String TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING = "bullet.topology.metrics.built.in.emit.interval.mapping"; public static final String TOPOLOGY_METRICS_CLASSES = "bullet.topology.metrics.classes"; public static final String REPLAY_ENABLE = "bullet.topology.replay.enable"; public static final String REPLAY_REQUEST_INTERVAL = "bullet.topology.replay.request.interval"; public static final String REPLAY_BATCH_SIZE = "bullet.topology.replay.batch.size"; public static final String REPLAY_BATCH_COMPRESS_ENABLE = "bullet.topology.replay.batch.compress.enable"; public static final String DSL_SPOUT_ENABLE = "bullet.topology.dsl.spout.enable"; public static final String DSL_SPOUT_PARALLELISM = "bullet.topology.dsl.spout.parallelism"; public static final String DSL_SPOUT_CPU_LOAD = "bullet.topology.dsl.spout.cpu.load"; public static final String DSL_SPOUT_MEMORY_ON_HEAP_LOAD = "bullet.topology.dsl.spout.memory.on.heap.load"; public static final String DSL_SPOUT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.dsl.spout.memory.off.heap.load"; public static final String DSL_SPOUT_CONNECTOR_CLASS_NAME = "bullet.topology.dsl.spout.connector.class.name"; public static final String DSL_SPOUT_CONNECTOR_SPOUT_ENABLE = "bullet.topology.dsl.spout.connector.as.spout.enable"; public static final String DSL_BOLT_ENABLE = "bullet.topology.dsl.bolt.enable"; public static final String DSL_BOLT_PARALLELISM = "bullet.topology.dsl.bolt.parallelism"; public static final String DSL_BOLT_CPU_LOAD = "bullet.topology.dsl.bolt.cpu.load"; public static final String DSL_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.dsl.bolt.memory.on.heap.load"; public static final String DSL_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.dsl.bolt.memory.off.heap.load"; public static final String DSL_DESERIALIZER_ENABLE = "bullet.topology.dsl.deserializer.enable"; public static final String BULLET_SPOUT_CLASS_NAME = "bullet.topology.bullet.spout.class.name"; public static final String BULLET_SPOUT_ARGS = "bullet.topology.bullet.spout.args"; public static final String BULLET_SPOUT_PARALLELISM = "bullet.topology.bullet.spout.parallelism"; public static final String BULLET_SPOUT_CPU_LOAD = "bullet.topology.bullet.spout.cpu.load"; public static final String BULLET_SPOUT_MEMORY_ON_HEAP_LOAD = "bullet.topology.bullet.spout.memory.on.heap.load"; public static final String BULLET_SPOUT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.bullet.spout.memory.off.heap.load"; public static final String QUERY_SPOUT_PARALLELISM = "bullet.topology.query.spout.parallelism"; public static final String QUERY_SPOUT_CPU_LOAD = "bullet.topology.query.spout.cpu.load"; public static final String QUERY_SPOUT_MEMORY_ON_HEAP_LOAD = "bullet.topology.query.spout.memory.on.heap.load"; public static final String QUERY_SPOUT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.query.spout.memory.off.heap.load"; public static final String TICK_SPOUT_CPU_LOAD = "bullet.topology.tick.spout.cpu.load"; public static final String TICK_SPOUT_MEMORY_ON_HEAP_LOAD = "bullet.topology.tick.spout.memory.on.heap.load"; public static final String TICK_SPOUT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.tick.spout.memory.off.heap.load"; public static final String FILTER_BOLT_PARALLELISM = "bullet.topology.filter.bolt.parallelism"; public static final String FILTER_BOLT_CPU_LOAD = "bullet.topology.filter.bolt.cpu.load"; public static final String FILTER_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.filter.bolt.memory.on.heap.load"; public static final String FILTER_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.filter.bolt.memory.off.heap.load"; public static final String JOIN_BOLT_PARALLELISM = "bullet.topology.join.bolt.parallelism"; public static final String JOIN_BOLT_CPU_LOAD = "bullet.topology.join.bolt.cpu.load"; public static final String JOIN_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.join.bolt.memory.on.heap.load"; public static final String JOIN_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.join.bolt.memory.off.heap.load"; public static final String RESULT_BOLT_PARALLELISM = "bullet.topology.result.bolt.parallelism"; public static final String RESULT_BOLT_CPU_LOAD = "bullet.topology.result.bolt.cpu.load"; public static final String RESULT_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.result.bolt.memory.on.heap.load"; public static final String RESULT_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.result.bolt.memory.off.heap.load"; public static final String LOOP_BOLT_PARALLELISM = "bullet.topology.loop.bolt.parallelism"; public static final String LOOP_BOLT_CPU_LOAD = "bullet.topology.loop.bolt.cpu.load"; public static final String LOOP_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.loop.bolt.memory.on.heap.load"; public static final String LOOP_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.loop.bolt.memory.off.heap.load"; public static final String REPLAY_BOLT_PARALLELISM = "bullet.topology.replay.bolt.parallelism"; public static final String REPLAY_BOLT_CPU_LOAD = "bullet.topology.replay.bolt.cpu.load"; public static final String REPLAY_BOLT_MEMORY_ON_HEAP_LOAD = "bullet.topology.replay.bolt.memory.on.heap.load"; public static final String REPLAY_BOLT_MEMORY_OFF_HEAP_LOAD = "bullet.topology.replay.bolt.memory.off.heap.load"; public static final String TICK_SPOUT_INTERVAL = "bullet.topology.tick.spout.interval.ms"; public static final String FILTER_BOLT_STATS_REPORT_TICKS = "bullet.topology.filter.bolt.stats.report.ticks"; public static final String JOIN_BOLT_QUERY_POST_FINISH_BUFFER_TICKS = "bullet.topology.join.bolt.query.post.finish.buffer.ticks"; public static final String JOIN_BOLT_WINDOW_PRE_START_DELAY_TICKS = "bullet.topology.join.bolt.query.pre.start.delay.ticks"; public static final String LOOP_BOLT_PUBSUB_OVERRIDES = "bullet.topology.loop.bolt.pubsub.overrides"; // Defaults public static final String DEFAULT_TOPOLOGY_NAME = "bullet-topology"; public static final boolean DEFAULT_TOPOLOGY_METRICS_ENABLE = false; public static final boolean DEFAULT_TOPOLOGY_METRICS_BUILT_IN_ENABLE = false; public static final Map<String, Number> DEFAULT_TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING = new HashMap<>(); public static final String DEFAULT_BUILT_IN_METRICS_INTERVAL_KEY = "default"; static { DEFAULT_TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING.put("bullet_active_queries", 10); DEFAULT_TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING.put(DEFAULT_BUILT_IN_METRICS_INTERVAL_KEY, 10); } public static final List<String> DEFAULT_TOPOLOGY_METRICS_CLASSES = new ArrayList<>(); static { DEFAULT_TOPOLOGY_METRICS_CLASSES.add(SigarLoggingMetricsConsumer.class.getName()); } public static final boolean DEFAULT_REPLAY_ENABLE = false; public static final long DEFAULT_REPLAY_REQUEST_INTERVAL = 30000L; public static final int DEFAULT_REPLAY_BATCH_SIZE = 10000; public static final boolean DEFAULT_REPLAY_BATCH_COMPRESS_ENABLE = false; public static final boolean DEFAULT_DSL_SPOUT_ENABLE = false; public static final boolean DEFAULT_DSL_SPOUT_CONNECTOR_SPOUT_ENABLE = false; public static final int DEFAULT_DSL_SPOUT_PARALLELISM = 10; public static final double DEFAULT_DSL_SPOUT_CPU_LOAD = 50.0; public static final double DEFAULT_DSL_SPOUT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_DSL_SPOUT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final boolean DEFAULT_DSL_BOLT_ENABLE = false; public static final int DEFAULT_DSL_BOLT_PARALLELISM = 10; public static final double DEFAULT_DSL_BOLT_CPU_LOAD = 50.0; public static final double DEFAULT_DSL_BOLT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_DSL_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final boolean DEFAULT_DSL_DESERIALIZER_ENABLE = false; public static final int DEFAULT_BULLET_SPOUT_PARALLELISM = 10; public static final double DEFAULT_BULLET_SPOUT_CPU_LOAD = 50.0; public static final double DEFAULT_BULLET_SPOUT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_BULLET_SPOUT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_QUERY_SPOUT_PARALLELISM = 2; public static final double DEFAULT_QUERY_SPOUT_CPU_LOAD = 20.0; public static final double DEFAULT_QUERY_SPOUT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_QUERY_SPOUT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final double DEFAULT_TICK_SPOUT_CPU_LOAD = 20.0; public static final double DEFAULT_TICK_SPOUT_MEMORY_ON_HEAP_LOAD = 128.0; public static final double DEFAULT_TICK_SPOUT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final Number DEFAULT_FILTER_BOLT_PARALLELISM = 16; public static final double DEFAULT_FILTER_BOLT_CPU_LOAD = 100.0; public static final double DEFAULT_FILTER_BOLT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_FILTER_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_JOIN_BOLT_PARALLELISM = 2; public static final double DEFAULT_JOIN_BOLT_CPU_LOAD = 100.0; public static final double DEFAULT_JOIN_BOLT_MEMORY_ON_HEAP_LOAD = 512.0; public static final double DEFAULT_JOIN_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_RESULT_BOLT_PARALLELISM = 2; public static final double DEFAULT_RESULT_BOLT_CPU_LOAD = 20.0; public static final double DEFAULT_RESULT_BOLT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_RESULT_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_LOOP_BOLT_PARALLELISM = 2; public static final double DEFAULT_LOOP_BOLT_CPU_LOAD = 20.0; public static final double DEFAULT_LOOP_BOLT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_LOOP_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_REPLAY_BOLT_PARALLELISM = 2; public static final double DEFAULT_REPLAY_BOLT_CPU_LOAD = 100.0; public static final double DEFAULT_REPLAY_BOLT_MEMORY_ON_HEAP_LOAD = 256.0; public static final double DEFAULT_REPLAY_BOLT_MEMORY_OFF_HEAP_LOAD = 160.0; public static final int DEFAULT_TICK_SPOUT_INTERVAL = 100; public static final int DEFAULT_FILTER_BOLT_STATS_REPORT_TICKS = 3000; public static final int DEFAULT_JOIN_BOLT_QUERY_POST_FINISH_BUFFER_TICKS = 3; public static final int DEFAULT_JOIN_BOLT_QUERY_PRE_START_DELAY_TICKS = 2; public static final Map<String, Object> DEFAULT_LOOP_BOLT_PUBSUB_OVERRIDES = Collections.emptyMap(); // Other constants // Used automatically by the Storm code. Not for user setting. // This is the key to place the Storm configuration as public static final String STORM_CONFIG = "bullet.topology.storm.config"; // This is the key to place the TopologyContext as public static final String STORM_CONTEXT = "bullet.topology.storm.context"; public static final String CUSTOM_STORM_SETTING_PREFIX = "bullet.topology.custom."; // The number of tick spouts in the topology. This should be 1 since it is broadcast to all filter and join bolts. public static final int TICK_SPOUT_PARALLELISM = 1; // The smallest value that Tick Interval can be public static final int TICK_INTERVAL_MINIMUM = 10; public static final double SMALLEST_WINDOW_MIN_EMIT_EVERY_MULTIPLE = 2.0; public static final int PRE_START_DELAY_BUFFER_TICKS = 2; public static final String DEFAULT_STORM_CONFIGURATION = "bullet_storm_defaults.yaml"; // Validations private static final Validator VALIDATOR = BulletConfig.getValidator(); static { VALIDATOR.define(TOPOLOGY_NAME) .defaultTo(DEFAULT_TOPOLOGY_NAME) .checkIf(Validator::isString); VALIDATOR.define(TOPOLOGY_METRICS_ENABLE) .defaultTo(DEFAULT_TOPOLOGY_METRICS_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(TOPOLOGY_METRICS_BUILT_IN_ENABLE) .defaultTo(DEFAULT_TOPOLOGY_METRICS_BUILT_IN_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING) .checkIf(Validator::isMap) .checkIf(BulletStormConfig::isMetricMapping) .defaultTo(DEFAULT_TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING); VALIDATOR.define(TOPOLOGY_METRICS_CLASSES) .checkIf(Validator::isList) .checkIf(BulletStormConfig::areMetricsConsumerClasses) .defaultTo(DEFAULT_TOPOLOGY_METRICS_CLASSES); VALIDATOR.define(REPLAY_ENABLE) .defaultTo(DEFAULT_REPLAY_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(REPLAY_REQUEST_INTERVAL) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_REPLAY_REQUEST_INTERVAL) .castTo(Validator::asLong); VALIDATOR.define(REPLAY_BATCH_SIZE) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_REPLAY_BATCH_SIZE) .castTo(Validator::asInt); VALIDATOR.define(REPLAY_BATCH_COMPRESS_ENABLE) .defaultTo(DEFAULT_REPLAY_BATCH_COMPRESS_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(DSL_SPOUT_ENABLE) .defaultTo(DEFAULT_DSL_SPOUT_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(DSL_SPOUT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_DSL_SPOUT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(DSL_SPOUT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_SPOUT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_SPOUT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_SPOUT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_SPOUT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_SPOUT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_SPOUT_CONNECTOR_CLASS_NAME) .checkIf(Validator::isClassName) .orFail() .unless(Validator::isNull); VALIDATOR.define(DSL_SPOUT_CONNECTOR_SPOUT_ENABLE) .defaultTo(DEFAULT_DSL_SPOUT_CONNECTOR_SPOUT_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(DSL_BOLT_ENABLE) .defaultTo(DEFAULT_DSL_BOLT_ENABLE) .checkIf(Validator::isBoolean); VALIDATOR.define(DSL_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_DSL_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(DSL_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_DSL_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(DSL_DESERIALIZER_ENABLE) .checkIf(Validator::isBoolean) .defaultTo(DEFAULT_DSL_DESERIALIZER_ENABLE); VALIDATOR.define(BULLET_SPOUT_CLASS_NAME) .checkIf(Validator::isClassName) .orFail() .unless(Validator::isNull); VALIDATOR.define(BULLET_SPOUT_ARGS) .checkIf(Validator::isList); VALIDATOR.define(BULLET_SPOUT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_BULLET_SPOUT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(BULLET_SPOUT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_BULLET_SPOUT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(BULLET_SPOUT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_BULLET_SPOUT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(BULLET_SPOUT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_BULLET_SPOUT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(QUERY_SPOUT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_QUERY_SPOUT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(QUERY_SPOUT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_QUERY_SPOUT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(QUERY_SPOUT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_QUERY_SPOUT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(QUERY_SPOUT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_QUERY_SPOUT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(TICK_SPOUT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_TICK_SPOUT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(TICK_SPOUT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_TICK_SPOUT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(TICK_SPOUT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_TICK_SPOUT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(FILTER_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_FILTER_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(FILTER_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_FILTER_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(FILTER_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_FILTER_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(FILTER_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_FILTER_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(JOIN_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_JOIN_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(JOIN_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_JOIN_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(JOIN_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_JOIN_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(JOIN_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_JOIN_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(RESULT_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_RESULT_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(RESULT_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_RESULT_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(RESULT_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_RESULT_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(RESULT_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_RESULT_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(LOOP_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_LOOP_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(LOOP_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_LOOP_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(LOOP_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_LOOP_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(LOOP_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_LOOP_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(REPLAY_BOLT_PARALLELISM) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_REPLAY_BOLT_PARALLELISM) .castTo(Validator::asInt); VALIDATOR.define(REPLAY_BOLT_CPU_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_REPLAY_BOLT_CPU_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(REPLAY_BOLT_MEMORY_ON_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_REPLAY_BOLT_MEMORY_ON_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(REPLAY_BOLT_MEMORY_OFF_HEAP_LOAD) .checkIf(Validator::isPositive) .checkIf(Validator::isFloat) .defaultTo(DEFAULT_REPLAY_BOLT_MEMORY_OFF_HEAP_LOAD) .castTo(Validator::asDouble); VALIDATOR.define(TICK_SPOUT_INTERVAL) .checkIf(Validator::isPositiveInt) .checkIf(Validator.isInRange(TICK_INTERVAL_MINIMUM, Double.POSITIVE_INFINITY)) .defaultTo(DEFAULT_TICK_SPOUT_INTERVAL) .castTo(Validator::asInt); VALIDATOR.define(FILTER_BOLT_STATS_REPORT_TICKS) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_FILTER_BOLT_STATS_REPORT_TICKS) .castTo(Validator::asInt); VALIDATOR.define(JOIN_BOLT_QUERY_POST_FINISH_BUFFER_TICKS) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_JOIN_BOLT_QUERY_POST_FINISH_BUFFER_TICKS) .castTo(Validator::asInt); VALIDATOR.define(JOIN_BOLT_WINDOW_PRE_START_DELAY_TICKS) .checkIf(Validator::isPositiveInt) .defaultTo(DEFAULT_JOIN_BOLT_QUERY_PRE_START_DELAY_TICKS) .castTo(Validator::asInt); VALIDATOR.define(LOOP_BOLT_PUBSUB_OVERRIDES) .checkIf(Validator::isMap) .checkIf(BulletStormConfig::isMapWithStringKeys) .defaultTo(DEFAULT_LOOP_BOLT_PUBSUB_OVERRIDES); VALIDATOR.relate("Built-in metrics enabled but no intervals provided", TOPOLOGY_METRICS_BUILT_IN_ENABLE, TOPOLOGY_METRICS_BUILT_IN_EMIT_INTERVAL_MAPPING) .checkIf(BulletStormConfig::areNeededIntervalsProvided); VALIDATOR.evaluate("Minimum window emit every should be >= pre-start buffer delay + " + PRE_START_DELAY_BUFFER_TICKS + " ticks", TICK_SPOUT_INTERVAL, BulletStormConfig.JOIN_BOLT_WINDOW_PRE_START_DELAY_TICKS, BulletConfig.WINDOW_MIN_EMIT_EVERY) .checkIf(BulletStormConfig::isStartDelayEnough) .orFail(); } /** * Constructor that loads the defaults. */ public BulletStormConfig() { super(DEFAULT_STORM_CONFIGURATION); VALIDATOR.validate(this); } /** * Constructor that loads specific file augmented with defaults. * * @param file YAML file to load. */ public BulletStormConfig(String file) { this(new Config(file)); } /** * Constructor that loads the defaults and augments it with defaults. * * @param other The other config to wrap. */ public BulletStormConfig(Config other) { // Load Bullet and Storm defaults. Then merge the other. super(DEFAULT_STORM_CONFIGURATION); merge(other); VALIDATOR.validate(this); } @Override public BulletStormConfig validate() { VALIDATOR.validate(this); return this; } /** * Returns a copy of the {@link Validator} used by this config. This validator also includes the definitions * in the {@link BulletConfig#getValidator()} validator. * * @return The validator used by this class. */ public static Validator getValidator() { return VALIDATOR.copy(); } /** * Gets all the custom settings defined with {@link #CUSTOM_STORM_SETTING_PREFIX}. The prefix is removed. * * @return A {@link Map} of these custom settings. */ public Map<String, Object> getCustomStormSettings() { return getAllWithPrefix(Optional.empty(), CUSTOM_STORM_SETTING_PREFIX, true); } @SuppressWarnings("unchecked") private static boolean isMetricMapping(Object metricMap) { try { Map<String, Number> map = (Map<String, Number>) metricMap; return map.entrySet().stream().allMatch(BulletStormConfig::isMetricInterval); } catch (ClassCastException e) { log.warn("Interval mapping is not a map of metric string names: {} to numbers", BUILT_IN_METRICS); return false; } } private static boolean isMetricInterval(Map.Entry<String, Number> entry) { String metric = entry.getKey(); Number interval = entry.getValue(); if (!BUILT_IN_METRICS.contains(metric) || !Validator.isPositiveInt(interval)) { log.warn("{} is not a valid metric interval mapping. Supported metrics: {}", entry, BUILT_IN_METRICS); return false; } return true; } @SuppressWarnings("unchecked") private static boolean areMetricsConsumerClasses(Object metricClassList) { try { List<String> classes = (List<String>) metricClassList; return classes.stream().allMatch(ReflectionUtils::isIMetricsConsumer); } catch (ClassCastException e) { log.warn("Metrics classes is not provided as a list of strings: {}", metricClassList); return false; } } @SuppressWarnings("unchecked") private static boolean isMapWithStringKeys(Object maybeMap) { try { Map<String, Object> map = (Map<String, Object>) maybeMap; return map.keySet().stream().noneMatch(String::isEmpty); } catch (ClassCastException e) { log.warn("{} is not a valid map of non-empty strings to objects", maybeMap); return false; } } @SuppressWarnings("unchecked") private static boolean areNeededIntervalsProvided(Object builtInEnable, Object intervalMapping) { boolean enabled = (boolean) builtInEnable; // return false when enabled and map is empty return !(enabled && Utilities.isEmpty((Map<String, Number>) intervalMapping)); } @SuppressWarnings("unchecked") private static boolean isStartDelayEnough(List<Object> objects) { int tickInterval = (Integer) objects.get(0); int preStartDelayTicks = (Integer) objects.get(1); int minEmitEvery = (Integer) objects.get(2); return minEmitEvery >= tickInterval * (preStartDelayTicks + PRE_START_DELAY_BUFFER_TICKS); } }
53.04584
138
0.694725
5a8fb2196170a940b26e4486a2202022c326672a
1,433
/* * BooleanType.java * * Created on 19 de enero de 2004, 20:47 */ package com.innowhere.jnieasy.core.impl.common.classtype.model.mustbe.data; import com.innowhere.jnieasy.core.impl.common.classtype.model.ClassTypeNativeBooleanImpl; import com.innowhere.jnieasy.core.impl.common.classtype.model.ClassTypeManagerImpl; public class ClassTypeNativeBooleanObjectImpl extends ClassTypeNativePrimitiveObjectImpl { public static final Class CLASS = Boolean.class; /** Creates a new instance of BooleanType */ public ClassTypeNativeBooleanObjectImpl(ClassTypeManagerImpl classTypeMgr) { super(ClassTypeNativeBooleanImpl.getClassTypeNativeBoolean(classTypeMgr),classTypeMgr); } public static void registerClassTypeNativeBooleanObject(ClassTypeManagerImpl mgr) { ClassTypeNativeBooleanObjectImpl classType = new ClassTypeNativeBooleanObjectImpl(mgr); classType.registerClassType(); } public static ClassTypeNativeBooleanObjectImpl getClassTypeNativeBooleanObject(ClassTypeManagerImpl mgr) { return (ClassTypeNativeBooleanObjectImpl)mgr.findClassType(CLASS.getName()); } public String getVMClassName() { return CLASS.getName(); } public Class getDefaultImplClass() { return CLASS; } public Object newValueDefaultClass() { return Boolean.valueOf(false); } }
29.854167
108
0.732729
edd2d02f64e89c38114bdc5f0a26eebc18821586
1,161
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2018 Adobe * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.adobe.acs.commons.remoteassets; import com.adobe.granite.jmx.annotation.Description; /** * MBean interface for interacting with the Remote Asset Node Sync. */ @Description("Services for managing the Remote Asset nodes sync.") public interface RemoteAssetsNodeSyncTriggerMBean { /** * Method to run when triggering the syncAssetNodes() located in {@link RemoteAssetsNodeSync}. */ @Description("Executes remote asset node sync based on configured paths.") void syncAssetNodes(); }
32.25
98
0.727821
e777b75a3f1ec9ab13a5b270647e7196bd5320c3
510
class StringComparison { private static final String CONST = "foo"; public void test(String param) { String variable = "hello"; variable = param; String variable2 = "world"; variable2 += "it's me"; // OK if("" == "a") return; // OK if("" == param.intern()) return; // OK if("" == CONST) return; // OK if("".equals(variable)) return; // NOT OK if("" == variable) return; // NOT OK if("" == param) return; // NOT OK if("" == variable2) return; } }
15.454545
43
0.541176
c496b994c84c243a88f6dc3b65a0218532375e5a
5,324
/* * Copyright 2015 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.project.editor.variables; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.jface.viewers.AlwaysDeactivatingCellEditor; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.rf.ide.core.project.RobotProjectConfig.ReferencedVariableFile; import org.robotframework.ide.eclipse.main.plugin.RedWorkspace; import org.robotframework.ide.eclipse.main.plugin.project.RobotProjectConfigEvents; import org.robotframework.ide.eclipse.main.plugin.project.editor.RedProjectEditorInput; import org.robotframework.red.viewers.ElementsAddingEditingSupport; /** * @author Michal Anglart * */ class VariableFilesPathEditingSupport extends ElementsAddingEditingSupport { VariableFilesPathEditingSupport(final ColumnViewer viewer, final Supplier<ReferencedVariableFile> elementsCreator) { super(viewer, 0, elementsCreator); } @Override protected int getColumnShift() { return 1; } @Override protected CellEditor getCellEditor(final Object element) { return new AlwaysDeactivatingCellEditor((Composite) getViewer().getControl()); } @Override protected Object getValue(final Object element) { return null; } @Override protected void setValue(final Object element, final Object value) { if (element instanceof ReferencedVariableFile) { final VariableFileCreator variableFileCreator = (VariableFileCreator) elementsCreator; scheduleViewerRefreshAndEditorActivation( variableFileCreator.modifyExisting((ReferencedVariableFile) element)); } else { super.setValue(element, value); } } private static IEventBroker getEventBroker() { return PlatformUI.getWorkbench().getService(IEventBroker.class); } static class VariableFileCreator implements Supplier<ReferencedVariableFile> { private final Shell shell; private final RedProjectEditorInput editorInput; VariableFileCreator(final Shell shell, final RedProjectEditorInput editorInput) { this.shell = shell; this.editorInput = editorInput; } @Override public ReferencedVariableFile get() { final FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI); dialog.setFilterExtensions(new String[] { "*.py", "*.*" }); dialog.setFilterPath(editorInput.getRobotProject().getProject().getLocation().toPortableString()); ReferencedVariableFile firstFile = null; if (dialog.open() != null) { final List<ReferencedVariableFile> variableFiles = new ArrayList<>(); final String[] chosenFiles = dialog.getFileNames(); for (final String file : chosenFiles) { final IPath path = RedWorkspace.Paths .toWorkspaceRelativeIfPossible(new Path(dialog.getFilterPath())) .addTrailingSeparator() //add separator when filterPath is e.g. 'D:' .append(file); variableFiles.add(ReferencedVariableFile.create(path.toPortableString())); } for (final ReferencedVariableFile variableFile : variableFiles) { if (firstFile == null) { firstFile = variableFile; } editorInput.getProjectConfiguration().addReferencedVariableFile(variableFile); } getEventBroker().send(RobotProjectConfigEvents.ROBOT_CONFIG_VAR_FILE_STRUCTURE_CHANGED, variableFiles); } return firstFile; } ReferencedVariableFile modifyExisting(final ReferencedVariableFile varFile) { final FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI); dialog.setFilterExtensions(new String[] { "*.py", "*.*" }); final IPath startingPath = RedWorkspace.Paths .toAbsoluteFromWorkspaceRelativeIfPossible(new Path(varFile.getPath())).removeLastSegments(1); dialog.setFilterPath(startingPath.toPortableString()); final String chosenFile = dialog.open(); if (chosenFile != null) { final IPath path = RedWorkspace.Paths.toWorkspaceRelativeIfPossible(new Path(chosenFile)); varFile.setPath(path.toPortableString()); getEventBroker().send(RobotProjectConfigEvents.ROBOT_CONFIG_VAR_FILE_PATH_CHANGED, varFile); } return varFile; } } }
40.953846
120
0.660406
7d81fb4db4f4715ec60fc558c3eb628a1c091d2b
9,434
package es.udc.paproject.backend.rest.controllers; import static es.udc.paproject.backend.rest.dtos.ProgramConversor.toFullProgramDto; import static es.udc.paproject.backend.rest.dtos.ProgramConversor.toProgramDto; import static es.udc.paproject.backend.rest.dtos.ProgramConversor.toProgramDtos; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import es.udc.paproject.backend.model.common.exceptions.InstanceNotFoundException; import es.udc.paproject.backend.model.entities.Exercise; import es.udc.paproject.backend.model.entities.Program; import es.udc.paproject.backend.model.entities.User; import es.udc.paproject.backend.model.services.ExerciseService; import es.udc.paproject.backend.model.services.GroupService; import es.udc.paproject.backend.model.services.PermissionException; import es.udc.paproject.backend.model.services.ProgramService; import es.udc.paproject.backend.rest.dtos.FullProgramDto; import es.udc.paproject.backend.rest.dtos.ProgramDto; import es.udc.paproject.backend.rest.dtos.ProgramIdDto; import es.udc.paproject.backend.rest.dtos.ProgramParamsDto; import es.udc.paproject.backend.rest.dtos.ProgramParamsDto2; import es.udc.paproject.backend.rest.dtos.ProgramParamsDto3; @RestController @RequestMapping("/programs") public class ProgramController { @Autowired private ProgramService programService; @Autowired private ExerciseService exerciseService; @Autowired private GroupService groupService; @PostMapping("/create") public ProgramDto createProgram(@RequestAttribute Long userId, @RequestBody ProgramParamsDto programParamsDto) throws InstanceNotFoundException, PermissionException { if (!programParamsDto.getUserId().equals(userId)) { throw new PermissionException(); } return toProgramDto(programService.createProgram(programParamsDto.getUserId(), programParamsDto.getExerciseId(), programParamsDto.getProgramName(), programParamsDto.getProgramDesc(), programParamsDto.getCode(), programParamsDto.getPrivateProgram())); } @PostMapping("/delete") public void deleteProgram(@RequestAttribute Long userId, @RequestBody ProgramIdDto programIdDto) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programIdDto.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } programService.deleteProgram(programIdDto.getProgramId()); } @GetMapping("/{programId}") public ProgramDto getProgramInfo(@RequestAttribute Long userId, @PathVariable Long programId) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programId); if (program.getPrivateProgram()) { if (program.getUser().getId() != userId) { List<User> users = programService.getSharedUsersByProgram(programId); boolean shared = false; if (users.size() == 0) { throw new PermissionException(); } for (User user : users) { if (user.getId() == userId) { shared = true; } } if (!shared) { throw new PermissionException(); } } } return toProgramDto(program); } @GetMapping("/example") public ProgramDto getExampleProgram() throws InstanceNotFoundException { Program program = programService.getProgram((long)1); return toProgramDto(program); } @GetMapping("/fullinfo/{programId}") public FullProgramDto getProgramFullInfo(@RequestAttribute Long userId, @PathVariable Long programId) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programId); if (program.getUser().getId() != userId) { throw new PermissionException(); } return toFullProgramDto(program, programService.getSharedUsersByProgram(programId)); } @PutMapping("/update") public ProgramDto updateProgram(@RequestAttribute Long userId, @RequestBody ProgramParamsDto2 programParamsDto2) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programParamsDto2.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } return toProgramDto(programService.updateProgram(programParamsDto2.getProgramId(), programParamsDto2.getProgramName(), programParamsDto2.getProgramDesc(), programParamsDto2.getCode())); } @GetMapping("/all/{id}") public List<FullProgramDto> getAllProgramsByUser(@RequestAttribute Long userId, @PathVariable Long id) throws InstanceNotFoundException, PermissionException { if (!id.equals(userId)) { throw new PermissionException(); } List<Program> programs = programService.getProgramsByUser(id); List<FullProgramDto> fullProgramDtos = new ArrayList<>(); for (Program p : programs) { fullProgramDtos.add(toFullProgramDto(p, programService.getSharedUsersByProgram(p.getId()))); } return fullProgramDtos; } @PutMapping("/setpublic") public FullProgramDto setPublic(@RequestAttribute Long userId, @RequestBody ProgramIdDto programIdDto) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programIdDto.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } return toFullProgramDto(programService.setPublic(programIdDto.getProgramId()), programService.getSharedUsersByProgram(programIdDto.getProgramId())); } @PutMapping("/setprivate") public FullProgramDto setPrivate(@RequestAttribute Long userId, @RequestBody ProgramIdDto programIdDto) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programIdDto.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } return toFullProgramDto(programService.setPrivate(programIdDto.getProgramId()), programService.getSharedUsersByProgram(programIdDto.getProgramId())); } @GetMapping("/public/{userId}") public List<ProgramDto> getPublicProgramsByUser(@PathVariable Long userId) throws InstanceNotFoundException { return toProgramDtos(programService.getPublicProgramsByUser(userId)); } @PutMapping("/share") public void shareProgram(@RequestAttribute Long userId, @RequestBody ProgramParamsDto3 programParamsDto3 ) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programParamsDto3.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } programService.shareProgram(programParamsDto3.getUserId(), programParamsDto3.getProgramId()); } @PutMapping("/unshare") public void unshareProgram(@RequestAttribute Long userId, @RequestBody ProgramParamsDto3 programParamsDto3 ) throws InstanceNotFoundException, PermissionException { // Check permissions Program program = programService.getProgram(programParamsDto3.getProgramId()); if (program.getUser().getId() != userId) { throw new PermissionException(); } programService.unshareProgram(programParamsDto3.getUserId(), programParamsDto3.getProgramId()); } @GetMapping("/shared/{id}") public List<ProgramDto> getSharedProgramsByUser(@RequestAttribute Long userId, @PathVariable Long id) throws InstanceNotFoundException, PermissionException { if (!id.equals(userId)) { throw new PermissionException(); } return toProgramDtos(programService.getSharedProgramsWithMe(id)); } @GetMapping("/shared/{myUserId}/{otherUserId}") public List<ProgramDto> getSharedProgramsWithMeByUser(@RequestAttribute Long userId, @PathVariable Long myUserId, @PathVariable Long otherUserId) throws InstanceNotFoundException, PermissionException { if (!myUserId.equals(userId)) { throw new PermissionException(); } return toProgramDtos(programService.getSharedProgramsWithMeByUser(myUserId, otherUserId)); } @GetMapping("/search/{keyword}") public List<ProgramDto> getProgramsByKeyword(@PathVariable String keyword) { // Public programs only return toProgramDtos(programService.getProgramsByKeyword(keyword)); } @GetMapping("/exercise/{exerciseId}") public List<ProgramDto> getProgramsByExercise(@RequestAttribute Long userId, @PathVariable Long exerciseId) throws InstanceNotFoundException, PermissionException { // Check permissions Exercise exercise = exerciseService.getExercise(exerciseId); List<User> members = groupService.getAllUsersByGroup(exercise.getGroup().getId()); boolean isMember = false; for (User user : members) { if (user.getId() == userId) { isMember = true; } } if (!isMember) { throw new PermissionException(); } return toProgramDtos(programService.getProgramsByExercise(exerciseId)); } }
33.572954
97
0.780581
3e83a4fb09bab7818367d86fc073a81109d53eda
704
package com.paascloud.provider.model.vo; import com.paascloud.provider.model.dto.user.BindRoleDto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.Set; /** * The class Role bind user dto. * * @author paascloud.net@gmail.com */ @Data @ApiModel(value = "角色绑定用户") public class UserBindRoleVo implements Serializable { private static final long serialVersionUID = -2521583668470612548L; /** * 未绑定的用户集合 */ @ApiModelProperty(value = "所有用户集合") private Set<BindRoleDto> allRoleSet; /** * 已经绑定的用户集合 */ @ApiModelProperty(value = "已经绑定的用户集合") private Set<Long> alreadyBindRoleIdSet; }
21.333333
68
0.755682
47923e84d7a93f9087241fb1970ea1050cad8a55
8,980
/* * 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.mesos.util; import org.apache.flink.mesos.Utils; import org.apache.mesos.Protos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.ListIterator; import java.util.Set; import static org.apache.flink.mesos.Utils.UNRESERVED_ROLE; import static org.apache.flink.util.Preconditions.checkNotNull; /** * An allocation of resources on a particular host from one or more Mesos offers, to be portioned * out to tasks. * * <p>A typical offer contains a mix of reserved and unreserved resources. The below example depicts * 2 cpus reserved for 'myrole' plus 3 unreserved cpus for a total of 5 cpus: * * <pre>{@code * cpus(myrole):2.0; mem(myrole):4096.0; ports(myrole):[1025-2180]; * disk(*):28829.0; cpus(*):3.0; mem(*):10766.0; ports(*):[2182-3887,8082-8180,8182-32000] * }</pre> * * <p>This class assumes that the resources were offered <b>without</b> the {@code * RESERVATION_REFINEMENT} capability, as detailed in the "Resource Format" section of the Mesos * protocol definition. * * <p>This class is not thread-safe. */ public class MesosResourceAllocation { protected static final Logger LOG = LoggerFactory.getLogger(MesosResourceAllocation.class); static final double EPSILON = 1e-5; private final List<Protos.Resource> resources; /** * Creates an allocation of resources for tasks to take. * * @param resources the resources to add to the allocation. */ public MesosResourceAllocation(Collection<Protos.Resource> resources) { this.resources = new ArrayList<>(checkNotNull(resources)); // sort the resources to prefer reserved resources this.resources.sort(Comparator.comparing(r -> UNRESERVED_ROLE.equals(r.getRole()))); } /** Gets the remaining resources. */ public List<Protos.Resource> getRemaining() { return Collections.unmodifiableList(resources); } /** * Takes some amount of scalar resources (e.g. cpus, mem). * * @param amount the (approximate) amount to take from the available quantity. * @param roles the roles to accept */ public List<Protos.Resource> takeScalar(String resourceName, double amount, Set<String> roles) { if (LOG.isDebugEnabled()) { LOG.debug("Allocating {} {}", amount, resourceName); } List<Protos.Resource> result = new ArrayList<>(1); for (ListIterator<Protos.Resource> i = resources.listIterator(); i.hasNext(); ) { if (amount <= EPSILON) { break; } // take from next available scalar resource that is unreserved or reserved for an // applicable role Protos.Resource available = i.next(); if (!resourceName.equals(available.getName()) || !available.hasScalar()) { continue; } if (!UNRESERVED_ROLE.equals(available.getRole()) && !roles.contains(available.getRole())) { continue; } double amountToTake = Math.min(available.getScalar().getValue(), amount); Protos.Resource taken = available .toBuilder() .setScalar(Protos.Value.Scalar.newBuilder().setValue(amountToTake)) .build(); amount -= amountToTake; result.add(taken); if (LOG.isDebugEnabled()) { LOG.debug("Taking {} from {}", amountToTake, Utils.toString(available)); } // keep remaining amount (if any) double remaining = available.getScalar().getValue() - taken.getScalar().getValue(); if (remaining > EPSILON) { i.set( available .toBuilder() .setScalar(Protos.Value.Scalar.newBuilder().setValue(remaining)) .build()); } else { i.remove(); } } if (LOG.isDebugEnabled()) { LOG.debug("Allocated: {}, unsatisfied: {}", Utils.toString(result), amount); } return result; } /** * Takes some amount of range resources (e.g. ports). * * @param amount the number of values to take from the available range(s). * @param roles the roles to accept */ public List<Protos.Resource> takeRanges(String resourceName, int amount, Set<String> roles) { if (LOG.isDebugEnabled()) { LOG.debug("Allocating {} {}", amount, resourceName); } List<Protos.Resource> result = new ArrayList<>(1); for (ListIterator<Protos.Resource> i = resources.listIterator(); i.hasNext(); ) { if (amount <= 0) { break; } // take from next available range resource that is unreserved or reserved for an // applicable role Protos.Resource available = i.next(); if (!resourceName.equals(available.getName()) || !available.hasRanges()) { continue; } if (!UNRESERVED_ROLE.equals(available.getRole()) && !roles.contains(available.getRole())) { continue; } List<Protos.Value.Range> takenRanges = new ArrayList<>(); List<Protos.Value.Range> remainingRanges = new ArrayList<>(available.getRanges().getRangeList()); for (ListIterator<Protos.Value.Range> j = remainingRanges.listIterator(); j.hasNext(); ) { if (amount <= 0) { break; } // take from next available range (note: ranges are inclusive) Protos.Value.Range availableRange = j.next(); long amountToTake = Math.min(availableRange.getEnd() - availableRange.getBegin() + 1, amount); Protos.Value.Range takenRange = availableRange .toBuilder() .setEnd(availableRange.getBegin() + amountToTake - 1) .build(); amount -= amountToTake; takenRanges.add(takenRange); // keep remaining range (if any) long remaining = availableRange.getEnd() - takenRange.getEnd(); if (remaining > 0) { j.set(availableRange.toBuilder().setBegin(takenRange.getEnd() + 1).build()); } else { j.remove(); } } Protos.Resource taken = available .toBuilder() .setRanges(Protos.Value.Ranges.newBuilder().addAllRange(takenRanges)) .build(); if (LOG.isDebugEnabled()) { LOG.debug( "Taking {} from {}", Utils.toString(taken.getRanges()), Utils.toString(available)); } result.add(taken); // keep remaining ranges (if any) if (remainingRanges.size() > 0) { i.set( available .toBuilder() .setRanges( Protos.Value.Ranges.newBuilder() .addAllRange(remainingRanges)) .build()); } else { i.remove(); } } if (LOG.isDebugEnabled()) { LOG.debug("Allocated: {}, unsatisfied: {}", Utils.toString(result), amount); } return result; } @Override public String toString() { return "MesosResourceAllocation{" + "resources=" + Utils.toString(resources) + '}'; } }
38.212766
100
0.560579
f92b4ddf50a4922b74677f83803581452d348a53
382
public class SauceMozzarella extends Decorator { public SauceMozzarella(Interface pizza_interface) { super(pizza_interface); } public int price = 5; public String getDescription() { return super.getDescription() + "\n+ Mozarella = " + price + " euro"; } @Override public int getPrice() { return super.getPrice() + price; } }
25.466667
77
0.63089
721e4c0c1d28e8ae9786187f7c1d2a728502afe7
1,745
package com.qa.choonz.service; import com.qa.choonz.exception.ArtistNotFoundException; import com.qa.choonz.persistence.domain.Artist; import com.qa.choonz.persistence.repository.ArtistRepository; import com.qa.choonz.rest.dto.ArtistDTO; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class ArtistService { private final ArtistRepository repo; private final ModelMapper mapper; @Autowired public ArtistService(ArtistRepository repo, ModelMapper mapper) { super(); this.repo = repo; this.mapper = mapper; } private ArtistDTO mapToDTO(Artist artist) { return this.mapper.map(artist, ArtistDTO.class); } public ArtistDTO create(Artist artist) { Artist created = this.repo.save(artist); return this.mapToDTO(created); } public List<ArtistDTO> read() { return this.repo.findAll().stream().map(this::mapToDTO).collect(Collectors.toList()); } public ArtistDTO read(long id) { Artist found = this.repo.findById(id).orElseThrow(ArtistNotFoundException::new); return this.mapToDTO(found); } public ArtistDTO update(Artist artist, long id) { Artist toUpdate = this.repo.findById(id).orElseThrow(ArtistNotFoundException::new); toUpdate.setName(artist.getName()); toUpdate.setAlbums(artist.getAlbums()); Artist updated = this.repo.save(toUpdate); return this.mapToDTO(updated); } public boolean delete(long id) { this.repo.deleteById(id); return !this.repo.existsById(id); } }
30.086207
93
0.704298
d2b25ca3294fa0924e10f86d66ac93b9a1d3812f
7,694
// The Worker servlet should be mapped to the "/worker" URL. package student; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.util.logging.*; import com.google.appengine.api.datastore.*; import com.google.appengine.api.memcache.*; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.users.*; import com.google.appengine.api.datastore.Query.*; import java.util.*; import java.util.logging.*; import java.io.*; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.CompositeFilter; import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Entity; public class StudentWorker extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService sync = MemcacheServiceFactory.getMemcacheService(); /*String perm = request.getParameter("perm"); String lastName = request.getParameter("lastName"); String firstName = request.getParameter("firstName"); String email = request.getParameter("email"); String courseID = request.getParameter("courseID");*/ String courseID = request.getParameter("courseID"); String wholeInfor = request.getParameter("wholeInfor"); String[] stuInfor = wholeInfor.split(";"); for(int i=0;i<stuInfor.length;i++){ String[] singleInfor = stuInfor[i].split(","); String perm = singleInfor[0].trim(); String lastName = singleInfor[1].trim(); String firstName = singleInfor[2].trim(); String email = singleInfor[3].trim(); //String courseID = singleInfor[4].trim(); //add roster in course entity Filter propertyFilter1 = new FilterPredicate("courseID", FilterOperator.EQUAL, courseID); Query q1 = new Query("Course").setFilter(propertyFilter1); List<Entity> courses = datastore.prepare(q1).asList(FetchOptions.Builder.withDefaults()); for(Entity course : courses){ ArrayList<String> roster = (ArrayList<String>) course.getProperty("roster"); List<String> newRoster = new ArrayList<String>(); if(roster==null){ roster = new ArrayList<String>(); roster.add(perm); course.setProperty("roster", roster); datastore.put(course); } else{ roster.add(perm); course.setProperty("roster", roster); datastore.put(course); } } //create new student entity Filter propertyFilter = new FilterPredicate("email", FilterOperator.EQUAL, email); Query q = new Query("Student").setFilter(propertyFilter); List<Entity> students = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(students.size()!=0){ for(Entity student : students){ ArrayList<String> courseIDs = (ArrayList<String>) student.getProperty("courseID"); ArrayList<String> courseids = new ArrayList<String>(); if(courseIDs.size()!=0){ for(String courseid : courseIDs){ if(!courseid.equals(courseID)) courseids.add(courseid); } } courseids.add(courseID); student.setProperty("courseID", courseids); datastore.put(student); } } else{ // String userId = request.getParameter("userId"); // Do something with key. Entity student = new Entity("Student", perm); student.setProperty("perm", perm); student.setProperty("lastName", lastName); student.setProperty("firstName", firstName); student.setProperty("email", email); ArrayList<String> courseIDs = new ArrayList<String>(); courseIDs.add(courseID); student.setProperty("courseID", courseIDs); // student.setProperty("userId", userId); datastore.put(student); } } /*Filter propertyFilter1 = new FilterPredicate("courseID", FilterOperator.EQUAL, courseID); Query q1 = new Query("Course").setFilter(propertyFilter1); List<Entity> courses = datastore.prepare(q1).asList(FetchOptions.Builder.withDefaults()); for(Entity course : courses){ ArrayList<String> roster = (ArrayList<String>) course.getProperty("roster"); List<String> newRoster = new ArrayList<String>(); if(roster==null){ roster = new ArrayList<String>(); roster.add(perm); course.setProperty("roster", roster); datastore.put(course); } else{ roster.add(perm); course.setProperty("roster", roster); datastore.put(course); } }*/ /*Filter propertyFilter = new FilterPredicate("email", FilterOperator.EQUAL, email); Query q = new Query("Student").setFilter(propertyFilter); List<Entity> students = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(students.size()!=0){ for(Entity student : students){ ArrayList<String> courseIDs = (ArrayList<String>) student.getProperty("courseID"); ArrayList<String> courseids = new ArrayList<String>(); if(courseIDs.size()!=0){ for(String courseid : courseIDs){ if(!courseid.equals(courseID)) courseids.add(courseid); } } courseids.add(courseID); student.setProperty("courseID", courseids); datastore.put(student); } } else{ // String userId = request.getParameter("userId"); // Do something with key. Entity student = new Entity("Student", perm); student.setProperty("perm", perm); student.setProperty("lastName", lastName); student.setProperty("firstName", firstName); student.setProperty("email", email); ArrayList<String> courseIDs = new ArrayList<String>(); courseIDs.add(courseID); student.setProperty("courseID", courseIDs); // student.setProperty("userId", userId); datastore.put(student); }*/ } }
46.914634
103
0.579283
ffa7970e1c85dbffe74c68fd91700e18c94ee5a5
1,702
package datadog.trace.instrumentation.java.completablefuture; import static datadog.trace.agent.tooling.bytebuddy.matcher.DDElementMatchers.extendsClass; import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.nameStartsWith; import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named; import static datadog.trace.instrumentation.java.completablefuture.CompletableFutureUniCompletionInstrumentation.*; import static java.util.Collections.singletonMap; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; import com.google.auto.service.AutoService; import datadog.trace.agent.tooling.Instrumenter; import datadog.trace.bootstrap.instrumentation.java.concurrent.ConcurrentState; import java.util.Map; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; /** Described in {@link CompletableFutureUniCompletionInstrumentation} */ @AutoService(Instrumenter.class) public class CompletableFutureUniCompletionSubclassInstrumentation extends Instrumenter.Tracing { public CompletableFutureUniCompletionSubclassInstrumentation() { super("java_completablefuture", "java_concurrent"); } @Override public ElementMatcher<TypeDescription> typeMatcher() { return nameStartsWith(COMPLETABLE_FUTURE).and(extendsClass(named(UNI_COMPLETION))); } @Override public Map<String, String> contextStore() { return singletonMap(UNI_COMPLETION, ConcurrentState.class.getName()); } @Override public void adviceTransformations(AdviceTransformation transformation) { transformation.applyAdvice( named("tryFire").and(takesArguments(int.class)), ADVICE_BASE + "UniSubTryFire"); } }
41.512195
115
0.82785
d8fc442665c518d49760940a1c86326d97982574
80
package com.spbsu.flamestream.runtime.edge.api; public class BatchAccepted { }
16
47
0.8
ed196c967d3513303fe9e4742db7740282d52ea8
5,792
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import com.google.cloud.translate.Translate; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation; import com.google.cloud.language.v1.Document; import com.google.cloud.language.v1.LanguageServiceClient; import com.google.cloud.language.v1.Sentiment; import com.google.appengine.api.datastore.*; import com.google.appengine.api.datastore.Query.SortDirection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.sps.data.Comment; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that returns some example content. */ @WebServlet("/data") public class DataServlet extends HttpServlet { private static final List<String> ACCEPTED_LANGUAGES = Arrays.asList("EN", "ZH", "ES", "AR"); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String page = request.getParameter("file"); String maxNumString = getParameter(request, "max", "10"); String lang = getParameter(request, "lang", "EN"); if (!ACCEPTED_LANGUAGES.contains(lang)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("language not accepted"); return; } int maxNum = Integer.parseInt(maxNumString); Query query = new Query("Comment_" + page).addSort("timestamp", SortDirection.DESCENDING); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery results = datastore.prepare(query); List<Comment> comments = new ArrayList<>(); for (Entity entity : results.asIterable()) { long id = entity.getKey().getId(); String name = (String) entity.getProperty("name"); String comment = (String) entity.getProperty("comment"); long timestamp = (long) entity.getProperty("timestamp"); double sentimentScore = (double) entity.getProperty("sentimentScore"); Translate translate = TranslateOptions.getDefaultInstance().getService(); Translation translation = translate.translate(comment, Translate.TranslateOption.targetLanguage(lang)); String translatedText = translation.getTranslatedText(); Comment commentData = new Comment(id, name, translatedText, new Date(timestamp), sentimentScore); comments.add(commentData); } comments = comments.subList(0, Math.min(comments.size(), maxNum)); String json = convertToJsonUsingGson(comments); // Send the JSON as the response response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;"); response.getWriter().println(json); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // adds comment to specific blog post String name = getParameter(request, "name", "A random person"); String comment = getParameter(request, "comment", "Unspecified comment"); String page = getParameter(request, "page", ""); long timestamp = System.currentTimeMillis(); Document doc = Document.newBuilder().setContent(comment).setType(Document.Type.PLAIN_TEXT).build(); LanguageServiceClient languageService = LanguageServiceClient.create(); Sentiment sentiment = languageService.analyzeSentiment(doc).getDocumentSentiment(); double sentimentScore = sentiment.getScore(); languageService.close(); Entity commentEntity = new Entity("Comment_" + page); commentEntity.setProperty("name", name); commentEntity.setProperty("comment", comment); commentEntity.setProperty("timestamp", timestamp); commentEntity.setProperty("sentimentScore", sentimentScore); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(commentEntity); response.sendRedirect("/blog/?" + page); } private String convertToJsonUsingGson(List<Comment> commentData) { // dates are converted to unix epoch time Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date( json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive( date.getTime())) .create(); return gson.toJson(commentData); } /** * @return the request parameter, or the default value if the parameter was not specified by the * client */ private String getParameter(HttpServletRequest request, String name, String defaultValue) { String value = request.getParameter(name); if (value == null) { return defaultValue; } return value; } }
38.357616
99
0.731699
e1869068eedf106bc9e2c9e3c4bfdc524ddf5b00
5,892
package com.cisco.axlsamples; // Performs a <getPhone> operation and extracts the 'product' type // using the AXL API. // Copyright (c) 2019 Cisco and/or its affiliates. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import javax.xml.ws.BindingProvider; import java.security.cert.X509Certificate; import java.util.Map; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; // Import only the AXL package modules needed for this sample import com.cisco.axlsamples.api.AXLAPIService; import com.cisco.axlsamples.api.AXLPort; import com.cisco.axlsamples.api.GetPhoneReq; import com.cisco.axlsamples.api.GetPhoneRes; // Dotenv for Java import io.github.cdimascio.dotenv.Dotenv; // To import the entire AXL package contents: // // import com.cisco.axlsamples.api.*; public class getPhone { public static void main(String[] args) { // Retrieve environment variables from .env, if present Dotenv dotenv = Dotenv.load(); Boolean debug = dotenv.get( "DEBUG" ).equals( "True" ); if ( debug ) { System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true"); // Increase the dump output permitted size System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dumpTreshold", "999999"); } // Verify the JVM has a console for user input if (System.console() == null) { System.err.println("Error: This sample app requires a console"); System.exit(1); } // Instantiate the generated AXL API Service client AXLAPIService axlService = new AXLAPIService(); // Get access to the request context so we can set custom params AXLPort axlPort = axlService.getAXLPort(); Map< String, Object > requestContext = ( ( BindingProvider ) axlPort ).getRequestContext(); // Set the AXL API endpoint address, user, and password // for our particular environment in the JAX-WS client. // Configure these values in .env requestContext.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://" + dotenv.get( "CUCM" ) + ":8443/axl/"); requestContext.put( BindingProvider.USERNAME_PROPERTY, dotenv.get( "AXL_USER" ) ); requestContext.put( BindingProvider.PASSWORD_PROPERTY, dotenv.get( "AXL_PASSWORD" ) ); // Enable cookies for AXL authentication session reuse requestContext.put( BindingProvider.SESSION_MAINTAIN_PROPERTY, true ); // Uncomment the section below to disable HTTPS certificate checking, // otherwise import the CUCM Tomcat certificate - see README.md // X509TrustManager[] trustAll = new X509TrustManager[] { new X509TrustManager() { // public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } // public void checkClientTrusted( X509Certificate[] arg0, String arg1) throws CertificateException { }; // public void checkServerTrusted( X509Certificate[] arg0, String arg1) throws CertificateException { }; // } // }; // SSLContext context = SSLContext.getInstance( "TLS" ); // context.init( null, trustAll, new java.security.SecureRandom() ); // provider.getRequestContext().put( "com.sun.xml.ws.transport.https.client.SSLSocketFactory", context.getSocketFactory() ); // Use a local trust store file to validate HTTPS certificates. // Requires importing the CUCM Tomcat certificate from CUCM into file certificate/local_truststore, see README.md System.setProperty( "javax.net.ssl.trustStore", "certificate/cacerts" ); System.setProperty( "javax.net.ssl.trustStorePassword", "changeit" ); // Create a new <getPhone> request object GetPhoneReq req = new GetPhoneReq(); // Get the device name to retrieve from the user via the console String phoneName = System.console().readLine("%nPhone device name to retrieve: "); req.setName(phoneName); // Prepare a GetPhoneRes object to receive the response from AXL GetPhoneRes getPhoneResponse; // Execute the request, wrapped in try/catch in case an exception is thrown try { getPhoneResponse = axlPort.getPhone(req); // Dive into the response object's hierarchy to retrieve the <product> value System.console().format("%nPhone product type is: " + getPhoneResponse.getReturn().getPhone().getProduct() + "%n%n"); } catch (Exception err) { // If an exception occurs, dump the stacktrace to the console err.printStackTrace(); } } }
46.761905
132
0.692804
dafb40212061aa6f6a069c7fb188daab012913cd
8,999
/* * Free Public License 1.0.0 * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.atr.spacerocks.effects; import com.atr.spacerocks.control.BodyCont; import com.atr.spacerocks.gameobject.Player; import com.atr.spacerocks.effects.particles.LaserParticles; import com.atr.spacerocks.gameobject.powerup.BlackHole; import com.atr.spacerocks.sound.SoundFX; import com.atr.spacerocks.state.GameState; import com.atr.spacerocks.util.SRay; import com.atr.spacerocks.util.Tools; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Vector3f; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; /** * * @author Adam T. Ryder * <a href="http://1337atr.weebly.com">http://1337atr.weebly.com</a> */ public class LaserCannons { private static final float minSpawnTime = 0.1f; private static final float maxSpawnTime = 0.2f; private final Player player; private final GameState gameState; private final Vector3f laser1 = new Vector3f(-1.12324f, 0, -5.04729f); private final Vector3f laser2 = new Vector3f(1.12324f, 0, -5.04729f); private final Vector3f tmpV = new Vector3f(); private final Vector3f tmpV2 = new Vector3f(); private final Vector3f tmp = new Vector3f(); private boolean side1 = true; private final CollisionResults collisionResults = new CollisionResults(); private final Ray ray = new Ray(); private final SRay sRay = new SRay(); private final Vector3f velocity = new Vector3f(0, 0, 250); private final LaserBeam[] lasers = new LaserBeam[32]; private short lastDeadLaser = 0; private int count = 0; private final LaserParticles mesh; private final Geometry laserGeom; private float spawnTime = maxSpawnTime; private float force = 0; public LaserCannons(Player player, GameState gameState) { this.player = player; this.gameState = gameState; for (int i = 0; i < lasers.length; i++) { LaserBeam beam = new LaserBeam(); beam.lastDead = (short)(i + 1); beam.index = (short)i; lasers[i] = beam; } lasers[lasers.length - 1].lastDead = 0; mesh = new LaserParticles(lasers); laserGeom = new Geometry("Laser Beams", mesh); Material mat = new Material(gameState.getApp().getAssetManager(), "MatDefs/Unshaded/circle_glow.j3md"); mat.setColor("Color", new ColorRGBA(1f, 0.749f, 0.455f, 1f)); mat.setColor("Color2", new ColorRGBA(1f, 0.143f, 0.031f, 0.5f)); mat.setColor("Color3", new ColorRGBA(1f, 0f, 0f, 0f)); mat.setFloat("Pos1", 0.134f); mat.setFloat("Pos2", 0.648f); laserGeom.setMaterial(mat); laserGeom.setQueueBucket(RenderQueue.Bucket.Transparent); laserGeom.setCullHint(Spatial.CullHint.Never); gameState.getApp().getRootNode().attachChild(laserGeom); } public void reCenter(Vector3f center) { //laserGeom.setLocalTranslation(0, 0, 0); for (LaserBeam beam : lasers) { beam.loc.subtractLocal(center); } } public void update(float tpf) { for (LaserBeam beam : lasers) { if (beam.alive) beam.update(tpf); } spawnBeams(tpf); mesh.updateMesh(lasers); } private void spawnBeams(float tpf) { spawnTime += tpf; if (!gameState.getHUD().isFiring()) { if (spawnTime > maxSpawnTime) spawnTime = maxSpawnTime; return; } float nextSpawn = ((maxSpawnTime - minSpawnTime) * (1 - gameState.getHUD().getEnergy())) + minSpawnTime; gameState.getHUD().setEnergyPercent(gameState.getHUD().getEnergy() - (0.02f * tpf)); if (spawnTime < nextSpawn) return; /*do { spawnTime -= nextSpawn; } while(spawnTime >= nextSpawn);*/ spawnTime = 0; tmpV.set(side1 ? laser1 : laser2); side1 = !side1; player.spatial.getChild(0).localToWorld(tmpV, tmpV); count = 0; LaserBeam beam = null; do { LaserBeam b = lasers[lastDeadLaser]; lastDeadLaser = b.lastDead; if (!b.alive) { beam = b; break; } count++; } while (count < lasers.length); if (beam == null) return; beam.set(tmpV, player.spatial.getLocalRotation()); SoundFX.playLaser(gameState.getApp().getAssetManager()); } public class LaserBeam { private final float maxZ = GameState.FIELDHEIGHTHALF + GameState.ASTEROID_PADDING + GameState.ASTEROID_PADDING; private final float maxX = ((GameState.FIELDHEIGHT * ((float)gameState.getApp().getWidth() / gameState.getApp().getHeight())) / 2f) + GameState.ASTEROID_PADDING + GameState.ASTEROID_PADDING; public final Vector3f loc = new Vector3f(); public final Quaternion rot = new Quaternion(); public boolean alive = false; public short lastDead = 0; public short index = 0; private LaserBeam() { } private void set(Vector3f loc, Quaternion rot) { this.loc.set(loc); this.rot.set(rot); alive = true; } private void update(float tpf) { velocity.mult(tpf, tmpV); rot.mult(tmpV, tmpV); tmpV.addLocal(loc); for (BlackHole bh : gameState.getTracker().getBlackHoles()) { if (!bh.getController().isActive()) continue; bh.getController().getSpatial().getLocalTranslation() .subtract(tmpV, tmp).normalizeLocal(); force = Tools.GRAVITATIONALCONSTANT * ((BlackHole.MASS * 0.04f) / FastMath.sqr(tmpV.distance(bh.getController() .getSpatial().getLocalTranslation()) / 2)) * tpf; tmp.multLocal(force); tmpV.addLocal(tmp); sRay.set(loc, tmpV.subtract(loc, tmp)); if (sRay.intersectsCircle(bh.getLocation(), BlackHole.SINGULARITY, tmp)) { alive = false; break; } } if (alive) { rot.lookAt(tmpV.subtract(loc, tmp), Vector3f.UNIT_Y); tmpV2.set(0, 0, LaserParticles.getLength() + tmpV.distance(loc)); rot.mult(tmpV2, tmpV2); tmpV2.addLocal(loc); float limit = tmpV2.distance(loc); tmpV2.subtractLocal(loc); collisionResults.clear(); ray.setOrigin(loc); ray.setDirection(tmpV2.normalizeLocal()); ray.setLimit(limit); gameState.collideNode.collideWith(ray, collisionResults); for (CollisionResult hit : collisionResults) { BodyCont cont = hit.getGeometry().getUserData(BodyCont.key); if (cont != null && cont.weaponHit(tmpV2.normalizeLocal())) { gameState.getTracker().laserDestroy(); alive = false; break; } } } if (alive) { loc.set(tmpV); tmpV.subtractLocal(player.spatial.getLocalTranslation()); alive = !(tmpV.x > maxX || tmpV.x < -maxX || tmpV.z > maxZ || tmpV.z < -maxZ); } if (alive) return; if (lastDead != lastDeadLaser) lastDead = lastDeadLaser; lastDeadLaser = index; } } }
35.152344
96
0.567063