hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923134cc0edc5daaad6b63222be3e54aa7b7ff2a
504
java
Java
opencron-common/src/main/java/org/opencron/common/exception/UnknownException.java
LantenGao/opencron
2e291b0733dc8bc15e998421d59450f1038858c1
[ "Apache-2.0" ]
19
2018-12-25T08:50:10.000Z
2022-01-13T11:43:21.000Z
opencron-common/src/main/java/org/opencron/common/exception/UnknownException.java
hitechr/opencron
be352e95d202a5b128cab342f27e829b9732aa30
[ "Apache-2.0" ]
null
null
null
opencron-common/src/main/java/org/opencron/common/exception/UnknownException.java
hitechr/opencron
be352e95d202a5b128cab342f27e829b9732aa30
[ "Apache-2.0" ]
11
2018-12-25T08:50:12.000Z
2022-01-13T11:43:23.000Z
18
67
0.746032
995,750
package org.opencron.common.exception; /** * 未知异常 * * @author wanghuajie 2012.8.23 */ public class UnknownException extends BasicException { private static final long serialVersionUID = 9108301934211924250L; public UnknownException() { super(); } public UnknownException(String msg) { super(msg); } public UnknownException(Throwable nestedThrowable) { super(nestedThrowable); } public UnknownException(String msg, Throwable nestedThrowable) { super(msg, nestedThrowable); } }
9231353ba1ff6025cb49f824aaf7156a46715cce
4,305
java
Java
forge/addons/openshift/src/test/java/io/fabric8/forge/openshift/GitHelpersTest.java
hekonsek/fabric8
c3988ff4f06fdf4752e1f08a55bcad17eb27f34e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
forge/addons/openshift/src/test/java/io/fabric8/forge/openshift/GitHelpersTest.java
hekonsek/fabric8
c3988ff4f06fdf4752e1f08a55bcad17eb27f34e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
forge/addons/openshift/src/test/java/io/fabric8/forge/openshift/GitHelpersTest.java
hekonsek/fabric8
c3988ff4f06fdf4752e1f08a55bcad17eb27f34e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
42.386139
92
0.555711
995,751
/** * 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 * <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 io.fabric8.forge.openshift; import io.fabric8.openshift.api.model.BuildConfig; import io.fabric8.openshift.api.model.ImageStream; import io.fabric8.utils.cxf.JsonHelper; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; /** */ public class GitHelpersTest { @Test public void testExtractGitUrlFromOnlyRemote() throws Exception { assertExtractGitUrl("envkt@example.com:fabric8io/example-camel-cdi.git", "[core]\n" + "\trepositoryformatversion = 0\n" + "\tfilemode = true\n" + "\tbare = false\n" + "\tlogallrefupdates = true\n" + "\tignorecase = true\n" + "\tprecomposeunicode = true\n" + "[remote \"origin\"]\n" + "\turl = envkt@example.com:fabric8io/example-camel-cdi.git\n" + "\tfetch = +refs/heads/*:refs/remotes/origin/*\n" + "[branch \"master\"]\n" + "\tremote = origin\n" + "\tmerge = refs/heads/master"); } @Test public void testExtractGitUrlFromOrigin() throws Exception { assertExtractGitUrl("envkt@example.com:jstrachan/fabric8.git", "[core]\n" + " repositoryformatversion = 0\n" + " filemode = true\n" + " bare = false\n" + " logallrefupdates = true\n" + " ignorecase = true\n" + " precomposeunicode = true\n" + "[remote \"upstream\"]\n" + " url = envkt@example.com:fabric8io/fabric8.git\n" + " fetch = +refs/heads/*:refs/remotes/upstream/*\n" + "[remote \"origin\"]\n" + " url = envkt@example.com:jstrachan/fabric8.git\n" + " fetch = +refs/heads/*:refs/remotes/origin/*\n"); } @Test public void testExtractGitUrlFromFirstWhenNoOrigin() throws Exception { assertExtractGitUrl("envkt@example.com:fabric8io/fabric8.git", "[core]\n" + " repositoryformatversion = 0\n" + " filemode = true\n" + " bare = false\n" + " logallrefupdates = true\n" + " ignorecase = true\n" + " precomposeunicode = true\n" + "[remote \"upstream\"]\n" + " url = envkt@example.com:fabric8io/fabric8.git\n" + " fetch = +refs/heads/*:refs/remotes/upstream/*\n" + "[remote \"cheese\"]\n" + " url = envkt@example.com:jstrachan/fabric8.git\n" + " fetch = +refs/heads/*:refs/remotes/origin/*\n"); } @Test public void testExtractGitUrlWhenNoRemote() throws Exception { assertExtractGitUrl(null, "[core]\n" + " repositoryformatversion = 0\n" + " filemode = true\n" + " bare = false\n" + " logallrefupdates = true\n" + " ignorecase = true\n" + " precomposeunicode = true\n"); } public static void assertExtractGitUrl(String expectedUrl, String gitConfigText) { String actual = GitHelpers.extractGitUrl(gitConfigText); assertEquals("Expected git url from config: " + gitConfigText, expectedUrl, actual); } }
923135e346eaca912f433a550bfdc183107431c8
732
java
Java
src/main/java/org/przybyl/logs/web/EncodingFilter.java
pioorg/loggerWebSample
9bb6bb6302cfa5cb7ae67df56a2ea602342148f8
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/przybyl/logs/web/EncodingFilter.java
pioorg/loggerWebSample
9bb6bb6302cfa5cb7ae67df56a2ea602342148f8
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/przybyl/logs/web/EncodingFilter.java
pioorg/loggerWebSample
9bb6bb6302cfa5cb7ae67df56a2ea602342148f8
[ "BSD-2-Clause" ]
null
null
null
25.241379
82
0.644809
995,752
package org.przybyl.logs.web; import javax.servlet.*; import java.io.IOException; /** * Created by Piotr Przybył (hzdkv@example.com) on 2017-05-07. */ public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { //NOOP } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } @Override public void destroy() { //NOOP } }
923135f5cd46c5aed1b7d2f9a37e330b593ce574
2,455
java
Java
src/main/com/sailthru/client/SailthruUtil.java
kryptx/sailthru-java-client
c1847a83fff2b2736776d2479b48b040a1547a8f
[ "MIT" ]
6
2015-04-28T16:48:36.000Z
2021-12-16T10:54:41.000Z
src/main/com/sailthru/client/SailthruUtil.java
kryptx/sailthru-java-client
c1847a83fff2b2736776d2479b48b040a1547a8f
[ "MIT" ]
19
2015-02-19T13:38:45.000Z
2022-01-25T20:55:35.000Z
src/main/com/sailthru/client/SailthruUtil.java
kryptx/sailthru-java-client
c1847a83fff2b2736776d2479b48b040a1547a8f
[ "MIT" ]
17
2015-02-17T21:19:26.000Z
2021-07-30T20:41:35.000Z
31.883117
142
0.624847
995,753
package com.sailthru.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.codec.digest.DigestUtils; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * few static utility methods * @author Prajwal Tuladhar <envkt@example.com> */ public class SailthruUtil { public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; /** * generates MD5 Hash * @param data parameter data * @return MD5 hashed string */ public static String md5(String data) { try { return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return DigestUtils.md5Hex(data.toString()); } } /** * Converts String ArrayList to CSV string * @param list List of String to create a CSV string * @return CSV string */ public static String arrayListToCSV(List<String> list) { StringBuilder csv = new StringBuilder(); for (String str : list) { csv.append(str); csv.append(","); } int lastIndex = csv.length() - 1; char last = csv.charAt(lastIndex); if (last == ',') { return csv.substring(0, lastIndex); } return csv.toString(); } public static Gson createGson() { return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) .create(); } /** * Add a new image entry to the images map. * * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry * @param key key for the map, either "full" or "thumb" * @param url url for the image to use * @return a new map instance of the images parameter was null otherwise the updated map. */ public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { if (images == null) { images = new HashMap<String, Map<String, String>>(); } Map<String, String> urlMap = new HashMap<String, String>(); urlMap.put("url", url); images.put(key, urlMap); return images; } }
923136adc45da259728f115eb499012ed0b764b0
6,874
java
Java
jive-sdk/src/main/java/com/jivesoftware/sdk/api/entity/JiveInstance.java
yingjieg/jive-sdk-java-jersey
93648c6d2680862400d67b609265c9bc9a525d13
[ "Apache-2.0" ]
11
2015-03-12T23:30:06.000Z
2021-05-22T06:58:07.000Z
jive-sdk/src/main/java/com/jivesoftware/sdk/api/entity/JiveInstance.java
albertlr/jive-sdk-java-jersey
de0930115f31a656ab6877eb07b8013ca491bd5d
[ "Apache-2.0" ]
1
2015-01-19T06:55:36.000Z
2015-01-19T06:55:36.000Z
jive-sdk/src/main/java/com/jivesoftware/sdk/api/entity/JiveInstance.java
albertlr/jive-sdk-java-jersey
de0930115f31a656ab6877eb07b8013ca491bd5d
[ "Apache-2.0" ]
11
2015-03-11T15:29:17.000Z
2018-05-02T16:27:48.000Z
32.578199
119
0.61769
995,754
/* * * * Copyright 2013 Jive Software * * * * 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.jivesoftware.sdk.api.entity; import com.jivesoftware.sdk.client.oauth.OAuthCredentials; import com.jivesoftware.sdk.client.oauth.OAuthCredentialsSupport; import com.jivesoftware.sdk.service.instance.action.InstanceRegisterAction; import javax.persistence.*; import java.io.Serializable; /** * Represents a Jive instance where this add-on has been installed * Created by rrutan on 1/30/14. */ @Entity public class JiveInstance implements OAuthCredentialsSupport, Serializable { @Id @GeneratedValue @Column(name = "jive_instance_id") private Long id; private String tenantId = null; private String jiveSignatureURL = null; private String timestamp = null; private String jiveUrl = null; private String jiveSignature = null; private String clientSecret = null; private String clientId = null; private String code = null; private String scope = null; @Embedded private OAuthCredentials credentials = null; public JiveInstance() { credentials = new OAuthCredentials(); } // end constructor public JiveInstance(InstanceRegisterAction instance) { this(); this.tenantId = instance.getTenantId(); this.jiveSignatureURL = instance.getJiveSignatureURL(); this.timestamp = instance.getTimestamp(); this.jiveUrl = instance.getJiveUrl(); this.jiveSignature = instance.getJiveSignature(); this.clientSecret = instance.getClientSecret(); this.clientId = instance.getClientId(); this.code = instance.getCode(); this.scope = instance.getScope(); } // end constructor public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getJiveSignatureURL() { return jiveSignatureURL; } public void setJiveSignatureURL(String jiveSignatureURL) { this.jiveSignatureURL = jiveSignatureURL; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getJiveUrl() { return jiveUrl; } public void setJiveUrl(String jiveUrl) { this.jiveUrl = jiveUrl; } public String getJiveSignature() { return jiveSignature; } public void setJiveSignature(String jiveSignature) { this.jiveSignature = jiveSignature; } public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public OAuthCredentials getCredentials() { return credentials; } public void setCredentials(OAuthCredentials credentials) { this.credentials = credentials; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JiveInstance that = (JiveInstance) o; if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) return false; if (clientSecret != null ? !clientSecret.equals(that.clientSecret) : that.clientSecret != null) return false; if (code != null ? !code.equals(that.code) : that.code != null) return false; if (credentials != null ? !credentials.equals(that.credentials) : that.credentials != null) return false; if (jiveSignature != null ? !jiveSignature.equals(that.jiveSignature) : that.jiveSignature != null) return false; if (jiveSignatureURL != null ? !jiveSignatureURL.equals(that.jiveSignatureURL) : that.jiveSignatureURL != null) return false; if (jiveUrl != null ? !jiveUrl.equals(that.jiveUrl) : that.jiveUrl != null) return false; if (scope != null ? !scope.equals(that.scope) : that.scope != null) return false; if (tenantId != null ? !tenantId.equals(that.tenantId) : that.tenantId != null) return false; if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) return false; return true; } @Override public int hashCode() { int result = tenantId != null ? tenantId.hashCode() : 0; result = 31 * result + (jiveSignatureURL != null ? jiveSignatureURL.hashCode() : 0); result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0); result = 31 * result + (jiveUrl != null ? jiveUrl.hashCode() : 0); result = 31 * result + (jiveSignature != null ? jiveSignature.hashCode() : 0); result = 31 * result + (clientSecret != null ? clientSecret.hashCode() : 0); result = 31 * result + (clientId != null ? clientId.hashCode() : 0); result = 31 * result + (code != null ? code.hashCode() : 0); result = 31 * result + (scope != null ? scope.hashCode() : 0); result = 31 * result + (credentials != null ? credentials.hashCode() : 0); return result; } @Override public String toString() { return "JiveInstance{" + "tenantId='" + tenantId + '\'' + ", jiveSignatureURL='" + jiveSignatureURL + '\'' + ", timestamp='" + timestamp + '\'' + ", jiveUrl='" + jiveUrl + '\'' + ", jiveSignature='" + jiveSignature + '\'' + ", clientSecret='" + clientSecret + '\'' + ", clientId='" + clientId + '\'' + ", code='" + code + '\'' + ", scope='" + scope + '\'' + ", credentials=" + credentials + '}'; } }
923136ce45d4b9d9254694cd57fdf3da7508072d
6,757
java
Java
modules/core/src/test/java/org/apache/ignite/internal/metric/CacheMetricsAddRemoveTest.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/core/src/test/java/org/apache/ignite/internal/metric/CacheMetricsAddRemoveTest.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/core/src/test/java/org/apache/ignite/internal/metric/CacheMetricsAddRemoveTest.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
32.023697
119
0.674264
995,755
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.metric; import java.util.Arrays; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.jetbrains.annotations.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.cacheMetricsRegistryName; import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName; /** */ @RunWith(Parameterized.class) public class CacheMetricsAddRemoveTest extends GridCommonAbstractTest { /** */ public static final String CACHE_GETS = "CacheGets"; /** */ public static final String CACHE_PUTS = "CachePuts"; /** Cache modes. */ @Parameterized.Parameters(name = "cacheMode={0},nearEnabled={1}") public static Iterable<Object[]> params() { return Arrays.asList( new Object[] {CacheMode.PARTITIONED, false}, new Object[] {CacheMode.PARTITIONED, true}, new Object[] {CacheMode.REPLICATED, false}, new Object[] {CacheMode.REPLICATED, true} ); } /** . */ @Parameterized.Parameter(0) public CacheMode mode; /** Use index. */ @Parameterized.Parameter(1) public boolean nearEnabled; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { return super.getConfiguration(igniteInstanceName) .setDataStorageConfiguration(new DataStorageConfiguration() .setDataRegionConfigurations( new DataRegionConfiguration().setName("persisted").setPersistenceEnabled(true))); } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { cleanPersistenceDir(); startGridsMultiThreaded(2); IgniteConfiguration clientCfg = getConfiguration("client") .setClientMode(true); startGrid(clientCfg); } /** */ @Test public void testCacheMetricsAddRemove() throws Exception { String cachePrefix = cacheMetricsRegistryName(DEFAULT_CACHE_NAME, false); checkMetricsEmpty(cachePrefix); createCache(); checkMetricsNotEmpty(cachePrefix); destroyCache(); checkMetricsEmpty(cachePrefix); } /** */ @Test public void testCacheMetricsNotRemovedOnStop() throws Exception { String cachePrefix = cacheMetricsRegistryName("other-cache", false); checkMetricsEmpty(cachePrefix); createCache("persisted", "other-cache"); grid("client").cache("other-cache").put(1L, 1L); checkMetricsNotEmpty(cachePrefix); //Cache will be stopped during deactivation. grid("client").cluster().state(ClusterState.INACTIVE); checkMetricsNotEmpty(cachePrefix); grid("client").cluster().state(ClusterState.ACTIVE); assertEquals(1L, grid("client").cache("other-cache").get(1L)); checkMetricsNotEmpty(cachePrefix); destroyCache(); checkMetricsEmpty(cachePrefix); } /** */ private void destroyCache() throws InterruptedException { IgniteEx client = grid("client"); for (String name : client.cacheNames()) client.destroyCache(name); awaitPartitionMapExchange(); } /** */ private void createCache() throws InterruptedException { createCache(null, null); } /** */ private void createCache(@Nullable String dataRegionName, @Nullable String cacheName) throws InterruptedException { CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME); if (dataRegionName != null) ccfg.setDataRegionName(dataRegionName); if (cacheName != null) ccfg.setName(cacheName); if (nearEnabled) ccfg.setNearConfiguration(new NearCacheConfiguration()); grid("client").createCache(ccfg); awaitPartitionMapExchange(); } /** */ private void checkMetricsNotEmpty(String cachePrefix) { for (int i = 0; i < 2; i++) { GridMetricManager mmgr = metricManager(i); MetricRegistry mreg = mmgr.registry(cachePrefix); assertNotNull(mreg.findMetric(CACHE_GETS)); assertNotNull(mreg.findMetric(CACHE_PUTS)); if (nearEnabled) { mreg = mmgr.registry(metricName(cachePrefix, "near")); assertNotNull(mreg.findMetric(CACHE_GETS)); assertNotNull(mreg.findMetric(CACHE_PUTS)); } } } /** */ private void checkMetricsEmpty(String cachePrefix) { for (int i = 0; i < 3; i++) { GridMetricManager mmgr = metricManager(i); MetricRegistry mreg = mmgr.registry(cachePrefix); assertNull(mreg.findMetric(metricName(cachePrefix, CACHE_GETS))); assertNull(mreg.findMetric(metricName(cachePrefix, CACHE_PUTS))); if (nearEnabled) { mreg = mmgr.registry(metricName(cachePrefix, "near")); assertNull(mreg.findMetric(CACHE_GETS)); assertNull(mreg.findMetric(CACHE_PUTS)); } } } /** */ private GridMetricManager metricManager(int gridIdx) { if (gridIdx < 2) return grid(0).context().metric(); else return grid("client").context().metric(); } }
9231387e58753159068ada1ead485f216cb466a3
405
java
Java
parallel-tasks-exec-framework/src/main/java/com/asksunny/tasks/ParallePartitioner.java
devsunny/app-galleries
98aed1b18031ded93056ad12bda5b2c62c40a85b
[ "MIT" ]
null
null
null
parallel-tasks-exec-framework/src/main/java/com/asksunny/tasks/ParallePartitioner.java
devsunny/app-galleries
98aed1b18031ded93056ad12bda5b2c62c40a85b
[ "MIT" ]
15
2020-05-15T21:00:34.000Z
2022-01-21T23:19:52.000Z
parallel-tasks-exec-framework/src/main/java/com/asksunny/tasks/ParallePartitioner.java
devsunny/app-galleries
98aed1b18031ded93056ad12bda5b2c62c40a85b
[ "MIT" ]
1
2016-03-09T18:35:46.000Z
2016-03-09T18:35:46.000Z
20.25
77
0.681481
995,756
package com.asksunny.tasks; import java.util.List; public interface ParallePartitioner { public void init(String[] args); /** * If negative or 0 return, TaskMaster will wait forever; otherwise it will * wait until the specified time. TaskAgent may chose to kill the * partitionedtask * * @return */ public long getTimeout(); public List<String[]> doPartition(); }
923139e87b7b5730243368491de9bb40cfdd504f
1,498
java
Java
src/main/java/models/CaesarCipher.java
ubelyse/CaesarCipher
4eba8a5c63b5055d8466b344d326b60475f1d78a
[ "Unlicense" ]
null
null
null
src/main/java/models/CaesarCipher.java
ubelyse/CaesarCipher
4eba8a5c63b5055d8466b344d326b60475f1d78a
[ "Unlicense" ]
null
null
null
src/main/java/models/CaesarCipher.java
ubelyse/CaesarCipher
4eba8a5c63b5055d8466b344d326b60475f1d78a
[ "Unlicense" ]
null
null
null
26.280702
118
0.593458
995,757
package models; public class CaesarCipher { String chara; int numbe; public CaesarCipher(String chara, int numbe) { this.chara = chara; this.numbe = numbe; } public String getChara() { return chara; } public void setChara(String chara) { this.chara = chara; } public int getNumbe() { return numbe; } public void setNumbe(int numbe) { this.numbe = numbe; } public static char rotateEndofAlphabet(char y, int a) { final int lengthofalphabets = 26; //ascii has different codes according to letter so this line is checking whether letter is upper or lower case final char asciiShift = Character.isUpperCase(y) ? 'A' : 'a'; final int caesarciphershift = a % lengthofalphabets; char shifted = (char) (y - asciiShift); // this line is for rotating the letter shifted = (char) ((shifted + caesarciphershift + lengthofalphabets) % lengthofalphabets); return (char) (shifted + asciiShift); } // Rotating normally public String rotateEndofAlphabet(){ StringBuilder stringBuilder=new StringBuilder(); for(int i=0;i<chara.length();i++){ if (chara.charAt(i)==' '){ stringBuilder.append(""); } else { stringBuilder.append(rotateEndofAlphabet(chara.charAt(i), numbe)); } } return stringBuilder.toString(); } }
92313a1293db0f4e7c40846745e48c196ef8ff1c
11,513
java
Java
src/main/java/com/tabeldata/dao/SkpdDao.java
arraisi/resource-api-blud
e992ab0f2dc323db34ad4eee0c4e7be62fec5209
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tabeldata/dao/SkpdDao.java
arraisi/resource-api-blud
e992ab0f2dc323db34ad4eee0c4e7be62fec5209
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tabeldata/dao/SkpdDao.java
arraisi/resource-api-blud
e992ab0f2dc323db34ad4eee0c4e7be62fec5209
[ "Apache-2.0" ]
null
null
null
52.570776
144
0.540259
995,758
package com.tabeldata.dao; import com.tabeldata.dto.SkpdPersetujuanDto; import com.tabeldata.entity.SkpdEntity; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; import java.util.Map; @Slf4j @Repository public class SkpdDao { @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public SkpdEntity getSkpdById(Integer skpdId) throws EmptyResultDataAccessException { String sql = "select I_ID AS id,\n" + " I_IDINDUK AS idInduk,\n" + " C_SKPD AS kodeSkpd,\n" + " C_UNITKERJA AS kodeUnitKerja,\n" + " N_SKPD AS namaSkpd,\n" + " N_SKPD_PENDEK AS namaSingkatSkpd,\n" + " C_BLUD AS blud,\n" + " C_AKTIF AS statusAktif,\n" + " C_TAHUN_BERLAKU AS tahunBerlaku,\n" + " C_TAHUN_BERAKHIR AS tahunBerakhir,\n" + " I_PGUN_REKAM AS idRekamPengguna,\n" + " D_PGUN_REKAM AS tanggalRekamPengguna,\n" + " I_PGUN_UBAH AS idUbahPengguna,\n" + " D_REKAM_UBAH AS tanggalUbahPengguna\n" + "from TRRBASKPD\n" + "WHERE I_ID = :vId"; Map<String, Object> param = new HashMap<>(); param.put("vId", skpdId); return this.namedParameterJdbcTemplate.queryForObject(sql, param, (rs, i) -> { SkpdEntity skpdEntity = new SkpdEntity(); skpdEntity.setId(rs.getInt("id")); skpdEntity.setIdInduk(rs.getInt("idInduk")); skpdEntity.setKodeSkpd(rs.getString("kodeSkpd")); skpdEntity.setKodeUnitKerja(rs.getString("kodeUnitKerja")); skpdEntity.setNamaSkpd(rs.getString("namaSkpd")); skpdEntity.setNamaSingkatSkpd(rs.getString("namaSingkatSkpd")); skpdEntity.setBlud(rs.getString("blud")); skpdEntity.setStatusAktif(rs.getString("statusAktif")); skpdEntity.setTahunBerlaku(rs.getString("tahunBerlaku")); skpdEntity.setTahunBerakhir(rs.getString("tahunBerakhir")); skpdEntity.setIdRekamPengguna(rs.getInt("idRekamPengguna")); skpdEntity.setTanggalRekamPengguna(rs.getTimestamp("tanggalRekamPengguna")); skpdEntity.setIdUbahPengguna(rs.getInt("idUbahPengguna")); skpdEntity.setTanggalUbahPengguna(rs.getTimestamp("tanggalUbahPengguna")); return skpdEntity; }); } public List<SkpdPersetujuanDto> getListSkpdPersetujuan(String tahunAnggaran) throws DataAccessException { String sql = "select skpd.I_ID AS id,\n" + " skpd.I_IDINDUK AS idInduk,\n" + " skpd.C_SKPD AS kodeSkpd,\n" + " skpd.C_UNITKERJA AS kodeUnitKerja,\n" + " skpd.N_SKPD AS namaSkpd,\n" + " skpd.N_SKPD_PENDEK AS namaSingkatSkpd,\n" + " skpd.C_BLUD AS blud,\n" + " skpd.C_AKTIF AS statusAktif,\n" + " skpd.C_TAHUN_BERLAKU AS tahunBerlaku,\n" + " skpd.C_TAHUN_BERAKHIR AS tahunBerakhir,\n" + " skpd.I_PGUN_REKAM AS idRekamPengguna,\n" + " skpd.D_PGUN_REKAM AS tanggalRekamPengguna,\n" + " skpd.I_PGUN_UBAH AS idUbahPengguna,\n" + " skpd.D_REKAM_UBAH AS tanggalUbahPengguna,\n" + " (select SUM(NVL(kegiatan.V_ANGG_TAPD, 0))\n" + " from TRRBASKPD sk\n" + " join TMRBAKEGIATAN kegiatan on sk.I_ID = kegiatan.I_IDSKPD\n" + " where sk.I_ID = skpd.I_ID\n" + " and C_ANGG_TAHUN = :tahun) AS totalAnggaran,\n" + " (select r.C_STATDINAS_APPV\n" + " from TMRBA r\n" + " where r.I_IDSKPD = skpd.I_ID\n" + " and r.C_ANGG_TAHUN = :tahun) AS statusDinas\n" + "from TRRBASKPD skpd\n" + "where skpd.C_AKTIF = '1'\n" + " and skpd.C_BLUD = '1'"; Map<String, Object> param = new HashMap<>(); param.put("tahun", tahunAnggaran); return this.namedParameterJdbcTemplate.query(sql, param, (rs, i) -> { SkpdPersetujuanDto skpdEntity = new SkpdPersetujuanDto(); skpdEntity.setId(rs.getInt("id")); skpdEntity.setIdInduk(rs.getInt("idInduk")); skpdEntity.setKodeSkpd(rs.getString("kodeSkpd")); skpdEntity.setKodeUnitKerja(rs.getString("kodeUnitKerja")); skpdEntity.setNamaSkpd(rs.getString("namaSkpd")); skpdEntity.setNamaSingkatSkpd(rs.getString("namaSingkatSkpd")); skpdEntity.setBlud(rs.getString("blud")); skpdEntity.setStatusAktif(rs.getString("statusAktif")); skpdEntity.setTahunBerlaku(rs.getString("tahunBerlaku")); skpdEntity.setTahunBerakhir(rs.getString("tahunBerakhir")); skpdEntity.setIdRekamPengguna(rs.getInt("idRekamPengguna")); skpdEntity.setTanggalRekamPengguna(rs.getTimestamp("tanggalRekamPengguna")); skpdEntity.setIdUbahPengguna(rs.getInt("idUbahPengguna")); skpdEntity.setTanggalUbahPengguna(rs.getTimestamp("tanggalUbahPengguna")); skpdEntity.setTotalAnggaran(rs.getBigDecimal("totalAnggaran")); skpdEntity.setStatusDinasId(rs.getString("statusDinas")); skpdEntity.setStatusDinasName(mapperStatusAppv(rs.getString("statusDinas") != null ? rs.getString("statusDinas") : "-")); skpdEntity.setStatusDinasBadge(mapperStatusAppvColorBadge(rs.getString("statusDinas") != null ? rs.getString("statusDinas") : "-")); return skpdEntity; }); } public List<SkpdPersetujuanDto> getListSkpdPersetujuanByIdSkpd(String tahunAnggaran, Integer skpdId) throws DataAccessException { String sql = "select skpd.I_ID AS id,\n" + " skpd.I_IDINDUK AS idInduk,\n" + " skpd.C_SKPD AS kodeSkpd,\n" + " skpd.C_UNITKERJA AS kodeUnitKerja,\n" + " skpd.N_SKPD AS namaSkpd,\n" + " skpd.N_SKPD_PENDEK AS namaSingkatSkpd,\n" + " skpd.C_BLUD AS blud,\n" + " skpd.C_AKTIF AS statusAktif,\n" + " skpd.C_TAHUN_BERLAKU AS tahunBerlaku,\n" + " skpd.C_TAHUN_BERAKHIR AS tahunBerakhir,\n" + " skpd.I_PGUN_REKAM AS idRekamPengguna,\n" + " skpd.D_PGUN_REKAM AS tanggalRekamPengguna,\n" + " skpd.I_PGUN_UBAH AS idUbahPengguna,\n" + " skpd.D_REKAM_UBAH AS tanggalUbahPengguna,\n" + " (select SUM(NVL(kegiatan.V_ANGG_TAPD, 0))\n" + " from TRRBASKPD sk\n" + " join TMRBAKEGIATAN kegiatan on sk.I_ID = kegiatan.I_IDSKPD\n" + " where sk.I_ID = skpd.I_ID\n" + " and C_ANGG_TAHUN = :tahun) AS totalAnggaran,\n" + " (select r.C_STATDINAS_APPV\n" + " from TMRBA r\n" + " where r.I_IDSKPD = skpd.I_ID\n" + " and r.C_ANGG_TAHUN = :tahun) AS statusDinas\n" + "from TRRBASKPD skpd\n" + "where skpd.C_AKTIF = '1'\n" + " and skpd.C_BLUD = '1'\n" + " and skpd.I_ID = :vSkpdId"; Map<String, Object> param = new HashMap<>(); param.put("tahun", tahunAnggaran); param.put("vSkpdId", skpdId); return this.namedParameterJdbcTemplate.query(sql, param, (rs, i) -> { SkpdPersetujuanDto skpdEntity = new SkpdPersetujuanDto(); skpdEntity.setId(rs.getInt("id")); skpdEntity.setIdInduk(rs.getInt("idInduk")); skpdEntity.setKodeSkpd(rs.getString("kodeSkpd")); skpdEntity.setKodeUnitKerja(rs.getString("kodeUnitKerja")); skpdEntity.setNamaSkpd(rs.getString("namaSkpd")); skpdEntity.setNamaSingkatSkpd(rs.getString("namaSingkatSkpd")); skpdEntity.setBlud(rs.getString("blud")); skpdEntity.setStatusAktif(rs.getString("statusAktif")); skpdEntity.setTahunBerlaku(rs.getString("tahunBerlaku")); skpdEntity.setTahunBerakhir(rs.getString("tahunBerakhir")); skpdEntity.setIdRekamPengguna(rs.getInt("idRekamPengguna")); skpdEntity.setTanggalRekamPengguna(rs.getTimestamp("tanggalRekamPengguna")); skpdEntity.setIdUbahPengguna(rs.getInt("idUbahPengguna")); skpdEntity.setTanggalUbahPengguna(rs.getTimestamp("tanggalUbahPengguna")); skpdEntity.setTotalAnggaran(rs.getBigDecimal("totalAnggaran")); skpdEntity.setStatusDinasId(rs.getString("statusDinas")); skpdEntity.setStatusDinasName(mapperStatusAppv(rs.getString("statusDinas") != null ? rs.getString("statusDinas") : "-")); skpdEntity.setStatusDinasBadge(mapperStatusAppvColorBadge(rs.getString("statusDinas") != null ? rs.getString("statusDinas") : "-")); return skpdEntity; }); } public String mapperStatusAppv(String id) { String status; switch (id) { case "0": status = "Baru"; break; case "1": status = "Dikirim"; break; case "2": status = "Diterima"; break; case "3": status = "Ditolak"; break; case "4": status = "Revisi"; break; default: status = "Tidak Ditemukan"; } return status; } public String mapperStatusAppvColorBadge(String id) { String statusColor; switch (id) { case "0": statusColor = "badge-secondary"; break; case "1": statusColor = "badge-green"; break; case "2": statusColor = "badge-blue"; break; case "3": statusColor = "badge-red"; break; case "4": statusColor = "badge-yellow"; break; default: statusColor = "badge-secondary"; } return statusColor; } }
92313a6a2d0999cb119a904207ce5a11c6621629
61,098
java
Java
src/main/java/de/dlr/ivf/tapas/plan/TPS_Plan.java
DLR-VF/TAPAS
f4c7f7ab10eee23ed8c56f23995d074059cdf211
[ "MIT" ]
9
2020-12-02T13:32:08.000Z
2021-11-17T04:56:44.000Z
src/main/java/de/dlr/ivf/tapas/plan/TPS_Plan.java
DLR-VF/TAPAS
f4c7f7ab10eee23ed8c56f23995d074059cdf211
[ "MIT" ]
43
2020-12-02T14:02:21.000Z
2021-11-04T11:13:19.000Z
src/main/java/de/dlr/ivf/tapas/plan/TPS_Plan.java
DLR-VF/TAPAS
f4c7f7ab10eee23ed8c56f23995d074059cdf211
[ "MIT" ]
5
2020-12-02T13:39:10.000Z
2022-03-22T13:47:23.000Z
43.209335
201
0.555877
995,759
/* * Copyright (c) 2020 DLR Institute of Transport Research * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package de.dlr.ivf.tapas.plan; import de.dlr.ivf.tapas.constants.TPS_ActivityConstant; import de.dlr.ivf.tapas.constants.TPS_ActivityConstant.TPS_ActivityCodeType; import de.dlr.ivf.tapas.constants.TPS_ActivityConstant.TPS_ActivityConstantAttribute; import de.dlr.ivf.tapas.constants.TPS_AgeClass.TPS_AgeCodeType; import de.dlr.ivf.tapas.constants.TPS_DrivingLicenseInformation; import de.dlr.ivf.tapas.constants.TPS_Income; import de.dlr.ivf.tapas.constants.TPS_SettlementSystem.TPS_SettlementSystemType; import de.dlr.ivf.tapas.loc.TPS_Location; import de.dlr.ivf.tapas.log.LogHierarchy; import de.dlr.ivf.tapas.log.TPS_Logger; import de.dlr.ivf.tapas.log.TPS_LoggingInterface.HierarchyLogLevel; import de.dlr.ivf.tapas.log.TPS_LoggingInterface.SeverenceLogLevel; import de.dlr.ivf.tapas.mode.TPS_ExtMode; import de.dlr.ivf.tapas.persistence.TPS_PersistenceManager; import de.dlr.ivf.tapas.person.TPS_Car; import de.dlr.ivf.tapas.person.TPS_Household; import de.dlr.ivf.tapas.person.TPS_Person; import de.dlr.ivf.tapas.scheme.*; import de.dlr.ivf.tapas.util.ExtendedWritable; import de.dlr.ivf.tapas.util.TPS_AttributeReader.TPS_Attribute; import de.dlr.ivf.tapas.util.Timeline; import de.dlr.ivf.tapas.util.parameters.*; import java.io.IOException; import java.io.Writer; import java.util.*; import java.util.Map.Entry; /** * Class for a TAPAS plan. * Contains trips, budgets, and many more stuff for plan related work */ @LogHierarchy(hierarchyLogLevel = HierarchyLogLevel.PLAN) public class TPS_Plan implements ExtendedWritable, Comparable<TPS_Plan> { /// The environment for this plan public TPS_PlanEnvironment pe; public List<TPS_Car> usedCars = new LinkedList<>(); public boolean usesBike = false; public boolean mustPayToll = false; HashMap<TPS_Attribute, Integer> myAttributes = new HashMap<>(); /// Fix (reused) locations Map<TPS_ActivityConstant, TPS_Location> fixLocations = new HashMap<>(); /// The reference to the persistence manager private TPS_PersistenceManager PM = null; /// private double budgetAcceptanceProbability, timeAcceptanceProbability, acceptanceProbability; /// Adapted Episode, which is currently under work private TPS_AdaptedEpisode currentAdaptedEpisode; /// Map of located stays for stays during this plan private final Map<TPS_Stay, TPS_LocatedStay> locatedStays; /// A map of planned trips so far private final Map<TPS_Trip, TPS_PlannedTrip> plannedTrips; /// the actual selected scheme private final TPS_Scheme scheme; /// the feasibility flag private boolean feasible = false; /// variable for time adaptation analysis private int adapt = 0; /// variable for time adaptation differenceanalysis private int adaptAbsSum = 0; /** * Constructor for this class * * @param person the person the scheme was selected for * @param pe * @param schemeIn the scheme selected for the person * @param pm reference to the persistence manager for db-access */ public TPS_Plan(TPS_Person person, TPS_PlanEnvironment pe, TPS_Scheme schemeIn, TPS_PersistenceManager pm) { this.pe = pe; this.PM = pm; this.locatedStays = new HashMap<>(); this.plannedTrips = new TreeMap<>(new Comparator<TPS_Trip>() { public int compare(TPS_Trip trip1, TPS_Trip trip2) { return trip1.getOriginalStart() - trip2.getOriginalStart(); } }); this.scheme = schemeIn.clone(); myAttributes.put(TPS_Attribute.HOUSEHOLD_INCOME_CLASS_CODE, TPS_Income.getCode(person.getHousehold().getIncome())); myAttributes.put(TPS_Attribute.PERSON_AGE, person.getAge()); myAttributes.put(TPS_Attribute.PERSON_AGE_CLASS_CODE_PERSON_GROUP, person.getPersonGroup().getCode()); myAttributes.put(TPS_Attribute.PERSON_AGE_CLASS_CODE_STBA, person.getAgeClass().getCode(TPS_AgeCodeType.STBA)); int code; if (person.hasDrivingLicenseInformation()) { code = person.getDrivingLicenseInformation().getCode(); } else { if (person.getAge() >= 18) { code = TPS_DrivingLicenseInformation.CAR.getCode(); } else { code = TPS_DrivingLicenseInformation.NO_DRIVING_LICENSE.getCode(); } } if (code == 0) { //BUGFIX: no driving license is coded in MID2008 as 2! code = 2; } myAttributes.put(TPS_Attribute.PERSON_DRIVING_LICENSE_CODE, code); myAttributes.put(TPS_Attribute.CURRENT_TAZ_SETTLEMENT_CODE_TAPAS, person.getHousehold().getLocation().getTrafficAnalysisZone().getBbrType() .getCode(TPS_SettlementSystemType.TAPAS)); myAttributes.put(TPS_Attribute.PERSON_AGE_CLASS_CODE_STBA, person.getAgeClass().getCode(TPS_AgeCodeType.STBA)); myAttributes.put(TPS_Attribute.PERSON_HAS_BIKE, person.hasBike() ? 1 : 0); myAttributes.put(TPS_Attribute.HOUSEHOLD_CARS, person.getHousehold() .getNumberOfCars()); // TODO: note that this is set once again in selectLocationsAndModesAndTravelTimes myAttributes.put(TPS_Attribute.PERSON_SEX_CLASS_CODE, person.getSex().getCode()); if (this.scheme != null) { for (TPS_Episode e : this.scheme.getEpisodeIterator()) { if (e.isStay()) { TPS_Stay stay = (TPS_Stay) e; TPS_LocatedStay locatedStay = new TPS_LocatedStay(this, stay); if (stay.isAtHome()) { locatedStay.setLocation(person.getHousehold().getLocation()); } this.locatedStays.put(stay, locatedStay); } else { TPS_Trip trip = (TPS_Trip) e; this.plannedTrips.put(trip, new TPS_PlannedTrip(this, trip, this.getPM().getParameters())); } } } } public TPS_Plan(TPS_Plan src) { this.pe = src.pe; this.PM = src.PM; src.usedCars.addAll(this.usedCars); this.locatedStays = new HashMap<>(); this.plannedTrips = new TreeMap<>(Comparator.comparingInt(TPS_Episode::getOriginalStart)); // same as(trip1, trip2) -> trip1.getOriginalStart() - trip2.getOriginalStart() this.scheme = src.scheme; // TODO: clarify: scheme is not changed after being adapted to the person (student hack or whatever) once for (TPS_Attribute attr : src.myAttributes.keySet()) { this.myAttributes.put(attr, src.myAttributes.get(attr)); } for (TPS_Stay stay : src.locatedStays.keySet()) { TPS_LocatedStay locStay = new TPS_LocatedStay(this, stay); this.locatedStays.put(stay, locStay); if (src.isLocated(stay)) { locStay.setLocation(src.locatedStays.get(stay).getLocation()); } } for (TPS_Episode e : this.scheme.getEpisodeIterator()) { if (e.isStay()) { continue; } TPS_Trip trip = (TPS_Trip) e; this.plannedTrips.put(trip, new TPS_PlannedTrip(this, trip, this.getPM().getParameters())); } } /** * Returns whether the given car may be used for this plan * * @param car The car to use * @return Whether the given car may be used */ public boolean allowsCar(TPS_Car car) { double dist = 0; for (TPS_SchemePart schemePart : this.scheme) { //collect car specific distances if (schemePart.isTourPart()) { TPS_Car c = ((TPS_TourPart) schemePart).getCar(); if (c != null) { //trip with car dist += ((TPS_TourPart) schemePart).getTourpartDistance(); } } } return car.getRangeLeft() > dist; } /** * Function tries to modify the scheme in such way, that the travel times and duration of the stays do not vary too * much from the initial times reported. This is done by varying the timing (duration / start / end) of the episodes * within the varianze reported for similar schemes * * @return 0 > error (no adoption), !0 > OK */ public int balanceStarts() { int absAdaptation = 0; TPS_Episode reference = null, act; TPS_AdaptedEpisode actAdapted = null; for (TPS_SchemePart schemePart : this.scheme) { if (schemePart.isTourPart()) { TPS_TourPart tourpart = (TPS_TourPart) schemePart; act = tourpart.getPriorisedStayIterable().iterator().next(); if (reference == null || ((TPS_Stay) reference).compareTo(((TPS_Stay) act)) < 0) { reference = act; } } } if (reference != null) { //adopt all previous act = reference; actAdapted = this.getAdaptedEpisode(act); do { //get estimated start int endOfLastEpisode = actAdapted.getStart(); //go one back act = act.getSchemePart().getPreviousEpisode(act); if (act != null) { actAdapted = this.getAdaptedEpisode(act); //get duration int duration = actAdapted.getDuration(); //statistics this.adapt += actAdapted.getEnd() - endOfLastEpisode; absAdaptation += Math.abs(actAdapted.getEnd() - endOfLastEpisode); this.adaptAbsSum += absAdaptation; //set new start actAdapted.setStart(endOfLastEpisode - duration); } } while (act != null); //adopt allsucceding act = reference; actAdapted = this.getAdaptedEpisode(act); do { //get estimated start int startOfNextEpisode = actAdapted.getEnd(); //go one further act = act.getSchemePart().getNextEpisode(act); if (act != null) { actAdapted = this.getAdaptedEpisode(act); //get duration double start = actAdapted.getStart(); //statistics this.adapt += start - startOfNextEpisode; absAdaptation += Math.abs(start - startOfNextEpisode); this.adaptAbsSum += absAdaptation; //set new start actAdapted.setStart(startOfNextEpisode); } } while (act != null); } int lastStart = Integer.MIN_VALUE, start; TPS_PlannedTrip pt; for (TPS_TourPart tp : this.scheme.getTourPartIterator()) { for (TPS_Trip t : tp.getTripIterator()) { pt = this.getPlannedTrip(t); start = pt.getStart(); if (start <= lastStart) { TPS_Logger.log(SeverenceLogLevel.WARN, "Same or earlier start of episode detected! last:" + lastStart + " act:" + start); start = lastStart + 1; pt.setStart(start); } lastStart = start; } } return absAdaptation; } /** * This method returns if the selected plan is feasible. * If any start of a stay/trip is after the end of the previous trip/stay it returns false. * If everythig is ok or there are no stays or trips it returns true. * * @return result if this plan is feasible */ public void calcPlanFeasiblity() { feasible = true; Timeline tl = new Timeline(); int start = 0, end = 0; Vector<TPS_Episode> sortedEpisodes = new Vector<>(); //copy episodes from iterator to vector for (TPS_Episode e : this.scheme.getEpisodeIterator()) { sortedEpisodes.add(e); } //sort episodes according original start time sortedEpisodes.sort(Comparator.comparingInt(TPS_Episode::getOriginalStart)); //insert episodes in the timeline double dist = 0; for (TPS_Episode e : sortedEpisodes) { TPS_AdaptedEpisode es = this.getAdaptedEpisode(e); if (es.isPlannedTrip()) dist += es.getDistance(); //set minimum duration! if (es.getDuration() < this.PM.getParameters().getIntValue(ParamValue.SEC_TIME_SLOT)) es.setDuration( this.PM.getParameters().getIntValue(ParamValue.SEC_TIME_SLOT)); start = es.getStart(); end = es.getDuration() + es.getStart(); //if(start<0||end<0){ //quick bugfix for negative start times // feasible = false; // break; //} if (!tl.add(start, end)) { feasible = false; break; } } boolean bookCar = feasible; if (bookCar && //disable car booking for COST_OPTIMUM sorting this.PM.getParameters().isDefined(ParamString.HOUSEHOLD_MEMBERSORTING) && this.PM.getParameters().getString(ParamString.HOUSEHOLD_MEMBERSORTING).equalsIgnoreCase( TPS_Household.Sorting.COST_OPTIMUM.name())) { bookCar = false; } //now we check if the cars are used and if they have enough range to fullfill the plan if (bookCar) { Map<TPS_Car, Double> cars = new HashMap<>(); for (TPS_SchemePart schemePart : this.scheme) { //collect car specific distances if (schemePart.isTourPart()) { TPS_Car car = ((TPS_TourPart) schemePart).getCar(); if (car != null) { //trip with car dist = 0; if (cars.containsKey(car)) { dist = cars.get(car); } cars.put(car, dist + ((TPS_TourPart) schemePart).getTourpartDistance()); } } } //now check every used car, if it has enough range left for (Entry<TPS_Car, Double> e : cars.entrySet()) { if (e.getKey().getRangeLeft() < e.getValue()) { // not enough? feasible = false; break; } } } } /** * compare Plans according to their acceptance probability */ public int compareTo(TPS_Plan o) { return this.getAcceptanceProbability() > o.getAcceptanceProbability() ? 1 : -1; } /** * Method to create the output for log-file * * @return */ public List<List<String>> createOutput() { List<List<String>> outList = new ArrayList<>(); TPS_Stay nextStay, prevStay; TPS_PlannedTrip plannedTrip; int personID = pe.getPerson().getId(); int schemeID = scheme.getId(); int sex = pe.getPerson().getSex().ordinal(); int mainActivity; double hHIncome = pe.getPerson().getHousehold().getIncome(); int numberOfPersonsHH = pe.getPerson().getHousehold().getNumberOfMembers(); for (TPS_TourPart tour : this.scheme.getTourPartIterator()) { //get highest priority trip if (tour.getPriorisedStayIterable().iterator().hasNext()) mainActivity = tour.getPriorisedStayIterable().iterator().next().getActCode().getCode( TPS_ActivityCodeType.ZBE); else mainActivity = -999; for (TPS_Trip trip : tour.getTripIterator()) { List<String> out = new ArrayList<>(); plannedTrip = this.getPlannedTrip(trip); nextStay = plannedTrip.getTrip().getSchemePart().getNextStay(trip); prevStay = plannedTrip.getTrip().getSchemePart().getPreviousStay(trip); out.add(Integer.toString(personID)); // PersonID out.add(Integer.toString(schemeID)); // SchemeID out.add(Integer.toString(pe.getPerson().getPersonGroup().getCode())); // job out.add(Integer.toString(mainActivity)); // actCode // fahrten haben keine Aktivitätencodes! daher: Aktivitätencode der nächsten location int actCode = nextStay.getActCode().getCode(TPS_ActivityCodeType.ZBE); // TODO Mantis 0002615 if (actCode == 410 && pe.getPerson().isStudent()) actCode = 411; out.add(Integer.toString(actCode)); // actCode out.add(Integer.toString(pe.getPerson().getAgeClass().getCode(TPS_AgeCodeType.STBA))); // ageCat out.add(Integer.toString(sex)); // sex // TAZ departure out.add(Integer.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .getTAZId())); // TAZ arrival out.add(Integer.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .getTAZId())); // is next stay AtHome out.add(Integer.toString(nextStay.isAtHome() ? 1 : 0)); // id of Mode of Trip out.add(Integer.toString(plannedTrip.getMode().getMCTCode())); // bee line Distance out.add(Integer.toString((int) plannedTrip.getDistanceBeeline())); // Distance out.add(Double.toString(Math.round(plannedTrip.getDistance()))); // netDistance out.add(Double.toString(Math.round(plannedTrip.getDistanceEmptyNet()))); // travel time out.add(Integer.toString(plannedTrip.getDuration())); // HouseHold Income out.add(Integer.toString(TPS_Income.getCode(hHIncome))); // Number of Persons Household out.add(Integer.toString(numberOfPersonsHH)); // Coming Block ID if (this.getLocatedStay(prevStay).getLocation().hasBlock()) { out.add(Integer.toString(this.getLocatedStay(prevStay).getLocation().getBlock().getId())); } else { out.add("0"); } // going Block ID if (this.getLocatedStay(nextStay).getLocation().hasBlock()) { out.add(Integer.toString(this.getLocatedStay(nextStay).getLocation().getBlock().getId())); } else { out.add("0"); } // coming X Coordinate out.add(Double.toString(this.getLocatedStay(prevStay).getLocation().getCoordinate().getValue(0))); // coming Y Coordinate out.add(Double.toString(this.getLocatedStay(prevStay).getLocation().getCoordinate().getValue(1))); // going X Coordinate out.add(Double.toString(this.getLocatedStay(nextStay).getLocation().getCoordinate().getValue(0))); // going Y Coordinate out.add(Double.toString(this.getLocatedStay(nextStay).getLocation().getCoordinate().getValue(1))); // startTime // Die in myStart abgelegte Zeit ist in Sekunden nach mitternacht abgelegt;übersetzten in Minuten nach // Mitternacht int time = (int) (plannedTrip.getStart() * 1.66666666e-2); out.add(Double.toString(time)); // FOBIRD departure out.add(Integer.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .getBbrType().getCode(TPS_SettlementSystemType.FORDCP))); // FOBIRD going out.add(Integer.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .getBbrType().getCode(TPS_SettlementSystemType.FORDCP))); // coming Has Toll out.add(Boolean.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .hasToll(SimulationType.SCENARIO))); // going Has Toll out.add(Boolean.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .hasToll(SimulationType.SCENARIO))); // locId int locId = Math.max(-1, this.getLocatedStay(nextStay).getLocation().getId()); out.add(Integer.toString(locId)); outList.add(out); } } return outList; } /** * Method to look if a trip of this plan enters a restricted area * * @return true if it enters a restricted area */ public boolean entersRestrictedAreas() { for (TPS_LocatedStay stay : locatedStays.values()) { if (stay.isLocated() && stay.getLocation().getTrafficAnalysisZone().isRestricted()) { return true; } } return false; } /** * Gets the general acceptance probability based on the deviation of the travel time compared to the original travel time. * * @return A value between 0 and 1 describing the acceptance */ public double getAcceptanceProbability() { return acceptanceProbability; } /** * Sets the general acceptance probability based on the deviation of the travel time compared to the original travel time. * * @param acceptanceProbability A value between 0 and 1 describing the acceptance */ public void setAcceptanceProbability(double acceptanceProbability) { this.acceptanceProbability = acceptanceProbability; } /** * gets the adapted episode for the given key * * @param key key for the episode to look for * @return null if key is not in the planed trips or located stays */ public TPS_AdaptedEpisode getAdaptedEpisode(TPS_Episode key) { if (key.isStay()) { return locatedStays.get(key); } else { return plannedTrips.get(key); } } /** * Getter for a specific attribute value. Throws a runtime exception, if the value is not set! * * @param att The attribute to look for * @return the value or RuntimeException */ public int getAttributeValue(TPS_Attribute att) { if (this.myAttributes.containsKey(att)) { return this.myAttributes.get(att); } else { throw new RuntimeException("Attribute " + att.toString() + " not set!"); } } /** * Getter for the attribute map * * @return */ public Map<TPS_Attribute, Integer> getAttributes() { return this.myAttributes; } /** * Gets the budget acceptance probability based on the deviation of the travel costs compared to the available budget. * * @return A value between 0 and 1 describing the acceptance */ public double getBudgetAcceptanceProbability() { return budgetAcceptanceProbability; } /** * Sets the budget acceptance probability based on the deviation of the travel costs compared to the available budget. * * @param budgetAcceptanceProbability A value between 0 and 1 describing the acceptance */ public void setBudgetAcceptanceProbability(double budgetAcceptanceProbability) { this.budgetAcceptanceProbability = budgetAcceptanceProbability; } /** * Gets the acceptance probability based on the deviation of the travel costs compared to the available budget and the time deviation compared to the time deviation in the scheme class of the plan. * * @return A value between 0 and 1 describing the acceptance */ public double getCombinedAcceptanceProbability() { return timeAcceptanceProbability * budgetAcceptanceProbability; } /** * gets the current episode, which is adapted * * @return */ public TPS_AdaptedEpisode getCurrentAdaptedEpisode() { return currentAdaptedEpisode; } /** * sets the currently adapted episode * * @param currentAdaptedEpisode */ public void setCurrentAdaptedEpisode(TPS_AdaptedEpisode currentAdaptedEpisode) { this.currentAdaptedEpisode = currentAdaptedEpisode; } /** * Gets the previous Stay with respect tho the Hierarchy of the actual schemepart * * @param adaptedEpisode * @return */ public TPS_LocatedStay getHierarchizedPreviousStay(TPS_AdaptedEpisode adaptedEpisode) { TPS_TourPart tp = (TPS_TourPart) adaptedEpisode.getEpisode().getSchemePart(); return this.getLocatedStay(tp.getStayHierarchy((TPS_Stay) adaptedEpisode.getEpisode()).getPrevStay()); } /** * gets the located stay for the given key * * @param key * @return null if key is not found in locatedStays or the stay otherwise */ public TPS_LocatedStay getLocatedStay(TPS_Stay key) { return locatedStays.get(key); } /** * Getter for a Collection of the located stays for this plan. * * @return The Collection of TPS_LocatedStay */ public Collection<TPS_LocatedStay> getLocatedStays() { return locatedStays.values(); } /** * Return the persistence manager * * @return The persistence manager */ public TPS_PersistenceManager getPM() { return PM; } /** * Return the parameter class reference (through the persistence manager) * * @return parameter class reference */ public TPS_ParameterClass getParameters() { return this.PM.getParameters(); } /** * gets the person for this plan from the plan environment * * @return */ public TPS_Person getPerson() { return this.pe.getPerson(); } /** * gets the local plan environment * * @return */ public TPS_PlanEnvironment getPlanEnvironment() { return pe; } /** * gets the planed trip for the given key * * @param key key for the trip to look for * @return null if key is not in the planed trips or the trip elsewise */ public TPS_PlannedTrip getPlannedTrip(TPS_Trip key) { return plannedTrips.get(key); } /** * Getter for a Collection of the planned trips for this plan. * * @return The Collection of TPS_PlannedTrip */ public Collection<TPS_PlannedTrip> getPlannedTrips() { return plannedTrips.values(); } /** * gets the previous stay for the actual adapted Episode * * @param adaptedEpisode * @return */ public TPS_LocatedStay getPreviousLocatedStay(TPS_AdaptedEpisode adaptedEpisode) { return this.getLocatedStay( adaptedEpisode.getEpisode().getSchemePart().getPreviousStay(adaptedEpisode.getEpisode())); } /** * gets the actual scheme for this plan * * @return */ public TPS_Scheme getScheme() { return scheme; } /** * This method returns the absolute sum of time adaptations to make this plan feasible * * @return the time adaptation in seconds */ public int getSumOfTimeAdaptation() { return this.adaptAbsSum; } /** * Gets the budget acceptance probability based on the deviation of the travel time deviation compared to the time deviation in the scheme class of the plan. * * @return A value between 0 and 1 describing the acceptance */ public double getTimeAcceptanceProbability() { return timeAcceptanceProbability; } /** * Sets the budget acceptance probability based on the deviation of the travel time deviation compared to the time deviation in the scheme class of the plan. * * @param timeAcceptanceProbability A value between 0 and 1 describing the acceptance */ public void setTimeAcceptanceProbability(double timeAcceptanceProbability) { this.timeAcceptanceProbability = timeAcceptanceProbability; } /** * This method returns the time adaptation to make this plan feasible * * @return the time adaptation in seconds */ public int getTimeAdaptation() { return this.adapt; } /** * Calculates the financial expenditures for the modal use in the scheme in Euro * * @return sum of the travel costs */ public double getTravelCosts() { double sumFinancialCosts = 0.0; for (TPS_PlannedTrip pt : this.plannedTrips.values()) { sumFinancialCosts += pt.getCosts(CURRENCY.EUR); } return sumFinancialCosts; } /** * Calculates the aggregate travel time of the scheme resulting from the chosen modes and locations. * * @return sum of travel time of the scheme */ public double getTravelDuration() { double sumTravelTime = 0.0; for (TPS_PlannedTrip pt : this.plannedTrips.values()) { sumTravelTime += pt.getDuration(); } return sumTravelTime; } /** * Change all 410 codes for students to 411 */ public void hackStudents() { for (TPS_SchemePart part : this.scheme) { for (TPS_Stay stay : part.getStayIterator()) { if (stay.getActCode().hasAttribute(TPS_ActivityConstantAttribute.SCHOOL)) { stay.setActCode(TPS_ActivityConstant.getActivityCodeByTypeAndCode(TPS_ActivityCodeType.ZBE, 411)); } } } } /** * Determines whether a stay has been located * * @param stay stay to check * @return true if a location has been chosen; false else */ public boolean isLocated(TPS_Stay stay) { return this.getLocatedStay(stay).isLocated(); } /** * Determines whether the travel times resulting from the chosen modes and locations for the plan exceed too much * the travel times initially scheduled for the scheme. The acceptance limit is defined in the configuration. * * @return true, if the plan with its travel times is not too far off the designated travel times; false if the * travel times exceed the maximum difference defined in the configuration */ public boolean isPlanAccepted() { return this.pe.isPlanAccepted(this) && this.isPlanFeasible(); } /** * This method returns if the selected plan is feasible. * If any start of a stay/trip is after the end of the previous trip/stay it returns false. * If everythig is ok or there are no stays or trips it returns true. * * @return result if this plan is feasible */ public boolean isPlanFeasible() { return feasible; } /** * sets the feasibility of this plan by expert analysis * * @param feasible the feasibility for this plan */ public void setPlanFeasible(boolean feasible) { this.feasible = feasible; } /** * Removes a given Attribute. If it does not exist nothing happens. * * @param att The Attribute to remove */ public void removeAttribute(TPS_Attribute att) { this.myAttributes.remove(att); } /** * Resets a scheme to its initial state; e.g. clears modes and locations selected */ public void reset() { TPS_Stay stay; TPS_Trip trip; TPS_LocatedStay locStay = null; this.usesBike = false; this.usedCars.clear(); for (TPS_TourPart tp : this.scheme.getTourPartIterator()) { if (tp.isCarUsed()) tp.releaseCar(); } for (TPS_Episode e : this.scheme.getEpisodeIterator()) { if (e.isStay()) { stay = (TPS_Stay) e; locStay = this.getLocatedStay(stay); locStay.init(); if (stay.isAtHome()) { locStay.setLocation(this.getPerson().getHousehold().getLocation()); } } else { trip = (TPS_Trip) e; this.plannedTrips.get(trip).setMode(null); this.plannedTrips.get(trip).setDuration(trip.getOriginalDuration()); } } } /** * Initiates the determination of locations and modes for stays and trips of the scheme */ public void selectLocationsAndModesAndTravelTimes(TPS_PlanningContext pc) { if (TPS_Logger.isLogging(SeverenceLogLevel.DEBUG)) { TPS_Logger.log(SeverenceLogLevel.DEBUG, "Start select locations procedure for plan (number=" + pe.getNumberOfRejectedPlans() + ") with scheme (id=" + this.scheme.getId() + ")"); } long start = System.currentTimeMillis(); // We need several loops to resolve the hierarchy of episodes. // No we can use the priority of the stays to solve all locations searches in one loop for (TPS_SchemePart schemePart : this.scheme) { if (schemePart.isHomePart()) { // Home Parts are already set if (TPS_Logger.isLogging(SeverenceLogLevel.FINE)) { TPS_Logger.log(SeverenceLogLevel.FINE, "Skip home part (id=" + schemePart.getId() + ")"); } continue; } TPS_TourPart tourpart = (TPS_TourPart) schemePart; if (TPS_Logger.isLogging(SeverenceLogLevel.FINE)) { TPS_Logger.log(SeverenceLogLevel.FINE, "Start select location for each stay in tour part (id=" + tourpart.getId() + ")"); } // check mobility options if (tourpart.isCarUsed()) { pc.carForThisPlan = tourpart.getCar(); } else if (!pc.influenceCarUsageInPlan) { //check if a car could be used pc.carForThisPlan = TPS_Car.selectCar(this, tourpart); if (pc.carForThisPlan != null && // if there is an available car !this.getPerson().mayDriveACar() && //but the person has no driver's license // AND the available car is not automated (i.e. below the defined automation level) (pc.carForThisPlan.getAutomationLevel() < this.getParameters().getIntValue( ParamValue.AUTOMATIC_VEHICLE_LEVEL))) { pc.carForThisPlan = null; //we make the car unavailable for the person } } if (tourpart.isBikeUsed()) { //was the bike used before? pc.isBikeAvailable = true; } else if (!pc.influenceBikeUsageInPlan) { // is the bike availability modded outside? pc.isBikeAvailable = this.getPerson().hasBike(); } myAttributes.put(TPS_Attribute.PERSON_HAS_BIKE, pc.isBikeAvailable ? 1 : 0); if (pc.carForThisPlan == null) { myAttributes.put(TPS_Attribute.HOUSEHOLD_CARS, 0); } else { myAttributes.put(TPS_Attribute.HOUSEHOLD_CARS, this.getPerson().getHousehold().getNumberOfCars()); } for (TPS_Stay stay : tourpart.getPriorisedStayIterable()) { myAttributes.put(TPS_Attribute.CURRENT_EPISODE_ACTIVITY_CODE_TAPAS, stay.getActCode().getCode(TPS_ActivityCodeType.TAPAS)); pc.pe.getPerson().estimateAccessibilityPreference(stay, this.PM.getParameters().isTrue(ParamFlag.FLAG_USE_SHOPPING_MOTIVES)); TPS_LocatedStay currentLocatedStay = this.getLocatedStay(stay); if (!currentLocatedStay.isLocated()) { setCurrentAdaptedEpisode(currentLocatedStay); TPS_ActivityConstant currentActCode = stay.getActCode(); // Register locations for activities where the location will be used again. // Flag for the case of a activity with unique location. pc.fixLocationAtBase = currentActCode.isFix() && this.PM.getParameters().isTrue( ParamFlag.FLAG_USE_FIXED_LOCS_ON_BASE) && !this.fixLocations.containsKey(currentActCode); // when all tour parts are correctly instantiated the else case will never happen, because every // tour part starts with a trip. In the current episode file there exist tour parts with no first // trip (e.g. shopping in the same building where you live) //TPS_Trip previousTrip = null; if (!tourpart.isFirst(stay)) { pc.previousTrip = tourpart.getPreviousTrip(stay); } else { pc.previousTrip = new TPS_Trip(-999, TPS_ActivityConstant.DUMMY, -999, 0, this.getParameters()); } //First execution: fix locations will be set (ELSE branch) //Further executions: fix locations are set already, take locations from map (IF branch) //Non fix location, i.e. everything except home and work: also ELSE branch //E.g.: Provides a work location, when ActCode is working in ELSE if (currentActCode.isFix() && this.fixLocations.containsKey(currentActCode)) { //now we check if the mode is fix and if we can reach the fix location with the fix mode! //TODO: check only for restricted cars, but bike could also be fixed and no connection! if (pc.carForThisPlan != null && // we have a car pc.carForThisPlan.isRestricted() && //we have a restricted car this.fixLocations.get(currentActCode).getTrafficAnalysisZone() .isRestricted()) // we have a restricted car wanting to go to a restricted area! -> BAD! { currentLocatedStay.selectLocation(this, pc); if (currentActCode.isFix()) { this.fixLocations.put(currentActCode, this.getLocatedStay(stay).getLocation()); } } else { currentLocatedStay.setLocation(this.fixLocations.get(currentActCode)); } if (TPS_Logger.isLogging(HierarchyLogLevel.EPISODE, SeverenceLogLevel.FINE)) { TPS_Logger.log(HierarchyLogLevel.EPISODE, SeverenceLogLevel.FINE, "Set location from fix locations"); } } else { currentLocatedStay.selectLocation(this, pc); if (currentActCode.isFix()) { this.fixLocations.put(currentActCode, this.getLocatedStay(stay).getLocation()); } } if (currentLocatedStay.getLocation() == null) { TPS_Logger.log(SeverenceLogLevel.ERROR, "No Location found!"); } if (TPS_Logger.isLogging(SeverenceLogLevel.DEBUG)) { String s = "gewählte Location zu Stay: " + currentLocatedStay.getEpisode().getId() + ": " + currentLocatedStay.getLocation().getId() + " in TAZ:" + currentLocatedStay.getLocation().getTrafficAnalysisZone().getTAZId() + " in block: " + (currentLocatedStay.getLocation().hasBlock() ? currentLocatedStay.getLocation() .getBlock() .getId() : -1) + " via" + currentLocatedStay.getModeArr().getName() + "/" + currentLocatedStay.getModeDep().getName(); TPS_Logger.log(SeverenceLogLevel.DEBUG, s); TPS_Logger.log(SeverenceLogLevel.DEBUG, "Selected location (id=" + currentLocatedStay.getLocation().getId() + ") for stay (id=" + currentLocatedStay.getEpisode().getId() + " in TAZ (id=" + currentLocatedStay.getLocation().getTrafficAnalysisZone().getTAZId() + ") in block (id= " + (currentLocatedStay.getLocation().hasBlock() ? currentLocatedStay.getLocation() .getBlock() .getId() : -1) + ") via modes " + currentLocatedStay.getModeArr().getName() + "/" + currentLocatedStay.getModeDep().getName()); } } // fetch previous and next stay TPS_Stay prevStay = tourpart.getStayHierarchy(stay).getPrevStay(); TPS_Stay goingTo = tourpart.getStayHierarchy(stay).getNextStay(); if (currentLocatedStay.getModeArr() == null || currentLocatedStay.getModeDep() == null) { if (TPS_Logger.isLogging(SeverenceLogLevel.FINE)) { TPS_Logger.log(SeverenceLogLevel.FINE, "Start select mode for each stay in tour part (id=" + tourpart.getId() + ")"); } //do we have a fixed mode from the previous trip? if (tourpart.isFixedModeUsed()) { currentLocatedStay.setModeArr(tourpart.getUsedMode()); currentLocatedStay.setModeDep(tourpart.getUsedMode()); } else { TPS_Location pLocGoingTo = this.getLocatedStay(goingTo).getLocation(); TPS_Car tmpCar = pc.carForThisPlan; if (tmpCar != null && tmpCar.isRestricted() && (currentLocatedStay.getLocation().getTrafficAnalysisZone().isRestricted() || pLocGoingTo.getTrafficAnalysisZone().isRestricted())) { pc.carForThisPlan = null; } PM.getModeSet().selectMode(this, prevStay, currentLocatedStay, goingTo, pc); pc.carForThisPlan = tmpCar; //set the mode and car (if used) tourpart.setUsedMode(currentLocatedStay.getModeDep(), pc.carForThisPlan); //set some variables for the fixed modes TPS_ExtMode em = tourpart.getUsedMode(); usesBike = em.isBikeUsed(); if (em.isCarUsed()) { usedCars.add(pc.carForThisPlan); } //set variables for fixed modes: pc.carForThisPlan = tourpart.getCar(); pc.isBikeAvailable = tourpart.isBikeUsed(); if (pc.carForThisPlan == null) { myAttributes.put(TPS_Attribute.HOUSEHOLD_CARS, 0); } else { myAttributes.put(TPS_Attribute.HOUSEHOLD_CARS, this.getPerson().getHousehold().getNumberOfCars()); } myAttributes.put(TPS_Attribute.PERSON_HAS_BIKE, pc.isBikeAvailable ? 1 : 0); } } if (TPS_Logger.isLogging(SeverenceLogLevel.DEBUG)) { String s = "Chosen mode of Stay: " + currentLocatedStay.getEpisode().getId() + ": " + currentLocatedStay.getModeArr() == null ? "NULL" : currentLocatedStay.getModeArr().getName() + " in TAZ:" + currentLocatedStay.getLocation().getTrafficAnalysisZone().getTAZId() + " in block: " + (currentLocatedStay.getLocation().hasBlock() ? currentLocatedStay.getLocation() .getBlock() .getId() : -1) + " via" + currentLocatedStay.getModeArr().getName() + "/" + currentLocatedStay.getModeDep().getName(); TPS_Logger.log(SeverenceLogLevel.DEBUG, s); TPS_Logger.log(SeverenceLogLevel.DEBUG, "Selected mode (id=" + currentLocatedStay.getModeArr() == null ? "NULL" : currentLocatedStay.getModeArr().getName() + ") for stay (id=" + currentLocatedStay.getEpisode().getId() + " in TAZ (id=" + currentLocatedStay.getLocation().getTrafficAnalysisZone().getTAZId() + ") in block (id= " + (currentLocatedStay.getLocation() .hasBlock() ? currentLocatedStay.getLocation() .getBlock() .getId() : -1) + ") via modes " + currentLocatedStay.getModeArr().getName() + "/" + currentLocatedStay.getModeDep().getName()); } //set travel time for the arriving mode if (!tourpart.isFirst(stay)) { this.getPlannedTrip(tourpart.getPreviousTrip(stay)).setTravelTime(this.getLocatedStay(prevStay), this.getLocatedStay(stay)); } //set travel time for the departure mode if (!tourpart.isLast(stay)) { this.getPlannedTrip(tourpart.getNextTrip(stay)).setTravelTime(this.getLocatedStay(stay), this.getLocatedStay(goingTo)); } //update the travel durations for this plan tourpart.updateActualTravelDurations(this); myAttributes.put(TPS_Attribute.CURRENT_TAZ_SETTLEMENT_CODE_TAPAS, currentLocatedStay.getLocation().getTrafficAnalysisZone().getBbrType() .getCode(TPS_SettlementSystemType.TAPAS)); }//end for tourpart } /* At this point everything should be ready, but: * locations within the same location group (malls etc.) should be accessed by foot. * You should not drive through a mall with an SUV, unless you play cruel video games. * * So check, if two adjacent locations are within the same group and adopt the mode accordingly. * This is done AFTER mode estimation, this might result in slightly wrong travel times within a mall. * TODO: Check if this inaccuracy is acceptable. */ //tourpart.setUsedMode(null, null); TPS_LocatedStay prevLocatedStay = null; for (TPS_LocatedStay locatedStay : this.getLocatedStays()) { if (prevLocatedStay != null) { // not for the first stay, which starts at home if (locatedStay.isLocated() && prevLocatedStay.isLocated()) { if (locatedStay.getLocation().isSameLocationGroup(prevLocatedStay.getLocation())) { prevLocatedStay.setModeDep(TPS_ExtMode.simpleWalk); locatedStay.setModeArr(TPS_ExtMode.simpleWalk); } } else { if (TPS_Logger.isLogging(SeverenceLogLevel.WARN)) { TPS_Logger.log(SeverenceLogLevel.WARN, "One location is null"); } } } prevLocatedStay = locatedStay; } //now we set the final travel times for (TPS_SchemePart schemePart : this.scheme) { if (schemePart.isTourPart()) { TPS_TourPart tourpart = (TPS_TourPart) schemePart; //update the travel durations for this plan tourpart.updateActualTravelDurations(this); } } TPS_Logger.log(SeverenceLogLevel.DEBUG, "Selected all locations in " + (System.currentTimeMillis() - start) + "ms"); } /** * Setter for a specific attribute of this plan * * @param att the Attribute from TPS_Attribute * @param val the value */ public void setAttributeValue(TPS_Attribute att, int val) { this.myAttributes.put(att, val); } /** * Calls for each trip of the plan the routine setTravelTime von {@link TPS_PlannedTrip}. */ public void setTravelTimes() { // If the first Episode is a trip, we cannot say how far it is and how // much time was needed TPS_Trip trip = null; TPS_Stay from = null; TPS_Stay to = null; for (TPS_SchemePart sp : this.scheme) { if (sp.isTourPart()) { for (TPS_Episode episode : sp) { /* * Es wird erwartet das an Stelle it ein Trip und an Stelle itComingFrom = it - 1 und an Stelle * itGoingTo = it + 1 ein Stay ist. Es kann abgesichert werden, dass nur trips verarbeitet werden, * bei denen das der Fall ist. Im Input-File ist das aber nicht immer so. Was passiert mit diesen * Trips, für die das nicht der Fall ist? */ if (episode.isTrip()) { trip = (TPS_Trip) episode; from = sp.getPreviousStay(episode); to = sp.getNextStay(episode); // TPS_Location locFrom = // this.getLocatedStay(from).getLocation(); // TPS_Location locTo = // this.getLocatedStay(to).getLocation(); // if (locFrom != null && locTo != null) // LOG.warn("\t\t\t\t '--> Aufruf trip.setTravelTime it: " // + (it + 1) + " from stay: " // + from.getMyNumber() + " loc: " + locFrom.getMyId() + // " in Bez: " // + from.getPLocation().getBez92() + " (" + // from.getPLocation().getRw() + ", " // + from.getPLocation().getHw() + "); to stay: " + // to.getMyNumber() + " loc: " // + locTo.getMyId() + " in Bez: " + // to.getPLocation().getBez92() + " (" // + to.getPLocation().getRw() + ", " + // to.getPLocation().getHw() + ")"); // else // LOG.debug("\t\t\t\t '--> Aufruf trip.setTravelTime it: " // + (it + 1) + " from stay: " // + from.getMyNumber() + " (null, null) to stay: " + // to.getMyNumber() + " (null, null)"); this.getPlannedTrip(trip).setTravelTime(this.getLocatedStay(from), this.getLocatedStay(to)); } } } } } /** * overrides toString to use local toString function */ @Override public String toString() { return this.toString(""); } /** * puts a prefix to the toString functionality of this specially formated output. * PREFIX is currently disabled! */ public String toString(String prefix) { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName() + "\n"); sb.append(this.scheme.toString(" ") + "\n"); for (TPS_Episode e : this.scheme.getEpisodeIterator()) { Object ew = null; if (e.isStay()) { ew = this.getLocatedStay((TPS_Stay) e); } else if (e.isTrip()) { ew = this.getPlannedTrip((TPS_Trip) e); } sb.append(" " + e.getId() + " -> " + ew.toString() + "\n"); } sb.setLength(sb.length() - 1); return sb.toString(); } /** * Returns whether a car is used within this plan * * @return Whether a car is used */ public boolean usesCar() { return this.usedCars.size() > 0; } /** * Method to write this trip to an output-stream * * @param out * @throws IOException */ public void writeOutputStream(Writer out) throws IOException { TPS_Stay nextStay, prevStay; TPS_PlannedTrip plannedTrip; int personID = pe.getPerson().getId(); int schemeID = scheme.getId(); int sex = pe.getPerson().getSex().ordinal(); //int mainActivity; double hHIncome = pe.getPerson().getHousehold().getIncome(); int numberOfPersonsHH = pe.getPerson().getHousehold().getNumberOfMembers(); for (TPS_TourPart tour : this.scheme.getTourPartIterator()) { //get highest priority trip //if(tour.getPriorisedStayIterable().iterator().hasNext()) // mainActivity = tour.getPriorisedStayIterable().iterator().next().getActCode().getCode(TPS_ActivityCodeType.ZBE); //else // mainActivity = -999; for (TPS_Trip trip : tour.getTripIterator()) { plannedTrip = this.getPlannedTrip(trip); nextStay = plannedTrip.getTrip().getSchemePart().getNextStay(trip); prevStay = plannedTrip.getTrip().getSchemePart().getPreviousStay(trip); out.write(Integer.toString(personID)); // PersonID out.write(", "); out.write(Integer.toString(schemeID)); // SchemeID out.write(", "); out.write(Integer.toString(pe.getPerson().getPersonGroup().getCode())); // job out.write(", "); //hauptaktivität //out.write(Integer.toString(mainActivity)); // actCode //out.write(", "); // aktuelle Priorität int actCode = nextStay.getActCode().getCode(TPS_ActivityCodeType.ZBE); // TODO Mantis 0002615 if (actCode == 410 && pe.getPerson().isStudent()) { actCode = 411; } out.write(Integer.toString(actCode)); // actCode out.write(", "); out.write(Integer.toString(pe.getPerson().getAgeClass().getCode(TPS_AgeCodeType.STBA))); // ageCat out.write(", "); out.write(Integer.toString(sex)); // sex out.write(", "); // TAZ departure out.write(Integer.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .getTAZId())); out.write(", "); // TAZ arrival out.write(Integer.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .getTAZId())); out.write(", "); // is next stay AtHome out.write(Integer.toString(nextStay.isAtHome() ? 1 : 0)); out.write(", "); // id of Mode of Trip out.write(Integer.toString(plannedTrip.getMode().getMCTCode())); out.write(", "); // bee line Distance out.write(Integer.toString((int) plannedTrip.getDistanceBeeline())); out.write(", "); out.write(Double.toString(Math.round(plannedTrip.getDistance()))); out.write(", "); // netDistance out.write(Double.toString(Math.round(plannedTrip.getDistanceEmptyNet()))); out.write(", "); // travel time out.write(Integer.toString(plannedTrip.getDuration())); out.write(", "); // HouseHold Income out.write(Integer.toString(TPS_Income.getCode(hHIncome))); out.write(", "); // Number of Persons Household out.write(Integer.toString(numberOfPersonsHH)); out.write(", "); // Coming Block ID if (this.getLocatedStay(prevStay).getLocation().hasBlock()) { out.write(Integer.toString(this.getLocatedStay(prevStay).getLocation().getBlock().getId())); } else { out.write("0"); } out.write(", "); // going Block ID if (this.getLocatedStay(nextStay).getLocation().hasBlock()) { out.write(Integer.toString(this.getLocatedStay(nextStay).getLocation().getBlock().getId())); } else { out.write("0"); } out.write(", "); // coming X Coordinate out.write(Double.toString(this.getLocatedStay(prevStay).getLocation().getCoordinate().getValue(0))); out.write(", "); // coming Y Coordinate out.write(Double.toString(this.getLocatedStay(prevStay).getLocation().getCoordinate().getValue(1))); out.write(", "); // going X Coordinate out.write(Double.toString(this.getLocatedStay(nextStay).getLocation().getCoordinate().getValue(0))); out.write(", "); // going Y Coordinate out.write(Double.toString(this.getLocatedStay(nextStay).getLocation().getCoordinate().getValue(1))); out.write(", "); // startTime // Die in myStart abgelegte Zeit ist in Sekunden seit mitternacht abgelegt;übersetzten in Minuten nach // Mitternacht int time = (int) (plannedTrip.getStart() * 1.66666666e-2); out.write(Double.toString(time)); out.write(", "); // FOBIRD departure out.write(Integer.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .getBbrType().getCode(TPS_SettlementSystemType.FORDCP))); out.write(", "); // FOBIRD going out.write(Integer.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .getBbrType().getCode(TPS_SettlementSystemType.FORDCP))); out.write(", "); // coming Has Toll out.write(Boolean.toString(this.getLocatedStay(prevStay).getLocation().getTrafficAnalysisZone() .hasToll(SimulationType.SCENARIO))); out.write(", "); // going Has Toll out.write(Boolean.toString(this.getLocatedStay(nextStay).getLocation().getTrafficAnalysisZone() .hasToll(SimulationType.SCENARIO))); out.write(", "); // locId int locId = Math.max(-1, this.getLocatedStay(nextStay).getLocation().getId()); out.write(Integer.toString(locId)); out.write("\n"); } } out.flush(); } }
92313b2abb7f917583a1decdfe3f7f36cf4e55f8
460
java
Java
src/main/java/com/sixteen/school/star/scan/MultiServiceFactoryBean.java
key-value/school_java
17fa1c7aff4c163a055dbf168ba2b9d51b6d92c0
[ "CC0-1.0" ]
null
null
null
src/main/java/com/sixteen/school/star/scan/MultiServiceFactoryBean.java
key-value/school_java
17fa1c7aff4c163a055dbf168ba2b9d51b6d92c0
[ "CC0-1.0" ]
null
null
null
src/main/java/com/sixteen/school/star/scan/MultiServiceFactoryBean.java
key-value/school_java
17fa1c7aff4c163a055dbf168ba2b9d51b6d92c0
[ "CC0-1.0" ]
null
null
null
19.166667
75
0.68913
995,760
package com.sixteen.school.star.scan; import org.springframework.beans.factory.FactoryBean; public class MultiServiceFactoryBean implements FactoryBean<MultiService> { @Override public MultiService getObject() throws Exception { return new MultiBaseService(); } @Override public Class<?> getObjectType() { return MultiService.class; } @Override public boolean isSingleton() { return true; } }
92313c05d35ba1dfad556d0400f262ccbf3dc1e5
1,081
java
Java
src/LuoGu/P1135.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
2
2019-09-16T03:56:16.000Z
2019-10-12T03:30:37.000Z
src/LuoGu/P1135.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
null
null
null
src/LuoGu/P1135.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
null
null
null
26.365854
67
0.508788
995,761
package LuoGu; import java.util.Scanner; /** * @author kid1999 * @create 2020-10-13 14:32 * @description TODO **/ public class P1135 { static int minDep = Integer.MAX_VALUE; static int[] to = new int[205]; static boolean[] vis = new boolean[205]; static int n,a,b; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = sc.nextInt(); b = sc.nextInt(); for (int i = 1; i <=n ; i++) { to[i] = sc.nextInt(); } vis[a] = true; dfs(a,0); if(minDep != Integer.MAX_VALUE) System.out.println(minDep); else System.out.println(-1); } public static void dfs(int now,int dep){ if(now == b) { minDep = Math.min(minDep,dep); return; } if(dep > minDep) return; vis[now] = true; int up = now+to[now]; int down = now-to[now]; if(up <= b && !vis[up]) dfs(up,dep+1); if(down >=1 && !vis[down]) dfs(down,dep+1); vis[a] = false; } }
92313c1f6519f29a50da997aa35b710f116ddbf2
2,546
java
Java
Algorithm/sort/QuickSortStack.java
sara0606/leetcode-Notes
dfadb20e2575f6276c7682fff5959c3d080c03a7
[ "MIT" ]
null
null
null
Algorithm/sort/QuickSortStack.java
sara0606/leetcode-Notes
dfadb20e2575f6276c7682fff5959c3d080c03a7
[ "MIT" ]
null
null
null
Algorithm/sort/QuickSortStack.java
sara0606/leetcode-Notes
dfadb20e2575f6276c7682fff5959c3d080c03a7
[ "MIT" ]
null
null
null
30.674699
92
0.558523
995,762
package com.tuniu.cls.rcl.algorithm.sort; import com.tuniu.cls.rcl.intf.dto.vendor.ota_2007a.ImageDescriptionType; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * 用栈实现快排 * * @date 2019/12/31 15:55 */ public class QuickSortStack { public static void quickSortByStack(int[] arr, int startIndex, int endIndex) { //用一个集合栈来代替递归的函数栈 Stack<Map<String, Integer>> quickSortStack = new Stack<Map<String, Integer>>(); //整个数列的起止下标,以哈希的形式入栈 Map rootParam = new HashMap(); rootParam.put("startIndex", startIndex); rootParam.put("endIndex", endIndex); quickSortStack.push(rootParam); //循环结束条件:栈为空 while (!quickSortStack.isEmpty()) { //栈顶元素出栈,得到起止下标 Map<String, Integer> param = quickSortStack.pop(); //得到基准元素 int pivotIndex = partition(arr, param.get("startIndex"), param.get("endIndex")); //根据基准元素分成两部分,把每一部分的起止下标入栈 if (param.get("startIndex") < pivotIndex - 1) { Map<String, Integer> leftParam = new HashMap<String, Integer>(); leftParam.put("startIndex", param.get("startIndex")); leftParam.put("endIndex", pivotIndex - 1); quickSortStack.push(leftParam); } if (pivotIndex + 1 < param.get("endIndex")) { Map<String, Integer> rightParam = new HashMap<String, Integer>(); rightParam.put("startIndex", pivotIndex + 1); rightParam.put("endIndex", param.get("endIndex")); quickSortStack.push(rightParam); } } } /** * 分治(单边循环法) * @param arr 待交换的数组 * @param startIndex 起始下标 * @param endIndex 结束下标 * @return */ private static int partition(int[] arr, int startIndex, int endIndex) { //取第一个元素的位置(也可以选择随机位置)的元素作为基准元素 int pivot = arr[startIndex]; int mark = startIndex; for (int i = startIndex + 1; i <= endIndex; i++) { if (arr[i] < pivot) { mark++; int temp = arr[mark]; arr[mark] = arr[i]; arr[i] = temp; } } arr[startIndex] = arr[mark]; arr[mark] = pivot; return mark; } public static void main(String[] args) { int[] arr = new int[]{4, 7, 5, 3, 2, 8, 1}; quickSortByStack(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
92313eb2a56880fc65307af9d79a5cd40e4c0674
3,935
java
Java
src/main/java/com/alibabacloud/polar_race/engine/common/index/map/ConcurrentMapIndexer.java
zhenzou/polar_race
73be631ec12f2666902b96e10961162f1a94ef8b
[ "WTFPL" ]
1
2018-12-10T01:59:20.000Z
2018-12-10T01:59:20.000Z
src/main/java/com/alibabacloud/polar_race/engine/common/index/map/ConcurrentMapIndexer.java
zhenzou/polar_race
73be631ec12f2666902b96e10961162f1a94ef8b
[ "WTFPL" ]
null
null
null
src/main/java/com/alibabacloud/polar_race/engine/common/index/map/ConcurrentMapIndexer.java
zhenzou/polar_race
73be631ec12f2666902b96e10961162f1a94ef8b
[ "WTFPL" ]
null
null
null
30.503876
78
0.54587
995,763
package com.alibabacloud.polar_race.engine.common.index.map; import com.alibabacloud.polar_race.engine.common.Constants; import com.alibabacloud.polar_race.engine.common.index.Indexer; import com.alibabacloud.polar_race.engine.common.util.Convert; import com.carrotsearch.hppc.LongLongHashMap; import com.carrotsearch.hppc.cursors.LongLongCursor; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import static com.alibabacloud.polar_race.engine.common.util.Utils.log; /** * @since 0.1 * create at 2018/10/1 */ public class ConcurrentMapIndexer implements Indexer { private static final int BATCH_SIZE = 32 * 1024 * 1024; private static final int BATCH = BATCH_SIZE / Constants.INDEX_ENTRY_SIZE; private LongLongHashMap indexes = new LongLongHashMap(4000000, 0.99); private File file; private long checkPoint; @Override public void open(String path) { path = String.join(File.separator, path, Constants.INDEX_FILE_NAME); file = new File(path); if (file.exists()) { load(); } else { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } } } private void load() { log("map index start to load"); try (FileInputStream in = new FileInputStream(file)) { FileChannel fc = in.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BATCH_SIZE); long checkPoint = this.checkPoint; while (true) { buffer.clear(); final int read = fc.read(buffer); final int count = read / Constants.INDEX_ENTRY_SIZE; buffer.flip(); for (int i = 0; i < count; i++) { final long key = buffer.getLong(); final long value = buffer.getLong(); indexes.put(key, value); if (value > checkPoint) { checkPoint = value; } } if (read < BATCH_SIZE) { break; } } this.checkPoint = checkPoint; } catch (EOFException e) { log(e.getMessage()); } catch (IOException e) { throw new RuntimeException(e); } log("map index load %d", indexes.size()); } @Override public synchronized void set(byte[] key, long address) { indexes.put(Convert.bytes2long(key), address); } @Override public long get(byte[] key) { return indexes.getOrDefault(Convert.bytes2long(key), -1); } @Override public long getCheckPoint() { return checkPoint; } private void write(FileChannel fc, ByteBuffer buffer) throws IOException { while (buffer.hasRemaining()) { fc.write(buffer); } } @Override public void close() { log("map index start to close"); try (FileOutputStream out = new FileOutputStream(file)) { FileChannel fc = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BATCH_SIZE); int count = 0; for (LongLongCursor cursor : indexes) { buffer.putLong(cursor.key); buffer.putLong(cursor.value); count++; if (count == BATCH) { buffer.flip(); write(fc, buffer); buffer.clear(); count = 0; } } if (count != 0) { buffer.flip(); write(fc, buffer); } log("write %d %d", indexes.size(), count); } catch (IOException e) { throw new RuntimeException(e); } log("map index close"); } }
92313f3bce1129097aec29504b56353816a7ff9a
1,037
java
Java
modules/citrus-admin/src/main/java/com/consol/citrus/admin/converter/ObjectConverter.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
null
null
null
modules/citrus-admin/src/main/java/com/consol/citrus/admin/converter/ObjectConverter.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
null
null
null
modules/citrus-admin/src/main/java/com/consol/citrus/admin/converter/ObjectConverter.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
1
2021-03-25T17:39:49.000Z
2021-03-25T17:39:49.000Z
27.289474
75
0.691418
995,764
/* * Copyright 2006-2013 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 com.consol.citrus.admin.converter; /** * @author Christoph Deppisch * @since 1.3.1 */ public interface ObjectConverter<T, S> { /** * Converts a configuration definition object to desired object. * @param definition * @return */ T convert(S definition); /** * Gets the model class usually the jaxb model class. * @return */ Class<S> getModelClass(); }
9231400d870041d4e75baeebb31617215a39c2dd
2,201
java
Java
src/java/org/jsfml/graphics/CircleShape.java
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
41
2015-01-10T16:39:36.000Z
2022-02-03T12:06:12.000Z
src/java/org/jsfml/graphics/CircleShape.java
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
22
2015-01-26T01:36:16.000Z
2019-01-05T07:31:49.000Z
src/java/org/jsfml/graphics/CircleShape.java
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
38
2015-03-12T00:55:51.000Z
2021-11-08T22:38:43.000Z
24.455556
93
0.629259
995,765
package org.jsfml.graphics; /** * A specialized shape representing a circle. */ public class CircleShape extends Shape { //cache private float radius = 0; /** * Constructs a new circle shape with a zero radius, approximated using 30 points. */ public CircleShape() { super(); } /** * Constructs a new circle shape with the specified radius, approximated using 30 points. * * @param radius the circle's radius. */ public CircleShape(float radius) { this(); setRadius(radius); } /** * Constructs a new circle shape with the specified parameters. * * @param radius the circle's radius. * @param points the amount of points to approximate the circle with. * @see CircleShape#setPointCount(int) */ public CircleShape(float radius, int points) { this(radius); setPointCount(points); } @Override @Deprecated @SuppressWarnings("deprecation") protected native long nativeCreate(); @Override @Deprecated @SuppressWarnings("deprecation") protected native void nativeSetExPtr(); @Override @Deprecated @SuppressWarnings("deprecation") protected native void nativeDelete(); private native void nativeSetRadius(float radius); /** * Sets the radius of this circle. * * @param radius the new radius of the circle shape. */ public void setRadius(float radius) { nativeSetRadius(radius); this.radius = radius; pointsNeedUpdate = true; } /** * Gets the radius of this circle. * * @return the radius of this circle shape. */ public float getRadius() { return radius; } private native void nativeSetPointCount(int count); /** * Sets the amount of points the circle should be approximated with. * <p/> * A higher amount of points will yield a smoother result at the cost of performance. * * @param count the amount of points used to approximate the circle. */ public void setPointCount(int count) { nativeSetPointCount(count); pointsNeedUpdate = true; } }
923141c5bc9bb374c5359fbff45feca80b3d76ac
2,248
java
Java
src/main/java/net/imglib2/ops/operation/iterable/unary/Max.java
imagej/imagej-deprecated
56d0c480ee62f32838ba40c7a5bd5f02d9c96a63
[ "BSD-2-Clause" ]
null
null
null
src/main/java/net/imglib2/ops/operation/iterable/unary/Max.java
imagej/imagej-deprecated
56d0c480ee62f32838ba40c7a5bd5f02d9c96a63
[ "BSD-2-Clause" ]
1
2020-12-11T18:17:08.000Z
2020-12-12T17:24:12.000Z
src/main/java/net/imglib2/ops/operation/iterable/unary/Max.java
imagej/imagej-deprecated
56d0c480ee62f32838ba40c7a5bd5f02d9c96a63
[ "BSD-2-Clause" ]
2
2016-04-28T10:38:51.000Z
2018-02-13T14:44:25.000Z
32.57971
113
0.728203
995,766
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2020 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imglib2.ops.operation.iterable.unary; import java.util.Iterator; import net.imglib2.ops.operation.UnaryOperation; import net.imglib2.type.numeric.RealType; /** * @author Felix Schoenenberger (University of Konstanz) * @param <T> * @deprecated Use net.imagej.ops instead. */ @Deprecated public class Max< T extends RealType< T >, V extends RealType< V >> implements UnaryOperation< Iterator< T >, V > { @Override public V compute( Iterator< T > input, V output ) { double max = -Double.MAX_VALUE; while ( input.hasNext() ) { double val = input.next().getRealDouble(); if ( val > max ) { max = val; } } output.setReal( max ); return output; } @Override public UnaryOperation< Iterator< T >, V > copy() { return new Max< T, V >(); } }
923141f3813329ca12036c22a34c58a030eb3b33
135
java
Java
user-service/src/main/java/com/ciel/loadstar/user/client/model/CreateUserReturnModel.java
cielqian/LoadStar
6edb41c815bd739cc13e03fc450c6710a144c5ea
[ "Apache-2.0" ]
3
2019-11-11T11:21:26.000Z
2021-09-04T18:14:28.000Z
user-service/src/main/java/com/ciel/loadstar/user/client/model/CreateUserReturnModel.java
cielqian/LoadStar
6edb41c815bd739cc13e03fc450c6710a144c5ea
[ "Apache-2.0" ]
2
2021-07-02T18:46:59.000Z
2021-08-09T20:53:15.000Z
user-service/src/main/java/com/ciel/loadstar/user/client/model/CreateUserReturnModel.java
cielqian/LoadStar
6edb41c815bd739cc13e03fc450c6710a144c5ea
[ "Apache-2.0" ]
1
2020-10-19T08:19:17.000Z
2020-10-19T08:19:17.000Z
15
44
0.77037
995,767
package com.ciel.loadstar.user.client.model; import lombok.Data; @Data public class CreateUserReturnModel { private String id; }
923142e53ba31ffcb79443eb26c8bf2a5d418118
1,219
java
Java
app/src/main/java/com/songjachin/himalaya/utils/LogUtil.java
songjachin/Himalaya
99975f017a499ead920bf46bc5ac2206fff58bb0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/songjachin/himalaya/utils/LogUtil.java
songjachin/Himalaya
99975f017a499ead920bf46bc5ac2206fff58bb0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/songjachin/himalaya/utils/LogUtil.java
songjachin/Himalaya
99975f017a499ead920bf46bc5ac2206fff58bb0
[ "Apache-2.0" ]
null
null
null
22.574074
64
0.534865
995,768
package com.songjachin.himalaya.utils; import android.util.Log; /** * Created by matthew on 2020/4/23 20:09 * day day up! */ public class LogUtil { public static String sTAG = "LogUtil"; //控制是否要输出log public static boolean sIsRelease = false; /** * 如果是要发布了,可以在application里面把这里release一下,这样子就没有log输出了 */ public static void init(String baseTag, boolean isRelease) { sTAG = baseTag; sIsRelease = isRelease; } public static void d(String TAG, String content) { if (!sIsRelease) { Log.d("[" + sTAG + "]" + TAG, content); } } public static void v(String TAG, String content) { if (!sIsRelease) { Log.d("[" + sTAG + "]" + TAG, content); } } public static void i(String TAG, String content) { if (!sIsRelease) { Log.d("[" + sTAG + "]" + TAG, content); } } public static void w(String TAG, String content) { if (!sIsRelease) { Log.d("[" + sTAG + "]" + TAG, content); } } public static void e(String TAG, String content) { if (!sIsRelease) { Log.d("[" + sTAG + "]" + TAG, content); } } }
9231438ae3a216e5a03e661fe6080b2e65509c64
643
java
Java
TestingQuickFigures/TestingTools/testing/TestExample.java
grishkam/QuickFigures
a662d4507a73b08729e67aa001641b14e066e7c7
[ "Apache-2.0" ]
21
2020-09-27T07:20:58.000Z
2022-03-28T14:47:43.000Z
TestingQuickFigures/TestingTools/testing/TestExample.java
grishkam/QuickFigures
a662d4507a73b08729e67aa001641b14e066e7c7
[ "Apache-2.0" ]
3
2021-02-03T19:31:30.000Z
2022-03-07T20:12:26.000Z
TestingQuickFigures/TestingTools/testing/TestExample.java
grishkam/QuickFigures
a662d4507a73b08729e67aa001641b14e066e7c7
[ "Apache-2.0" ]
5
2020-09-28T07:17:19.000Z
2022-02-14T20:41:19.000Z
27.956522
178
0.758942
995,769
/** * Author: Greg Mazo * Date Modified: Mar 6, 2021 * Copyright (C) 2021 Gregory Mazo * */ /** * */ package testing; /** * */ public enum TestExample{ DIVERSE_SHAPES, RECTANGLE_AND_OTHERS, MANY_COLORS, MANY_STROKES , MANY_ANGLES,MANY_ANGLE_TEXT , MANY_ANGLE_COMPLEX_TEXT , MULTIPLE_FONTS,MULTIPLE_FONT_DIMS, MANY_ARROWS, EMPTY, SPLIT_CHANNEL_FIGURE, MERGE_PANEL_FIGURE, FIGURE_WITH_INSETS, MANY_SPLIT_CHANNEL, MANY_SIZE_IMAGEPANEL,_FIGURE, MANY_SPLIT_CHANNEL_SCRAMBLE, MANY_SPLIT_CHANNEL_SCRAMBLE_LIGHT, COLUMN_PLOTS, XY_PLOTS, GROUPED_PLOTS, KM_PLOTS, SCALE_BAR_STYLES_, MANY_SCALE_IMAGEPANEL; }
923143e375309ee0ca44fbf31f316eff6c4984c4
1,790
java
Java
src/main/java/scotip/app/service/module/ModuleService.java
Monpoke/scotipweb
85b40742dc1c726fa911367c8d245e31d08267e7
[ "MIT" ]
null
null
null
src/main/java/scotip/app/service/module/ModuleService.java
Monpoke/scotipweb
85b40742dc1c726fa911367c8d245e31d08267e7
[ "MIT" ]
null
null
null
src/main/java/scotip/app/service/module/ModuleService.java
Monpoke/scotipweb
85b40742dc1c726fa911367c8d245e31d08267e7
[ "MIT" ]
null
null
null
38.085106
100
0.76648
995,770
/* * Copyright (c) 2016. Pierre BOURGEOIS * * 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 scotip.app.service.module; import scotip.app.dto.ModuleDto; import scotip.app.dto.ModuleUpdateDto; import scotip.app.exceptions.OperationException; import scotip.app.model.Company; import scotip.app.model.Module; /** * Created by Pierre on 13/05/2016. */ public interface ModuleService { Module findByIdAndCompany(int id, Company currentCompany); Module createNewModule(int parentId, String modelSlug, Company currentCompany) throws Exception; Module save(Module module); Module removeModule(int parentId, Company currentCompany) throws OperationException; void saveUpdate(Module module, ModuleDto moduleUpdateDto); }
9231443ebecdc84cebd930c8c796edad4efec70f
1,152
java
Java
src/main/java/im/cave/ms/provider/info/SkillOption.java
Heasn/ms
80c6152e2ddf68650577d064291d7d047455fdb5
[ "Apache-2.0" ]
3
2021-02-18T11:37:25.000Z
2021-04-09T03:15:26.000Z
src/main/java/im/cave/ms/provider/info/SkillOption.java
Heasn/ms
80c6152e2ddf68650577d064291d7d047455fdb5
[ "Apache-2.0" ]
3
2021-05-05T07:43:40.000Z
2021-05-20T14:24:28.000Z
src/main/java/im/cave/ms/provider/info/SkillOption.java
Heasn/ms
80c6152e2ddf68650577d064291d7d047455fdb5
[ "Apache-2.0" ]
7
2021-04-27T16:19:20.000Z
2022-03-26T16:33:03.000Z
20.210526
74
0.633681
995,771
package im.cave.ms.provider.info; import im.cave.ms.tools.Pair; import org.objectweb.asm.Handle; import java.util.ArrayList; import java.util.List; /** * @author fair * @version V1.0 * @Package im.cave.ms.provider.info * @date 2/24 16:30 */ public class SkillOption { private int id; private int skillId; private int reqLevel; private List<Pair<Integer, Integer>> tempOptions = new ArrayList<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public int getSkillId() { return skillId; } public void setSkillId(int skillId) { this.skillId = skillId; } public int getReqLevel() { return reqLevel; } public void setReqLevel(int reqLevel) { this.reqLevel = reqLevel; } public List<Pair<Integer, Integer>> getTempOptions() { return tempOptions; } public void setTempOptions(List<Pair<Integer, Integer>> tempOptions) { this.tempOptions = tempOptions; } public void addTempOption(Pair<Integer, Integer> tempOption) { tempOptions.add(tempOption); } }
92314621255ee85222f58b8f81904f7ccedac260
3,571
java
Java
apache/mina/src/main/java/com/evangel/example/udp/MemoryMonitor.java
King-Maverick007/websites
fd5ddf7f79ce12658e95e26cd58e3488c90749e2
[ "Apache-2.0" ]
4
2018-03-16T08:50:00.000Z
2020-05-18T01:29:23.000Z
apache/mina/src/main/java/com/evangel/example/udp/MemoryMonitor.java
King-Maverick007/websites
fd5ddf7f79ce12658e95e26cd58e3488c90749e2
[ "Apache-2.0" ]
null
null
null
apache/mina/src/main/java/com/evangel/example/udp/MemoryMonitor.java
King-Maverick007/websites
fd5ddf7f79ce12658e95e26cd58e3488c90749e2
[ "Apache-2.0" ]
2
2020-10-01T07:30:33.000Z
2021-12-05T05:52:01.000Z
34.336538
80
0.760851
995,772
/* * 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 com.evangel.example.udp; import java.awt.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.ConcurrentHashMap; import javax.swing.*; import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.NioDatagramAcceptor; /** * The class that will accept and process clients in order to properly track the * memory usage. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class MemoryMonitor { private static final long serialVersionUID = 1L; public static final int PORT = 18567; protected static final Dimension PANEL_SIZE = new Dimension(300, 200); private JFrame frame; private JTabbedPane tabbedPane; private ConcurrentHashMap<SocketAddress, ClientPanel> clients; public MemoryMonitor() throws IOException { NioDatagramAcceptor acceptor = new NioDatagramAcceptor(); acceptor.setHandler(new MemoryMonitorHandler(this)); DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); chain.addLast("logger", new LoggingFilter()); DatagramSessionConfig dcfg = acceptor.getSessionConfig(); dcfg.setReuseAddress(true); frame = new JFrame("Memory monitor"); tabbedPane = new JTabbedPane(); tabbedPane.add("Welcome", createWelcomePanel()); frame.add(tabbedPane, BorderLayout.CENTER); clients = new ConcurrentHashMap<SocketAddress, ClientPanel>(); frame.pack(); frame.setLocation(300, 300); frame.setVisible(true); acceptor.bind(new InetSocketAddress(PORT)); System.out.println("UDPServer listening on port " + PORT); } private JPanel createWelcomePanel() { JPanel panel = new JPanel(); panel.setPreferredSize(PANEL_SIZE); panel.add(new JLabel("Welcome to the Memory Monitor")); return panel; } protected void recvUpdate(SocketAddress clientAddr, long update) { ClientPanel clientPanel = clients.get(clientAddr); if (clientPanel != null) { clientPanel.updateTextField(update); } else { System.err.println("Received update from unknown client"); } } protected void addClient(SocketAddress clientAddr) { if (!containsClient(clientAddr)) { ClientPanel clientPanel = new ClientPanel(clientAddr.toString()); tabbedPane.add(clientAddr.toString(), clientPanel); clients.put(clientAddr, clientPanel); } } protected boolean containsClient(SocketAddress clientAddr) { return clients.contains(clientAddr); } protected void removeClient(SocketAddress clientAddr) { clients.remove(clientAddr); } public static void main(String[] args) throws IOException { new MemoryMonitor(); } }
923147daa60db018defb343fd92ae9b97f720276
6,449
java
Java
src/ec/edu/ups/vista/VentanaIniciarSesion.java
mtoledot1/Practica-02-Programacion-Aplicada
bc1e1b6a0959091aef8676d595481893449d0270
[ "MIT" ]
1
2020-11-13T10:36:35.000Z
2020-11-13T10:36:35.000Z
src/ec/edu/ups/vista/VentanaIniciarSesion.java
mtoledot1/Practica-02-Programacion-Aplicada
bc1e1b6a0959091aef8676d595481893449d0270
[ "MIT" ]
null
null
null
src/ec/edu/ups/vista/VentanaIniciarSesion.java
mtoledot1/Practica-02-Programacion-Aplicada
bc1e1b6a0959091aef8676d595481893449d0270
[ "MIT" ]
null
null
null
44.171233
163
0.683982
995,773
/* * 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 ec.edu.ups.vista; import ec.edu.ups.controlador.ControladorPersona; import javax.swing.JOptionPane; /** * * @author tano */ public class VentanaIniciarSesion extends javax.swing.JInternalFrame { private ControladorPersona controladorPersona; private VentanaPrincipal ventanaPrincipal; public VentanaIniciarSesion(ControladorPersona controladorPersona, VentanaPrincipal ventanaPrincipal) { initComponents(); this.controladorPersona = controladorPersona; this.ventanaPrincipal = ventanaPrincipal; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lblCorreo = new javax.swing.JLabel(); txtCorreo = new javax.swing.JTextField(); lblPass = new javax.swing.JLabel(); txtPass = new javax.swing.JPasswordField(); btnIniciar = new javax.swing.JButton(); setClosable(true); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosed(evt); } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); lblCorreo.setText("Correo"); txtCorreo.setColumns(10); lblPass.setText("Contraseña"); txtPass.setColumns(10); btnIniciar.setText("Iniciar Sesión"); btnIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(72, 72, 72) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCorreo) .addComponent(lblPass)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(40, 40, 40)) .addGroup(layout.createSequentialGroup() .addGap(148, 148, 148) .addComponent(btnIniciar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblCorreo) .addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPass) .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(56, 56, 56) .addComponent(btnIniciar) .addContainerGap(81, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed String correo = txtCorreo.getText(); String pass = new String(txtPass.getPassword()); if(controladorPersona.iniciarSesion(correo, pass)){ ventanaPrincipal.getMenuAgenda().setVisible(true); ventanaPrincipal.getMenuItemCerrar().setVisible(true); limpiar(); JOptionPane.showMessageDialog(this, "Bienvenido", "Mensaje", JOptionPane.INFORMATION_MESSAGE); ventanaPrincipal.getMenuAgenda().setVisible(true); ventanaPrincipal.getMenuItemCerrar().setVisible(true); this.dispose(); }else{ JOptionPane.showMessageDialog(this, "Datos incorrectos", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnIniciarActionPerformed private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed limpiar(); }//GEN-LAST:event_formInternalFrameClosed public void limpiar(){ txtCorreo.setText(""); txtPass.setText(""); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnIniciar; private javax.swing.JLabel lblCorreo; private javax.swing.JLabel lblPass; private javax.swing.JTextField txtCorreo; private javax.swing.JPasswordField txtPass; // End of variables declaration//GEN-END:variables }
923148c6f18dfffe31240f54b6d6c019f3f6cd04
3,679
java
Java
src/java_tools/buildjar/java/com/google/devtools/build/buildjar/resourcejar/ResourceJarOptions.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
1
2021-06-11T19:51:12.000Z
2021-06-11T19:51:12.000Z
src/java_tools/buildjar/java/com/google/devtools/build/buildjar/resourcejar/ResourceJarOptions.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
null
null
null
src/java_tools/buildjar/java/com/google/devtools/build/buildjar/resourcejar/ResourceJarOptions.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
null
null
null
32.27193
100
0.720576
995,774
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.buildjar.resourcejar; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; /** Resource jar builder options. */ public class ResourceJarOptions { private final String output; private final ImmutableList<String> messages; private final ImmutableList<String> resources; private final ImmutableList<String> resourceJars; private final ImmutableList<String> classpathResources; public ResourceJarOptions( String output, ImmutableList<String> messages, ImmutableList<String> resources, ImmutableList<String> resourceJars, ImmutableList<String> classpathResources) { this.output = output; this.messages = messages; this.resources = resources; this.resourceJars = resourceJars; this.classpathResources = classpathResources; } public String output() { return output; } /** * Resources to include in the jar. * * <p>The format is {@code <prefix>:<name>}, where {@code <prefix>/<name>} is the path to the * resource file, and {code <name>} is the relative name that will be used for the resource jar * entry. */ public ImmutableList<String> resources() { return resources; } /** Message files to include in the resource jar. The format is the same as {@link #resources}. */ public ImmutableList<String> messages() { return messages; } /** Jar files of resources to append to the resource jar. */ public ImmutableList<String> resourceJars() { return resourceJars; } /** Files to include as top-level entries in the resource jar. */ public ImmutableList<String> classpathResources() { return classpathResources; } public static Builder builder() { return new Builder(); } /** A builder for {@link ResourceJarOptions}. */ public static class Builder { private String output; private ImmutableList<String> messages = ImmutableList.of(); private ImmutableList<String> resources = ImmutableList.of(); private ImmutableList<String> resourceJars = ImmutableList.of(); private ImmutableList<String> classpathResources = ImmutableList.of(); public ResourceJarOptions build() { return new ResourceJarOptions(output, messages, resources, resourceJars, classpathResources); } public Builder setOutput(String output) { this.output = checkNotNull(output); return this; } public Builder setMessages(ImmutableList<String> messages) { this.messages = checkNotNull(messages); return this; } public Builder setResources(ImmutableList<String> resources) { this.resources = checkNotNull(resources); return this; } public Builder setResourceJars(ImmutableList<String> resourceJars) { this.resourceJars = checkNotNull(resourceJars); return this; } public Builder setClasspathResources(ImmutableList<String> classpathResources) { this.classpathResources = checkNotNull(classpathResources); return this; } } }
923148eb710ffcda57074b507f87d5b1398b5824
2,875
java
Java
ApplianceGenerator.java
alekpop2/Java-Power-System-Management-Simulator
9e96159d85870da172a150c9484f632f30921c41
[ "MIT" ]
null
null
null
ApplianceGenerator.java
alekpop2/Java-Power-System-Management-Simulator
9e96159d85870da172a150c9484f632f30921c41
[ "MIT" ]
null
null
null
ApplianceGenerator.java
alekpop2/Java-Power-System-Management-Simulator
9e96159d85870da172a150c9484f632f30921c41
[ "MIT" ]
null
null
null
33.045977
87
0.671304
995,775
package cs116Project; import java.util.Scanner; import java.util.StringTokenizer; import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class ApplianceGenerator { public static int LOCATION_COUNT=100, APPLIANCES_PER_LOCATION_LOW=15, APPLIANCES_PER_LOCATION_HIGH=20; public static class Appliance { public String name; public int onW, offW; public double probOn; public boolean smart; public double probSmart; public Appliance (String n, int on, int off, double pOn, boolean s, double pSmart) { name=n; onW=on; offW=off; probOn=pOn; smart=s; probSmart=pSmart; } public String toString () { return name + "," + onW + "," + offW + "," + probOn + "," + smart + "," + probSmart; } } public static void main( String [] args ) throws IOException { Appliance [] app = new Appliance[100]; // default 100 possible appliance types File inputFile = new File( "ApplianceDetail.txt" ); Scanner scan = new Scanner( inputFile ); int count=0; while ( scan.hasNext( ) ) { StringTokenizer stringToken = new StringTokenizer(scan.nextLine()); app[count] = new Appliance(stringToken.nextToken(","), Integer.parseInt(stringToken.nextToken(",")), Integer.parseInt(stringToken.nextToken(",")), Double.parseDouble(stringToken.nextToken(",")), Boolean.parseBoolean(stringToken.nextToken(",")), Double.parseDouble(stringToken.nextToken())); count++; } /* output a comma delimited file the location (represented by an 8 digit numeric account number) type (string) "on" wattage used (integer) "off" wattage used (integer) probability (floating point, i.e..01=1%) that the appliance is "on" at any time smart (boolean) Smart appliances (if "on") power reduction percent (floating point, i.e..33=33%). */ try { FileWriter fw = new FileWriter( "output.txt", false); BufferedWriter bw = new BufferedWriter( fw ); for (long location=1;location<=LOCATION_COUNT ;location++ ) { int applianceCount=(int)(Math.random() * (APPLIANCES_PER_LOCATION_HIGH - APPLIANCES_PER_LOCATION_LOW+1)) + APPLIANCES_PER_LOCATION_LOW; for (int i=1;i<=applianceCount;i++ ){ int index=(int)(Math.random()*count); // pick an appliance randomly bw.write(String.valueOf(10000000+location)); bw.write( "," ); bw.write(app[index].name); bw.write( "," ); bw.write(String.valueOf(app[index].onW)); bw.write( "," ); bw.write(String.valueOf(app[index].offW)); bw.write( "," ); bw.write(String.valueOf(app[index].probOn)); bw.write( "," ); bw.write(String.valueOf(app[index].smart)); bw.write( "," ); bw.write(String.valueOf(app[index].probSmart)); bw.newLine( ); bw.flush(); } } bw.close(); } catch( IOException ioe ) { ioe.printStackTrace( ); } } }
9231491c69f96a6520b7e3edc8cb1919078cefd8
3,451
java
Java
mobile/src/main/java/com/marcouberti/sonicboomwatchface/ConfigListModel.java
marcouberti/sonic_boom_watch_face
2dc9f0f4a2324bdd6eecfe338c889c4886005a5a
[ "Apache-2.0" ]
21
2016-12-21T15:45:35.000Z
2019-06-23T08:48:25.000Z
mobile/src/main/java/com/marcouberti/sonicboomwatchface/ConfigListModel.java
marcouberti/sonic_boom_watch_face
2dc9f0f4a2324bdd6eecfe338c889c4886005a5a
[ "Apache-2.0" ]
null
null
null
mobile/src/main/java/com/marcouberti/sonicboomwatchface/ConfigListModel.java
marcouberti/sonic_boom_watch_face
2dc9f0f4a2324bdd6eecfe338c889c4886005a5a
[ "Apache-2.0" ]
3
2018-06-04T14:44:56.000Z
2019-06-23T08:48:29.000Z
25.375
64
0.553463
995,776
package com.marcouberti.sonicboomwatchface; import java.io.Serializable; import java.util.ArrayList; /** * Created by Marco on 01/12/15. */ public class ConfigListModel implements Serializable{ public static int TYPE_UNKNOWN = -1; public static int TYPE_GROUP = 0; public static int TYPE_SEPARATOR = 1; public static int TYPE_ACCENT_COLOR = 2; public static int TYPE_SECOND_TIMEZONE = 3; public static int TYPE_RATE_THIS_ASPP = 4; public static int TYPE_FOOTER = 5; private ArrayList<Item> items= new ArrayList<>(); public void clear() { items.clear(); } public Item getItemByAbsoluteIndex(int absoluteIndex) { for(int i=0; i<items.size(); i++) { if(i == absoluteIndex) return items.get(i); } return null; } public int getRowType(int absoluteIndex) { for(int i=0; i<items.size(); i++) { if(i == absoluteIndex) { Item item = items.get(i); if (item instanceof GroupItem) { return TYPE_GROUP; } else if (item instanceof SeparatorItem) { return TYPE_SEPARATOR; } else if (item instanceof AccentColorItem) { return TYPE_ACCENT_COLOR; } else if (item instanceof SecondTimezoneItem) { return TYPE_SECOND_TIMEZONE; }else if (item instanceof RateAppItem) { return TYPE_RATE_THIS_ASPP; }else if (item instanceof FooterItem) { return TYPE_FOOTER; }else{ return TYPE_UNKNOWN; } } } return TYPE_UNKNOWN; } public void addItem(Item item) { items.add(item); } public int getTotalRowCount() { return items.size(); } //region items classes /** * Base list item type */ public static class Item implements Serializable{ public boolean disabled = false; public Item() {} } /** * Generic group item */ public static class GroupItem extends Item { public int keyTitleRes; public GroupItem(int keyTitleRes) { super(); this.keyTitleRes = keyTitleRes; } } /** * Generic separator item */ public static class SeparatorItem extends Item { public SeparatorItem() { super(); } } /** * Generic button item */ public static class RateAppItem extends Item { public int keyTitleRes; public RateAppItem(int keyTitleRes) { super(); this.keyTitleRes = keyTitleRes; } } /** * Generic action item */ public static class AccentColorItem extends Item { public String colorName; public int colorID; public AccentColorItem(String colorName, int colorID) { super(); this.colorName = colorName; this.colorID = colorID; } } /** * Custom footer item */ public static class FooterItem extends Item { public FooterItem() { super(); } } /** * Generica activity navigation item */ public static class SecondTimezoneItem extends Item { public SecondTimezoneItem() { super(); } } //endregion }
923149274de6946ee3e4314199cedf5d7a274a6f
2,633
java
Java
hmf-common/src/main/java/com/hartwig/hmftools/common/circos/CircosFileWriter.java
j-hudecek/hmftools
f619e02cdb166594e7dd4d7d1dd7fe8592267f2d
[ "MIT" ]
null
null
null
hmf-common/src/main/java/com/hartwig/hmftools/common/circos/CircosFileWriter.java
j-hudecek/hmftools
f619e02cdb166594e7dd4d7d1dd7fe8592267f2d
[ "MIT" ]
null
null
null
hmf-common/src/main/java/com/hartwig/hmftools/common/circos/CircosFileWriter.java
j-hudecek/hmftools
f619e02cdb166594e7dd4d7d1dd7fe8592267f2d
[ "MIT" ]
null
null
null
38.720588
114
0.652108
995,777
package com.hartwig.hmftools.common.circos; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collection; import java.util.function.Function; import java.util.function.ToDoubleFunction; import com.google.common.collect.Lists; import com.hartwig.hmftools.common.position.GenomePosition; import com.hartwig.hmftools.common.region.GenomeRegion; import org.jetbrains.annotations.NotNull; public class CircosFileWriter { public static <T extends GenomeRegion> void writeRegions(@NotNull final String filePath, @NotNull Collection<T> values, @NotNull ToDoubleFunction<T> valueExtractor) throws IOException { Function<T, String> toString = t -> transformRegion(valueExtractor, t); writeCircosFile(filePath, values, toString); } public static <T extends GenomePosition> void writePositions(@NotNull final String filePath, @NotNull Collection<T> values, @NotNull ToDoubleFunction<T> valueExtractor) throws IOException { Function<T, String> toString = t -> transformPosition(valueExtractor, t); writeCircosFile(filePath, values, toString); } private static <T> void writeCircosFile(@NotNull final String filePath, @NotNull Collection<T> values, Function<T, String> toStringFunction) throws IOException { final Collection<String> lines = Lists.newArrayList(); lines.add(header()); values.stream().map(toStringFunction).forEach(lines::add); Files.write(new File(filePath).toPath(), lines); } private static String header() { return "#chromosome\tstart\tend\tvalue"; } private static <T extends GenomePosition> String transformPosition(ToDoubleFunction<T> valueExtractor, T position) { return new StringBuilder().append("hs") .append(position.chromosome()) .append('\t') .append(position.position()) .append('\t') .append(position.position()) .append('\t') .append(valueExtractor.applyAsDouble(position)) .toString(); } private static <T extends GenomeRegion> String transformRegion(ToDoubleFunction<T> valueExtractor, T region) { return new StringBuilder().append("hs") .append(region.chromosome()) .append('\t') .append(region.start()) .append('\t') .append(region.end()) .append('\t') .append(valueExtractor.applyAsDouble(region)) .toString(); } }
923149421c51d666b703eb0a0d83aeb36e775b12
13,896
java
Java
src/main/java/fi/jgke/minpascal/compiler/std/CExpressionResult.java
jgke/minpascal
a050919bebd84e8852cb6985dfea55f68212bf3a
[ "Apache-2.0" ]
null
null
null
src/main/java/fi/jgke/minpascal/compiler/std/CExpressionResult.java
jgke/minpascal
a050919bebd84e8852cb6985dfea55f68212bf3a
[ "Apache-2.0" ]
null
null
null
src/main/java/fi/jgke/minpascal/compiler/std/CExpressionResult.java
jgke/minpascal
a050919bebd84e8852cb6985dfea55f68212bf3a
[ "Apache-2.0" ]
null
null
null
51.276753
190
0.576209
995,778
package fi.jgke.minpascal.compiler.std; import com.google.common.collect.Streams; import fi.jgke.minpascal.astparser.nodes.AstNode; import fi.jgke.minpascal.compiler.CType; import fi.jgke.minpascal.compiler.IdentifierContext; import fi.jgke.minpascal.data.Position; import fi.jgke.minpascal.exception.TypeError; import lombok.Data; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static fi.jgke.minpascal.compiler.IdentifierContext.genIdentifier; @Data public class CExpressionResult { private final CType type; private String identifier; private final List<String> temporaries; private final List<String> post; public CExpressionResult(CType type, String identifier, List<String> temporaries, List<String> post) { this.type = type; this.identifier = identifier; this.temporaries = new ArrayList<>(temporaries); this.post = new ArrayList<>(post); } public static CExpressionResult fromExpression(AstNode arg) { AstNode left = arg.getFirstChild("SimpleExpression"); AstNode relOp = arg.getFirstChild("RelOp"); return relOp.toOptional().map(rel -> getType(fromSimple(left), getRelOp(rel), fromSimple(rel.getFirstChild("RelOp").getFirstChild("SimpleExpression")), arg.getPosition()) ).orElse(fromSimple(left)); } private static String getAddOp(AstNode node) { return node.getFirstChild("AddOp").getFirstChild("AddOp") .<String>toMap() .map("plus", AstNode::getContentString) .map("minus", AstNode::getContentString) .map("or", AstNode::getContentString) .unwrap(); } private static String getRelOp(AstNode node) { return node.getFirstChild("RelOp").getFirstChild("RelOp") .<String>toMap() .map("lessthanequals", AstNode::getContentString) .map("morethanequals", AstNode::getContentString) .map("lessthan", AstNode::getContentString) .map("morethan", AstNode::getContentString) .map("notequals", AstNode::getContentString) .map("equals", AstNode::getContentString) .unwrap(); } private static CExpressionResult fromSimple(AstNode simple) { simple = simple.getFirstChild("Sign"); Optional<String> sign = simple.getFirstChild("Sign") .toOptional() .map(CExpressionResult::getSign); AstNode left = simple.getFirstChild("Term"); return left.getFirstChild("AddOp").toOptional() .map(add -> getType( addSign(sign, left.getPosition()).apply(fromTerm(left.getFirstChild("Term"))), getAddOp(add), fromTerm(add.getFirstChild("AddOp").getFirstChild("Term")), left.getPosition() )).orElse(addSign(sign, left.getPosition()).apply(fromTerm(left.getFirstChild("Term")))); } private static CExpressionResult getType(CExpressionResult left, String op, CExpressionResult right, Position position) { return CBinaryExpressions.apply(left, CBinaryExpressionFnPrivate.getOperator(op), right, position); } private static Function<CExpressionResult, CExpressionResult> addSign(Optional<String> sign, Position position) { return result -> { sign.ifPresent(s -> { CType type = result.getType(); if (!type.equals(CType.CINTEGER) && !type.equals(CType.CDOUBLE)) throw new TypeError("Expected integer or real, got " + type.formatType(), position); String id = genIdentifier(); result.temporaries.add(type.toDeclaration(id, Optional.empty()) + " = " + s + " " + result.getIdentifier()); result.identifier = id; }); return result; }; } private static String getMulOp(AstNode node) { return node.getFirstChild("MulOp").getFirstChild("MulOp") .<String>toMap() .map("times", AstNode::getContentString) .map("mod", AstNode::getContentString) .map("divide", AstNode::getContentString) .map("and", AstNode::getContentString) .unwrap(); } private static CExpressionResult fromTerm(AstNode left) { AstNode relOp = left.getFirstChild("MulOp"); return relOp.toOptional().map(rel -> getType(fromFactor(left.getFirstChild("Factor")), getMulOp(rel), fromFactor(rel.getFirstChild("MulOp").getFirstChild("Factor")), relOp.getPosition()) ).orElse(fromFactor(left.getFirstChild("Factor"))); } private static CExpressionResult fromFactor(AstNode factor) { Optional<String> post = factor.getFirstChild("SizeExpression") .toOptional() .map($ -> "[-1]"); AstNode subFactor = factor.getFirstChild("SubFactor"); CExpressionResult unwrap = subFactor.<CExpressionResult>toMap() .map("Variable", CExpressionResult::fromVariable) .map("Literal", CExpressionResult::getLiteralType) .map("op", p -> CExpressionResult.fromExpression(p.getFirstChild("Expression"))) .map("not", CExpressionResult::fromNot) .unwrap(); if (post.isPresent()) { String identifier = unwrap.getIdentifier(); CType type = unwrap.getType().getPtrTo() .orElseThrow(() -> new TypeError("Expected " + identifier + " to be an array but it isn't", factor.getPosition())); String s = post.get(); String tmp = genIdentifier(); ArrayList<String> temps = new ArrayList<>(unwrap.getTemporaries()); temps.add(type.toDeclaration(tmp, Optional.empty()) + " = " + identifier + s + ";"); unwrap = new CExpressionResult(type, tmp, temps, unwrap.getPost()); } return unwrap; } private static CExpressionResult fromNot(AstNode astNode) { CExpressionResult factor = fromFactor(astNode.getFirstChild("Factor")); if (!factor.getType().equals(CType.CBOOLEAN)) { throw new TypeError("Expected boolean but got " + factor.getType().formatType(), astNode.getPosition()); } String identifier = factor.getIdentifier(); factor.getTemporaries().add(identifier + " = !" + identifier + ";"); return factor; } private static CExpressionResult fromVariable(AstNode astNode) { String identifier = astNode .getFirstChild("Variable") .getFirstChild("identifier").getContentString(); Optional<AstNode> arrayIndex = astNode.getFirstChild("Variable") .getFirstChild("ob").toOptional(); CType type = IdentifierContext.getType(identifier, astNode.getPosition()); String realName = IdentifierContext.getRealName(identifier, astNode.getPosition()); Function<CExpressionResult, CExpressionResult> addPre = Function.identity(); if (arrayIndex.isPresent()) { AstNode idx = arrayIndex.get(); String finalIdentifier1 = identifier; String newIdentifier = genIdentifier(); type = type.getPtrTo() .orElseThrow(() -> new TypeError("Expected " + finalIdentifier1 + " to be an array but it isn't", astNode.getPosition())); IdentifierContext.addIdentifier(newIdentifier, type, astNode.getPosition()); CExpressionResult cExpressionResult = fromExpression(idx.getFirstChild("ob").getFirstChild("Expression")); identifier = newIdentifier; realName = newIdentifier; CType finalType1 = type; String assertionCondition = cExpressionResult.getIdentifier() + " <= " + finalIdentifier1 + "[-1]"; String assertion = "_builtin_assert(" + assertionCondition + ", " + idx.getPosition().getLine() + ", " + idx.getPosition().getColumn() + ");\n"; addPre = o -> { cExpressionResult.getTemporaries().add(assertion); cExpressionResult.getTemporaries().add(finalType1.toDeclaration(newIdentifier, Optional.empty()) + " = " + finalIdentifier1 + "[" + cExpressionResult.getIdentifier() + "];"); o.getTemporaries().addAll(0, cExpressionResult.getTemporaries()); o.getPost().addAll(cExpressionResult.getPost()); return o; }; } CType finalType = type; String finalIdentifier = identifier; String finalRealName = realName; return addPre.apply(astNode.getFirstChild("Arguments").toOptional() .map(args -> fromCall(finalIdentifier, finalType, args)) .orElseGet(() -> new CExpressionResult(finalType, finalRealName, Collections.emptyList(), Collections.emptyList()))); } private static String getSign(AstNode sign) { return sign.<String>toMap() .map("plus", $ -> "+") .map("minus", $ -> "-") .unwrap(); } private static CExpressionResult fromCall(String identifier, CType type, AstNode call) { CType returnType = type.getReturnType() .orElseThrow(() -> new TypeError(identifier + " isn't a function", call.getPosition())); List<CExpressionResult> expressions = CExpressionResult.getArguments(call.getFirstChild("Arguments")); List<String> temporaries = expressions.stream() .flatMap(e -> e.getTemporaries().stream()) .collect(Collectors.toList()); List<String> post = expressions.stream() .flatMap(e -> e.getPost().stream()) .collect(Collectors.toList()); if (type.getParameters().size() != expressions.size()) { throw new TypeError("Invalid arity: Got " + expressions.size() + " parameters but expected " + type.getParameters().size(), call.getPosition()); } String arguments = Streams.zip(expressions.stream(), type.getParameters().stream(), (a, b) -> a.getType().assignTo(b, a.getIdentifier(), call.getPosition())) .collect(Collectors.joining(",")); String result = genIdentifier(); temporaries.add(returnType.toDeclaration(result, Optional.empty()) + " = " + IdentifierContext.getRealName(identifier, call.getPosition()) + "(" + arguments + ");"); return new CExpressionResult(returnType, result, temporaries, post); } private static CExpressionResult toExpression(CType type, Object value) { String id = genIdentifier(); return new CExpressionResult(type, id, Collections.singletonList(type.toDeclaration(id, Optional.empty()) + " = " + value + ";"), Collections.emptyList()); } private static CExpressionResult getLiteralType(AstNode literalNode) { return literalNode.<CExpressionResult>toMap() .map("realliteral", d -> toExpression(CType.CDOUBLE, Double.parseDouble(d.getContentString()))) .map("integerliteral", d -> toExpression(CType.CINTEGER, Integer.parseInt(d.getContentString()))) .map("stringliteral", d -> toExpression(CType.CSTRING, d.getContentString())) .unwrap(); } public static String formatExpressions(List<CExpressionResult> expressions, Function<List<CExpressionResult>, Object> core) { List<List<String>> steps = new ArrayList<>(); List<String> post = new ArrayList<>(); for (CExpressionResult result : expressions) { steps.add(result.getTemporaries()); post.addAll(result.getPost()); } String pre = steps.stream() .map(list -> list.stream() .collect(Collectors.joining("\n")) + "\n") .collect(Collectors.joining("\n")) + "\n"; String clean = post.stream().collect(Collectors.joining("\n")) + "\n"; return pre + core.apply(expressions) + clean; } public static List<CExpressionResult> getArguments(AstNode argumentsNode) { Optional<AstNode> astNode = argumentsNode.getFirstChild("Expression") .getFirstChild("Expression").toOptional(); return astNode.map(args -> Stream.concat(Stream.of(args.getFirstChild("Expression")), args.getFirstChild("more") .getList().stream() .map(m -> m.getFirstChild("Expression"))) .map(CExpressionResult::fromExpression) .collect(Collectors.toList())) .orElse(Collections.emptyList()); } }
923149accde32eb73d82e4f6ac7c8a121c8a874f
4,427
java
Java
src/main/java/waveview/SingleBitPainter.java
jbush001/WaveView
a0a162844a19537ec21c1cc845af21b87674d748
[ "Apache-2.0" ]
11
2016-11-24T01:40:59.000Z
2021-04-22T05:35:17.000Z
src/main/java/waveview/SingleBitPainter.java
jbush001/WaveView
a0a162844a19537ec21c1cc845af21b87674d748
[ "Apache-2.0" ]
37
2016-08-15T14:23:33.000Z
2019-02-05T15:36:38.000Z
src/main/java/waveview/SingleBitPainter.java
jbush001/WaveView
a0a162844a19537ec21c1cc845af21b87674d748
[ "Apache-2.0" ]
3
2016-09-21T20:52:23.000Z
2021-04-22T05:35:20.000Z
37.837607
93
0.586176
995,779
// // Copyright 2011-2012 Jeff Bush // // 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 waveview; import java.awt.Graphics; import java.awt.Rectangle; import java.util.Iterator; import waveview.wavedata.BitValue; import waveview.wavedata.Transition; import waveview.wavedata.TransitionVector; /// /// Delegate that draws the waveform for a single net that has only one /// bit in it. /// final class SingleBitPainter implements WaveformPainter { @Override public void paint(Graphics g, TransitionVector transitionVector, int topOffset, Rectangle visibleRect, double horizontalScale, ValueFormatter formatter) { g.setColor(AppPreferences.getInstance().waveformColor); BitValue lastValue = BitValue.ZERO; int lastX = visibleRect.x + visibleRect.width; long firstTimestamp = (long) (visibleRect.x / horizontalScale); Iterator<Transition> i = transitionVector.findTransition(firstTimestamp); while (true) { Transition transition = i.next(); // Compute the boundaries of this segment int x = (int) (transition.getTimestamp() * horizontalScale); BitValue value = transition.getBit(0); drawSpan(g, lastValue, lastX, x, topOffset); // Draw transition line at beginning of interval drawTransition(g, value, lastValue, x, topOffset); if (x > visibleRect.x + visibleRect.width) { break; } lastValue = value; lastX = x; if (!i.hasNext()) { drawSpan(g, lastValue, x, visibleRect.x + visibleRect.width, topOffset); break; } } } private void drawTransition( Graphics g, BitValue value, BitValue lastValue, int x, int topOffset) { if (lastValue != value) { if (lastValue == BitValue.Z && value != BitValue.X) { if (value == BitValue.ZERO) { g.drawLine(x, topOffset + DrawMetrics.WAVEFORM_HEIGHT / 2, x, topOffset + DrawMetrics.WAVEFORM_HEIGHT); } else { g.drawLine(x, topOffset + DrawMetrics.WAVEFORM_HEIGHT / 2, x, topOffset); } } else if (value == BitValue.Z && lastValue != BitValue.X) { if (lastValue == BitValue.ZERO) { g.drawLine(x, topOffset + DrawMetrics.WAVEFORM_HEIGHT, x, topOffset + DrawMetrics.WAVEFORM_HEIGHT / 2); } else { g.drawLine(x, topOffset, x, topOffset + DrawMetrics.WAVEFORM_HEIGHT / 2); } } else { g.drawLine(x, topOffset, x, topOffset + DrawMetrics.WAVEFORM_HEIGHT); } } } private void drawSpan(Graphics g, BitValue value, int left, int right, int top) { if (left >= right) { return; } switch (value) { case ONE: g.drawLine(left, top, right, top); break; case ZERO: g.drawLine(left, top + DrawMetrics.WAVEFORM_HEIGHT, right, top + DrawMetrics.WAVEFORM_HEIGHT); break; case Z: g.drawLine(left, top + DrawMetrics.WAVEFORM_HEIGHT / 2, right, top + DrawMetrics.WAVEFORM_HEIGHT / 2); break; case X: default: g.setColor(AppPreferences.getInstance().conflictColor); g.fillRect(left, top, right - left, DrawMetrics.WAVEFORM_HEIGHT); g.setColor(AppPreferences.getInstance().waveformColor); g.drawLine(left, top, right, top); g.drawLine(left, top + DrawMetrics.WAVEFORM_HEIGHT, right, top + DrawMetrics.WAVEFORM_HEIGHT); break; } } }
923149b620158ba2f797fe5bf081fb447b079209
977
java
Java
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/OClusterAwareWALRecord.java
jeff90/orientdb
1db47be6f1780e5d00db1883c80e489f5991bd33
[ "Apache-2.0" ]
1
2016-07-18T21:23:06.000Z
2016-07-18T21:23:06.000Z
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/OClusterAwareWALRecord.java
jeff90/orientdb
1db47be6f1780e5d00db1883c80e489f5991bd33
[ "Apache-2.0" ]
4
2020-05-15T22:14:37.000Z
2022-03-08T21:12:01.000Z
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/OClusterAwareWALRecord.java
jeff90/orientdb
1db47be6f1780e5d00db1883c80e489f5991bd33
[ "Apache-2.0" ]
1
2015-05-25T15:44:28.000Z
2015-05-25T15:44:28.000Z
32.566667
80
0.683726
995,780
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.core.storage.impl.local.paginated.wal; /** * @author Andrey Lomakin * @since 30.05.13 */ public interface OClusterAwareWALRecord { int getClusterId(); }
92314a1a1365886e780a0707bf466017188dbbb4
9,860
java
Java
project-generator/src/com/nkasenides/athlos/generator/client/JavaStubManagerGenerator.java
nkasenides/athlos
e60cc12cab5c36e79f85d897ee52861afbe1450a
[ "Apache-2.0" ]
null
null
null
project-generator/src/com/nkasenides/athlos/generator/client/JavaStubManagerGenerator.java
nkasenides/athlos
e60cc12cab5c36e79f85d897ee52861afbe1450a
[ "Apache-2.0" ]
null
null
null
project-generator/src/com/nkasenides/athlos/generator/client/JavaStubManagerGenerator.java
nkasenides/athlos
e60cc12cab5c36e79f85d897ee52861afbe1450a
[ "Apache-2.0" ]
null
null
null
55.393258
231
0.54929
995,781
package com.nkasenides.athlos.generator.client; import com.nkasenides.athlos.editor.Main; import com.nkasenides.athlos.editor.model.service.ServiceModel; import com.nkasenides.athlos.editor.model.service.ServiceType; import com.nkasenides.athlos.editor.model.type.ActionModel; import com.nkasenides.athlos.editor.settings.RuntimeEnvironmentType; import com.nkasenides.athlos.editor.settings.ServerlessType; import com.nkasenides.athlos.editor.util.FileManager; import com.nkasenides.athlos.editor.util.IOUtils; import com.nkasenides.athlos.generator.main.MainGenerator; import com.nkasenides.athlos.generator.util.GenStringBuilder; import java.io.File; import java.util.Map; public class JavaStubManagerGenerator extends StubManagerGenerator { @Override public void generate(String filePath) throws Exception { builder.appendLine(generateHeader()); builder.appendLine(generateContainer()); builder.appendLine(generateImports()); builder.appendLine(generateClassDefinition()); builder.appendLine(generateStaticAttributes()); builder.appendLine(generateNonStaticAttributes()); builder.appendLine(generateConstructor()); builder.appendLine("}"); final String classFolderPath = filePath + File.separator + "client" + File.separator + "stubs"; if (!FileManager.isDirectory(classFolderPath)) { FileManager.createDirectory(classFolderPath, true); } final String classFilePath = classFolderPath + File.separator + "Stubs." + Main.CURRENT_PROJECT_CONFIG.getServerEnvironmentType().getSourceFileExtension(); FileManager.writeFile(classFilePath, builder.toString()); } public String generateHeader() { return MainGenerator.generateInfoHeader(); } public String generateImports() { if (Main.CURRENT_PROJECT_CONFIG.getRuntimeEnvironmentType() == RuntimeEnvironmentType.SERVERLESS) { switch (Main.CURRENT_PROJECT_CONFIG.getPreferredServerless()) { case NONE: break; case APP_ENGINE_STANDARD: return "import com.raylabz.mocha.Mocha;\n" + "import " + Main.CURRENT_PROJECT_CONFIG.getContainerName() + ".client." + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client;\n" + "import java.io.IOException;\n" + "import java.util.HashMap;\n"; case APP_ENGINE_FLEXIBLE: int numOfWebsockets = Main.CURRENT_PROJECT_CONFIG.getActionModels().size(); for (ServiceModel serviceModel : Main.CURRENT_PROJECT_CONFIG.getServiceModels().values()) { if (serviceModel.getServiceType() == ServiceType.S_TO_S || serviceModel.getServiceType() == ServiceType.M_TO_S) { numOfWebsockets++; } } return "import " + Main.CURRENT_PROJECT_CONFIG.getContainerName() + ".client." + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client;\n" + ( numOfWebsockets > 0 ? "import " + Main.CURRENT_PROJECT_CONFIG.getContainerName() + ".client.websocket.*;\n" + "import com.neovisionaries.ws.client.WebSocketException;\n" : "" ) + "import java.io.IOException;\n" + "import java.util.HashMap;\n" + "import com.raylabz.mocha.Mocha;\n"; case GOOGLE_CLOUD_FUNCTIONS: return "import com.raylabz.mocha.Mocha;\n" + "import " + Main.CURRENT_PROJECT_CONFIG.getContainerName() + ".client." + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client;\n" + "import java.io.IOException;\n" + "import java.util.HashMap;\n"; } } return ""; } public String generateContainer() { return "package " + packagePath + ".client.stubs;\n"; } public String generateClassDefinition() { return "public final class Stubs {\n"; } public String generateStaticAttributes() { GenStringBuilder builder = new GenStringBuilder(); builder.addIndent(); builder.appendDoubleLine("public static final String BASE_URL = \"" + Main.CURRENT_PROJECT_CONFIG.getBaseURL() + "\";"); if (Main.CURRENT_PROJECT_CONFIG.getRuntimeEnvironmentType() == RuntimeEnvironmentType.SERVERLESS) { switch (Main.CURRENT_PROJECT_CONFIG.getPreferredServerless()) { case NONE: break; case APP_ENGINE_STANDARD: case GOOGLE_CLOUD_FUNCTIONS: builder.appendLine("public static class Actions {").addIndent(); for (Map.Entry<String, ActionModel> action : Main.CURRENT_PROJECT_CONFIG.getActionModels().entrySet()) { builder.appendLine("public static " + action.getKey() + " " + IOUtils.decapitalize(action.getKey()) + "Stub() {") .addIndent() .appendLine("return new " + action.getKey() + "();") .removeIndent() .appendLine("}"); } builder.removeIndent().appendDoubleLine("}"); break; case APP_ENGINE_FLEXIBLE: builder.appendLine("public static class Actions {").addIndent(); for (Map.Entry<String, ActionModel> action : Main.CURRENT_PROJECT_CONFIG.getActionModels().entrySet()) { builder.appendDoubleLine("\n" + " private static final HashMap<String, " + action.getKey() + "Stub> " + IOUtils.decapitalize(action.getKey()) + "StubsMap = new HashMap<>();\n" + " public static " + action.getKey() + "Stub get" + action.getKey() + "Stub(" + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client client) throws WebSocketException, IOException {\n" + " if (" + IOUtils.decapitalize(action.getKey()) + "StubsMap.get(client.getPlayer().getId()) == null) {\n" + " final " + action.getKey() + "Stub stub = new " + action.getKey() + "Stub(client);\n" + " Mocha.start(stub);\n" + " " + IOUtils.decapitalize(action.getKey()) + "StubsMap.put(client.getPlayer().getId(), stub);\n" + " }\n" + " return " + IOUtils.decapitalize(action.getKey()) + "StubsMap.get(client.getPlayer().getId());\n" + " }"); } builder.removeIndent().appendDoubleLine("}"); break; } } for (Map.Entry<String, ServiceModel> service : Main.CURRENT_PROJECT_CONFIG.getServiceModels().entrySet()) { if (service.getValue().getServiceType() == ServiceType.M_TO_M) { builder.appendDoubleLine("\n\n" + " private static final HashMap<String, " + service.getKey() + "> " + IOUtils.decapitalize(service.getKey()) + "StubMap = new HashMap<>();\n" + " public static " + service.getKey() + " " + IOUtils.decapitalize(service.getKey()) + "Stub(" + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client client) {\n" + " if (" + IOUtils.decapitalize(service.getKey()) + "StubMap.get(client.getPlayer().getId()) == null) {\n" + " final " + service.getKey() + " stub = new " + service.getKey() + "();\n" + " " + IOUtils.decapitalize(service.getKey()) + "StubMap.put(client.getPlayer().getId(), stub);\n" + " }\n" + " return " + IOUtils.decapitalize(service.getKey()) + "StubMap.get(client.getPlayer().getId());\n" + " }\n"); } else if (service.getValue().getServiceType() == ServiceType.S_TO_S) { builder.appendDoubleLine("\n" + " private static final HashMap<String, " + service.getKey() + "Stub> " + IOUtils.decapitalize(service.getKey()) + "StubsMap = new HashMap<>();\n" + " public static " + service.getKey() + "Stub get" + service.getKey() + "Stub(" + Main.CURRENT_PROJECT_CONFIG.getGameAbbreviation() + "Client client) throws WebSocketException, IOException {\n" + " if (" + IOUtils.decapitalize(service.getKey()) + "StubsMap.get(client.getPlayer().getId()) == null) {\n" + " final " + service.getKey() + "Stub stub = new " + service.getKey() + "Stub(client);\n" + " Mocha.start(stub);\n" + " " + IOUtils.decapitalize(service.getKey()) + "StubsMap.put(client.getPlayer().getId(), stub);\n" + " }\n" + " return " + IOUtils.decapitalize(service.getKey()) + "StubsMap.get(client.getPlayer().getId());\n" + " }\n\n"); } } return builder.toString(); } public String generateNonStaticAttributes() { return ""; } public String generateConstructor() { return ""; } }
92314a56e936d211dd6c3e40b8ee098b51db5da3
8,111
java
Java
src/interfaceGrafica/JanelaPrincipal.java
gustavoresque/ProgramacaoII_2019
1dc0b1690c018d134ecffeb2b043e19556db6499
[ "MIT" ]
null
null
null
src/interfaceGrafica/JanelaPrincipal.java
gustavoresque/ProgramacaoII_2019
1dc0b1690c018d134ecffeb2b043e19556db6499
[ "MIT" ]
null
null
null
src/interfaceGrafica/JanelaPrincipal.java
gustavoresque/ProgramacaoII_2019
1dc0b1690c018d134ecffeb2b043e19556db6499
[ "MIT" ]
2
2019-09-18T20:02:37.000Z
2019-09-18T21:03:25.000Z
42.244792
136
0.621625
995,782
/* * 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 interfaceGrafica; import aula1.Mago; import aula1.Personagem; import javax.swing.JFrame; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * * @author Gustavo */ public class JanelaPrincipal extends JFrame { int contador=0; private Personagem p; /** * Creates new form JanelaPrincipal */ public JanelaPrincipal(Personagem p) { initComponents(); this.p = p; ThreadDeBatalha tb = new ThreadDeBatalha(p); tb.setListener(new ThreadDeBatalha.BattleActionListener() { @Override public void battleEnd() { labelForca.setText("Força: "+p.getForca()); labelInteligencia .setText("Inteligência: "+p.getInteligencia()); } @Override public void roundEnd(Personagem p, Personagem en) { tAreaLog.setText(p.getApelido()+" tem " +p.getHp()+ " de HP e o enimo "+ en.getApelido()+" tem "+ en.getHp()+" de HP.\n"+ tAreaLog.getText()); } }); tb.start(); // p.apelido = "alo"; this.labelApelido.setText(p.getApelido()); this.labelForca.setText("Força: "+p.getForca()); this.labelInteligencia .setText("Inteligência: "+p.getInteligencia()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tAreaLog = new javax.swing.JTextArea(); labelApelido = new javax.swing.JLabel(); labelForca = new javax.swing.JLabel(); labelInteligencia = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); tAreaLog.setEditable(false); tAreaLog.setColumns(20); tAreaLog.setRows(5); jScrollPane1.setViewportView(tAreaLog); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 162, Short.MAX_VALUE)) ); labelApelido.setText("jLabel1"); labelForca.setText("jLabel1"); labelInteligencia.setText("jLabel2"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelApelido) .addComponent(labelForca)) .addComponent(labelInteligencia)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelApelido) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelForca) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelInteligencia) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(JanelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(JanelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(JanelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(JanelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> //// JanelaPrincipal jp = new JanelaPrincipal(); //// jp.setVisible(true); // // /* Create and display the form */ // EventQueue.invokeLater(() -> { // new JanelaPrincipal().setVisible(true); // }); //// JanelaPrincipal.MinhaThread mt = new MinhaThread(); //// EventQueue.invokeLater(mt); // } // public static class MinhaThread implements Runnable{ // // @Override // public void run() { // JanelaPrincipal jp = new JanelaPrincipal(); // jp.setVisible(true); // } // // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel labelApelido; private javax.swing.JLabel labelForca; private javax.swing.JLabel labelInteligencia; private javax.swing.JTextArea tAreaLog; // End of variables declaration//GEN-END:variables }
92314ad0b2bc3d979c94b614e4a0d1657c42dd12
928
java
Java
src/main/java/com/biskot/app/rest/CartResponseAdapter.java
zomet/biskot-api
e6d4782e1f14ebf537cf5b178efa9bc1f023250f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/biskot/app/rest/CartResponseAdapter.java
zomet/biskot-api
e6d4782e1f14ebf537cf5b178efa9bc1f023250f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/biskot/app/rest/CartResponseAdapter.java
zomet/biskot-api
e6d4782e1f14ebf537cf5b178efa9bc1f023250f
[ "Apache-2.0" ]
null
null
null
33.142857
172
0.710129
995,783
package com.biskot.app.rest; import com.biskot.domain.model.Cart; import org.springframework.stereotype.Component; import java.util.stream.Collectors; @Component public class CartResponseAdapter { private final ItemResponeAdapter itemResponeAdapter; public CartResponseAdapter(ItemResponeAdapter itemResponeAdapter) { this.itemResponeAdapter = itemResponeAdapter; } public CartResponse fromCart(Cart cart) { CartResponse cartResponse = new CartResponse(); cartResponse.setId(cart.getId().getValue()); cartResponse.setItems(cart.getItems() .stream() .map(itemResponeAdapter::fromItem) .collect(Collectors.toList())); cartResponse.setTotalPrice(cartResponse.getItems().stream().map(itemResponse -> itemResponse.getUnitPrice() * itemResponse.getQuantity()).reduce(0.0, Double::sum)); return cartResponse; } }
92314c582b804f43588c3bfbc9b00339773afcf0
978
java
Java
examples/integrationTest/src/main/java/org/androidtransfuse/integrationTest/About.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
114
2015-01-04T09:46:29.000Z
2021-11-09T10:58:46.000Z
examples/integrationTest/src/main/java/org/androidtransfuse/integrationTest/About.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
72
2015-01-23T20:13:05.000Z
2021-01-20T09:27:57.000Z
examples/integrationTest/src/main/java/org/androidtransfuse/integrationTest/About.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
30
2015-04-05T22:21:05.000Z
2020-10-27T03:26:06.000Z
31.548387
75
0.765849
995,784
/** * Copyright 2011-2015 John Ericksen * * 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.androidtransfuse.integrationTest; import android.view.Window; import org.androidtransfuse.annotations.Activity; import org.androidtransfuse.annotations.Layout; import org.androidtransfuse.annotations.WindowFeature; /** * @author John Ericksen */ @Activity(label = "About") @Layout(R.layout.about) @WindowFeature(Window.FEATURE_NO_TITLE) public class About { }
92314cb9b8c9bfe1faa2b38bb342b0d3a5e7b223
9,298
java
Java
src/main/java/algorithms/ilp/Solver.java
bink81/java-experiments
6f1277d9f4856477d2b89adf1ae347e45e372e7c
[ "MIT" ]
null
null
null
src/main/java/algorithms/ilp/Solver.java
bink81/java-experiments
6f1277d9f4856477d2b89adf1ae347e45e372e7c
[ "MIT" ]
null
null
null
src/main/java/algorithms/ilp/Solver.java
bink81/java-experiments
6f1277d9f4856477d2b89adf1ae347e45e372e7c
[ "MIT" ]
null
null
null
31.62585
94
0.71553
995,785
package algorithms.ilp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import java.util.Arrays; import java.util.Comparator; import java.util.Deque; import java.util.Set; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.linear.LinearConstraint; import org.apache.commons.math3.optim.linear.LinearConstraintSet; import org.apache.commons.math3.optim.linear.LinearObjectiveFunction; import org.apache.commons.math3.optim.linear.NoFeasibleSolutionException; import org.apache.commons.math3.optim.linear.NonNegativeConstraint; import org.apache.commons.math3.optim.linear.PivotSelectionRule; import org.apache.commons.math3.optim.linear.Relationship; import org.apache.commons.math3.optim.linear.SimplexSolver; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import com.google.common.base.Optional; import com.google.common.collect.Queues; import com.google.common.collect.Sets; /** * This class is used to solve integer linear programming problems, i.e. * problems that can be expressed as * <ul> * <li>maximize function c<sup>T</sup>x (T = transpose)</li> * <li>with constraint Ax <= b</li> * <li>and x >= 0</li> * <li>with x vector of integers</li> * </ul> * with A matrix of integers, b, c vectors of integers. * * @see https://en.wikipedia.org/wiki/Integer_programming * @see https://en.wikipedia.org/wiki/Branch_and_bound */ public final class Solver { private static final double EPSILON = Math.pow(10, -6); private final double[][] aMatrix; private final double[] bVector; private final double[] cVector; private final double timeout; private Optional<PointValuePair> bestSolutionSoFar = Optional.absent(); private Long start; private boolean reachedTimeout = false; private final TraversingStrategy type; private final Deque<SubSpaceSolver> queue = Queues.newArrayDeque(); /** * @param aMatrix * the matrix A so that Ax <= b * @param bVector * the vector b so that Ax <= b * @param cVector * the coefficients for the function to maximize cTx * @param timeout * (in milliseconds) the timeout for the algorithm iteration. When * reached, we will use the best solution we got within the time, * even though we can't determine if it is the theoretical best. */ public Solver(double[][] aMatrix, double[] bVector, double[] cVector, double timeout, TraversingStrategy traversingStrategy) { super(); this.timeout = timeout; this.type = traversingStrategy; checkArgument(aMatrix.length == bVector.length); checkArgument(aMatrix[0].length == cVector.length); checkFoZeroRowsAndColumns(aMatrix); this.aMatrix = new double[aMatrix.length][]; for (int i = 0; i < aMatrix.length; i++) { this.aMatrix[i] = aMatrix[i].clone(); } this.bVector = bVector.clone(); this.cVector = cVector.clone(); } /** Check that the matrix does not have any zeroes row or column */ private static void checkFoZeroRowsAndColumns(double[][] aMatrix) { RealMatrix realMatrix = new Array2DRowRealMatrix(aMatrix); checkNonZeroColumns(aMatrix, realMatrix); } private static void checkNonZeroColumns(double[][] aMatrix, RealMatrix realMatrix) { double[] zeroesColumn = new double[aMatrix.length]; for (int i = 0; i < aMatrix[0].length; i++) { checkArgument(!realMatrix.getColumn(i).equals(zeroesColumn)); } } /** * Computes an integer solution for the problem. * * @return the array x that maximizes the function under the given * constraints. */ public int[] solve() { reset(); // Linear constraints (Ax <= b) Set<LinearConstraint> constraints = Sets.newHashSetWithExpectedSize(bVector.length); for (int i = 0; i < bVector.length; i++) { constraints.add(new LinearConstraint(aMatrix[i], Relationship.LEQ, bVector[i])); } /* * We are going to solve the Linear programming problem (where x is an array * of double) recursively on subspaces of the feasible space, and take the * best integer solution we can reach in the given timeout. */ start = System.currentTimeMillis(); queue.offer(new SubSpaceSolver(constraints)); // This could use several threads if needed while (!queue.isEmpty()) { queue.poll().solve(); } checkState(bestSolutionSoFar.isPresent(), "No solution found in the allowed time"); double[] bestSolution = bestSolutionSoFar.get().getPoint(); return convertToIntegerArray(bestSolution); } private int[] convertToIntegerArray(double[] bestCoefs) { int[] result = new int[bestCoefs.length]; for (int i = 0; i < bestCoefs.length; i++) { Double coef = bestCoefs[i]; result[i] = (int) Math.round(coef); } return result; } private void reset() { reachedTimeout = false; bestSolutionSoFar = Optional.absent(); } public final class SubSpaceSolver { private final Set<LinearConstraint> constraints; public SubSpaceSolver(Set<LinearConstraint> constraints) { super(); this.constraints = constraints; } public void solve() { try { solveOnSubSpace(constraints); } catch (NoFeasibleSolutionException e) { // If there is no feasible solution for this space, just skip it return; } } } public void solveOnSubSpace(Set<LinearConstraint> constraints) { if (System.currentTimeMillis() - start > timeout) { reachedTimeout = true; return; } LinearObjectiveFunction functionToBeMaximized = new LinearObjectiveFunction(cVector, 0); PointValuePair optimize = new SimplexSolver().optimize(functionToBeMaximized, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, PivotSelectionRule.BLAND, new NonNegativeConstraint(true)); Optional<Double> maxSoFar = getMaxSoFar(); if (maxSoFar.isPresent() && maxSoFar.get().compareTo(optimize.getValue()) >= 0) { // We won't find any better on this subspace return; } /* * Once we have a solution for the LP problem (not necessarily integer), we * subdivide the feasible region in 2 like described in Integer Programming, * chapter 9 */ double[] solution = optimize.getPoint(); for (int i = solution.length - 1; i >= 0; i--) { int indexOfGreatestElement = getIndexOfGreatestElement(solution, i); double max = solution[indexOfGreatestElement]; double round = Math.round(max); if (Math.abs(max - round) < EPSILON) { if (i == 0) { // All elements in x are integer. This is a potential solution to the // ILP // problem. if (!maxSoFar.isPresent() || maxSoFar.get().compareTo(optimize.getValue()) < 0) { updateBestSolutionSoFar(optimize); } } } else { // Separate space and start again double[] selectMaxResult = new double[cVector.length]; selectMaxResult[indexOfGreatestElement] = 1; // Here we have a solution with x[g]=d is a double. But we are looking // for integers. // We will search the solution on 2 sub-regions: x[g] <= floor(d) and // x[g] >= // ceil(d). // For this we just need to add a linear constraint to the existing // ones. // See documentation mentioned above. LinearConstraint constraintBelow = new LinearConstraint(selectMaxResult, Relationship.LEQ, Math.floor(max)); Set<LinearConstraint> constraintsBelow = Sets.newHashSet(constraints); constraintsBelow.add(constraintBelow); addToQueue(new SubSpaceSolver(constraintsBelow)); LinearConstraint constraintAbove = new LinearConstraint(selectMaxResult, Relationship.GEQ, Math.ceil(max)); Set<LinearConstraint> constraintsAbove = Sets.newHashSet(constraints); constraintsAbove.add(constraintAbove); addToQueue(new SubSpaceSolver(constraintsAbove)); break; } } } private void addToQueue(SubSpaceSolver solver) { if (type == TraversingStrategy.DEPTH_FIRST) { queue.addFirst(solver); } else { queue.add(solver); } } private void updateBestSolutionSoFar(PointValuePair optimize) { bestSolutionSoFar = Optional.of(optimize); } private Optional<Double> getMaxSoFar() { if (bestSolutionSoFar.isPresent()) { return Optional.of(bestSolutionSoFar.get().getValue()); } return Optional.absent(); } public boolean hasReachedTimout() { return reachedTimeout; } /** * Gets the index of the n-th greatest element in an array. */ private int getIndexOfGreatestElement(double[] array, int n) { checkArgument(n >= 0); checkArgument(n < array.length); ArrayIndexComparator comparator = new ArrayIndexComparator(array); Integer[] indexes = comparator.createIndexArray(); Arrays.sort(indexes, comparator); return indexes[n]; } private static class ArrayIndexComparator implements Comparator<Integer> { private final double[] array; public ArrayIndexComparator(double[] array) { this.array = array; } public Integer[] createIndexArray() { Integer[] indexes = new Integer[array.length]; for (int i = 0; i < array.length; i++) { indexes[i] = i; } return indexes; } @Override public int compare(Integer index1, Integer index2) { return Double.compare(array[index1], array[index2]); } } }
92314cd71cecd98f0e86d9dc3a261f7e60b909ce
1,719
java
Java
org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
1
2022-02-24T01:32:41.000Z
2022-02-24T01:32:41.000Z
org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
41.926829
119
0.763234
995,786
package org.apache.fop.render.intermediate; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import org.apache.fop.util.GenerationHelperContentHandler; import org.xml.sax.ContentHandler; public abstract class AbstractXMLWritingIFDocumentHandler extends AbstractIFDocumentHandler { protected SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); protected GenerationHelperContentHandler handler; public void setResult(Result result) throws IFException { if (result instanceof SAXResult) { SAXResult saxResult = (SAXResult)result; this.handler = new GenerationHelperContentHandler(saxResult.getHandler(), this.getMainNamespace()); } else { this.handler = new GenerationHelperContentHandler(this.createContentHandler(result), this.getMainNamespace()); } } protected abstract String getMainNamespace(); protected ContentHandler createContentHandler(Result result) throws IFException { try { TransformerHandler tHandler = this.tFactory.newTransformerHandler(); Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.setOutputProperty("method", "xml"); tHandler.setResult(result); return tHandler; } catch (TransformerConfigurationException var4) { throw new IFException("Error while setting up the serializer for XML output", var4); } } }
92314ce9a8854a5de7c44f63fe7a9ce30a1533ec
7,886
java
Java
src/main/java/org/tugraz/sysds/runtime/compress/cocode/PlanningCoCoder.java
Shafaq-Siddiqi/systemds
a5a8d4e0040308993d7892be11dae63c81575efd
[ "Apache-2.0" ]
42
2018-11-23T16:55:30.000Z
2021-03-15T15:01:44.000Z
src/main/java/org/tugraz/sysds/runtime/compress/cocode/PlanningCoCoder.java
kev-inn/systemds
2d0f219e02af1174a97a04191590441821fbfab6
[ "Apache-2.0" ]
120
2019-02-07T22:13:40.000Z
2020-04-15T10:42:17.000Z
src/main/java/org/tugraz/sysds/runtime/compress/cocode/PlanningCoCoder.java
kev-inn/systemds
2d0f219e02af1174a97a04191590441821fbfab6
[ "Apache-2.0" ]
28
2019-02-07T11:13:14.000Z
2021-12-20T10:14:25.000Z
35.205357
116
0.730789
995,787
/* * Modifications Copyright 2020 Graz University of Technology * * 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.tugraz.sysds.runtime.compress.cocode; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.tugraz.sysds.runtime.DMLRuntimeException; import org.tugraz.sysds.runtime.compress.estim.CompressedSizeEstimator; import org.tugraz.sysds.runtime.compress.estim.CompressedSizeInfo; import org.tugraz.sysds.runtime.util.CommonThreadPool; public class PlanningCoCoder { // internal configurations private final static PartitionerType COLUMN_PARTITIONER = PartitionerType.BIN_PACKING; private static final Log LOG = LogFactory.getLog(PlanningCoCoder.class.getName()); public enum PartitionerType { BIN_PACKING, STATIC, } public static List<int[]> findCocodesByPartitioning(CompressedSizeEstimator sizeEstimator, List<Integer> cols, CompressedSizeInfo[] colInfos, int numRows, int k) { // filtering out non-groupable columns as singleton groups // weight is the ratio of its cardinality to the number of rows int numCols = cols.size(); List<Integer> groupCols = new ArrayList<>(); HashMap<Integer, GroupableColInfo> groupColsInfo = new HashMap<>(); for(int i = 0; i < numCols; i++) { int colIx = cols.get(i); double cardinality = colInfos[colIx].getEstCard(); double weight = cardinality / numRows; groupCols.add(colIx); groupColsInfo.put(colIx, new GroupableColInfo(weight, colInfos[colIx].getMinSize())); } // use column group partitioner to create partitions of columns List<int[]> bins = createColumnGroupPartitioner(COLUMN_PARTITIONER).partitionColumns(groupCols, groupColsInfo); // brute force grouping within each partition return (k > 1) ? getCocodingGroupsBruteForce(bins, groupColsInfo, sizeEstimator, numRows, k) : getCocodingGroupsBruteForce(bins, groupColsInfo, sizeEstimator, numRows); } private static List<int[]> getCocodingGroupsBruteForce(List<int[]> bins, HashMap<Integer, GroupableColInfo> groupColsInfo, CompressedSizeEstimator estim, int rlen) { List<int[]> retGroups = new ArrayList<>(); for(int[] bin : bins) { // building an array of singleton CoCodingGroup ArrayList<PlanningCoCodingGroup> sgroups = new ArrayList<>(); for(int col : bin) sgroups.add(new PlanningCoCodingGroup(col, groupColsInfo.get(col))); // brute force co-coding PlanningCoCodingGroup[] outputGroups = findCocodesBruteForce(estim, rlen, sgroups.toArray(new PlanningCoCodingGroup[0])); for(PlanningCoCodingGroup grp : outputGroups) retGroups.add(grp.getColIndices()); } return retGroups; } private static List<int[]> getCocodingGroupsBruteForce(List<int[]> bins, HashMap<Integer, GroupableColInfo> groupColsInfo, CompressedSizeEstimator estim, int rlen, int k) { List<int[]> retGroups = new ArrayList<>(); try { ExecutorService pool = CommonThreadPool.get(k); ArrayList<CocodeTask> tasks = new ArrayList<>(); for(int[] bin : bins) { // building an array of singleton CoCodingGroup ArrayList<PlanningCoCodingGroup> sgroups = new ArrayList<>(); for(int col : bin) sgroups.add(new PlanningCoCodingGroup(col, groupColsInfo.get(col))); tasks.add(new CocodeTask(estim, sgroups, rlen)); } List<Future<PlanningCoCodingGroup[]>> rtask = pool.invokeAll(tasks); for(Future<PlanningCoCodingGroup[]> lrtask : rtask) for(PlanningCoCodingGroup grp : lrtask.get()) retGroups.add(grp.getColIndices()); pool.shutdown(); } catch(Exception ex) { throw new DMLRuntimeException(ex); } return retGroups; } /** * Identify columns to code together. Uses a greedy approach that merges pairs of column groups into larger groups. * Each phase of the greedy algorithm considers all combinations of pairs to merge. * * @param sizeEstimator compressed size estimator * @param numRowsWeight number of rows weight * @param singltonGroups planning co-coding groups * @return */ private static PlanningCoCodingGroup[] findCocodesBruteForce(CompressedSizeEstimator estim, int numRows, PlanningCoCodingGroup[] singletonGroups) { if(LOG.isTraceEnabled()) LOG.trace("Cocoding: process " + singletonGroups.length); List<PlanningCoCodingGroup> workset = new ArrayList<>(Arrays.asList(singletonGroups)); // establish memo table for extracted column groups PlanningMemoTable memo = new PlanningMemoTable(); // process merging iterations until no more change boolean changed = true; while(changed && workset.size() > 1) { // find best merge, incl memoization PlanningCoCodingGroup tmp = null; for(int i = 0; i < workset.size(); i++) { for(int j = i + 1; j < workset.size(); j++) { PlanningCoCodingGroup c1 = workset.get(i); PlanningCoCodingGroup c2 = workset.get(j); memo.incrStats(1, 0, 0); // pruning filter: skip dominated candidates if(-Math.min(c1.getEstSize(), c2.getEstSize()) > memo.getOptChangeInSize()) continue; // memoization or newly created group (incl bitmap extraction) PlanningCoCodingGroup c1c2 = memo.getOrCreate(c1, c2, estim, numRows); // keep best merged group only if(tmp == null || c1c2.getChangeInSize() < tmp.getChangeInSize() || (c1c2.getChangeInSize() == tmp.getChangeInSize() && c1c2.getColIndices().length < tmp.getColIndices().length)) tmp = c1c2; } } // modify working set if(tmp != null && tmp.getChangeInSize() < 0) { workset.remove(tmp.getLeftGroup()); workset.remove(tmp.getRightGroup()); workset.add(tmp); memo.remove(tmp); if(LOG.isTraceEnabled()) { LOG.trace("--merge groups: " + Arrays.toString(tmp.getLeftGroup().getColIndices()) + " and " + Arrays.toString(tmp.getRightGroup().getColIndices())); } } else { changed = false; } } if(LOG.isTraceEnabled()) LOG.trace("--stats: " + Arrays.toString(memo.getStats())); return workset.toArray(new PlanningCoCodingGroup[0]); } private static ColumnGroupPartitioner createColumnGroupPartitioner(PartitionerType type) { switch(type) { case BIN_PACKING: return new ColumnGroupPartitionerBinPacking(); case STATIC: return new ColumnGroupPartitionerStatic(); default: throw new RuntimeException("Unsupported column group partitioner: " + type.toString()); } } public static class GroupableColInfo { public final double cardRatio; public final long size; public GroupableColInfo(double lcardRatio, long lsize) { cardRatio = lcardRatio; size = lsize; } } private static class CocodeTask implements Callable<PlanningCoCodingGroup[]> { private CompressedSizeEstimator _estim = null; private ArrayList<PlanningCoCodingGroup> _sgroups = null; private int _rlen = -1; protected CocodeTask(CompressedSizeEstimator estim, ArrayList<PlanningCoCodingGroup> sgroups, int rlen) { _estim = estim; _sgroups = sgroups; _rlen = rlen; } @Override public PlanningCoCodingGroup[] call() { // brute force co-coding return findCocodesBruteForce(_estim, _rlen, _sgroups.toArray(new PlanningCoCodingGroup[0])); } } }
92314d6edf017a9864dc4f9eae8165e33b9e75f1
386
java
Java
src/main/java/com/github/guitsilva/rebelsapi/security/components/Encoder.java
guitsilva/rebels-api
f495314bbc15bf613444fe05b05f6572cce44da7
[ "MIT" ]
null
null
null
src/main/java/com/github/guitsilva/rebelsapi/security/components/Encoder.java
guitsilva/rebels-api
f495314bbc15bf613444fe05b05f6572cce44da7
[ "MIT" ]
null
null
null
src/main/java/com/github/guitsilva/rebelsapi/security/components/Encoder.java
guitsilva/rebels-api
f495314bbc15bf613444fe05b05f6572cce44da7
[ "MIT" ]
null
null
null
25.733333
72
0.797927
995,788
package com.github.guitsilva.rebelsapi.security.components; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; @Component public class Encoder { @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
92314e4ad2c0c35b51e1471cfc3edbd9d6a60d00
8,901
java
Java
app/src/main/java/com/ojrdude/minesweeperwithassistant/Cell.java
ojrdude/minesweeperwithassistant
2ac630a3bdd0614df164d66eaac3126667678e9e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ojrdude/minesweeperwithassistant/Cell.java
ojrdude/minesweeperwithassistant
2ac630a3bdd0614df164d66eaac3126667678e9e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ojrdude/minesweeperwithassistant/Cell.java
ojrdude/minesweeperwithassistant
2ac630a3bdd0614df164d66eaac3126667678e9e
[ "Apache-2.0" ]
null
null
null
34.234615
144
0.615324
995,789
package com.ojrdude.minesweeperwithassistant; /** * The Cell class represents a cell on the Minesweeper game board. The values that a cell * can contain (i.e. the number of mines around the cell) are defined by the CellConstants * enumerated type. */ public class Cell { public static final String NULL_PARAMETER_PASSED_TO_CONSTRUCTOR = "Null parameter passed to constructor"; public static final String ATTEMPTED_TO_UNCOVER_A_CELL_THAT_IS_ALREADY_UNCOVERED = "Attempted to uncover a cell that is already uncovered."; public static final String ATTEMPTED_TO_FLAG_UNCOVERED_CELL = "Attempted to flag a cell that is uncovered."; public static final String ATTEMPTED_TO_FLAG_CELL_ALREADY_FLAGGED = "Attempted to flag a cell that is already flag."; public static final String ATTEMPTED_TO_UNFLAG_UNCOVERED_CELL = "Attempted to unflag a cell that is uncovered."; public static final String ATTEMPTED_TO_UNFLAG_CELL_ALREADY_UNFLAGGED = "Attempted to unflag a cell that is already unflagged."; /** * Enumerated type that represents the allowed values * of a cell (i.e. the number of mines known to surround the cell). * MINE represents a cell that itself contains a mine, and UNKNOWN represents * a covered cell. */ public enum CellContents{ MINE(-1), ZERO(0), ONE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), UNKNOWN(9); public static final String CELL_VALUE_OUT_OF_RANGE = "The parameter 'Value' must be between -1 and 9 inclusive. Illegal Value: "; private int intValue; /** * Constructor for CellContents, sets the value to the parameter given. * @param intValue The numerical definition of the Cell value. The allowed * values are -1 to 9 inclusive. -1 symbolises a mine and 9 * symbolises unknown (i.e. a covered cell). All other numbers * are the number that is displayed in the cell. */ CellContents(int intValue){ if(intValue > 9 || intValue < -1){ throw new IllegalArgumentException(CELL_VALUE_OUT_OF_RANGE + intValue); } this.intValue = intValue; } /** * Accessor method for CellContents intValue. * @return The intValue of the Cell's contents */ public int getIntValue() { return intValue; } /** * Returns a String representation of the CellContents. * @return A String a representation of the CellContents. */ public String toString(){ switch (intValue){ case -1: return "MINE"; case 9: return "UNKNOWN"; default: return String.valueOf(intValue); } } } public static final String X_COORDINATE_LESS_THAN_ZERO = "Coordinates must be 0 or greater. XCoord: "; public static final String Y_COORDINATE_LESS_THAN_ZERO = "Coordinates must be 0 or greater. YCoord: "; public static final String INITIALISE_CELL_UNKNOWN_VALUE = "Cannot initialise a Cell with an Unknown value"; private CellContents contents; private boolean uncovered; private boolean flagged; private int xCoordinate; private int yCoordinate; /** * Constructor for Cell class. * @param xCoordinate The X coordinate of this cell on the game board. Must be greater than 0. * @param yCoordinate The Y coordinate of this cell on the game board. Must be greater than 0. * @param contents What the cell "contains"; either a MINE, or a number which * counts the number of mines around cell. This parameter CANNOT be * UNKNOWN. * @throws IllegalArgumentException If a coordinate is less than zero is supplied, or if a * "contents" value of UNKNOWN is provided. */ public Cell(int xCoordinate, int yCoordinate, CellContents contents){ if(contents==CellContents.UNKNOWN){ throw new IllegalArgumentException(INITIALISE_CELL_UNKNOWN_VALUE); } if(contents == null){ throw new IllegalArgumentException(NULL_PARAMETER_PASSED_TO_CONSTRUCTOR); } if(xCoordinate < 0) { throw new IllegalArgumentException(X_COORDINATE_LESS_THAN_ZERO + xCoordinate); } if(yCoordinate < 0){ throw new IllegalArgumentException(Y_COORDINATE_LESS_THAN_ZERO + yCoordinate); } this.xCoordinate = xCoordinate; this.yCoordinate = yCoordinate; this.contents = contents; uncovered = false; flagged = false; } /** * Get the the contents of the cell. If the cell is not uncovered, UNKNOWN is returned. * @return The contents of the cell if uncovered, UNKNOWN if not. */ public CellContents getContents(){ if(uncovered){ return contents; } else{ return CellContents.UNKNOWN; } } /** * Accessor method for xCoordinate. * @return The xCoordinate of this cell. */ public int getXCoordinate() { return xCoordinate; } /** * Mutator method for xCoordinate. Sets the xCoordinate to x. * @param x The new xCoordinate for the cell, must be 0 or greater. * @throws IllegalArgumentException If the coordinate provided is less than 0. */ public void setXCoordinate(int x) { if(x < 0){ throw new IllegalArgumentException(X_COORDINATE_LESS_THAN_ZERO + x); } xCoordinate = x; } /** * Accessor method for yCoordinate. * @return The yCoordinate of this cell. */ public int getYCoordinate() { return yCoordinate; } /** * Mutator method for yCoordinate. Sets the yCoordinate to y. * @param y The new yCoordinate for the cell, must be 0 or greater. * @throws IllegalArgumentException If the coordinate provided is less than 0. */ public void setYCoordinate(int y) { if (y<0){ throw new IllegalArgumentException(Y_COORDINATE_LESS_THAN_ZERO + y); } yCoordinate = y; } /** * Equals method, returns whether this Cell is equal to another, based on Coordinates; * * @param obj The object to compare this cell to. * @return True if the parameter object is equal to this Cell, false if not. */ @Override public boolean equals(Object obj){ if(obj == this){ return true; } if(!(obj instanceof Cell)){ return false; } Cell objCell = (Cell) obj; return this.xCoordinate == objCell.getXCoordinate() && this.yCoordinate == objCell.getYCoordinate(); } /** * Generates a hashCode representation of the Cell. * @return this Cell's hashCode. */ @Override public int hashCode(){ int result = 23; int mult = 11; result = mult * result + xCoordinate; result = mult * result + yCoordinate; return result; } /** * Uncover a cell, making the cell's contents accessible. */ public void uncover(){ if(uncovered){ throw new IllegalStateException(ATTEMPTED_TO_UNCOVER_A_CELL_THAT_IS_ALREADY_UNCOVERED); } uncovered = true; } /** * Mark (flag) a cell as containing a mine. */ public void flag(){ if(uncovered){ throw new IllegalStateException(ATTEMPTED_TO_FLAG_UNCOVERED_CELL); } if(flagged){ throw new IllegalStateException(ATTEMPTED_TO_FLAG_CELL_ALREADY_FLAGGED); } flagged = true; } /** * Remove the flag that marks the cell as containing a mine. */ public void removeFlag(){ if(uncovered){ throw new IllegalStateException(ATTEMPTED_TO_UNFLAG_UNCOVERED_CELL); } if(!flagged){ throw new IllegalStateException(ATTEMPTED_TO_UNFLAG_CELL_ALREADY_UNFLAGGED); } flagged = false; } /** * Gets whethre or not this cell is flagged, i.e. marked as containing a mine. * @return True if the cell is flagged, false if not. */ public boolean isFlagged(){ return flagged; } /** * Returns a String representation of this Cell. * @return The String representation of this cell. */ public String toString(){ String result = "Cell: (" + xCoordinate + ", " + yCoordinate + ") Contents: "; if(uncovered){ result+=contents; } else{ result+=CellContents.UNKNOWN; } return result; } }
92314ea5480d89f1f21797bdecfabd44f7955a05
1,012
java
Java
src/main/java/calemiutils/gui/GuiOneSlot.java
infiniteblock/CalemiUtils-1.12.2
560d2c7485975a4697cb22576b54c52618e2aac1
[ "Apache-2.0" ]
2
2019-06-14T14:41:12.000Z
2019-06-15T02:18:21.000Z
src/main/java/calemiutils/gui/GuiOneSlot.java
infiniteblock/CalemiUtils-1.12.2
560d2c7485975a4697cb22576b54c52618e2aac1
[ "Apache-2.0" ]
36
2019-05-02T19:35:35.000Z
2020-02-15T19:56:19.000Z
src/main/java/calemiutils/gui/GuiOneSlot.java
infiniteblock/CalemiUtils-1.12.2
560d2c7485975a4697cb22576b54c52618e2aac1
[ "Apache-2.0" ]
3
2019-05-27T16:34:18.000Z
2019-12-10T15:47:37.000Z
20.653061
102
0.704545
995,790
package calemiutils.gui; import calemiutils.gui.base.GuiContainerBase; import calemiutils.tileentity.base.TileEntityInventoryBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class GuiOneSlot extends GuiContainerBase { private final String name; public GuiOneSlot(EntityPlayer player, TileEntityInventoryBase te, String name, Item... filters) { super(te.getTileContainer(player), player); this.name = name; } @Override public String getGuiTextureName() { return "one_slot"; } @Override public String getGuiTitle() { return name; } @Override public int getGuiSizeY() { return 123; } @Override public void drawGuiBackground(int mouseX, int mouseY) { } @Override public void drawGuiForeground(int mouseX, int mouseY) { } }
92314f2dcf114c6fc3db35952a4e93e402041cf4
3,360
java
Java
src/test/java/io/github/data4all/util/GeoDataConverterTest.java
Data4All/Data4All
81a7af8e1ef3fcfa27423a47ba96bc060a4e58f1
[ "Apache-2.0" ]
28
2015-02-07T14:20:10.000Z
2018-10-23T03:58:16.000Z
src/test/java/io/github/data4all/util/GeoDataConverterTest.java
Data4All/Data4All
81a7af8e1ef3fcfa27423a47ba96bc060a4e58f1
[ "Apache-2.0" ]
6
2015-01-16T20:15:49.000Z
2018-07-17T23:30:28.000Z
src/test/java/io/github/data4all/util/GeoDataConverterTest.java
Data4All/Data4All
81a7af8e1ef3fcfa27423a47ba96bc060a4e58f1
[ "Apache-2.0" ]
8
2015-05-01T23:57:52.000Z
2017-10-06T19:24:04.000Z
31.401869
89
0.640476
995,791
/* * Copyright (c) 2014, 2015 Data4All * * <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 io.github.data4all.util; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * Test class for io.github.data4all.util.GeoDataConverter. * * @author sbollen */ public class GeoDataConverterTest { @Before public void setUp() { } /** * Test method for * {@link io.github.data4all.util.GeoDataConverter#convertToDMS(double)}. */ @Test public void testConvertToDMS() { // normal positive input double degree = 20.00; Object value = GeoDataConverter.convertToDMS(degree); String result = (String) value; assertEquals("20/1,0/1,0/1000", result); // normal negative input double degree0 = -20.00; Object value0 = GeoDataConverter.convertToDMS(degree0); String result0 = (String) value0; assertEquals("20/1,0/1,0/1000", result0); // 0.00 as input double degree1 = 0; Object value1 = GeoDataConverter.convertToDMS(degree1); String result1 = (String) value1; assertEquals("0/1,0/1,0/1000", result1); // more complex input double degree2 = -56.2341; Object value2 = GeoDataConverter.convertToDMS(degree2); String result2 = (String) value2; assertEquals("56/1,14/1,2759/1000", result2); // another complex input double degree3 = 37.715183; Object value3 = GeoDataConverter.convertToDMS(degree3); String result3 = (String) value3; assertEquals("37/1,42/1,54658/1000", result3); } /** * Test method for * {@link io.github.data4all.util.GeoDataConverter#convertToDegree(java.lang.String)} * . */ @Test public void testConvertToDegree() { // normal positive input String dms = "20/1,0/1,0/1000"; Object value = GeoDataConverter.convertToDegree(dms); double result = (Double) value; assertEquals(20, result, 0.001); // 0.00 as input String dms1 = "0/1,0/1,0/1000"; Object value1 = GeoDataConverter.convertToDegree(dms1); double result1 = (Double) value1; assertEquals(0, result1, 0.001); // more complex input String dms2 = "56/1,14/1,2759/1000"; Object value2 = GeoDataConverter.convertToDegree(dms2); double result2 = (Double) value2; assertEquals(56.2341, result2, 0.001); // another complex input String dms3 = "37/1,42/1,54658/1000"; Object value3 = GeoDataConverter.convertToDegree(dms3); double result3 = (Double) value3; assertEquals(37.715183, result3, 0.001); // input in another format or with negative numbers is not possible } }
92314ffb482380c71af739207deb627c34f33ee1
882
java
Java
src/main/java/com/klgs/rmq/consumer/ProcessMessageRube.java
pulgupta/Events
2787226713efe688d8c9c2e24bf8f48cbd4f8614
[ "MIT" ]
null
null
null
src/main/java/com/klgs/rmq/consumer/ProcessMessageRube.java
pulgupta/Events
2787226713efe688d8c9c2e24bf8f48cbd4f8614
[ "MIT" ]
null
null
null
src/main/java/com/klgs/rmq/consumer/ProcessMessageRube.java
pulgupta/Events
2787226713efe688d8c9c2e24bf8f48cbd4f8614
[ "MIT" ]
null
null
null
25.941176
91
0.729025
995,792
package com.klgs.rmq.consumer; /** * Created by pulgupta on 08/10/16. */ import com.klgs.rmq.configuration.Order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.Message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class ProcessMessageRube { private static final Logger logger = LoggerFactory.getLogger(ProcessMessageRube.class); public void handleMessage(Message message) { logger.info("Received Message from rube " + message); } public void handleMessage(byte[] message) { logger.info("Received Message from rube as byte array " + message); } public void handleMessage(Order message) { logger.info("Received Message from rube as order " + message); } }
92315032981c62ad86eafc534ee6353aacf57c52
16,505
java
Java
src/test/java/com/infinities/nova/resource/ServersResourceTest.java
infinitiessoft/nova2.0-api
9fa7915cba5375f1f66b055f20cf2e694e0237e3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/infinities/nova/resource/ServersResourceTest.java
infinitiessoft/nova2.0-api
9fa7915cba5375f1f66b055f20cf2e694e0237e3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/infinities/nova/resource/ServersResourceTest.java
infinitiessoft/nova2.0-api
9fa7915cba5375f1f66b055f20cf2e694e0237e3
[ "Apache-2.0" ]
null
null
null
44.972752
113
0.712148
995,793
///******************************************************************************* // * Copyright 2015 InfinitiesSoft Solutions Inc. // * // * Licensed under the Apache License, Version 2.0 (the "License"); you may // * not use this file except in compliance with the License. You may obtain // * a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // * License for the specific language governing permissions and limitations // * under the License. // *******************************************************************************/ //package com.infinities.nova.resource; // //import static org.junit.Assert.assertEquals; //import static org.junit.Assert.assertFalse; //import static org.junit.Assert.assertNotNull; //import static org.junit.Assert.assertTrue; // //import java.io.IOException; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // //import javax.inject.Singleton; //import javax.ws.rs.client.Entity; //import javax.ws.rs.core.Application; //import javax.ws.rs.core.GenericType; //import javax.ws.rs.core.MediaType; //import javax.ws.rs.core.Response; // //import org.glassfish.hk2.utilities.binding.AbstractBinder; //import org.glassfish.jersey.server.ResourceConfig; //import org.junit.Test; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //import com.fasterxml.jackson.core.type.TypeReference; //import com.infinities.nova.api.EntityManagerFilter; //import com.infinities.nova.api.VersionsApi; //import com.infinities.nova.api.factory.VersionsApiFactory; //import com.infinities.nova.api.middleware.ComputeReqIdMiddleware; //import com.infinities.nova.api.middleware.NoAuthMiddleware; //import com.infinities.nova.api.openstack.FaultWrapper; //import com.infinities.nova.api.openstack.common.template.MetaItemTemplate; //import com.infinities.nova.api.openstack.common.template.MetadataTemplate; //import com.infinities.nova.api.openstack.compute.images.ImageMetadataController; //import com.infinities.nova.api.openstack.compute.images.ImageMetadataControllerFactory; //import com.infinities.nova.api.openstack.compute.images.ImagesController; //import com.infinities.nova.api.openstack.compute.images.ImagesControllerFactory; //import com.infinities.nova.api.openstack.compute.images.api.ImageMetadataApi; //import com.infinities.nova.api.openstack.compute.images.api.ImageMetadataApiFactory; //import com.infinities.nova.api.openstack.compute.images.api.ImagesApi; //import com.infinities.nova.api.openstack.compute.images.api.ImagesApiFactory; //import com.infinities.nova.api.openstack.compute.images.api.driver.ImagesDriver; //import com.infinities.nova.api.openstack.compute.images.api.driver.ImagesDriverFactory; //import com.infinities.nova.api.openstack.compute.servers.MinimalServer; //import com.infinities.nova.api.openstack.compute.servers.MinimalServersTemplate; //import com.infinities.nova.api.openstack.compute.servers.ServerTemplate; //import com.infinities.nova.api.openstack.compute.servers.ServersController; //import com.infinities.nova.api.openstack.compute.servers.ServersControllerFactory; //import com.infinities.nova.api.openstack.compute.servers.ServersTemplate; //import com.infinities.nova.api.openstack.compute.servers.metadata.ServerMetadataController; //import com.infinities.nova.api.openstack.compute.servers.metadata.ServerMetadataControllerFactory; //import com.infinities.nova.api.v2.Version2Api; //import com.infinities.nova.api.v2.factory.Version2ApiFactory; //import com.infinities.nova.response.model.Fault; //import com.infinities.nova.response.model.Server; //import com.infinities.nova.util.jackson.JacksonFeature; //import com.infinities.skyport.util.JsonUtil; // //public class ServersResourceTest extends ResourceTest { // // private final static Logger logger = LoggerFactory.getLogger(ServersResourceTest.class); // // // @Test // public void testIndexForMalformedRequestURL() throws IOException { // Response response = // target("/v2").path("test").path("servers").register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).get(); // // org.glassfish.jersey.filter.LoggingFilter // Map<String, Fault> faultData = response.readEntity(new GenericType<Map<String, Fault>>() { // }); // String ret = JsonUtil.toString(faultData); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // String key = faultData.keySet().iterator().next(); // Fault fault = faultData.get(key); // assertEquals(400, response.getStatus()); // assertEquals("badRequest", key); // assertEquals(response.getStatus(), fault.getCode()); // } // // @Test // public void testIndex() throws IOException { // Response response = // target("/v2").path("admin").path("servers").register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).get(); // assertEquals(200, response.getStatus()); // MinimalServersTemplate servers = response.readEntity(MinimalServersTemplate.class); // List<MinimalServer> serverList = servers.getList(); // ResponseUtils.printResponse(logger, response); // String ret = JsonUtil.toString(servers); // logger.debug("{}", ret); // assertEquals(2, serverList.size()); // for (MinimalServer server : serverList) { // assertNotNull(server.getId()); // assertNotNull(server.getName()); // assertFalse(server.getLinks().isEmpty()); // } // } // // @Test // public void testDatail() throws IOException { // Response response = // target("/v2").path("admin").path("servers").path("detail").register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).get(); // assertEquals(200, response.getStatus()); // String ret = response.readEntity(String.class); // ServersTemplate servers = JsonUtil.readJson(ret, ServersTemplate.class); // List<Server> serverList = servers.getList(); // logger.debug("servers size:{}", servers.getList().size()); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(2, serverList.size()); // } // // @Test // public void testShowNotFound() throws IOException { // String serverId = "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).get(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(404, response.getStatus()); // } // // @Test // public void testShow() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).get(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // ServerTemplate template = JsonUtil.readJson(ret, ServerTemplate.class); // Server server = template.getServer(); // assertEquals(serverId, server.getId()); // } // // @Test // public void testCreate() throws IOException { // Response response = // target("/v2").path("test").path("images").register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).post(null); // Map<String, Fault> faultData = response.readEntity(new GenericType<Map<String, Fault>>() { // }); // String ret = JsonUtil.toString(faultData); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // String key = faultData.keySet().iterator().next(); // Fault fault = faultData.get(key); // assertEquals(405, response.getStatus()); // assertEquals("badMethod", key); // assertEquals(response.getStatus(), fault.getCode()); // } // // @Test // public void testDelete() throws IOException { // String imageId = "c2e5db72bd7fd153f53ede5da5a06de3"; // Response response = // target("/v2").path("admin").path("images").path(imageId).register(JacksonFeature.class).request() // .header("X-Auth-Token", TOKEN).delete(); // ResponseUtils.printResponse(logger, response); // assertEquals(204, response.getStatus()); // // ImageWrapper wrapper = response.readEntity(ImageWrapper.class); // // Image image = wrapper.getImage(); // // assertEquals("1bea47ed-f6a9-463b-b423-14b9cca9ad27", image.getId()); // // String ret = JsonUtil.convertValue(wrapper); // // System.err.println(ret); // } // // @Test // public void testIndexMetadatasNotFound() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadatas").register(JacksonFeature.class) // .request().header("X-Auth-Token", TOKEN).get(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(404, response.getStatus()); // assertTrue(ret.startsWith("<html>")); // } // // @Test // public void testIndexMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").register(JacksonFeature.class) // .request().header("X-Auth-Token", TOKEN).get(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // MetadataTemplate metadata = JsonUtil.readJson(ret, MetadataTemplate.class); // Map<String, String> map = metadata.getMetadata(); // assertEquals(2, map.size()); // } // // @Test // public void testShowMetadataCouldNotFound() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").path("test3") // .register(JacksonFeature.class).request().header("X-Auth-Token", TOKEN).get(); // // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(404, response.getStatus()); // Map<String, Fault> faultData = JsonUtil.readJson(ret, new TypeReference<Map<String, Fault>>() { // }); // String key = faultData.keySet().iterator().next(); // Fault fault = faultData.get(key); // assertEquals("itemNotFound", key); // assertEquals(response.getStatus(), fault.getCode()); // } // // @Test // public void testShowMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").path("test") // .register(JacksonFeature.class).request().header("X-Auth-Token", TOKEN).get(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // MetaItemTemplate metadata = JsonUtil.readJson(ret, MetaItemTemplate.class); // Map<String, String> map = metadata.getMeta(); // assertEquals(1, map.size()); // } // // @Test // public void testPostMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // MetadataTemplate input = new MetadataTemplate(); // input.setMetadata(new HashMap<String, String>()); // input.getMetadata().put("test3", "val3"); // input.getMetadata().put("test4", "val4"); // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").register(JacksonFeature.class) // .request().header("X-Auth-Token", TOKEN).post(Entity.entity(input, MediaType.APPLICATION_JSON_TYPE)); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // MetadataTemplate metadata = JsonUtil.readJson(ret, MetadataTemplate.class); // Map<String, String> map = metadata.getMetadata(); // assertEquals(4, map.size()); // } // // @Test // public void testUpdateMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // MetaItemTemplate input = new MetaItemTemplate(); // input.setMeta(new HashMap<String, String>()); // input.getMeta().put("test2", "val3"); // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").path("test2") // .register(JacksonFeature.class).request().header("X-Auth-Token", TOKEN) // .put(Entity.entity(input, MediaType.APPLICATION_JSON_TYPE)); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // MetaItemTemplate meta = JsonUtil.readJson(ret, MetaItemTemplate.class); // Map<String, String> map = meta.getMeta(); // assertEquals(1, map.size()); // assertEquals("val3", map.get("test2")); // } // // @Test // public void testUpdateAllMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // MetadataTemplate input = new MetadataTemplate(); // input.setMetadata(new HashMap<String, String>()); // input.getMetadata().put("test3", "val3"); // input.getMetadata().put("test4", "val4"); // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").register(JacksonFeature.class) // .request().header("X-Auth-Token", TOKEN).put(Entity.entity(input, MediaType.APPLICATION_JSON_TYPE)); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(200, response.getStatus()); // MetadataTemplate metadata = JsonUtil.readJson(ret, MetadataTemplate.class); // Map<String, String> map = metadata.getMetadata(); // assertEquals(2, map.size()); // assertEquals("val3", map.get("test3")); // assertEquals("val4", map.get("test4")); // } // // @Test // public void testDeleteMetadata() throws IOException { // String serverId = "7b500017-5080-4fa0-b204-50e60d47e0db"; // Response response = // target("/v2").path("admin").path("servers").path(serverId).path("metadata").path("test") // .register(JacksonFeature.class).request().header("X-Auth-Token", TOKEN).delete(); // String ret = response.readEntity(String.class); // ResponseUtils.printResponse(logger, response); // logger.debug("{}", ret); // assertEquals(204, response.getStatus()); // } // // // public static class NovaResourceTestApplication extends ResourceConfig { // // public NovaResourceTestApplication() { // super(NovaResourceTestApplication.class); // // this.register(new AbstractBinder() { // // @Override // protected void configure() { // bindFactory(VersionsApiFactory.class).to(VersionsApi.class).in(Singleton.class); // bindFactory(Version2ApiFactory.class).to(Version2Api.class).in(Singleton.class); // bindFactory(ImagesDriverFactory.class).to(ImagesDriver.class); // bindFactory(ImagesApiFactory.class).to(ImagesApi.class); // bindFactory(ImagesControllerFactory.class).to(ImagesController.class); // bindFactory(ImageMetadataControllerFactory.class).to(ImageMetadataController.class); // bindFactory(ImageMetadataApiFactory.class).to(ImageMetadataApi.class); // bindFactory(ServersControllerFactory.class).to(ServersController.class); // // bindFactory(ComputeApiFactory.class).to(ComputeApi.class); // // bindFactory(ComputeTaskApiFactory.class).to(ComputeTaskApi.class); // bindFactory(ServerMetadataControllerFactory.class).to(ServerMetadataController.class); // // bindFactory(QuotaHomeFactory.class).to(QuotaHome.class); // } // // }); // this.register(FaultWrapper.class); // this.register(EntityManagerFilter.class); // this.register(ComputeReqIdMiddleware.class); // this.register(NoAuthMiddleware.class); // this.register(NovaResource.class); // this.register(JacksonFeature.class); // } // // } // // // @Override // protected Application getApplication() { // return new NovaResourceTestApplication(); // } // // }
9231505857c5c0e2230053be0b68156186800f42
2,670
java
Java
modules/core/nuxeo-core-test/src/test/java/org/nuxeo/ecm/core/io/marshallers/json/enrichers/JsonEnricherPriorityTest.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
null
null
null
modules/core/nuxeo-core-test/src/test/java/org/nuxeo/ecm/core/io/marshallers/json/enrichers/JsonEnricherPriorityTest.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
3
2021-07-03T21:32:41.000Z
2022-03-23T13:15:18.000Z
modules/core/nuxeo-core-test/src/test/java/org/nuxeo/ecm/core/io/marshallers/json/enrichers/JsonEnricherPriorityTest.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
null
null
null
38.185714
116
0.748223
995,794
/* * (C) Copyright 2021 Nuxeo SA (http://nuxeo.com/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Antoine Taillefer <upchh@example.com> */ package org.nuxeo.ecm.core.io.marshallers.json.enrichers; import java.io.IOException; import javax.inject.Inject; import org.junit.Test; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.io.marshallers.json.AbstractJsonWriterTest; import org.nuxeo.ecm.core.io.marshallers.json.JsonAssert; import org.nuxeo.ecm.core.io.marshallers.json.document.DocumentModelJsonWriter; import org.nuxeo.ecm.core.io.registry.context.RenderingContext; import org.nuxeo.ecm.core.io.registry.context.RenderingContext.CtxBuilder; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; /** * Tests the enricher priority: make sure that an enricher B with the same name as an enricher A and a higher * Setup#priority() than A takes precedence over A. * <p> * Note that enricher deployment order doesn't matter since the MarshallerRegistry keeps the writers in a SortedMap. * * @since 11.5 */ @Features(CoreFeature.class) @Deploy("org.nuxeo.ecm.core.test.tests:enrichers-contrib.xml") @Deploy("org.nuxeo.ecm.core.test.tests:enrichers-override-contrib.xml") public class JsonEnricherPriorityTest extends AbstractJsonWriterTest.Local<DocumentModelJsonWriter, DocumentModel> { @Inject protected CoreSession session; public JsonEnricherPriorityTest() { super(DocumentModelJsonWriter.class, DocumentModel.class); } @Test public void testPriorities() throws IOException { DocumentModel rootDoc = session.getRootDocument(); RenderingContext context = CtxBuilder.enrichDoc(OverrideDummyEnricher.NAME).get(); JsonAssert json = jsonAssert(rootDoc, context); json = json.has("contextParameters").isObject(); json = json.properties(1); json = json.has("dummyEnricher").isObject(); json = json.properties(1); json.has("joe").isText().isEquals("doe"); } }
9231507ab0ce22095df8a27a6f9e6de7091bda98
4,742
java
Java
mischedule/mischedule-service/src/main/java/com/xiaomi/youpin/mischedule/service/ElectionNode.java
Jackierchan/mone
50b60fd41cf76026dc234d1de267bd51fa7b2e2b
[ "Apache-2.0" ]
98
2021-01-22T06:06:01.000Z
2022-02-20T13:59:06.000Z
mischedule/mischedule-service/src/main/java/com/xiaomi/youpin/mischedule/service/ElectionNode.java
Jackierchan/mone
50b60fd41cf76026dc234d1de267bd51fa7b2e2b
[ "Apache-2.0" ]
3
2021-01-31T16:39:30.000Z
2022-01-04T07:01:28.000Z
mischedule/mischedule-service/src/main/java/com/xiaomi/youpin/mischedule/service/ElectionNode.java
Jackierchan/mone
50b60fd41cf76026dc234d1de267bd51fa7b2e2b
[ "Apache-2.0" ]
20
2021-01-25T06:37:07.000Z
2022-01-25T12:59:58.000Z
32.703448
112
0.648882
995,795
/* * Copyright 2020 Xiaomi * * 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.xiaomi.youpin.mischedule.service; import com.alipay.remoting.rpc.RpcServer; import com.alipay.sofa.jraft.Lifecycle; import com.alipay.sofa.jraft.Node; import com.alipay.sofa.jraft.RaftGroupService; import com.alipay.sofa.jraft.conf.Configuration; import com.alipay.sofa.jraft.entity.PeerId; import com.alipay.sofa.jraft.option.NodeOptions; import com.alipay.sofa.jraft.rpc.RaftRpcServerFactory; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Paths; @Slf4j public class ElectionNode implements Lifecycle<ElectionNodeOptions> { // private static final Logger LOG = LoggerFactory.getLogger(ElectionNode.class); private RaftGroupService raftGroupService; private Node node; private ElectionOnlyStateMachine fsm; private boolean started; @Setter private LeaderStateListener leaderStateListener; @Override public boolean init(final ElectionNodeOptions opts) { if (this.started) { log.info("[ElectionNode: {}] already started."); return true; } // node options NodeOptions nodeOpts = opts.getNodeOptions(); if (nodeOpts == null) { nodeOpts = new NodeOptions(); } this.fsm = new ElectionOnlyStateMachine(); if (null != this.leaderStateListener) { this.fsm.addLeaderStateListener(this.leaderStateListener); } nodeOpts.setFsm(this.fsm); final Configuration initialConf = new Configuration(); if (!initialConf.parse(opts.getInitialServerAddressList())) { throw new IllegalArgumentException("Fail to parse initConf: " + opts.getInitialServerAddressList()); } // 设置初始集群配置 nodeOpts.setInitialConf(initialConf); final String dataPath = opts.getDataPath(); try { FileUtils.forceMkdir(new File(dataPath)); } catch (final IOException e) { log.error("Fail to make dir for dataPath {}.", dataPath); return false; } // 设置存储路径 // 日志, 必须 nodeOpts.setLogUri(Paths.get(dataPath, "log").toString()); // 元信息, 必须 nodeOpts.setRaftMetaUri(Paths.get(dataPath, "meta").toString()); // 纯选举场景不需要设置 snapshot, 不设置可避免启动 snapshot timer // nodeOpts.setSnapshotUri(Paths.get(dataPath, "snapshot").toString()); final String groupId = opts.getGroupId(); final PeerId serverId = new PeerId(); if (!serverId.parse(opts.getServerAddress())) { throw new IllegalArgumentException("Fail to parse serverId: " + opts.getServerAddress()); } final RpcServer rpcServer = new RpcServer(serverId.getPort()); // 注册 raft 处理器 RaftRpcServerFactory.addRaftRequestProcessors(rpcServer); // 初始化 raft group 服务框架 this.raftGroupService = new RaftGroupService(groupId, serverId, nodeOpts, rpcServer); // 启动 this.node = this.raftGroupService.start(); if (this.node != null) { this.started = true; } return this.started; } @Override public void shutdown() { if (!this.started) { return; } if (this.raftGroupService != null) { this.raftGroupService.shutdown(); try { this.raftGroupService.join(); } catch (final InterruptedException e) { log.error(e.getMessage()); } } this.started = false; log.info("[RegionEngine] shutdown successfully: {}.", this); } public Node getNode() { return node; } public ElectionOnlyStateMachine getFsm() { return fsm; } public boolean isStarted() { return started; } public boolean isLeader() { return this.fsm.isLeader(); } public void addLeaderStateListener(final LeaderStateListener listener) { this.fsm.addLeaderStateListener(listener); } }
9231510d2f6b36614f5007da143caa38e3aef8b0
657
java
Java
src/main/java/com/telapi/api/example/SendDigitsExample.java
TelAPI/telapi-java
70331558bdec74030b9606637e96a3e0fb5a36bf
[ "MIT" ]
null
null
null
src/main/java/com/telapi/api/example/SendDigitsExample.java
TelAPI/telapi-java
70331558bdec74030b9606637e96a3e0fb5a36bf
[ "MIT" ]
null
null
null
src/main/java/com/telapi/api/example/SendDigitsExample.java
TelAPI/telapi-java
70331558bdec74030b9606637e96a3e0fb5a36bf
[ "MIT" ]
null
null
null
27.375
65
0.745814
995,796
package com.telapi.api.example; import com.telapi.api.TelapiConnector; import com.telapi.api.configuration.BasicTelapiConfiguration; import com.telapi.api.domain.Call; import com.telapi.api.exceptions.TelapiException; public class SendDigitsExample { public static void main(String[] args) { BasicTelapiConfiguration conf = new BasicTelapiConfiguration(); conf.setSid("{AccountSid}"); conf.setAuthToken("{AuthToken}"); TelapiConnector conn = new TelapiConnector(conf); try { Call call = conn.sendDigits("{CallSid}", "www2113", null); System.out.println(call.getSid()); } catch (TelapiException e) { e.printStackTrace(); } } }
92315156ebb0c92cccd6535a394a9f73f56d0ce7
5,516
java
Java
platform/lang-impl/src/com/intellij/execution/services/ServiceTreeView.java
Leidenn2509/intellij-community
83568c8c776934faaeffc0f860e0b6fa13d59f7c
[ "Apache-2.0" ]
null
null
null
platform/lang-impl/src/com/intellij/execution/services/ServiceTreeView.java
Leidenn2509/intellij-community
83568c8c776934faaeffc0f860e0b6fa13d59f7c
[ "Apache-2.0" ]
null
null
null
platform/lang-impl/src/com/intellij/execution/services/ServiceTreeView.java
Leidenn2509/intellij-community
83568c8c776934faaeffc0f860e0b6fa13d59f7c
[ "Apache-2.0" ]
null
null
null
35.818182
140
0.730058
995,797
// 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.execution.services; import com.intellij.execution.services.ServiceModel.ServiceViewItem; import com.intellij.ide.dnd.DnDManager; import com.intellij.ide.util.treeView.TreeState; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.pom.Navigatable; import com.intellij.ui.AppUIUtil; import com.intellij.ui.tree.TreeVisitor; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import org.jetbrains.concurrency.Promises; import javax.swing.tree.TreePath; import java.awt.*; import java.util.List; import java.util.Queue; import java.util.*; class ServiceTreeView extends ServiceView { private final ServiceViewTree myTree; private final ServiceViewTreeModel myTreeModel; private ServiceViewItem myLastSelection; private boolean mySelected; ServiceTreeView(@NotNull Project project, @NotNull ServiceViewModel model, @NotNull ServiceViewUi ui, @NotNull ServiceViewState state) { super(new BorderLayout(), project, model, ui); myTreeModel = new ServiceViewTreeModel(model); myTree = new ServiceViewTree(myTreeModel, this); ServiceViewActionProvider actionProvider = ServiceViewActionProvider.getInstance(); ui.setServiceToolbar(actionProvider); ui.setMasterPanel(myTree, actionProvider); DnDManager.getInstance().registerSource(ServiceViewDragHelper.createSource(this), myTree); add(myUi.getComponent(), BorderLayout.CENTER); myTree.addTreeSelectionListener(e -> onSelectionChanged()); model.addModelListener(() -> AppUIUtil.invokeOnEdt(() -> { if (mySelected && myLastSelection != null) { ServiceViewDescriptor descriptor = myLastSelection.getViewDescriptor(); myUi.setDetailsComponent(descriptor.getContentComponent()); } }, myProject.getDisposed())); state.treeState.applyTo(myTree, myTreeModel.getRoot()); } @Override void saveState(@NotNull ServiceViewState state) { myUi.saveState(state); state.treeState = TreeState.createOn(myTree); } @NotNull @Override List<ServiceViewItem> getSelectedItems() { int[] rows = myTree.getSelectionRows(); if (rows == null || rows.length == 0) return Collections.emptyList(); List<ServiceViewItem> result = new ArrayList<>(); Arrays.sort(rows); for (int row : rows) { TreePath path = myTree.getPathForRow(row); ServiceViewItem item = path == null ? null : ObjectUtils.tryCast(path.getLastPathComponent(), ServiceViewItem.class); if (item != null) { result.add(item); } } return result; } @Override Promise<Void> select(@NotNull Object service, @NotNull Class<?> contributorClass) { if (myLastSelection == null || !myLastSelection.getValue().equals(service)) { AsyncPromise<Void> result = new AsyncPromise<>(); myTreeModel.findPath(service, contributorClass) .onError(result::setError) .onSuccess(path -> TreeUtil.promiseSelect(myTree, new PathSelectionVisitor(path)) .onError(result::setError) .onSuccess(selectedPath -> result.setResult(null))); return result; } return Promises.resolvedPromise(); } @Override void onViewSelected() { mySelected = true; if (myLastSelection != null) { ServiceViewDescriptor descriptor = myLastSelection.getViewDescriptor(); descriptor.onNodeSelected(); myUi.setDetailsComponent(descriptor.getContentComponent()); } } @Override void onViewUnselected() { mySelected = false; if (myLastSelection != null) { myLastSelection.getViewDescriptor().onNodeUnselected(); } } private void onSelectionChanged() { List<ServiceViewItem> selected = getSelectedItems(); ServiceViewItem newSelection = ContainerUtil.getOnlyItem(selected); if (Comparing.equal(newSelection, myLastSelection)) return; ServiceViewDescriptor oldDescriptor = myLastSelection == null ? null : myLastSelection.getViewDescriptor(); if (oldDescriptor != null && mySelected) { oldDescriptor.onNodeUnselected(); } myLastSelection = newSelection; ServiceViewDescriptor newDescriptor = newSelection == null ? null : newSelection.getViewDescriptor(); if (newDescriptor != null) { newDescriptor.onNodeSelected(); } if (newDescriptor instanceof Navigatable) { Navigatable navigatable = (Navigatable)newDescriptor; if (ServiceViewManagerImpl.isAutoScrollToSourceEnabled(myProject) && navigatable.canNavigate()) navigatable.navigate(false); } myUi.setDetailsComponent(newDescriptor == null ? null : newDescriptor.getContentComponent()); } private static class PathSelectionVisitor implements TreeVisitor { private final Queue<Object> myPath; PathSelectionVisitor(TreePath path) { myPath = ContainerUtil.newLinkedList(path.getPath()); } @NotNull @Override public Action visit(@NotNull TreePath path) { Object node = path.getLastPathComponent(); if (node.equals(myPath.peek())) { myPath.poll(); return myPath.isEmpty() ? Action.INTERRUPT : Action.CONTINUE; } return Action.SKIP_CHILDREN; } } }
923151fe3cc2a282f53c6dc910e027a89b950e7a
4,528
java
Java
src/main/java/org/idpass/sam/SamSlot.java
idpass/card-sam-applet
61431bbc457db840f5de6d0d29406a6426a3425c
[ "Apache-2.0" ]
1
2019-11-04T01:10:36.000Z
2019-11-04T01:10:36.000Z
src/main/java/org/idpass/sam/SamSlot.java
idpass/card-sam-applet
61431bbc457db840f5de6d0d29406a6426a3425c
[ "Apache-2.0" ]
null
null
null
src/main/java/org/idpass/sam/SamSlot.java
idpass/card-sam-applet
61431bbc457db840f5de6d0d29406a6426a3425c
[ "Apache-2.0" ]
null
null
null
34.564885
112
0.656581
995,798
/* * Copyright (C) 2019 Newlogic Impact Lab Pte. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.idpass.sam; import org.idpass.tools.Utils; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.JCSystem; import javacard.framework.Util; import javacard.security.AESKey; import javacard.security.DESKey; import javacard.security.KeyBuilder; import javacard.security.RandomData; import javacard.security.Signature; import javacardx.crypto.Cipher; final class SamSlot implements Slot { private static final short OPENED_INDEX = 0; private static final short LENGTH_BYTE = 8; private static final short SIZE_RAM = 32; private static final short LENGTH_BLOCK = (short) (128 / LENGTH_BYTE); private AESKey keyEnc; private DESKey keyMac; private Cipher cipher; private Signature signature; private RandomData random; private byte[] ram; private boolean[] opened; private short id; SamSlot(short id, RandomData random, Cipher cipher, Signature signature) { this.id = id; this.random = random; this.cipher = cipher; this.signature = signature; ram = JCSystem.makeTransientByteArray(SIZE_RAM, JCSystem.CLEAR_ON_RESET); keyEnc = (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false); random.generateData(ram, (short) 0, (short) (keyEnc.getSize() / LENGTH_BYTE)); keyEnc.setKey(ram, (short) 0); keyMac = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false); random.generateData(ram, (short) 0, (short) (keyMac.getSize() / LENGTH_BYTE)); keyMac.setKey(ram, (short) 0); opened = JCSystem.makeTransientBooleanArray((short) (OPENED_INDEX + 1), JCSystem.CLEAR_ON_RESET); } public short getId() { return id; } public void open() { opened[OPENED_INDEX] = true; } public void close() { opened[OPENED_INDEX] = false; } public boolean isOpened() { return opened[OPENED_INDEX]; } public short encrypt(byte[] inBuf, short inOff, byte[] outBuf, short outOff, short inLen) { if (!this.isOpened()) { ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); } random.generateData(ram, Utils.SHORT_00, LENGTH_BLOCK); Util.arrayCopy(inBuf, inOff, outBuf, (short) (outOff + LENGTH_BLOCK), inLen); Util.arrayCopy(ram, Utils.SHORT_00, outBuf, outOff, LENGTH_BLOCK); cipher.init(keyEnc, Cipher.MODE_ENCRYPT); short encLength = cipher.doFinal(outBuf, outOff, (short) (inLen + LENGTH_BLOCK), outBuf, outOff); signature.init(keyMac, Signature.MODE_SIGN); short signatureLength = signature.sign(outBuf, outOff, encLength, outBuf, (short) (outOff + encLength)); return (short) (encLength + signatureLength); } public short decrypt(byte[] inBuf, short inOff, byte[] outBuf, short outOff, short inLen) { if (!this.isOpened()) { ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); } signature.init(keyMac, Signature.MODE_VERIFY); short signatureLength = signature.getLength(); if (!signature.verify(inBuf, inOff, (short) (inLen - signatureLength), inBuf, (short) (inLen - signatureLength), signatureLength)) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } cipher.init(keyEnc, Cipher.MODE_DECRYPT); short length = cipher.doFinal(inBuf, inOff, (short) (inLen - signatureLength), outBuf, outOff); short offset = Util.arrayCopy(outBuf, (short) (outOff + LENGTH_BLOCK), outBuf, outOff, (short) (length - LENGTH_BLOCK)); return (short) (offset - outOff); } }
92315265dfa3dd91f27b0a97b52fa002a8d1c2c2
342
java
Java
src/edu/iit/cs445/s2016/delectable/customer/Customer.java
apegadoboureghida/cs445_project
eed6329bde786e21ad240ffb02f93b4c577fe213
[ "MIT" ]
null
null
null
src/edu/iit/cs445/s2016/delectable/customer/Customer.java
apegadoboureghida/cs445_project
eed6329bde786e21ad240ffb02f93b4c577fe213
[ "MIT" ]
null
null
null
src/edu/iit/cs445/s2016/delectable/customer/Customer.java
apegadoboureghida/cs445_project
eed6329bde786e21ad240ffb02f93b4c577fe213
[ "MIT" ]
null
null
null
21.375
56
0.739766
995,799
package edu.iit.cs445.s2016.delectable.customer; import com.google.gson.annotations.SerializedName; import edu.iit.cs445.s2016.delectable.UniqueIdGenerator; public class Customer extends GenericCustomer { @SerializedName("id") protected int id; public Customer() { this.id = UniqueIdGenerator.getUniqueID(); } }
923152a5b2ec31f4821340e527ca300f03fbc335
1,016
java
Java
java-se/src/main/java/com/zhoutao123/java/se/collect/code/Code.java
taoes/architect
b8dc7818068172e0a478af7ff2502e50cdf87be9
[ "MIT" ]
null
null
null
java-se/src/main/java/com/zhoutao123/java/se/collect/code/Code.java
taoes/architect
b8dc7818068172e0a478af7ff2502e50cdf87be9
[ "MIT" ]
null
null
null
java-se/src/main/java/com/zhoutao123/java/se/collect/code/Code.java
taoes/architect
b8dc7818068172e0a478af7ff2502e50cdf87be9
[ "MIT" ]
null
null
null
23.090909
137
0.63189
995,800
package com.zhoutao123.java.se.collect.code; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Code { public static void main(String[] args) { Student student = () -> System.out.println("正在说活"); Student o = (Student) Proxy.newProxyInstance(Code.class.getClassLoader(), new Class[]{Student.class}, new StudentProxy(student)); o.speak(); } static class StudentProxy implements InvocationHandler { Student student; public StudentProxy(Student student) { this.student = student; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before"); Object invoke = method.invoke(student, args); System.out.println("After"); return invoke; } } @FunctionalInterface static interface Student { void speak(); } }
9231542ebc59dad965e6a0132ab4de1bced60911
809
java
Java
rational-master/src/main/java/com/mathbeta/rational/master/service/IBaseService.java
mathbeta/rational
676c91aec7c50b33adaae82ee95c4a0423e8a1a9
[ "Apache-2.0" ]
null
null
null
rational-master/src/main/java/com/mathbeta/rational/master/service/IBaseService.java
mathbeta/rational
676c91aec7c50b33adaae82ee95c4a0423e8a1a9
[ "Apache-2.0" ]
null
null
null
rational-master/src/main/java/com/mathbeta/rational/master/service/IBaseService.java
mathbeta/rational
676c91aec7c50b33adaae82ee95c4a0423e8a1a9
[ "Apache-2.0" ]
null
null
null
28.892857
77
0.746601
995,801
package com.mathbeta.rational.master.service; import com.mathbeta.rational.common.entity.BaseEntity; import com.mathbeta.rational.common.entity.Message; import com.mathbeta.rational.common.entity.Page; import java.util.List; import java.util.Map; /** * Created by Administrator on 17-4-18. */ public interface IBaseService<Entity extends BaseEntity> { Message save(Entity entity) throws Exception; Message update(Entity entity) throws Exception; List<Entity> queryByParams(Map<String, Object> params) throws Exception; int countByParams(Map<String, Object> params) throws Exception; Entity queryById(String id) throws Exception; Message deleteByIds(String ids) throws Exception; Page<Entity> queryByPage(Page<Entity> page) throws Exception; }
923154e3e755d922c9e999d202278b12bfa5d6c2
2,101
java
Java
app/src/main/java/com/example/hy/wanandroid/base/presenter/BasePresenter.java
zhoutianling/WanAndroid
dbb73f81c17c4f7a270d18b117d2691fae756c36
[ "Apache-2.0" ]
1
2019-01-04T01:50:55.000Z
2019-01-04T01:50:55.000Z
app/src/main/java/com/example/hy/wanandroid/base/presenter/BasePresenter.java
zhoutianling/WanAndroid
dbb73f81c17c4f7a270d18b117d2691fae756c36
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/hy/wanandroid/base/presenter/BasePresenter.java
zhoutianling/WanAndroid
dbb73f81c17c4f7a270d18b117d2691fae756c36
[ "Apache-2.0" ]
null
null
null
24.149425
103
0.670157
995,802
package com.example.hy.wanandroid.base.presenter; import com.example.hy.wanandroid.base.view.BaseView; import com.example.hy.wanandroid.config.RxBus; import com.example.hy.wanandroid.event.NetWorkChangeEvent; import com.example.hy.wanandroid.model.DataModel; import javax.inject.Inject; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; /** * Presenter的基类 * Created by 陈健宇 at 2018/10/21 */ public class BasePresenter<T extends BaseView> implements IPresenter<T> { protected T mView; protected DataModel mModel; private CompositeDisposable mCompositeDisposable; @Inject public BasePresenter(DataModel dataModel) { mModel = dataModel; } @Override public void attachView(T view) { this.mView = view; } @Override public boolean isAttachView() { return this.mView != null; } @Override public void detachView() { this.mView = null; if(mCompositeDisposable != null){ mCompositeDisposable.clear(); } } @Override public void addSubcriber(Disposable disposable){ if(mCompositeDisposable == null){ mCompositeDisposable = new CompositeDisposable(); } mCompositeDisposable.add(disposable); } @Override public void subscribleEvent() { addSubcriber( RxBus.getInstance().toObservable(NetWorkChangeEvent.class) .subscribe(netWorkChangeEvent -> mView.showTipsView(netWorkChangeEvent.isConnection())) ); } @Override public boolean getNoImageState() { return mModel.getNoImageState(); } @Override public boolean getAutoCacheState() { return mModel.getAutoCacheState(); } @Override public boolean getNightModeState() { return mModel.getNightModeState(); } @Override public boolean getStatusBarState() { return mModel.getStatusBarState(); } @Override public boolean getAutoUpdataState() { return mModel.getAutoUpdataState(); } }
923155cc8ba7d57bcf9bef5751027e2a651c40e2
539
java
Java
src/test/java/com/huawei/servicecomb/controller/TestProjectnznt.java
yi5637/springmvc
24272a97bbf60662048b96bd2d8d5069b828b711
[ "MIT" ]
null
null
null
src/test/java/com/huawei/servicecomb/controller/TestProjectnznt.java
yi5637/springmvc
24272a97bbf60662048b96bd2d8d5069b828b711
[ "MIT" ]
null
null
null
src/test/java/com/huawei/servicecomb/controller/TestProjectnznt.java
yi5637/springmvc
24272a97bbf60662048b96bd2d8d5069b828b711
[ "MIT" ]
null
null
null
22.458333
97
0.693878
995,803
package com.huawei.servicecomb.controller; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class TestProjectnznt { ProjectnzntDelegate projectnzntDelegate = new ProjectnzntDelegate(); @Test public void testhelloworld(){ String expactReturnValue = "hello"; // You should put the expect String type value here. String returnValue = projectnzntDelegate.helloworld("hello"); assertEquals(expactReturnValue, returnValue); } }
9231568db58bc1eb15fc58e88dccf3de0a50c678
513
java
Java
samples/535/b.java
yura-hb/sesame-sampled-pairs
33b061e3612a7b26198c17245c2835193f861151
[ "MIT" ]
null
null
null
samples/535/b.java
yura-hb/sesame-sampled-pairs
33b061e3612a7b26198c17245c2835193f861151
[ "MIT" ]
null
null
null
samples/535/b.java
yura-hb/sesame-sampled-pairs
33b061e3612a7b26198c17245c2835193f861151
[ "MIT" ]
null
null
null
27
72
0.682261
995,805
class LambdaTestMode extends Enum&lt;LambdaTestMode&gt; { /** * * @return the mode of test execution. */ public static LambdaTestMode getMode() { return IS_LAMBDA_SERIALIZATION_MODE ? SERIALIZATION : NORMAL; } /** * {@code true} if tests are executed in the mode for testing lambda * Serialization ANd Deserialization (SAND). */ private static final boolean IS_LAMBDA_SERIALIZATION_MODE = Boolean .getBoolean("org.openjdk.java.util.stream.sand.mode"); }
923158d07b62e9fe3ea1f3f64810baca1f316360
1,221
java
Java
processor/src/main/java/org/mapstruct/ap/internal/version/VersionInformation.java
agudian/mapstruct
ef1c95ad1bac1b3f54cc5d741d7df4b61841056e
[ "Apache-2.0" ]
1
2015-05-27T07:45:56.000Z
2015-05-27T07:45:56.000Z
processor/src/main/java/org/mapstruct/ap/internal/version/VersionInformation.java
agudian/mapstruct
ef1c95ad1bac1b3f54cc5d741d7df4b61841056e
[ "Apache-2.0" ]
null
null
null
processor/src/main/java/org/mapstruct/ap/internal/version/VersionInformation.java
agudian/mapstruct
ef1c95ad1bac1b3f54cc5d741d7df4b61841056e
[ "Apache-2.0" ]
null
null
null
31.307692
100
0.734644
995,806
/** * Copyright 2012-2017 Gunnar Morling (http://www.gunnarmorling.de/) * and/or other contributors as indicated by the @authors tag. See the * copyright.txt file in the distribution for a full listing of all * contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mapstruct.ap.internal.version; /** * Provides information about the processor version and the processor context implementation version * * @author Andreas Gudian */ public interface VersionInformation { String getRuntimeVersion(); String getRuntimeVendor(); String getMapStructVersion(); String getCompiler(); boolean isEclipseJDTCompiler(); boolean isJavacCompiler(); }
92315a9a5b48f15ebb6fd2074590f3fb72b04779
750
java
Java
src/main/java/edu/mum/dao/impl/CartItemDaoImpl.java
javietanh/cs544
01babd068f55235f76a586df425e403c125d7d05
[ "MIT" ]
null
null
null
src/main/java/edu/mum/dao/impl/CartItemDaoImpl.java
javietanh/cs544
01babd068f55235f76a586df425e403c125d7d05
[ "MIT" ]
null
null
null
src/main/java/edu/mum/dao/impl/CartItemDaoImpl.java
javietanh/cs544
01babd068f55235f76a586df425e403c125d7d05
[ "MIT" ]
1
2019-09-26T17:00:49.000Z
2019-09-26T17:00:49.000Z
34.090909
113
0.742667
995,807
package edu.mum.dao.impl; import edu.mum.domain.CartItem; import org.springframework.stereotype.Repository; import javax.persistence.Query; import java.util.List; @Repository public class CartItemDaoImpl extends GenericDaoImpl<CartItem> implements edu.mum.dao.CartItemDao { public CartItemDaoImpl() { super.setDaoType(CartItem.class ); } @Override public List<CartItem> getCartItemByBuyerId(Long buyerId) { // Query query = entityManager.createNamedQuery("CartItem.findByUserId").setParameter("buyerId", buyerId); Query query = entityManager.createQuery("select c from CartItem c where c.buyer.id = :buyerId"); return (List<CartItem>) query.setParameter("buyerId", buyerId).getResultList(); } }
92315b30ffd845674ca17965addf934bf762a385
956
java
Java
src/main/java/br/laab/askgomvc/dao/Imp/DAO.java
brunohmedeiros/AskGoMVC
3bd4410f43073be101e24e0c747b8da127f56c11
[ "MIT" ]
null
null
null
src/main/java/br/laab/askgomvc/dao/Imp/DAO.java
brunohmedeiros/AskGoMVC
3bd4410f43073be101e24e0c747b8da127f56c11
[ "MIT" ]
null
null
null
src/main/java/br/laab/askgomvc/dao/Imp/DAO.java
brunohmedeiros/AskGoMVC
3bd4410f43073be101e24e0c747b8da127f56c11
[ "MIT" ]
null
null
null
22.761905
96
0.698745
995,808
package br.laab.askgomvc.dao.Imp; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import br.laab.askgomvc.dao.IDAO; public abstract class DAO<T, I extends Serializable> implements IDAO<T, I> { @PersistenceContext protected EntityManager manager; public void insert(T entity) { manager.persist(entity); } public void update(T entity) { manager.merge(entity); } public void remove(T entity) { manager.remove(manager.contains(entity) ? entity : manager.merge(entity)); } public T getById(Class<T> classe, I pk) { try { return manager.find(classe, pk); } catch (NoResultException e) { return null; } } public List<T> getAll(Class<T> classe) { return manager.createQuery("select o from " + classe.getSimpleName() + " o").getResultList(); } }
92315b516f4c22dcda0b2015d13a39ef5a6711f0
5,027
java
Java
Practica 1/Parte 1/src/main/java/mx/iteso/desi/cloud/keyvalue/DynamoDBStorage.java
01FC/CloudPracticas
055f11f02086015f287a1f68a441f6a8814868ba
[ "MIT" ]
null
null
null
Practica 1/Parte 1/src/main/java/mx/iteso/desi/cloud/keyvalue/DynamoDBStorage.java
01FC/CloudPracticas
055f11f02086015f287a1f68a441f6a8814868ba
[ "MIT" ]
null
null
null
Practica 1/Parte 1/src/main/java/mx/iteso/desi/cloud/keyvalue/DynamoDBStorage.java
01FC/CloudPracticas
055f11f02086015f287a1f68a441f6a8814868ba
[ "MIT" ]
null
null
null
33.966216
135
0.642729
995,809
package mx.iteso.desi.cloud.keyvalue; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.*; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; import com.amazonaws.services.dynamodbv2.model.*; import mx.iteso.desi.cloud.lp1.Config; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class DynamoDBStorage extends BasicKeyValueStore { String dbName; AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withRegion(Config.amazonRegion).build(); DynamoDB dynamoDB = new DynamoDB(client); // Simple autoincrement counter to make sure we have unique entries int inx; Set<String> attributesToGet = new HashSet<String>(); public DynamoDBStorage(String dbName) { try { System.out.println("Looking for table " + dbName); ArrayList<KeySchemaElement> keySchema = new ArrayList<>(); ArrayList<AttributeDefinition> attributeDefinitions= new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName("Keyword").withKeyType(KeyType.HASH)); keySchema.add(new KeySchemaElement().withAttributeName("inx").withKeyType(KeyType.RANGE)); attributeDefinitions.add(new AttributeDefinition().withAttributeName("Keyword").withAttributeType("S")); attributeDefinitions.add(new AttributeDefinition().withAttributeName("inx").withAttributeType("N")); CreateTableRequest request = new CreateTableRequest() .withTableName(dbName) .withKeySchema(keySchema) .withAttributeDefinitions(attributeDefinitions) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(1L) .withWriteCapacityUnits(1L)); Table table = dynamoDB.createTable(request); table.waitForActive(); this.dbName = dbName; } catch (ResourceInUseException e){ this.dbName = dbName; System.out.println("Table already exists"); e.getStackTrace(); } catch (Exception e){ this.dbName = dbName; e.getStackTrace(); } } @Override public Set<String> get(String search) { Set<String> items = new HashSet<>(); Table table = dynamoDB.getTable(dbName); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("Keyword = :v_id") .withValueMap(new ValueMap().withString(":v_id", search)); ItemCollection<QueryOutcome> queryresult = table.query(spec); Iterator<Item> iterator = queryresult.iterator(); while (iterator.hasNext()){ items.add(iterator.next().get("Value").toString()); } return items; } @Override public boolean exists(String search) { Table table = dynamoDB.getTable(dbName); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("Keyword = :v_id") .withValueMap(new ValueMap().withString(":v_id", search)); return table.query(spec).iterator().hasNext(); } @Override public Set<String> getPrefix(String search) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void addToSet(String keyword, String value) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void put(String keyword, String value) { Table table = dynamoDB.getTable(dbName); try { Item item = new Item();//.withString("key" , keyword).withString("Value" , value).withInt("inx",inx); item.withPrimaryKey("inx",inx).withString("Value",value).withString("Keyword",keyword); table.putItem(item); System.out.println("uploaded "+inx); inx++; } catch (Exception e) { System.err.println("Create items failed."); System.err.println(e.getMessage()); } } @Override public void close() { dynamoDB.shutdown(); System.out.println("Connection to " + dbName + " has been closed"); } @Override public boolean supportsPrefixes() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void sync() { } @Override public boolean isCompressible() { return false; } @Override public boolean supportsMoreThan256Attributes() { return true; } }
92315e192cc7db968b3893950c4fbc5eb33f1ce0
260
java
Java
curdInfo-admin/src/main/java/com/his/app/service/Drug_wService.java
cgl-dong/curdInfo
bdb159388f4530c4e4cb59daaa97ff4f56158a3c
[ "Apache-2.0" ]
null
null
null
curdInfo-admin/src/main/java/com/his/app/service/Drug_wService.java
cgl-dong/curdInfo
bdb159388f4530c4e4cb59daaa97ff4f56158a3c
[ "Apache-2.0" ]
null
null
null
curdInfo-admin/src/main/java/com/his/app/service/Drug_wService.java
cgl-dong/curdInfo
bdb159388f4530c4e4cb59daaa97ff4f56158a3c
[ "Apache-2.0" ]
null
null
null
15.294118
59
0.688462
995,810
package com.his.app.service; import com.his.app.pojo.Drug_w; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author ${author} * @since 2020-08-29 */ public interface Drug_wService extends IService<Drug_w> { }
92315e37a3a260e954ed6dfb089355aca60f8273
769
java
Java
jg-backend/implementation/base/jg-security/interface/src/main/java/org/jgrades/security/api/dao/PasswordDataRepository.java
jgrades/jgrades
c2bf798fbb5265f87ac622eca1d116992995690d
[ "Apache-2.0" ]
1
2017-01-12T06:18:18.000Z
2017-01-12T06:18:18.000Z
jg-backend/implementation/base/jg-security/interface/src/main/java/org/jgrades/security/api/dao/PasswordDataRepository.java
jgrades/jgrades-legacy
c2bf798fbb5265f87ac622eca1d116992995690d
[ "Apache-2.0" ]
41
2015-08-03T19:00:00.000Z
2015-10-17T23:14:40.000Z
jg-backend/implementation/base/jg-security/interface/src/main/java/org/jgrades/security/api/dao/PasswordDataRepository.java
jgrades/jgrades-legacy
c2bf798fbb5265f87ac622eca1d116992995690d
[ "Apache-2.0" ]
3
2015-07-12T20:17:48.000Z
2016-09-22T03:04:33.000Z
33.434783
84
0.768531
995,811
/* * Copyright (C) 2016 the original author or authors. * * This file is part of jGrades Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jgrades.security.api.dao; import org.jgrades.security.api.entities.PasswordData; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface PasswordDataRepository extends CrudRepository<PasswordData, Long> { @Query("select pd from PasswordData pd where pd.user.login = ?1") PasswordData getPasswordDataWithUser(String login); }
9231613e4f3f87aad73e0b54f295fd4f797d5a64
2,323
java
Java
common-helper/src/main/java/io/github/kongpf8848/commonhelper/ByteHelper.java
kongpf8848/CommonHelper
45a0e297ffe4347cf216eb0dab20a542003e6fb7
[ "Apache-2.0" ]
2
2021-01-30T15:24:10.000Z
2021-07-07T06:26:43.000Z
common-helper/src/main/java/io/github/kongpf8848/commonhelper/ByteHelper.java
kongpf8848/CommonHelper
45a0e297ffe4347cf216eb0dab20a542003e6fb7
[ "Apache-2.0" ]
null
null
null
common-helper/src/main/java/io/github/kongpf8848/commonhelper/ByteHelper.java
kongpf8848/CommonHelper
45a0e297ffe4347cf216eb0dab20a542003e6fb7
[ "Apache-2.0" ]
2
2020-09-10T06:03:43.000Z
2021-03-07T14:21:16.000Z
29.0375
106
0.516573
995,812
package io.github.kongpf8848.commonhelper; /** * Created by pengf on 2018/2/28. */ public class ByteHelper { private static final String HEXSTRING = "0123456789ABCDEF"; public static byte hexChar2Byte(char c) { return (byte) (HEXSTRING.indexOf(String.valueOf(c).toUpperCase())); } public static String byteToHex(int b) { char[] result = new char[2]; result[0] = hexDigit((b >>> 4) & 0xf); result[1] = hexDigit(b & 0xf); return new String(result); } public static char hexDigit(int i) { return (char) (i < 10 ? i + '0' : i - 10 + 'a'); } public static String byteArray2HexString(byte[] bArr) { StringBuilder builder = new StringBuilder(); for (int i = 0, len = bArr.length; i < len; i++) { builder.append(String.format("%02X", bArr[i])); } return builder.toString(); } //16进制字符串转化为字节数组 public static byte[] hexString2ByteArray(String hexStr) { if (hexStr == null) { return null; } else if (hexStr.length() % 2 != 0) { return null; } else { int len = (hexStr.length() / 2); byte[] data = new byte[len]; char[] chArray = hexStr.toCharArray(); for (int i = 0; i < len; i++) { data[i] = (byte) ((hexChar2Byte(chArray[2 * i]) << 4) + hexChar2Byte(chArray[2 * i + 1])); } return data; } } public static byte[] subBytes(byte[] data, int offset, int len) { if ((offset < 0) || (data.length <= offset)) { return null; } if ((len < 0) || (data.length < offset + len)) { len = data.length - offset; } byte[] ret = new byte[len]; System.arraycopy(data, offset, ret, 0, len); return ret; } public static byte byteXOR(byte src1, byte src2) { return (byte) ((src1 & 0xFF) ^ (src2 & 0xFF)); } public static byte[] bytesXOR(byte[] src1, byte[] src2) { int length = src1.length; if (length != src2.length) { return null; } byte[] result = new byte[length]; for (int i = 0; i < length; i++) { result[i] = byteXOR(src1[i], src2[i]); } return result; } }
923161610927706efe3d767726694dd7eea9e84d
1,043
java
Java
src/org/mustbe/consulo/unity3d/Unity3dIcons.java
mefilt/consulo-unity3d
9dc98cee2362c3e4c6f71679e10208b79f2e7991
[ "Apache-2.0" ]
null
null
null
src/org/mustbe/consulo/unity3d/Unity3dIcons.java
mefilt/consulo-unity3d
9dc98cee2362c3e4c6f71679e10208b79f2e7991
[ "Apache-2.0" ]
null
null
null
src/org/mustbe/consulo/unity3d/Unity3dIcons.java
mefilt/consulo-unity3d
9dc98cee2362c3e4c6f71679e10208b79f2e7991
[ "Apache-2.0" ]
1
2021-01-13T23:01:55.000Z
2021-01-13T23:01:55.000Z
34.766667
75
0.741131
995,813
/* * Copyright 2013-2015 must-be.org * * 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.mustbe.consulo.unity3d; import javax.swing.Icon; import com.intellij.openapi.util.IconLoader; // Generated Consulo DevKit plugin public interface Unity3dIcons { Icon Attach = IconLoader.getIcon("/icons/attach.png"); // 12x16 Icon EventMethod = IconLoader.getIcon("/icons/eventMethod.png"); // 12x12 Icon Js = IconLoader.getIcon("/icons/js.PNG"); // 16x16 Icon Unity3d = IconLoader.getIcon("/icons/unity3d.png"); // 16x16 }
923161c1670b6e6c7dfc005306a8c05fa8041efa
951
java
Java
sat-rest/src/main/java/com/github/aha/sat/rest/config/SpringdocOpenapiConfig.java
arnosthavelka/spring-advanced-training
27213b41c803d8341711f75ad8290756fbca5ebf
[ "MIT" ]
9
2015-03-18T21:31:21.000Z
2022-02-04T07:47:26.000Z
sat-rest/src/main/java/com/github/aha/sat/rest/config/SpringdocOpenapiConfig.java
arnosthavelka/spring-advanced-training
27213b41c803d8341711f75ad8290756fbca5ebf
[ "MIT" ]
28
2020-12-15T07:36:10.000Z
2022-03-22T07:41:09.000Z
sat-rest/src/main/java/com/github/aha/sat/rest/config/SpringdocOpenapiConfig.java
arnosthavelka/spring-advanced-training
27213b41c803d8341711f75ad8290756fbca5ebf
[ "MIT" ]
6
2015-10-05T11:22:21.000Z
2021-11-21T23:44:35.000Z
28.818182
96
0.726604
995,814
package com.github.aha.sat.rest.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; /** * Usage: * * access UI - GET http://localhost:8080/swagger-ui.html * Swagger API - GET http://localhost:8080/v3/api-docs * * @see https://www.baeldung.com/spring-rest-openapi-documentation * @see https://springdoc.org/#migrating-from-springfox */ @Configuration public class SpringdocOpenapiConfig { @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title("SAT-REST API") .description("Usage of Springdoc Openapi in Spring Boot") .version("2.1") .license(new License().name("License MIT") .url("https://github.com/arnosthavelka/spring-advanced-training/blob/master/LICENSE"))); } }
923161f40417069f051807346657378c0acbc2e1
48,733
java
Java
modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java
winterheart/ignite
21a552a1259aff5f97930a4202efb9bde3ad1442
[ "Apache-2.0" ]
4,339
2015-08-21T21:13:25.000Z
2022-03-30T09:56:44.000Z
modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java
winterheart/ignite
21a552a1259aff5f97930a4202efb9bde3ad1442
[ "Apache-2.0" ]
1,933
2015-08-24T11:37:40.000Z
2022-03-31T08:37:08.000Z
modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java
winterheart/ignite
21a552a1259aff5f97930a4202efb9bde3ad1442
[ "Apache-2.0" ]
2,140
2015-08-21T22:09:00.000Z
2022-03-25T07:57:34.000Z
40.84912
130
0.649642
995,815
/* * 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.ignite.internal.metric; import java.lang.reflect.Field; import java.sql.Connection; import java.text.DateFormat; import java.time.LocalTime; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import javax.management.DynamicMBean; import javax.management.MBeanAttributeInfo; import javax.management.MBeanFeatureInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularDataSupport; import com.google.common.collect.Iterators; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteJdbcThinDriver; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.Ignition; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.cache.query.ContinuousQuery; import org.apache.ignite.cache.query.QueryCursor; import org.apache.ignite.cache.query.ScanQuery; import org.apache.ignite.client.IgniteClient; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.ClientConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses.TestObjectAllTypes; import org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses.TestObjectEnum; import org.apache.ignite.internal.client.thin.ProtocolVersion; import org.apache.ignite.internal.managers.systemview.walker.CachePagesListViewWalker; import org.apache.ignite.internal.metric.SystemViewSelfTest.TestPredicate; import org.apache.ignite.internal.metric.SystemViewSelfTest.TestRunnable; import org.apache.ignite.internal.metric.SystemViewSelfTest.TestTransformer; import org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.metastorage.DistributedMetaStorage; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.internal.processors.metric.impl.HistogramMetricImpl; import org.apache.ignite.internal.processors.metric.impl.MetricUtils; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcConnectionContext; import org.apache.ignite.internal.processors.service.DummyService; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.services.ServiceConfiguration; import org.apache.ignite.spi.metric.jmx.JmxMetricExporterSpi; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.GridTestUtils.RunnableX; import org.apache.ignite.transactions.Transaction; import org.junit.Test; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toSet; import static org.apache.ignite.internal.managers.systemview.ScanQuerySystemView.SCAN_QRY_SYS_VIEW; import static org.apache.ignite.internal.managers.systemview.SystemViewMBean.FILTER_OPERATION; import static org.apache.ignite.internal.managers.systemview.SystemViewMBean.VIEWS; import static org.apache.ignite.internal.metric.SystemViewSelfTest.TEST_PREDICATE; import static org.apache.ignite.internal.metric.SystemViewSelfTest.TEST_TRANSFORMER; import static org.apache.ignite.internal.processors.cache.CacheMetricsImpl.CACHE_METRICS; import static org.apache.ignite.internal.processors.cache.ClusterCachesInfo.CACHES_VIEW; import static org.apache.ignite.internal.processors.cache.ClusterCachesInfo.CACHE_GRPS_VIEW; import static org.apache.ignite.internal.processors.cache.GridCacheProcessor.CACHE_GRP_PAGE_LIST_VIEW; import static org.apache.ignite.internal.processors.cache.GridCacheUtils.cacheGroupId; import static org.apache.ignite.internal.processors.cache.GridCacheUtils.cacheId; import static org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl.BINARY_METADATA_VIEW; import static org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.METASTORE_VIEW; import static org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager.TXS_MON_LIST; import static org.apache.ignite.internal.processors.continuous.GridContinuousProcessor.CQ_SYS_VIEW; import static org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl.DISTRIBUTED_METASTORE_VIEW; import static org.apache.ignite.internal.processors.metric.GridMetricManager.CPU_LOAD; import static org.apache.ignite.internal.processors.metric.GridMetricManager.CPU_LOAD_DESCRIPTION; import static org.apache.ignite.internal.processors.metric.GridMetricManager.GC_CPU_LOAD; import static org.apache.ignite.internal.processors.metric.GridMetricManager.GC_CPU_LOAD_DESCRIPTION; import static org.apache.ignite.internal.processors.metric.GridMetricManager.IGNITE_METRICS; import static org.apache.ignite.internal.processors.metric.GridMetricManager.SYS_METRICS; import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName; import static org.apache.ignite.internal.processors.odbc.ClientListenerProcessor.CLI_CONN_VIEW; import static org.apache.ignite.internal.processors.pool.PoolProcessor.STREAM_POOL_QUEUE_VIEW; import static org.apache.ignite.internal.processors.pool.PoolProcessor.SYS_POOL_QUEUE_VIEW; import static org.apache.ignite.internal.processors.service.IgniteServiceProcessor.SVCS_VIEW; import static org.apache.ignite.internal.processors.task.GridTaskProcessor.TASKS_VIEW; import static org.apache.ignite.internal.util.IgniteUtils.toStringSafe; import static org.apache.ignite.spi.metric.jmx.MetricRegistryMBean.searchHistogram; import static org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause; import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC; import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE; import static org.apache.ignite.transactions.TransactionState.ACTIVE; /** */ public class JmxExporterSpiTest extends AbstractExporterSpiTest { /** */ private static IgniteEx ignite; /** */ private static final String REGISTRY_NAME = "test_registry"; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setDataStorageConfiguration(new DataStorageConfiguration() .setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true))); JmxMetricExporterSpi jmxSpi = new JmxMetricExporterSpi(); jmxSpi.setExportFilter(mgrp -> !mgrp.name().startsWith(FILTERED_PREFIX)); cfg.setMetricExporterSpi(jmxSpi); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { cleanPersistenceDir(); ignite = startGrid(0); ignite.cluster().active(true); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { Collection<String> caches = ignite.cacheNames(); for (String cache : caches) ignite.destroyCache(cache); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(true); cleanPersistenceDir(); } /** */ @Test public void testSysJmxMetrics() throws Exception { DynamicMBean sysMBean = metricRegistry(ignite.name(), null, SYS_METRICS); Set<String> res = stream(sysMBean.getMBeanInfo().getAttributes()) .map(MBeanFeatureInfo::getName) .collect(toSet()); assertTrue(res.contains(CPU_LOAD)); assertTrue(res.contains(GC_CPU_LOAD)); assertTrue(res.contains(metricName("memory", "heap", "init"))); assertTrue(res.contains(metricName("memory", "heap", "used"))); assertTrue(res.contains(metricName("memory", "nonheap", "committed"))); assertTrue(res.contains(metricName("memory", "nonheap", "max"))); Optional<MBeanAttributeInfo> cpuLoad = stream(sysMBean.getMBeanInfo().getAttributes()) .filter(a -> a.getName().equals(CPU_LOAD)) .findFirst(); assertTrue(cpuLoad.isPresent()); assertEquals(CPU_LOAD_DESCRIPTION, cpuLoad.get().getDescription()); Optional<MBeanAttributeInfo> gcCpuLoad = stream(sysMBean.getMBeanInfo().getAttributes()) .filter(a -> a.getName().equals(GC_CPU_LOAD)) .findFirst(); assertTrue(gcCpuLoad.isPresent()); assertEquals(GC_CPU_LOAD_DESCRIPTION, gcCpuLoad.get().getDescription()); } /** */ @Test public void testDataRegionJmxMetrics() throws Exception { DynamicMBean dataRegionMBean = metricRegistry(ignite.name(), "io", "dataregion.default"); Set<String> res = stream(dataRegionMBean.getMBeanInfo().getAttributes()) .map(MBeanFeatureInfo::getName) .collect(toSet()); assertTrue(res.containsAll(EXPECTED_ATTRIBUTES)); for (String metricName : res) assertNotNull(metricName, dataRegionMBean.getAttribute(metricName)); DataRegionConfiguration cfg = ignite.configuration().getDataStorageConfiguration().getDefaultDataRegionConfiguration(); assertEquals(cfg.getInitialSize(), dataRegionMBean.getAttribute("InitialSize")); assertEquals(cfg.getMaxSize(), dataRegionMBean.getAttribute("MaxSize")); } /** */ @Test public void testUnregisterRemovedRegistry() throws Exception { String n = "cache-for-remove"; IgniteCache c = ignite.createCache(n); DynamicMBean cacheBean = metricRegistry(ignite.name(), CACHE_METRICS, n); assertNotNull(cacheBean); ignite.destroyCache(n); assertThrowsWithCause(() -> metricRegistry(ignite.name(), CACHE_METRICS, n), IgniteException.class); } /** */ @Test public void testFilterAndExport() throws Exception { createAdditionalMetrics(ignite); assertThrowsWithCause(new RunnableX() { @Override public void runx() throws Exception { metricRegistry(ignite.name(), "filtered", "metric"); } }, IgniteException.class); DynamicMBean bean1 = metricRegistry(ignite.name(), "other", "prefix"); assertEquals(42L, bean1.getAttribute("test")); assertEquals(43L, bean1.getAttribute("test2")); DynamicMBean bean2 = metricRegistry(ignite.name(), "other", "prefix2"); assertEquals(44L, bean2.getAttribute("test3")); } /** */ @Test public void testRemoveFilteredRegistry() { String regName = MetricUtils.metricName(FILTERED_PREFIX, "registry-for-remove"); GridMetricManager mmgr = ignite.context().metric(); mmgr.registry(regName); assertTrue(Iterators.tryFind(mmgr.iterator(), mreg -> regName.equals(mreg.name())).isPresent()); assertThrowsWithCause(() -> metricRegistry(ignite.name(), null, regName), IgniteException.class); mmgr.remove(regName); assertFalse(Iterators.tryFind(mmgr.iterator(), mreg -> regName.equals(mreg.name())).isPresent()); assertThrowsWithCause(() -> metricRegistry(ignite.name(), null, regName), IgniteException.class); } /** */ @Test public void testCachesView() throws Exception { Set<String> cacheNames = new HashSet<>(Arrays.asList("cache-1", "cache-2")); for (String name : cacheNames) ignite.createCache(name); TabularDataSupport data = systemView(CACHES_VIEW); assertEquals(ignite.context().cache().cacheDescriptors().size(), data.size()); for (int i = 0; i < data.size(); i++) { CompositeData row = data.get(new Object[] {i}); cacheNames.remove(row.get("cacheName")); } assertTrue(cacheNames.toString(), cacheNames.isEmpty()); } /** */ @Test public void testCacheGroupsView() throws Exception { Set<String> grpNames = new HashSet<>(Arrays.asList("grp-1", "grp-2")); for (String grpName : grpNames) ignite.createCache(new CacheConfiguration<>("cache-" + grpName).setGroupName(grpName)); TabularDataSupport grps = systemView(CACHE_GRPS_VIEW); assertEquals(ignite.context().cache().cacheGroupDescriptors().size(), grps.size()); for (Map.Entry entry : grps.entrySet()) { CompositeData row = (CompositeData)entry.getValue(); grpNames.remove(row.get("cacheGroupName")); } assertTrue(grpNames.toString(), grpNames.isEmpty()); } /** */ @Test public void testServices() throws Exception { ServiceConfiguration srvcCfg = new ServiceConfiguration(); srvcCfg.setName("service"); srvcCfg.setMaxPerNodeCount(1); srvcCfg.setService(new DummyService()); ignite.services().deploy(srvcCfg); TabularDataSupport srvs = systemView(SVCS_VIEW); assertEquals(ignite.context().service().serviceDescriptors().size(), srvs.size()); CompositeData sysView = srvs.get(new Object[] {0}); assertEquals(srvcCfg.getName(), sysView.get("name")); assertEquals(srvcCfg.getMaxPerNodeCount(), sysView.get("maxPerNodeCount")); assertEquals(DummyService.class.getName(), sysView.get("serviceClass")); } /** */ @Test public void testComputeBroadcast() throws Exception { CyclicBarrier barrier = new CyclicBarrier(6); for (int i = 0; i < 5; i++) { ignite.compute().broadcastAsync(() -> { try { barrier.await(); barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } }); } barrier.await(); TabularDataSupport tasks = systemView(TASKS_VIEW); assertEquals(5, tasks.size()); CompositeData t = tasks.get(new Object[] {0}); assertFalse((Boolean)t.get("internal")); assertNull(t.get("affinityCacheName")); assertEquals(-1, t.get("affinityPartitionId")); assertTrue(t.get("taskClassName").toString().startsWith(getClass().getName())); assertTrue(t.get("taskName").toString().startsWith(getClass().getName())); assertEquals(ignite.localNode().id().toString(), t.get("taskNodeId")); assertEquals("0", t.get("userVersion")); barrier.await(); } /** */ @Test public void testClientsConnections() throws Exception { String host = ignite.configuration().getClientConnectorConfiguration().getHost(); if (host == null) host = ignite.configuration().getLocalHost(); int port = ignite.configuration().getClientConnectorConfiguration().getPort(); try (IgniteClient client = Ignition.startClient(new ClientConfiguration().setAddresses(host + ":" + port))) { try (Connection conn = new IgniteJdbcThinDriver().connect("jdbc:ignite:thin://" + host, new Properties())) { TabularDataSupport conns = systemView(CLI_CONN_VIEW); Consumer<CompositeData> checkThin = c -> { assertEquals("THIN", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), ProtocolVersion.LATEST_VER.toString()); }; Consumer<CompositeData> checkJdbc = c -> { assertEquals("JDBC", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), JdbcConnectionContext.CURRENT_VER.asString()); }; CompositeData c0 = conns.get(new Object[] {0}); CompositeData c1 = conns.get(new Object[] {1}); if (c0.get("type").equals("JDBC")) { checkJdbc.accept(c0); checkThin.accept(c1); } else { checkJdbc.accept(c1); checkThin.accept(c0); } assertEquals(2, conns.size()); } } boolean res = GridTestUtils.waitForCondition(() -> systemView(CLI_CONN_VIEW).isEmpty(), 5_000); assertTrue(res); } /** */ @Test public void testContinuousQuery() throws Exception { try (IgniteEx remoteNode = startGrid(1)) { IgniteCache<Integer, Integer> cache = ignite.createCache("cache-1"); assertEquals(0, systemView(CQ_SYS_VIEW).size()); assertEquals(0, systemView(remoteNode, CQ_SYS_VIEW).size()); try (QueryCursor qry = cache.query(new ContinuousQuery<>() .setInitialQuery(new ScanQuery<>()) .setPageSize(100) .setTimeInterval(1000) .setLocalListener(evts -> { // No-op. }) .setRemoteFilterFactory(() -> evt -> true) )) { for (int i = 0; i < 100; i++) cache.put(i, i); checkContinuousQueryView(ignite, ignite); checkContinuousQueryView(ignite, remoteNode); } assertEquals(0, systemView(CQ_SYS_VIEW).size()); assertTrue(waitForCondition(() -> systemView(remoteNode, CQ_SYS_VIEW).isEmpty(), getTestTimeout())); } } /** */ private void checkContinuousQueryView(IgniteEx origNode, IgniteEx checkNode) { TabularDataSupport qrys = systemView(checkNode, CQ_SYS_VIEW); assertEquals(1, qrys.size()); for (int i = 0; i < qrys.size(); i++) { CompositeData cq = qrys.get(new Object[] {i}); assertEquals("cache-1", cq.get("cacheName")); assertEquals(100, cq.get("bufferSize")); assertEquals(1000L, cq.get("interval")); assertEquals(origNode.localNode().id().toString(), cq.get("nodeId")); if (origNode.localNode().id().equals(checkNode.localNode().id())) assertTrue(cq.get("localListener").toString().startsWith(getClass().getName())); else assertNull(cq.get("localListener")); assertTrue(cq.get("remoteFilter").toString().startsWith(getClass().getName())); assertNull(cq.get("localTransformedListener")); assertNull(cq.get("remoteTransformer")); } } /** */ public TabularDataSupport systemView(String name) { return systemView(ignite, name); } /** */ public TabularDataSupport systemView(IgniteEx g, String name) { try { DynamicMBean caches = metricRegistry(g.name(), VIEWS, name); MBeanAttributeInfo[] attrs = caches.getMBeanInfo().getAttributes(); assertEquals(1, attrs.length); return (TabularDataSupport)caches.getAttribute(VIEWS); } catch (Exception e) { throw new RuntimeException(e); } } /** */ public TabularDataSupport filteredSystemView(IgniteEx g, String name, Map<String, Object> filter) { try { DynamicMBean mbean = metricRegistry(g.name(), VIEWS, name); MBeanOperationInfo[] opers = mbean.getMBeanInfo().getOperations(); assertEquals(1, opers.length); assertEquals(FILTER_OPERATION, opers[0].getName()); MBeanParameterInfo[] paramInfo = opers[0].getSignature(); Object params[] = new Object[paramInfo.length]; String signature[] = new String[paramInfo.length]; for (int i = 0; i < paramInfo.length; i++) { params[i] = filter.get(paramInfo[i].getName()); signature[i] = paramInfo[i].getType(); } return (TabularDataSupport)mbean.invoke(FILTER_OPERATION, params, signature); } catch (Exception e) { throw new RuntimeException(e); } } /** */ @Test public void testHistogramSearchByName() throws Exception { MetricRegistry mreg = new MetricRegistry("test", name -> null, name -> null, null); createTestHistogram(mreg); assertEquals(Long.valueOf(1), searchHistogram("histogram_0_50", mreg)); assertEquals(Long.valueOf(2), searchHistogram("histogram_50_500", mreg)); assertEquals(Long.valueOf(3), searchHistogram("histogram_500_inf", mreg)); assertEquals(Long.valueOf(1), searchHistogram("histogram_with_underscore_0_50", mreg)); assertEquals(Long.valueOf(2), searchHistogram("histogram_with_underscore_50_500", mreg)); assertEquals(Long.valueOf(3), searchHistogram("histogram_with_underscore_500_inf", mreg)); assertNull(searchHistogram("unknown", mreg)); assertNull(searchHistogram("unknown_0", mreg)); assertNull(searchHistogram("unknown_0_50", mreg)); assertNull(searchHistogram("unknown_test", mreg)); assertNull(searchHistogram("unknown_test_test", mreg)); assertNull(searchHistogram("unknown_0_inf", mreg)); assertNull(searchHistogram("histogram", mreg)); assertNull(searchHistogram("histogram_0", mreg)); assertNull(searchHistogram("histogram_0_100", mreg)); assertNull(searchHistogram("histogram_0_inf", mreg)); assertNull(searchHistogram("histogram_0_500", mreg)); assertNull(searchHistogram("histogram_with_underscore", mreg)); assertNull(searchHistogram("histogram_with_underscore_0", mreg)); assertNull(searchHistogram("histogram_with_underscore_0_100", mreg)); assertNull(searchHistogram("histogram_with_underscore_0_inf", mreg)); assertNull(searchHistogram("histogram_with_underscore_0_500", mreg)); } /** */ @Test public void testHistogramExport() throws Exception { MetricRegistry mreg = ignite.context().metric().registry("histogramTest"); createTestHistogram(mreg); DynamicMBean bean = metricRegistry(ignite.name(), null, "histogramTest"); MBeanAttributeInfo[] attrs = bean.getMBeanInfo().getAttributes(); assertEquals(6, attrs.length); assertEquals(1L, bean.getAttribute("histogram_0_50")); assertEquals(2L, bean.getAttribute("histogram_50_500")); assertEquals(3L, bean.getAttribute("histogram_500_inf")); assertEquals(1L, bean.getAttribute("histogram_with_underscore_0_50")); assertEquals(2L, bean.getAttribute("histogram_with_underscore_50_500")); assertEquals(3L, bean.getAttribute("histogram_with_underscore_500_inf")); } /** */ @Test public void testJmxHistogramNamesExport() throws Exception { MetricRegistry reg = ignite.context().metric().registry(REGISTRY_NAME); String simpleName = "testhist"; String nameWithUnderscore = "test_hist"; reg.histogram(simpleName, new long[] {10, 100}, null); reg.histogram(nameWithUnderscore, new long[] {10, 100}, null); DynamicMBean mbn = metricRegistry(ignite.name(), null, REGISTRY_NAME); assertNotNull(mbn.getAttribute(simpleName + '_' + 0 + '_' + 10)); assertEquals(0L, mbn.getAttribute(simpleName + '_' + 0 + '_' + 10)); assertNotNull(mbn.getAttribute(simpleName + '_' + 10 + '_' + 100)); assertEquals(0L, mbn.getAttribute(simpleName + '_' + 10 + '_' + 100)); assertNotNull(mbn.getAttribute(nameWithUnderscore + '_' + 10 + '_' + 100)); assertEquals(0L, mbn.getAttribute(nameWithUnderscore + '_' + 10 + '_' + 100)); assertNotNull(mbn.getAttribute(simpleName + '_' + 100 + "_inf")); assertEquals(0L, mbn.getAttribute(simpleName + '_' + 100 + "_inf")); } /** */ @Test public void testTransactions() throws Exception { IgniteCache<Integer, Integer> cache = ignite.createCache(new CacheConfiguration<Integer, Integer>("c") .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)); assertEquals(0, systemView(TXS_MON_LIST).size()); CountDownLatch latch = new CountDownLatch(1); try { AtomicInteger cntr = new AtomicInteger(); GridTestUtils.runMultiThreadedAsync(() -> { try (Transaction tx = ignite.transactions().withLabel("test").txStart(PESSIMISTIC, REPEATABLE_READ)) { cache.put(cntr.incrementAndGet(), cntr.incrementAndGet()); cache.put(cntr.incrementAndGet(), cntr.incrementAndGet()); latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } }, 5, "xxx"); boolean res = waitForCondition(() -> systemView(TXS_MON_LIST).size() == 5, 10_000L); assertTrue(res); CompositeData txv = systemView(TXS_MON_LIST).get(new Object[] {0}); assertEquals(ignite.localNode().id().toString(), txv.get("localNodeId")); assertEquals(REPEATABLE_READ.name(), txv.get("isolation")); assertEquals(PESSIMISTIC.name(), txv.get("concurrency")); assertEquals(ACTIVE.name(), txv.get("state")); assertNotNull(txv.get("xid")); assertFalse((boolean)txv.get("system")); assertFalse((boolean)txv.get("implicit")); assertFalse((boolean)txv.get("implicitSingle")); assertTrue((boolean)txv.get("near")); assertFalse((boolean)txv.get("dht")); assertTrue((boolean)txv.get("colocated")); assertTrue((boolean)txv.get("local")); assertEquals("test", txv.get("label")); assertFalse((boolean)txv.get("onePhaseCommit")); assertFalse((boolean)txv.get("internal")); assertEquals(0L, txv.get("timeout")); assertTrue(((long)txv.get("startTime")) <= System.currentTimeMillis()); //Only pessimistic transactions are supported when MVCC is enabled. if (Objects.equals(System.getProperty(IgniteSystemProperties.IGNITE_FORCE_MVCC_MODE_IN_TESTS), "true")) return; GridTestUtils.runMultiThreadedAsync(() -> { try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, SERIALIZABLE)) { cache.put(cntr.incrementAndGet(), cntr.incrementAndGet()); cache.put(cntr.incrementAndGet(), cntr.incrementAndGet()); latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } }, 5, "xxx"); res = waitForCondition(() -> systemView(TXS_MON_LIST).size() == 10, 10_000L); assertTrue(res); for (int i = 0; i < 9; i++) { txv = systemView(TXS_MON_LIST).get(new Object[] {i}); if (PESSIMISTIC.name().equals(txv.get("concurrency"))) continue; assertEquals(ignite.localNode().id().toString(), txv.get("localNodeId")); assertEquals(SERIALIZABLE.name(), txv.get("isolation")); assertEquals(OPTIMISTIC.name(), txv.get("concurrency")); assertEquals(ACTIVE.name(), txv.get("state")); assertNotNull(txv.get("xid")); assertFalse((boolean)txv.get("system")); assertFalse((boolean)txv.get("implicit")); assertFalse((boolean)txv.get("implicitSingle")); assertTrue((boolean)txv.get("near")); assertFalse((boolean)txv.get("dht")); assertTrue((boolean)txv.get("colocated")); assertTrue((boolean)txv.get("local")); assertNull(txv.get("label")); assertFalse((boolean)txv.get("onePhaseCommit")); assertFalse((boolean)txv.get("internal")); assertEquals(0L, txv.get("timeout")); assertTrue(((long)txv.get("startTime")) <= System.currentTimeMillis()); } } finally { latch.countDown(); } boolean res = waitForCondition(() -> systemView(TXS_MON_LIST).isEmpty(), 10_000L); assertTrue(res); } /** */ @Test public void testLocalScanQuery() throws Exception { IgniteCache<Integer, Integer> cache1 = ignite.createCache( new CacheConfiguration<Integer, Integer>("cache1") .setGroupName("group1")); int part = ignite.affinity("cache1").primaryPartitions(ignite.localNode())[0]; List<Integer> partKeys = partitionKeys(cache1, part, 11, 0); for (Integer key : partKeys) cache1.put(key, key); TabularDataSupport qrySysView0 = systemView(SCAN_QRY_SYS_VIEW); assertNotNull(qrySysView0); assertEquals(0, qrySysView0.size()); QueryCursor<Integer> qryRes1 = cache1.query( new ScanQuery<Integer, Integer>() .setFilter(new TestPredicate()) .setLocal(true) .setPartition(part) .setPageSize(10), new TestTransformer()); assertTrue(qryRes1.iterator().hasNext()); boolean res = waitForCondition(() -> !systemView(SCAN_QRY_SYS_VIEW).isEmpty(), 5_000); assertTrue(res); CompositeData view = systemView(SCAN_QRY_SYS_VIEW).get(new Object[] {0}); assertEquals(ignite.localNode().id().toString(), view.get("originNodeId")); assertEquals(0L, view.get("queryId")); assertEquals("cache1", view.get("cacheName")); assertEquals(cacheId("cache1"), view.get("cacheId")); assertEquals(cacheGroupId("cache1", "group1"), view.get("cacheGroupId")); assertEquals("group1", view.get("cacheGroupName")); assertTrue((Long)view.get("startTime") <= System.currentTimeMillis()); assertTrue((Long)view.get("duration") >= 0); assertFalse((Boolean)view.get("canceled")); assertEquals(TEST_PREDICATE, view.get("filter")); assertTrue((Boolean)view.get("local")); assertEquals(part, view.get("partition")); assertEquals(toStringSafe(ignite.context().discovery().topologyVersionEx()), view.get("topology")); assertEquals(TEST_TRANSFORMER, view.get("transformer")); assertFalse((Boolean)view.get("keepBinary")); assertNull(view.get("subjectId")); assertNull(view.get("taskName")); qryRes1.close(); res = waitForCondition(() -> systemView(SCAN_QRY_SYS_VIEW).isEmpty(), 5_000); assertTrue(res); } /** */ @Test public void testScanQuery() throws Exception { try (IgniteEx client1 = startClientGrid("client-1"); IgniteEx client2 = startClientGrid("client-2")) { IgniteCache<Integer, Integer> cache1 = client1.createCache( new CacheConfiguration<Integer, Integer>("cache1") .setGroupName("group1")); IgniteCache<Integer, Integer> cache2 = client2.createCache("cache2"); awaitPartitionMapExchange(); for (int i = 0; i < 100; i++) { cache1.put(i, i); cache2.put(i, i); } TabularDataSupport qrySysView0 = systemView(ignite, SCAN_QRY_SYS_VIEW); assertNotNull(qrySysView0); assertEquals(0, qrySysView0.size()); QueryCursor<Integer> qryRes1 = cache1.query( new ScanQuery<Integer, Integer>() .setFilter(new TestPredicate()) .setPageSize(10), new TestTransformer()); QueryCursor<?> qryRes2 = cache2.withKeepBinary().query(new ScanQuery<>() .setPageSize(20)); assertTrue(qryRes1.iterator().hasNext()); assertTrue(qryRes2.iterator().hasNext()); checkScanQueryView(client1, client2, ignite); qryRes1.close(); qryRes2.close(); boolean res = waitForCondition(() -> systemView(ignite, SCAN_QRY_SYS_VIEW).isEmpty(), 5_000); assertTrue(res); } } /** @throws Exception If failed. */ @Test public void testIgniteKernal() throws Exception { DynamicMBean mbn = metricRegistry(ignite.name(), null, IGNITE_METRICS); assertNotNull(mbn); assertEquals(36, mbn.getMBeanInfo().getAttributes().length); assertFalse(stream(mbn.getMBeanInfo().getAttributes()).anyMatch(a -> F.isEmpty(a.getDescription()))); assertFalse(F.isEmpty((String)mbn.getAttribute("fullVersion"))); assertFalse(F.isEmpty((String)mbn.getAttribute("copyright"))); assertFalse(F.isEmpty((String)mbn.getAttribute("osInformation"))); assertFalse(F.isEmpty((String)mbn.getAttribute("jdkInformation"))); assertFalse(F.isEmpty((String)mbn.getAttribute("vmName"))); assertFalse(F.isEmpty((String)mbn.getAttribute("discoverySpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("communicationSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("deploymentSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("checkpointSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("collisionSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("eventStorageSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("failoverSpiFormatted"))); assertFalse(F.isEmpty((String)mbn.getAttribute("loadBalancingSpiFormatted"))); assertEquals(System.getProperty("user.name"), (String)mbn.getAttribute("osUser")); assertNotNull(DateFormat.getDateTimeInstance().parse((String)mbn.getAttribute("startTimestampFormatted"))); assertNotNull(LocalTime.parse((String)mbn.getAttribute("uptimeFormatted"))); assertTrue((boolean)mbn.getAttribute("isRebalanceEnabled")); assertTrue((boolean)mbn.getAttribute("isNodeInBaseline")); assertTrue((boolean)mbn.getAttribute("active")); assertTrue((long)mbn.getAttribute("startTimestamp") > 0); assertTrue((long)mbn.getAttribute("uptime") > 0); assertEquals(ignite.name(), (String)mbn.getAttribute("instanceName")); assertEquals(Collections.emptyList(), mbn.getAttribute("userAttributesFormatted")); assertEquals(Collections.emptyList(), mbn.getAttribute("lifecycleBeansFormatted")); assertEquals(Collections.emptyMap(), mbn.getAttribute("longJVMPauseLastEvents")); assertEquals(0L, mbn.getAttribute("longJVMPausesCount")); assertEquals(0L, mbn.getAttribute("longJVMPausesTotalDuration")); long clusterStateChangeTime = (long)mbn.getAttribute("lastClusterStateChangeTime"); assertTrue(0 < clusterStateChangeTime && clusterStateChangeTime < System.currentTimeMillis()); assertEquals(String.valueOf(ignite.configuration().getPublicThreadPoolSize()), mbn.getAttribute("executorServiceFormatted")); assertEquals(ignite.configuration().isPeerClassLoadingEnabled(), mbn.getAttribute("isPeerClassLoadingEnabled")); assertTrue(((String)mbn.getAttribute("currentCoordinatorFormatted")) .contains(ignite.localNode().id().toString())); assertEquals(ignite.configuration().getIgniteHome(), (String)mbn.getAttribute("igniteHome")); assertEquals(ignite.localNode().id(), mbn.getAttribute("localNodeId")); assertEquals(ignite.configuration().getGridLogger().toString(), (String)mbn.getAttribute("gridLoggerFormatted")); assertEquals(ignite.configuration().getMBeanServer().toString(), (String)mbn.getAttribute("mBeanServerFormatted")); assertEquals(ClusterState.ACTIVE.toString(), mbn.getAttribute("clusterState")); } /** */ private void checkScanQueryView(IgniteEx client1, IgniteEx client2, IgniteEx server) throws Exception { boolean res = waitForCondition(() -> systemView(server, SCAN_QRY_SYS_VIEW).size() > 1, 5_000); assertTrue(res); Consumer<CompositeData> cache1checker = view -> { assertEquals(client1.localNode().id().toString(), view.get("originNodeId")); assertTrue((Long)view.get("queryId") != 0); assertEquals("cache1", view.get("cacheName")); assertEquals(cacheId("cache1"), view.get("cacheId")); assertEquals(cacheGroupId("cache1", "group1"), view.get("cacheGroupId")); assertEquals("group1", view.get("cacheGroupName")); assertTrue((Long)view.get("startTime") <= System.currentTimeMillis()); assertTrue((Long)view.get("duration") >= 0); assertFalse((Boolean)view.get("canceled")); assertEquals(TEST_PREDICATE, view.get("filter")); assertFalse((Boolean)view.get("local")); assertEquals(-1, view.get("partition")); assertEquals(toStringSafe(client1.context().discovery().topologyVersionEx()), view.get("topology")); assertEquals(TEST_TRANSFORMER, view.get("transformer")); assertFalse((Boolean)view.get("keepBinary")); assertNull(view.get("subjectId")); assertNull(view.get("taskName")); assertEquals(10, view.get("pageSize")); }; Consumer<CompositeData> cache2checker = view -> { assertEquals(client2.localNode().id().toString(), view.get("originNodeId")); assertTrue((Long)view.get("queryId") != 0); assertEquals("cache2", view.get("cacheName")); assertEquals(cacheId("cache2"), view.get("cacheId")); assertEquals(cacheGroupId("cache2", null), view.get("cacheGroupId")); assertEquals("cache2", view.get("cacheGroupName")); assertTrue((Long)view.get("startTime") <= System.currentTimeMillis()); assertTrue((Long)view.get("duration") >= 0); assertFalse((Boolean)view.get("canceled")); assertNull(view.get("filter")); assertFalse((Boolean)view.get("local")); assertEquals(-1, view.get("partition")); assertEquals(toStringSafe(client2.context().discovery().topologyVersionEx()), view.get("topology")); assertNull(view.get("transformer")); assertTrue((Boolean)view.get("keepBinary")); assertNull(view.get("subjectId")); assertNull(view.get("taskName")); assertEquals(20, view.get("pageSize")); }; boolean found1 = false; boolean found2 = false; TabularDataSupport qrySysView = systemView(server, SCAN_QRY_SYS_VIEW); for (int i = 0; i < qrySysView.size(); i++) { CompositeData view = systemView(SCAN_QRY_SYS_VIEW).get(new Object[] {i}); if ("cache2".equals(view.get("cacheName"))) { cache2checker.accept(view); found1 = true; } else { cache1checker.accept(view); found2 = true; } } assertTrue(found1 && found2); } /** */ @Test public void testSysStripedExecutor() throws Exception { checkStripeExecutorView(ignite.context().pools().getStripedExecutorService(), SYS_POOL_QUEUE_VIEW, "sys"); } /** */ @Test public void testStreamerStripedExecutor() throws Exception { checkStripeExecutorView(ignite.context().pools().getDataStreamerExecutorService(), STREAM_POOL_QUEUE_VIEW, "data-streamer"); } /** * Checks striped executor system view. * * @param execSvc Striped executor. * @param viewName System view. * @param poolName Executor name. */ private void checkStripeExecutorView(StripedExecutor execSvc, String viewName, String poolName) throws Exception { CountDownLatch latch = new CountDownLatch(1); execSvc.execute(0, new TestRunnable(latch, 0)); execSvc.execute(0, new TestRunnable(latch, 1)); execSvc.execute(1, new TestRunnable(latch, 2)); execSvc.execute(1, new TestRunnable(latch, 3)); try { boolean res = waitForCondition(() -> systemView(viewName).size() == 2, 5_000); assertTrue(res); TabularDataSupport view = systemView(viewName); CompositeData row0 = view.get(new Object[] {0}); assertEquals(0, row0.get("stripeIndex")); assertEquals(TestRunnable.class.getSimpleName() + '1', row0.get("description")); assertEquals(poolName + "-stripe-0", row0.get("threadName")); assertEquals(TestRunnable.class.getName(), row0.get("taskName")); CompositeData row1 = view.get(new Object[] {1}); assertEquals(1, row1.get("stripeIndex")); assertEquals(TestRunnable.class.getSimpleName() + '3', row1.get("description")); assertEquals(poolName + "-stripe-1", row1.get("threadName")); assertEquals(TestRunnable.class.getName(), row1.get("taskName")); } finally { latch.countDown(); } } /** */ @Test public void testPagesList() throws Exception { String cacheName = "cacheFL"; IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(new CacheConfiguration<Integer, Integer>() .setName(cacheName).setAffinity(new RendezvousAffinityFunction().setPartitions(2))); // Put some data to cache to init cache partitions. for (int i = 0; i < 10; i++) cache.put(i, i); TabularDataSupport view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, U.map( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId(cacheName), CachePagesListViewWalker.PARTITION_ID_FILTER, 0, CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 )); assertEquals(1, view.size()); view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, U.map( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId(cacheName), CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 )); assertEquals(2, view.size()); } /** */ @Test public void testBinaryMeta() { IgniteCache<Integer, TestObjectAllTypes> c1 = ignite.createCache("test-all-types-cache"); IgniteCache<Integer, TestObjectEnum> c2 = ignite.createCache("test-enum-cache"); c1.put(1, new TestObjectAllTypes()); c2.put(1, TestObjectEnum.A); TabularDataSupport view = systemView(BINARY_METADATA_VIEW); assertNotNull(view); assertEquals(2, view.size()); for (int i = 0; i < 2; i++) { CompositeData meta = view.get(new Object[] {i}); if (Objects.equals(TestObjectEnum.class.getName(), meta.get("typeName"))) { assertTrue((Boolean)meta.get("isEnum")); assertEquals(0, meta.get("fieldsCount")); } else { assertFalse((Boolean)meta.get("isEnum")); Field[] fields = TestObjectAllTypes.class.getDeclaredFields(); assertEquals(fields.length, meta.get("fieldsCount")); for (Field field : fields) assertTrue(meta.get("fields").toString().contains(field.getName())); } } } /** */ @Test public void testMetastorage() throws Exception { IgniteCacheDatabaseSharedManager db = ignite.context().cache().context().database(); String name = "test-key"; String val = "test-value"; String unmarshalledName = "unmarshalled-key"; String unmarshalledVal = "[Raw data. 0 bytes]"; db.checkpointReadLock(); try { db.metaStorage().write(name, val); db.metaStorage().writeRaw(unmarshalledName, new byte[0]); } finally { db.checkpointReadUnlock(); } TabularDataSupport view = systemView(METASTORE_VIEW); boolean found = false; boolean foundUnmarshalled = false; for (int i = 0; i < view.size(); i++) { CompositeData row = view.get(new Object[] {i}); if (row.get("name").equals(name) && val.equals(row.get("value"))) found = true; else if (row.get("name").equals(unmarshalledName) && row.get("value").equals(unmarshalledVal)) foundUnmarshalled = true; } assertTrue(found && foundUnmarshalled); } /** */ @Test public void testDistributedMetastorage() throws Exception { try (IgniteEx ignite1 = startGrid(1)) { DistributedMetaStorage dms = ignite.context().distributedMetastorage(); String name = "test-distributed-key"; String val = "test-distributed-value"; dms.write(name, val); TabularDataSupport view = systemView(DISTRIBUTED_METASTORE_VIEW); boolean found = false; for (int i = 0; i < view.size(); i++) { CompositeData row = view.get(new Object[] {i}); if (row.get("name").equals(name) && row.get("value").equals(val)) { found = true; break; } } assertTrue(found); assertTrue(waitForCondition(() -> { TabularDataSupport view1 = systemView(ignite1, DISTRIBUTED_METASTORE_VIEW); for (int i = 0; i < view1.size(); i++) { CompositeData row = view1.get(new Object[] {i}); if (row.get("name").equals(name) && row.get("value").equals(val)) return true; } return false; }, getTestTimeout())); } } /** */ private void createTestHistogram(MetricRegistry mreg) { long[] bounds = new long[] {50, 500}; HistogramMetricImpl histogram = mreg.histogram("histogram", bounds, null); histogram.value(10); histogram.value(51); histogram.value(60); histogram.value(600); histogram.value(600); histogram.value(600); histogram = mreg.histogram("histogram_with_underscore", bounds, null); histogram.value(10); histogram.value(51); histogram.value(60); histogram.value(600); histogram.value(600); histogram.value(600); } }
9231629124be0b7ba05f52829da8910de540e053
1,970
java
Java
src/main/java/com/esgov/jrw/jrwservice/service/authority/impl/PrivilegeServiceImpl.java
cby883/mygit
82031fa115d11d1977b5f0f47fa1c91911023ed1
[ "MIT" ]
null
null
null
src/main/java/com/esgov/jrw/jrwservice/service/authority/impl/PrivilegeServiceImpl.java
cby883/mygit
82031fa115d11d1977b5f0f47fa1c91911023ed1
[ "MIT" ]
null
null
null
src/main/java/com/esgov/jrw/jrwservice/service/authority/impl/PrivilegeServiceImpl.java
cby883/mygit
82031fa115d11d1977b5f0f47fa1c91911023ed1
[ "MIT" ]
null
null
null
33.965517
88
0.637056
995,816
package com.esgov.jrw.jrwservice.service.authority.impl; import com.esgov.jrw.jrwservice.common.dto.enums.ResponseCode; import com.esgov.jrw.jrwservice.common.dto.Menu; import com.esgov.jrw.jrwservice.common.dto.ServiceResponse; import com.esgov.jrw.jrwservice.dao.authority.SysMenuDao; import com.esgov.jrw.jrwservice.entity.authority.SysMenu; import com.esgov.jrw.jrwservice.service.authority.PrivilegeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; /** * Created by HZX on 2018/4/2. */ @Service public class PrivilegeServiceImpl implements PrivilegeService { @Autowired SysMenuDao sysMenuDao; @Override public ServiceResponse getMenuPrivileges(HashMap<String, String> paramMap) { Integer level = Integer.parseInt(paramMap.get("level")); Menu menu = formMenuPrivilege(paramMap.get("menuId"),level); return ServiceResponse.createByResponseCodeData(ResponseCode.GET_SUCCESS, menu); } /** * 构建菜单权限信息 * @param menuId * @param level * @return */ private Menu formMenuPrivilege(String menuId,int level) { Menu menu = null; SysMenu sysMenu = sysMenuDao.selectById(menuId); //先判断是否有访问此菜单的权限 if( (null!=sysMenu) && (sysMenu.getIsUsed().equals("1"))){ menu = Menu.transformer(sysMenuDao.selectById(menuId)); //菜单层级大于0 if(level > 0){ List<SysMenu> sysSubs = sysMenuDao.getMenuListByParentId(menuId); if(null!=sysSubs && !sysSubs.isEmpty()){ for(SysMenu sysSub: sysSubs){ Menu sub = formMenuPrivilege(sysSub.getId(),level-1); if(null!=sub){ menu.addSub(sub); } } } } } return menu; } }
9231635b52dc60758dd670b659ab65aa5c966af6
2,101
java
Java
Android/app/src/main/java/com/example/hermes/Delivery.java
DIT113-V22/group-10
926a7a11dd3c576890653443b488a07cbf8aaa85
[ "MIT" ]
null
null
null
Android/app/src/main/java/com/example/hermes/Delivery.java
DIT113-V22/group-10
926a7a11dd3c576890653443b488a07cbf8aaa85
[ "MIT" ]
16
2022-03-28T08:28:51.000Z
2022-03-31T13:58:05.000Z
Android/app/src/main/java/com/example/hermes/Delivery.java
DIT113-V22/group-10
926a7a11dd3c576890653443b488a07cbf8aaa85
[ "MIT" ]
null
null
null
25.621951
123
0.647311
995,817
package com.example.hermes; import android.os.Build; import androidx.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.Locale; public class Delivery { private Date date; private boolean isReady; private boolean isDone; private ArrayList<String> items; public Delivery(){ Date date = new Date(); this.date = date; this.isReady = false; this.isDone = false; this.items= new ArrayList<>(); } public String getDate(){ String[] split = date.toString().split(" "); return split[5] + " " + split[1] + " " + split[2]; } public String getFormatedDate(){ DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA); return dateFormat.format(this.date); } public void setDate(String yyyymmdd_hhmmss) throws ParseException { date = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).parse(yyyymmdd_hhmmss); } public void addItem(String ItemName){ items.add(ItemName); } public ArrayList <String> getItems(){ return items; } public boolean getReady() { return isReady; } public void setReady(boolean value) { this.isReady = value; } public boolean getDone() { return this.isDone; } public void setItems(ArrayList<String> items){ this.items = items; } public void setDone(boolean value) { this.isDone = value; } public String itemList(){ String result = ""; for(String item : items){ result += item + ", "; } return result; } @NonNull @Override public String toString(){ return this.date.toString(); } public static final Comparator<Delivery> byOldest = Comparator.comparing(delivery -> delivery.date); public static final Comparator<Delivery> byNewest = (delivery1, delivery2) -> delivery2.date.compareTo(delivery1.date); }
9231645efaead8732e959ebf550dfdde23e2204b
10,490
java
Java
extra/eclipse.jdt.ls/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/OrganizeImportsHandler.java
LoricAndre/dots
004d4e632e0eca1e6f5a4426dc92a2ba22a6dad0
[ "CC-BY-4.0" ]
null
null
null
extra/eclipse.jdt.ls/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/OrganizeImportsHandler.java
LoricAndre/dots
004d4e632e0eca1e6f5a4426dc92a2ba22a6dad0
[ "CC-BY-4.0" ]
null
null
null
extra/eclipse.jdt.ls/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/OrganizeImportsHandler.java
LoricAndre/dots
004d4e632e0eca1e6f5a4426dc92a2ba22a6dad0
[ "CC-BY-4.0" ]
null
null
null
43.526971
222
0.723451
995,818
/******************************************************************************* * Copyright (c) 2019-2020 Microsoft Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Microsoft Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ls.core.internal.handlers; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.manipulation.CodeStyleConfiguration; import org.eclipse.jdt.core.manipulation.CoreASTProvider; import org.eclipse.jdt.core.manipulation.ImportReferencesCollector; import org.eclipse.jdt.core.manipulation.OrganizeImportsOperation; import org.eclipse.jdt.core.search.TypeNameMatch; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ls.core.internal.JDTUtils; import org.eclipse.jdt.ls.core.internal.JSONUtility; import org.eclipse.jdt.ls.core.internal.JavaClientConnection; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.JobHelpers; import org.eclipse.jdt.ls.core.internal.corrections.SimilarElementsRequestor; import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; import org.eclipse.jdt.ls.core.internal.text.correction.SourceAssistProcessor; import org.eclipse.lsp4j.CodeActionParams; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.WorkspaceEdit; import org.eclipse.text.edits.DeleteEdit; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import com.google.gson.Gson; public final class OrganizeImportsHandler { public static final String CLIENT_COMMAND_ID_CHOOSEIMPORTS = "java.action.organizeImports.chooseImports"; // For test purpose public static TextEdit organizeImports(ICompilationUnit unit, Function<ImportSelection[], ImportCandidate[]> chooseImports) { return organizeImports(unit, chooseImports, new NullProgressMonitor()); } public static TextEdit organizeImports(ICompilationUnit unit, Function<ImportSelection[], ImportCandidate[]> chooseImports, IProgressMonitor monitor) { if (unit == null) { return null; } CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor); if (astRoot == null) { return null; } OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, (TypeNameMatch[][] openChoices, ISourceRange[] ranges) -> { List<ImportSelection> selections = new ArrayList<>(); for (int i = 0; i < openChoices.length; i++) { ImportCandidate[] candidates = Stream.of(openChoices[i]).map((choice) -> new ImportCandidate(choice)).toArray(ImportCandidate[]::new); Range range = null; try { range = JDTUtils.toRange(unit, ranges[i].getOffset(), ranges[i].getLength()); } catch (JavaModelException e) { range = JDTUtils.newRange(); } // TODO Sort the ambiguous candidates based on a relevance score. selections.add(new ImportSelection(candidates, range)); } ImportCandidate[] chosens = chooseImports.apply(selections.toArray(new ImportSelection[0])); if (chosens == null) { return null; } Map<String, TypeNameMatch> typeMaps = new HashMap<>(); Stream.of(openChoices).flatMap(x -> Arrays.stream(x)).forEach(x -> { typeMaps.put(x.getFullyQualifiedName() + "@" + x.hashCode(), x); }); return Stream.of(chosens).filter(chosen -> chosen != null && typeMaps.containsKey(chosen.id)).map(chosen -> typeMaps.get(chosen.id)).toArray(TypeNameMatch[]::new); }); try { JobHelpers.waitForJobs(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor); TextEdit edit = op.createTextEdit(null); // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283287 // and https://github.com/redhat-developer/vscode-java/issues/1472 TextEdit staticEdit = wrapStaticImports(edit, astRoot, unit); if (staticEdit.getChildrenSize() == 0) { return null; } return staticEdit; } catch (OperationCanceledException | CoreException e) { JavaLanguageServerPlugin.logException("Failed to resolve organize imports source action", e); } return null; } public static TextEdit wrapStaticImports(TextEdit edit, CompilationUnit root, ICompilationUnit unit) throws MalformedTreeException, CoreException { String[] favourites = PreferenceManager.getPrefs(unit.getResource()).getJavaCompletionFavoriteMembers(); if (favourites.length == 0) { return edit; } IJavaProject project = unit.getJavaProject(); if (JavaModelUtil.is50OrHigher(project)) { List<SimpleName> typeReferences = new ArrayList<>(); List<SimpleName> staticReferences = new ArrayList<>(); ImportReferencesCollector.collect(root, project, null, typeReferences, staticReferences); if (staticReferences.isEmpty()) { return edit; } ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(root, true); AST ast = root.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); for (SimpleName node : staticReferences) { addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, true); addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, false); } TextEdit staticEdit = importRewrite.rewriteImports(null); if (staticEdit != null && staticEdit.getChildrenSize() > 0) { TextEdit lastStatic = staticEdit.getChildren()[staticEdit.getChildrenSize() - 1]; if (lastStatic instanceof DeleteEdit) { if (edit.getChildrenSize() > 0) { TextEdit last = edit.getChildren()[edit.getChildrenSize() - 1]; if (last instanceof DeleteEdit && lastStatic.getOffset() == last.getOffset() && lastStatic.getLength() == last.getLength()) { edit.removeChild(last); } } } TextEdit firstStatic = staticEdit.getChildren()[0]; if (firstStatic instanceof InsertEdit) { if (edit.getChildrenSize() > 0) { TextEdit firstEdit = edit.getChildren()[0]; if (firstEdit instanceof InsertEdit) { if (areEqual((InsertEdit) firstEdit, (InsertEdit) firstStatic)) { edit.removeChild(firstEdit); } } } } try { staticEdit.addChild(edit); return staticEdit; } catch (MalformedTreeException e) { JavaLanguageServerPlugin.logException("Failed to resolve static organize imports source action", e); } } } return edit; } private static boolean areEqual(InsertEdit edit1, InsertEdit edit2) { if (edit1 != null && edit2 != null) { return edit1.getOffset() == edit2.getOffset() && edit1.getLength() == edit2.getLength() && edit1.getText().equals(edit2.getText()); } return false; } private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException { String name = node.getIdentifier(); String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites); if (imports.length > 1) { // See https://github.com/redhat-developer/vscode-java/issues/1472 return; } for (int i = 0; i < imports.length; i++) { String curr = imports[i]; String qualifiedTypeName = Signature.getQualifier(curr); String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite)); int dot = res.lastIndexOf('.'); if (dot != -1) { String usedTypeName = importRewrite.addImport(qualifiedTypeName); Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name)); astRewrite.replace(node, newName, null); } } } public static WorkspaceEdit organizeImports(JavaClientConnection connection, CodeActionParams params, IProgressMonitor monitor) { String uri = params.getTextDocument().getUri(); final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri()); if (unit == null) { return null; } TextEdit edit = organizeImports(unit, (selections) -> { Object commandResult = connection.executeClientCommand(CLIENT_COMMAND_ID_CHOOSEIMPORTS, uri, selections); String json = commandResult == null ? null : new Gson().toJson(commandResult); return JSONUtility.toModel(json, ImportCandidate[].class); }, monitor); return SourceAssistProcessor.convertToWorkspaceEdit(unit, edit); } public static class ImportCandidate { public String fullyQualifiedName; public String id; public ImportCandidate() { } public ImportCandidate(TypeNameMatch typeMatch) { fullyQualifiedName = typeMatch.getFullyQualifiedName(); id = typeMatch.getFullyQualifiedName() + "@" + typeMatch.hashCode(); } } public static class ImportSelection { public ImportCandidate[] candidates; public Range range; public ImportSelection(ImportCandidate[] candidates, Range range) { this.candidates = candidates; this.range = range; } } }
9231647b43a7d28e0f751148d33eeffd41e1ee96
1,032
java
Java
springboot-mvc/src/main/java/com/example/mvc/controller/ChatRoomController.java
xiaohundun/springboot-demo
0035cfbba2f2a2638163d0d84a8021d84d90242c
[ "MIT" ]
1
2020-06-13T04:16:27.000Z
2020-06-13T04:16:27.000Z
springboot-mvc/src/main/java/com/example/mvc/controller/ChatRoomController.java
xiaohundun/springboot-demo
0035cfbba2f2a2638163d0d84a8021d84d90242c
[ "MIT" ]
null
null
null
springboot-mvc/src/main/java/com/example/mvc/controller/ChatRoomController.java
xiaohundun/springboot-demo
0035cfbba2f2a2638163d0d84a8021d84d90242c
[ "MIT" ]
null
null
null
34.4
102
0.766473
995,819
package com.example.mvc.controller; /* * chou created at 2019-03-27 * @Description: * */ import com.example.commons.utils.ApplicationContextUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.CountDownLatch; @RestController("chatRoom") public class ChatRoomController { private final Logger LOGGER = LoggerFactory.getLogger(HelloController.class); @GetMapping("chatting") public Object chat() throws InterruptedException { StringRedisTemplate redisTemplate = ApplicationContextUtil.getBean(StringRedisTemplate.class); CountDownLatch countDownLatch = ApplicationContextUtil.getBean(CountDownLatch.class); LOGGER.info("Sending message..."); redisTemplate.convertAndSend("chat", "Hello from redis"); countDownLatch.await(); return ""; } }
9231650f71c8630b478722fab6e1017e48353a68
1,335
java
Java
DAFAdmin/security/src/main/java/com/fr/atgext/admin/logging/LogListenerQueueUtil.java
vkscorpio3/ATG11Extensions
e89bdd0bae63b0468383f6160da7c02508434964
[ "Apache-2.0" ]
null
null
null
DAFAdmin/security/src/main/java/com/fr/atgext/admin/logging/LogListenerQueueUtil.java
vkscorpio3/ATG11Extensions
e89bdd0bae63b0468383f6160da7c02508434964
[ "Apache-2.0" ]
null
null
null
DAFAdmin/security/src/main/java/com/fr/atgext/admin/logging/LogListenerQueueUtil.java
vkscorpio3/ATG11Extensions
e89bdd0bae63b0468383f6160da7c02508434964
[ "Apache-2.0" ]
null
null
null
29.666667
95
0.634457
995,820
package com.fr.atgext.admin.logging; import java.util.List; import atg.nucleus.GenericService; import atg.nucleus.Nucleus; import atg.nucleus.logging.LogListener; public class LogListenerQueueUtil { public static void overrideLogListeners(GenericService service, List<String> listenerPaths) { if (listenerPaths == null || listenerPaths.isEmpty()) { if (service.isLoggingWarning()) { service.logWarning("Can not override log listeners as no override value has been set"); } return; } if (service.isLoggingInfo()) { service.logInfo("Overriding logging queue"); } LogListener [] currentListeners = service.getLogListeners(); if (currentListeners != null) { for (int i = currentListeners.length - 1; i >= 0; i--) { service.removeLogListener(currentListeners[i]); } if (service.isLoggingInfo()) { service.logInfo("Log listeners have been overriden"); } } for (String path: listenerPaths) { LogListener l = (LogListener)Nucleus.getGlobalNucleus().resolveName(path); if (l != null) { service.addLogListener(l); } else { if (service.isLoggingError()) { service.vlogError("Could not resolve service with path {}", path); } } } } }
92316512e72f2f149acf0a018e2fd3768b64eb4b
1,972
java
Java
customer/src/main/java/io/openapitools/sample/rest/bank/customer/exposure/rs/model/CustomerUpdateRepresentation.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
3
2018-09-22T17:59:06.000Z
2020-12-17T13:54:10.000Z
customer/src/main/java/io/openapitools/sample/rest/bank/customer/exposure/rs/model/CustomerUpdateRepresentation.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
8
2017-10-28T20:50:31.000Z
2019-05-20T04:46:23.000Z
customer/src/main/java/io/openapitools/sample/rest/bank/customer/exposure/rs/model/CustomerUpdateRepresentation.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
null
null
null
25.61039
85
0.583164
995,821
package io.openapitools.sample.rest.bank.customer.exposure.rs.model; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * The necessary input for creation of an Customer and used for updating an Customer. */ @ApiModel(value = "CustomerUpdate", description = "the inout necessary for creating an Customer") public class CustomerUpdateRepresentation { @NotNull @Pattern(regexp = "^[a-zA-Z]{2,40}") private String firstName; @Pattern(regexp = "^[a-zA-Z]{2,40}") private String middleName; @NotNull @Pattern(regexp = "^[a-zA-Z]{2,40}") private String sirname; @NotNull @Pattern(regexp = "^[0-9]{10}") private String number; @ApiModelProperty( access = "public", name = "firstName", required = true, example = "Ole", value = "the first name of af customer") public String getFirstName() { return firstName; } @ApiModelProperty( access = "public", name = "middleName", required = true, example = "Valser", value = "the customers middle name") public String getMiddleName() { return middleName; } @ApiModelProperty( access = "public", name = "sirname", required = true, example = "Hansen", value = "the sirname of the customer.", notes = " the last name for a customer") public String getSirname() { return sirname; } @ApiModelProperty( access = "public", name = "number", required = true, example = "1234567890", value = "the customer number.", notes = " the identifier for a customer") public String getNumber() { return number; } }
9231652b027c95b3d212b347022d00c197a8d00f
8,021
java
Java
titus-common/src/main/java/com/netflix/titus/common/util/cache/Cache.java
backwardn/titus-control-plane
9b81a9bcba65ac6fa7e18dc93422c2a746c479b6
[ "Apache-2.0" ]
313
2018-04-18T16:51:10.000Z
2022-03-11T02:07:48.000Z
titus-common/src/main/java/com/netflix/titus/common/util/cache/Cache.java
backwardn/titus-control-plane
9b81a9bcba65ac6fa7e18dc93422c2a746c479b6
[ "Apache-2.0" ]
106
2018-06-11T22:17:05.000Z
2022-03-22T21:06:05.000Z
titus-common/src/main/java/com/netflix/titus/common/util/cache/Cache.java
backwardn/titus-control-plane
9b81a9bcba65ac6fa7e18dc93422c2a746c479b6
[ "Apache-2.0" ]
73
2018-04-18T16:53:07.000Z
2021-12-31T05:21:25.000Z
45.061798
123
0.687196
995,822
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.cache; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * A generic cache interface based on the open source library <a href="https://github.com/ben-manes/caffeine">Caffeine</a>. * * @param <K> - the type of the keys in the cache * @param <V> - the type of the values in the cache */ @ThreadSafe public interface Cache<K, V> { /** * Returns the value associated with the {@code key} in this cache, or {@code null} if there is no * cached value for the {@code key}. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or {@code null} if this map contains no * mapping for the key * @throws NullPointerException if the specified key is null */ @Nullable V getIfPresent(@Nonnull Object key); /** * Returns the value associated with the {@code key} in this cache, obtaining that value from the * {@code mappingFunction} if necessary. This method provides a simple substitute for the * conventional "if cached, return; otherwise create, cache and return" pattern. * <p> * If the specified key is not already associated with a value, attempts to compute its value * using the given mapping function and enters it into this cache unless {@code null}. The entire * method invocation is performed atomically, so the function is applied at most once per key. * Some attempted update operations on this cache by other threads may be blocked while the * computation is in progress, so the computation should be short and simple, and must not attempt * to update any other mappings of this cache. * <p> * <b>Warning:</b> {@code mappingFunction} <b>must not</b> * attempt to update any other mappings of this cache. * * @param key the key with which the specified value is to be associated * @param mappingFunction the function to compute a value * @return the current (existing or computed) value associated with the specified key, or null if * the computed value is null * @throws NullPointerException if the specified key or mappingFunction is null * @throws IllegalStateException if the computation detectably attempts a recursive update to this * cache that would otherwise never complete * @throws RuntimeException or Error if the mappingFunction does so, in which case the mapping is * left unestablished */ @Nullable V get(@Nonnull K key, @Nonnull Function<? super K, ? extends V> mappingFunction); /** * Returns a map of the values associated with the {@code keys} in this cache. The returned map * will only contain entries which are already present in the cache. * <p> * Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will be * ignored. * * @param keys the keys whose associated values are to be returned * @return the unmodifiable mapping of keys to values for the specified keys found in this cache * @throws NullPointerException if the specified collection is null or contains a null element */ @Nonnull Map<K, V> getAllPresent(@Nonnull Iterable<?> keys); /** * Associates the {@code value} with the {@code key} in this cache. If the cache previously * contained a value associated with the {@code key}, the old value is replaced by the new * {@code value}. * <p> * Prefer {@link #get(Object, Function)} when using the conventional "if cached, return; otherwise * create, cache and return" pattern. * * @param key the key with which the specified value is to be associated * @param value value to be associated with the specified key * @throws NullPointerException if the specified key or value is null */ void put(@Nonnull K key, @Nonnull V value); /** * Copies all of the mappings from the specified map to the cache. The effect of this call is * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined * if the specified map is modified while the operation is in progress. * * @param map the mappings to be stored in this cache * @throws NullPointerException if the specified map is null or the specified map contains null * keys or values */ void putAll(@Nonnull Map<? extends K, ? extends V> map); /** * Discards any cached value for the {@code key}. The behavior of this operation is undefined for * an entry that is being loaded and is otherwise not present. * * @param key the key whose mapping is to be removed from the cache * @throws NullPointerException if the specified key is null */ void invalidate(@Nonnull Object key); /** * Discards any cached values for the {@code keys}. The behavior of this operation is undefined * for an entry that is being loaded and is otherwise not present. * * @param keys the keys whose associated values are to be removed * @throws NullPointerException if the specified collection is null or contains a null element */ void invalidateAll(@Nonnull Iterable<?> keys); /** * Returns the approximate number of entries in this cache. The value returned is an estimate; the * actual count may differ if there are concurrent insertions or removals, or if some entries are * pending removal due to expiration or weak/soft reference collection. In the case of stale * entries this inaccuracy can be mitigated by performing a {@link #cleanUp()} first. * * @return the estimated number of mappings */ void invalidateAll(); /** * Returns a current snapshot of this cache's cumulative statistics. All statistics are * initialized to zero, and are monotonically increasing over the lifetime of the cache. * <p> * Due to the performance penalty of maintaining statistics, some implementations may not record * the usage history immediately or at all. * * @return the current snapshot of the statistics of this cache */ @Nonnegative long estimatedSize(); /** * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to * the map directly affect the cache. * <p> * Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for * concurrent use, but if the cache is modified (including by eviction) after the iterator is * created, it is undefined which of the changes (if any) will be reflected in that iterator. * * @return a thread-safe view of this cache supporting all of the optional {@link Map} operations */ @Nonnull ConcurrentMap<K, V> asMap(); /** * Performs any pending maintenance operations needed by the cache */ void cleanUp(); /** * Shuts down the cache */ void shutdown(); }
923165c9d750921bc64c2c672c0a6490acfa144a
14,443
java
Java
services/id/service/src/main/java/org/collectionspace/services/id/AlphabeticIDGeneratorPart.java
Pacific-Bonsai-Museum/services
064c4c099c299e397dcf54878d239787a2c0b817
[ "ECL-2.0" ]
9
2015-05-07T04:11:23.000Z
2020-05-13T10:04:34.000Z
services/id/service/src/main/java/org/collectionspace/services/id/AlphabeticIDGeneratorPart.java
Pacific-Bonsai-Museum/services
064c4c099c299e397dcf54878d239787a2c0b817
[ "ECL-2.0" ]
24
2015-03-14T00:38:25.000Z
2022-02-16T00:51:36.000Z
services/id/service/src/main/java/org/collectionspace/services/id/AlphabeticIDGeneratorPart.java
Pacific-Bonsai-Museum/services
064c4c099c299e397dcf54878d239787a2c0b817
[ "ECL-2.0" ]
28
2015-01-23T01:31:25.000Z
2022-03-05T17:51:05.000Z
38.108179
101
0.6194
995,823
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * * http://www.collectionspace.org * http://wiki.collectionspace.org * * Copyright © 2009 Regents of the University of California * * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * * 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. */ // @TODO: When auto expanding, we'll need to allow setting of a maximum length // to which the generated IDs can grow, likely as an additional parameter to be // passed to a constructor, with a default value hard-coded in the class. // If that length is exceeded, nextID() should throw an Exception. // @TODO: Consider handling escaped characters or sequences which represent // Unicode code points, both in the start and end characters of the sequence, // and in the initial value. // (Example: '\u0072' for the USASCII 'r' character; see // http://www.fileformat.info/info/unicode/char/0072/index.htm) // // Ideally, we should read these in free-text patterns, alongside unescaped characters, // but in practice we may wish to require some structured form for arguments // containing such characters. // // Some initial research on this: // http://www.velocityreviews.com/forums/t367758-unescaping-unicode-code-points-in-a-java-string.html // We might also look into the (protected) source code for // java.util.Properties.load() which reads escaped Unicode values. // // Note also that, if the goal is to cycle through a sequence of alphabetic // identifiers, such as the sequence of characters used in a particular // human language, it may or may not be the case that any contiguous Unicode // code point sequence reflects such a character sequence. // NOTE: This class currently hard-codes the assumption that the values in // alphabetic identifiers are ordered in significance from left-to-right; // that is, the most significant value appears in the left-most position. package org.collectionspace.services.id; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.collectionspace.services.common.document.BadRequestException; /** * AlphabeticIDGeneratorPart * * Generates identifiers (IDs) that consist of incrementing alphabetic * characters, from within a sequence of characters. * * $LastChangedRevision$ * $LastChangedDate$ */ public class AlphabeticIDGeneratorPart implements SequenceIDGeneratorPart { private static final char NULL_CHAR = '\u0000'; private static final String DEFAULT_START_CHAR = "a"; private static final String DEFAULT_END_CHAR = "z"; private static final String DEFAULT_INITIAL_VALUE = "a"; private char startChar = NULL_CHAR; private char endChar = NULL_CHAR; private Vector<Character> initialValue = new Vector<Character>(); private Vector<Character> currentValue = new Vector<Character>(); /** * Constructor using defaults for character sequence and initial value. * * If no start and end characters are provided for the alphabetic character * sequence, defaults to an 'a-z' sequence, representing the lowercase * alphabetic characters in the USASCII character set (within Java's internal * Unicode UTF-16 representation). * * Additionally defaults to an initial value of "a". */ public AlphabeticIDGeneratorPart() throws BadRequestException { this(DEFAULT_START_CHAR, DEFAULT_END_CHAR, DEFAULT_INITIAL_VALUE); } /** * Constructor using defaults for character sequence and initial value. * * If no start and end characters are provided for the alphabetic character * sequence, default to an 'a-z' sequence, representing the lowercase * alphabetic characters in the USASCII character set (within Java's internal * Unicode UTF-16 representation). * * @param initial The initial value of the alphabetic ID. Must be a * member of the valid alphabetic sequence. */ public AlphabeticIDGeneratorPart(String initial) throws BadRequestException { this(DEFAULT_START_CHAR, DEFAULT_END_CHAR, initial); } /** * Constructor * * @param sequenceStart The start character of the valid alphabetic sequence. * * @param sequenceEnd The end character of the valid alphabetic sequence. * * @param initial The initial value of the alphabetic ID. Must be a * member of the valid aphabetic sequence. */ public AlphabeticIDGeneratorPart(String sequenceStart, String sequenceEnd, String initial) throws BadRequestException { // Validate and store the start character in the character sequence. if (sequenceStart == null || sequenceStart.equals("")) { throw new BadRequestException( "Start character in the character sequence must not be " + "null or empty"); } if (sequenceStart.length() == 1) { this.startChar = sequenceStart.charAt(0); } else if (false) { // Handle representations of Unicode code points here } else { throw new BadRequestException( "Start character must be one character in length"); // "Start character must be one character in length or // a Unicode value such as '\u0000'"); } // Validate and store the end character in the character sequence. if (sequenceEnd == null || sequenceEnd.equals("")) { throw new BadRequestException( "End character in the character sequence must not be " + "null or empty"); } if (sequenceEnd.length() == 1) { this.endChar = sequenceEnd.charAt(0); } else if (false) { // Handle representations of Unicode code points here } else { throw new BadRequestException( "End character must be one character in length"); // "End character must be one character in length or // a Unicode value such as '\u0000'"); } if (this.endChar <= this.startChar) { throw new BadRequestException( "End (last) character in the character sequence must be " + "greater than the start character"); } // Validate and store the initial value of this identifier. if (initial == null || initial.equals("")) { throw new BadRequestException("Initial value must not be " + "null or empty"); } // @TODO: Add a check for maximum length of the initial value here. // Store the chars in the initial value as Characters in a Vector, // validating each character to identify whether it falls within // the provided sequence. // // (Since we're performing casts from char to Character, we can't just // use Arrays.asList() to copy the initial array to a Vector.) char[] chars = initial.toCharArray(); char ch; for (int i = 0; i < chars.length; i++) { // If the character falls within the provided sequence, // copy it to the Vector. ch = chars[i]; if (ch >= this.startChar && ch <= this.endChar) { this.initialValue.add(new Character(ch)); // Otherwise, we've detected a character not in the sequence. } else { throw new BadRequestException( "character " + "\'" + ch + "\'" + " is not valid"); } } } @Override public String getInitialID() { return toIDString(this.initialValue); } @Override public void setCurrentID(String value) throws BadRequestException { // @TODO Much of this code is copied from the main constructor, // and may be ripe for refactoring. if (value == null || value.equals("")) { throw new BadRequestException("Initial value must not be " + "null or empty"); } // @TODO: Add a check for maximum length of the value here. // Store the chars in the value as Characters in a Vector, // validating each character to identify whether it falls within // the provided sequence. // // (Since we're performing casts from char to Character, we can't just // use Arrays.asList() to copy the initial array to a Vector.) char[] chars = value.toCharArray(); char ch; Vector v = new Vector<Character>(); for (int i = 0; i < chars.length; i++) { // If the character falls within the range bounded by // the start and end characters, copy it to the Vector. ch = chars[i]; if (ch >= this.startChar && ch <= this.endChar) { v.add(new Character(ch)); // Otherwise, we've detected a character not in the sequence. } else { throw new BadRequestException( "character " + "\'" + ch + "\'" + " is not valid"); } } // Set the current value. this.currentValue = new Vector<Character>(v); } @Override public String getCurrentID() { if (this.currentValue == null || this.currentValue.size() == 0) { return toIDString(this.initialValue); } else { return toIDString(this.currentValue); } } // Currently, the number of characters auto-expands as the // value of the most significant character rolls over. // E.g. where the current ID is "z", this is auto-expanded // to "aa". Similarly, "ZZ" is auto-expanded to "AAA". // // See the TODOs at the top of this class for additional // functionality that needs to be implemented regarding auto-expansion. @Override public String nextID() throws IllegalStateException { // Get next values for each character, from right to left // (least significant to most significant). boolean expandIdentifier = false; int size = this.currentValue.size(); char ch; for (int i = (size - 1); i >= 0; i--) { ch = this.currentValue.get(i).charValue(); // When we reach the maximum value for any character, // 'roll over' to the minimum value in our character range. if (ch == this.endChar) { this.currentValue.set(i, Character.valueOf(this.startChar)); // If this rollover occurs in the most significant value, // set a flag to later expand the size of the identifier. // // @TODO: Set another flag to enable or disable this behavior, // as well as a mechanism for setting the maximum expansion // permitted. if (i == 0) { expandIdentifier = true; } // When we reach the most significant character whose value // doesn't roll over, increment that character and exit the loop. } else { ch++; this.currentValue.set(i, Character.valueOf(ch)); i = -1; break; } } // If we are expanding the size of the identifier, insert a new // value at the most significant (leftmost) character position, // sliding other values to the right. if (expandIdentifier) { this.currentValue.add(0, Character.valueOf(this.startChar)); } return toIDString(this.currentValue); } @Override public String newID() { // If there is no current value, return the initial value // and set the current value to the initial value. if (this.currentValue == null || this.currentValue.size() == 0) { this.currentValue = this.initialValue; return toIDString(this.currentValue); // Otherwise, return a new value. } else { return nextID(); } } @Override public boolean isValidID(String id) { if (id == null) return false; // @TODO May potentially throw java.util.regex.PatternSyntaxException. // We'll need to catch and handle this here, as well as in all // derived classes and test cases that invoke validation. Pattern pattern = Pattern.compile(getRegex()); Matcher matcher = pattern.matcher(id); if (matcher.matches()) { return true; } else { return false; } } @Override public String getRegex() { // @TODO May need to constrain the number of alphabetic // characters based on a maximum length value. // // Currently, this regex simply matches any sequence of one // or more alphabetic characters, with no explicit constraint // on length. String regex = "(" + "[" + String.valueOf(this.startChar) + "-" + String.valueOf(this.endChar) + "]" + "+" + ")"; return regex; } /** * Returns a String representation of a provided ID, by concatenating * the String values of each alphabetic character constituting the ID. * * @param characters The alphabetic characters constituting the ID. * * @return A String representation of the ID. */ public String toIDString(Vector<Character> characters) { StringBuffer sb = new StringBuffer(); for ( Character ch : characters ) { sb.append(ch.toString()); } return sb.toString(); } }
923165fbb73a23185ebd16fcfa8c546239c8c41d
626
java
Java
src/main/java/com/example/opentravel/service/EmailService.java
tansuluu/Opentravel
7d96bcfb2d9df22d5891a0e867e25ad1bbed9733
[ "MIT" ]
6
2019-03-02T18:36:10.000Z
2019-10-01T11:06:37.000Z
src/main/java/com/example/opentravel/service/EmailService.java
tansuluu/Opentravel
7d96bcfb2d9df22d5891a0e867e25ad1bbed9733
[ "MIT" ]
67
2019-02-27T16:39:12.000Z
2019-04-24T08:11:04.000Z
src/main/java/com/example/opentravel/service/EmailService.java
tansuluu/Opentravel
7d96bcfb2d9df22d5891a0e867e25ad1bbed9733
[ "MIT" ]
3
2019-02-28T17:36:20.000Z
2019-04-02T03:14:51.000Z
27.217391
62
0.777955
995,824
package com.example.opentravel.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service("emailService") public class EmailService { private JavaMailSender mailSender; @Autowired public EmailService(JavaMailSender mailSender) { this.mailSender = mailSender; } @Async public void sendEmail(SimpleMailMessage email) { mailSender.send(email); } }
923167663b79a07f3cd2ba201f6bcb7a3db1a565
337
java
Java
src/main/java/com/azhong/demo/jvm/EmptyObject.java
80sAzhong/javademo
81c444b2a8ca358d61fbd7139fd7e83d17b946ac
[ "Apache-2.0" ]
null
null
null
src/main/java/com/azhong/demo/jvm/EmptyObject.java
80sAzhong/javademo
81c444b2a8ca358d61fbd7139fd7e83d17b946ac
[ "Apache-2.0" ]
null
null
null
src/main/java/com/azhong/demo/jvm/EmptyObject.java
80sAzhong/javademo
81c444b2a8ca358d61fbd7139fd7e83d17b946ac
[ "Apache-2.0" ]
null
null
null
24.071429
76
0.664688
995,825
package main.java.com.azhong.demo.jvm; import org.openjdk.jol.info.ClassLayout; public class EmptyObject { int a=10; int[] c= {1,6,9}; int b=20; public static void main(String[] args) { EmptyObject object = new EmptyObject(); System.out.println(ClassLayout.parseInstance(object).toPrintable()); } }
9231688532d485b9f094a75af5fdd7b4646a2f70
388
java
Java
src/woutzeemote/java/zame/game/fragments/dialogs/GameMenuDialogFragmentZeemoteHelper.java
restorer/gloomy-dungeons-2
cff4c50cd7c15ce99f9b1ce9e1493a3ad8296a29
[ "MIT" ]
97
2015-03-01T16:38:01.000Z
2022-03-31T09:36:03.000Z
src/woutzeemote/java/zame/game/fragments/dialogs/GameMenuDialogFragmentZeemoteHelper.java
restorer/gloomy-dungeons-2
cff4c50cd7c15ce99f9b1ce9e1493a3ad8296a29
[ "MIT" ]
12
2015-12-03T12:41:11.000Z
2020-07-02T17:38:50.000Z
src/woutzeemote/java/zame/game/fragments/dialogs/GameMenuDialogFragmentZeemoteHelper.java
restorer/gloomy-dungeons-2
cff4c50cd7c15ce99f9b1ce9e1493a3ad8296a29
[ "MIT" ]
51
2015-10-20T10:33:11.000Z
2022-02-11T17:09:01.000Z
24.25
59
0.744845
995,826
package zame.game.fragments.dialogs; import android.view.ViewGroup; import zame.game.MainActivity; import zame.game.engine.Engine; public class GameMenuDialogFragmentZeemoteHelper { public static void onCreateDialog( ViewGroup viewGroup, Engine engine, final MainActivity activity, final GameMenuDialogFragment gameMenuDialogFragment ) { } }
923168893f91e0a9592cae6408d0533a6c7aa0e0
2,591
java
Java
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DefaultMetricResults.java
shusso/beam
5a851b734f53206c20efe08d93d15760bbc15b0c
[ "Apache-2.0" ]
35
2016-09-22T22:53:14.000Z
2020-02-13T15:12:21.000Z
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DefaultMetricResults.java
shusso/beam
5a851b734f53206c20efe08d93d15760bbc15b0c
[ "Apache-2.0" ]
71
2018-05-23T22:20:02.000Z
2019-04-30T15:37:46.000Z
runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DefaultMetricResults.java
shusso/beam
5a851b734f53206c20efe08d93d15760bbc15b0c
[ "Apache-2.0" ]
88
2016-11-27T02:16:11.000Z
2020-02-28T05:10:26.000Z
43.915254
99
0.769587
995,827
/* * 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.beam.runners.core.metrics; import javax.annotation.Nullable; import org.apache.beam.sdk.metrics.DistributionResult; import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.sdk.metrics.MetricFiltering; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables; /** * Default implementation of {@link org.apache.beam.sdk.metrics.MetricResults}, which takes static * {@link Iterable}s of counters, distributions, and gauges, and serves queries by applying {@link * org.apache.beam.sdk.metrics.MetricsFilter}s linearly to them. */ public class DefaultMetricResults extends MetricResults { private final Iterable<MetricResult<Long>> counters; private final Iterable<MetricResult<DistributionResult>> distributions; private final Iterable<MetricResult<GaugeResult>> gauges; public DefaultMetricResults( Iterable<MetricResult<Long>> counters, Iterable<MetricResult<DistributionResult>> distributions, Iterable<MetricResult<GaugeResult>> gauges) { this.counters = counters; this.distributions = distributions; this.gauges = gauges; } @Override public MetricQueryResults queryMetrics(@Nullable MetricsFilter filter) { return MetricQueryResults.create( Iterables.filter(counters, counter -> MetricFiltering.matches(filter, counter.getKey())), Iterables.filter( distributions, distribution -> MetricFiltering.matches(filter, distribution.getKey())), Iterables.filter(gauges, gauge -> MetricFiltering.matches(filter, gauge.getKey()))); } }
923168d7d40d7462c78b8306164ef9491437a35d
20,180
java
Java
teiid-webui-webapp/src/main/java/org/teiid/webui/client/widgets/vieweditor/DefineJoinCriteriaPage.java
mdrillin/teiid-webui
86aa2cac99fa012d7ae6f3dc0997d244bb2aa751
[ "Apache-2.0" ]
4
2015-03-06T14:42:57.000Z
2021-03-14T19:57:54.000Z
teiid-webui-webapp/src/main/java/org/teiid/webui/client/widgets/vieweditor/DefineJoinCriteriaPage.java
mdrillin/teiid-webui
86aa2cac99fa012d7ae6f3dc0997d244bb2aa751
[ "Apache-2.0" ]
1
2015-04-13T18:42:50.000Z
2015-04-13T18:42:50.000Z
teiid-webui-webapp/src/main/java/org/teiid/webui/client/widgets/vieweditor/DefineJoinCriteriaPage.java
mdrillin/teiid-webui
86aa2cac99fa012d7ae6f3dc0997d244bb2aa751
[ "Apache-2.0" ]
8
2015-02-18T21:56:53.000Z
2017-03-21T01:17:49.000Z
35.65371
138
0.690684
995,828
/* * Copyright 2014 JBoss 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 org.teiid.webui.client.widgets.vieweditor; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.jboss.errai.ui.shared.api.annotations.DataField; import org.jboss.errai.ui.shared.api.annotations.Templated; import org.teiid.webui.client.dialogs.UiEvent; import org.teiid.webui.client.dialogs.UiEventType; import org.teiid.webui.client.messages.ClientMessages; import org.teiid.webui.client.resources.AppResource; import org.teiid.webui.client.utils.DdlHelper; import org.teiid.webui.client.widgets.CheckableNameTypeRow; import org.teiid.webui.client.widgets.table.ColumnNamesTable; import org.teiid.webui.share.Constants; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.ToggleButton; import com.google.gwt.user.client.ui.VerticalPanel; @Dependent @Templated("./DefineJoinCriteriaPage.html") /** * ViewEditor wizard page for definition of the join criteria */ public class DefineJoinCriteriaPage extends Composite { @Inject private ClientMessages i18n; @Inject Event<UiEvent> setDdlEvent; @Inject @DataField("lbl-define-join-message") protected Label messageLabel; @Inject @DataField("lbl-joineditor-lhsTableTitle") protected Label lhsTableTitleLabel; @Inject @DataField("lbl-joineditor-rhsTableTitle") protected Label rhsTableTitleLabel; @Inject @DataField("tbl-lhs-columns") private ColumnNamesTable lhsJoinTable; @Inject @DataField("tbl-rhs-columns") private ColumnNamesTable rhsJoinTable; @Inject @DataField("btn-joineditor-togglePanel") protected VerticalPanel togglePanel; protected ToggleButton joinInnerButton; protected ToggleButton joinLeftOuterButton; protected ToggleButton joinRightOuterButton; protected ToggleButton joinFullOuterButton; @Inject @DataField("listbox-lhcriteria") protected ListBox lhCriteriaListBox; @Inject @DataField("listbox-rhcriteria") protected ListBox rhCriteriaListBox; private String currentStatus = ""; private String msgCheckOneOrMoreColumns; private String msgSelectLeftJoinCriteria; private String msgSelectRightJoinCriteria; private String msgClickApplyWhenFinished; private String lhTableName; private String rhTableName; private String lhTableSource; private String rhTableSource; private HandlerRegistration lhCriteriaHandlerRegistration; private HandlerRegistration rhCriteriaHandlerRegistration; private enum Side { LEFT, RIGHT } private ViewEditorManager editorManager = ViewEditorManager.getInstance(); private ViewEditorWizardPanel wizard; /** * Called after construction. */ @PostConstruct protected void postConstruct() { AppResource.INSTANCE.css().joinToggleStyle().ensureInjected(); lhsJoinTable.setOwner(this.getClass().getName()); rhsJoinTable.setOwner(this.getClass().getName()); msgCheckOneOrMoreColumns = i18n.format("define-join-criteria-page.check-one-or-more-columns.message"); msgSelectLeftJoinCriteria = i18n.format("define-join-criteria-page.select-left-join-criteria.message"); msgSelectRightJoinCriteria= i18n.format("define-join-criteria-page.select-right-join-criteria.message"); msgClickApplyWhenFinished = i18n.format("define-join-criteria-page.click-apply-when-finished.message"); lhsTableTitleLabel.setText(i18n.format("define-join-criteria-page.lhs-table.title")); rhsTableTitleLabel.setText(i18n.format("define-join-criteria-page.rhs-table.title")); joinInnerButton = new ToggleButton(new Image(AppResource.INSTANCE.images().joinInner_Image())); joinLeftOuterButton = new ToggleButton(new Image(AppResource.INSTANCE.images().joinLeftOuter_Image())); joinRightOuterButton = new ToggleButton(new Image(AppResource.INSTANCE.images().joinRightOuter_Image())); joinFullOuterButton = new ToggleButton(new Image(AppResource.INSTANCE.images().joinFullOuter_Image())); joinInnerButton.setTitle(i18n.format("define-join-criteria-page.inner-join.tooltip")); joinLeftOuterButton.setTitle(i18n.format("define-join-criteria-page.left-outer-join.tooltip")); joinRightOuterButton.setTitle(i18n.format("define-join-criteria-page.right-outer-join.tooltip")); joinFullOuterButton.setTitle(i18n.format("define-join-criteria-page.full-outer-join.tooltip")); joinInnerButton.setStylePrimaryName("joinToggle"); joinLeftOuterButton.setStylePrimaryName("joinToggle"); joinRightOuterButton.setStylePrimaryName("joinToggle"); joinFullOuterButton.setStylePrimaryName("joinToggle"); DOM.setStyleAttribute(joinInnerButton.getElement(), "padding", "0px"); DOM.setStyleAttribute(joinLeftOuterButton.getElement(), "padding", "0px"); DOM.setStyleAttribute(joinRightOuterButton.getElement(), "padding", "0px"); DOM.setStyleAttribute(joinFullOuterButton.getElement(), "padding", "0px"); DOM.setStyleAttribute(joinInnerButton.getElement(), "margin", "0px 0px 0px 0px"); DOM.setStyleAttribute(joinLeftOuterButton.getElement(), "margin", "5px 0px 0px 0px"); DOM.setStyleAttribute(joinRightOuterButton.getElement(), "margin", "5px 0px 0px 0px"); DOM.setStyleAttribute(joinFullOuterButton.getElement(), "margin", "5px 0px 0px 0px"); togglePanel.add(joinInnerButton); togglePanel.add(joinLeftOuterButton); togglePanel.add(joinRightOuterButton); togglePanel.add(joinFullOuterButton); // Default to inner join setJoinButtonSelection(Constants.JOIN_TYPE_INNER); joinInnerButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setJoinButtonStates(true,false,false,false); editorManager.setJoinType(Constants.JOIN_TYPE_INNER); } }); joinLeftOuterButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setJoinButtonStates(false,true,false,false); editorManager.setJoinType(Constants.JOIN_TYPE_LEFT_OUTER); } }); joinRightOuterButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setJoinButtonStates(false,false,true,false); editorManager.setJoinType(Constants.JOIN_TYPE_RIGHT_OUTER); } }); joinFullOuterButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setJoinButtonStates(false,false,false,true); editorManager.setJoinType(Constants.JOIN_TYPE_FULL_OUTER); } }); } /** * Refresh the panel using state from the ViewEditorManager */ public void update() { // Determine page number, set title int pageNumber = 2; int nTemplatePages = editorManager.getNumberTablesRequiringTemplates(); if(nTemplatePages==1) { pageNumber = 3; } else if(nTemplatePages==2) { pageNumber = 4; } this.wizard.setWizardPageTitle(i18n.format("define-join-page.title", pageNumber)); List<CheckableNameTypeRow> lhsColumns = editorManager.getColumns(0); List<CheckableNameTypeRow> rhsColumns = editorManager.getColumns(1); setTable(Side.LEFT, lhsColumns); setTable(Side.RIGHT, rhsColumns); String lhCriteriaCol = editorManager.getJoinColumn(0); String rhCriteriaCol = editorManager.getJoinColumn(1); setLHCriteriaSelection(lhCriteriaCol); setRHCriteriaSelection(rhCriteriaCol); setJoinButtonSelection(editorManager.getJoinType()); updateStatus(); } /** * Set the owner wizardPanel * @param wizard the wizard */ public void setWizard(ViewEditorWizardPanel wizard) { this.wizard = wizard; } /** * Set the Columns table rows for the specified table. * @param side the left or right table side * @param colList the list of column rows */ public void setTable(Side side, List<CheckableNameTypeRow> colList) { // Set table name and source name if(side==Side.LEFT) { lhTableName = editorManager.getTable(0); lhTableSource = editorManager.getSourceNameForTable(0); } else { rhTableName = editorManager.getTable(1); rhTableSource = editorManager.getSourceNameForTable(1); } // Set table data and title if(side==Side.LEFT) { if(colList!=null) lhsJoinTable.setData(colList); lhsTableTitleLabel.setText( lhTableName ); } else if (side==Side.RIGHT) { if(colList!=null) rhsJoinTable.setData(colList); rhsTableTitleLabel.setText( rhTableName ); } // Set the criteria listbox if(colList!=null) { List<String> colNames = new ArrayList<String>(colList.size()); for(CheckableNameTypeRow row : colList) { colNames.add(row.getName()); } populateCriteriaListBox(side, colNames); } } /** * Sets the join button selection * @param joinType the join type */ private void setJoinButtonSelection(String joinType) { if(joinType.equals(Constants.JOIN_TYPE_INNER)) { setJoinButtonStates(true,false,false,false); } else if(joinType.equals(Constants.JOIN_TYPE_LEFT_OUTER)) { setJoinButtonStates(false,true,false,false); } else if(joinType.equals(Constants.JOIN_TYPE_RIGHT_OUTER)) { setJoinButtonStates(false,false,true,false); } else if(joinType.equals(Constants.JOIN_TYPE_FULL_OUTER)) { setJoinButtonStates(false,false,false,true); } } private void setJoinButtonStates(boolean innerState, boolean leftOuterStatus, boolean rightOuterState, boolean fullOuterState) { joinInnerButton.setValue(innerState); joinLeftOuterButton.setValue(leftOuterStatus); joinRightOuterButton.setValue(rightOuterState); joinFullOuterButton.setValue(fullOuterState); } /** * Populate left or right criteria listBox * @param side left or right * @param columnNames list of columnNames for the listBox */ private void populateCriteriaListBox(Side side, List<String> columnNames) { ListBox criteriaListBox = null; if(side==Side.LEFT) { if(this.lhCriteriaHandlerRegistration!=null) this.lhCriteriaHandlerRegistration.removeHandler(); criteriaListBox = this.lhCriteriaListBox; } else { if(this.rhCriteriaHandlerRegistration!=null) this.rhCriteriaHandlerRegistration.removeHandler(); criteriaListBox = this.rhCriteriaListBox; } // Make sure clear first criteriaListBox.clear(); // For no columns, the displayed item0 is different String item0 = null; if(columnNames.size()==0) { item0 = Constants.NO_CRITERIA_COLUMNS; } else { item0 = Constants.NO_CRITERIA_SELECTION; } criteriaListBox.insertItem(item0, 0); // Repopulate the ListBox with column names int i = 1; for(String columnName: columnNames) { criteriaListBox.insertItem(columnName, i); i++; } // Initialize by setting the selection to the first item. criteriaListBox.setSelectedIndex(0); if(side==Side.LEFT) { // Add the change handler for status updates ChangeHandler criteriaChangeHandler = new ChangeHandler() { // Changing the updates status public void onChange(ChangeEvent event) { String sel = getLHCriteriaSelection(); editorManager.setJoinColumn(0, sel); updateStatus(); } }; lhCriteriaHandlerRegistration = criteriaListBox.addChangeHandler(criteriaChangeHandler); } else { // Add the change handler for status updates ChangeHandler criteriaChangeHandler = new ChangeHandler() { // Changing the updates status public void onChange(ChangeEvent event) { String sel = getRHCriteriaSelection(); editorManager.setJoinColumn(1, sel); updateStatus(); } }; rhCriteriaHandlerRegistration = criteriaListBox.addChangeHandler(criteriaChangeHandler); } } /** * Get the selected LH Criteria Column * @return */ public String getLHCriteriaSelection() { int index = lhCriteriaListBox.getSelectedIndex(); return lhCriteriaListBox.getValue(index); } /** * Set the selected LH Criteria Column * @return */ public void setLHCriteriaSelection(String columnName) { int indx = 0; int nItems = lhCriteriaListBox.getItemCount(); for(int i=0; i<nItems; i++) { String itemText = lhCriteriaListBox.getItemText(i); if(itemText.equalsIgnoreCase(columnName)) { indx = i; break; } } lhCriteriaListBox.setSelectedIndex(indx); } /** * Get the selected RH Criteria Column * @return */ public String getRHCriteriaSelection() { int index = rhCriteriaListBox.getSelectedIndex(); return rhCriteriaListBox.getValue(index); } /** * Set the selected RH Criteria Column * @return */ public void setRHCriteriaSelection(String columnName) { int indx = 0; int nItems = rhCriteriaListBox.getItemCount(); for(int i=0; i<nItems; i++) { String itemText = rhCriteriaListBox.getItemText(i); if(itemText.equalsIgnoreCase(columnName)) { indx = i; break; } } rhCriteriaListBox.setSelectedIndex(indx); } /** * Handler for Replace DDL button click. */ public void replaceDdlClicked( ) { String ddl = buildDdl(); UiEvent uiEvent = new UiEvent(UiEventType.VIEW_DEFN_REPLACE_FROM_JOIN_EDITOR); uiEvent.setViewDdl(ddl); List<String> viewSources = new ArrayList<String>(); viewSources.add(getLHTableSource()); String rhTable = getRHTableSource(); if(!viewSources.contains(rhTable)) { viewSources.add(rhTable); } uiEvent.setViewSources(viewSources); setDdlEvent.fire(uiEvent); } /** * Build the DDL from the editor selections * @return the DDL */ private String buildDdl( ) { List<String> lhsColNames = lhsJoinTable.getSelectedColumnNames(); List<String> lhsColTypes = lhsJoinTable.getSelectedColumnTypes(); List<String> rhsColNames = rhsJoinTable.getSelectedColumnNames(); List<String> rhsColTypes = rhsJoinTable.getSelectedColumnTypes(); String lhsCriteriaCol = getLHCriteriaSelection(); String rhsCriteriaCol = getRHCriteriaSelection(); String lhsTableName = getLHTable(); String rhsTableName = getRHTable(); String jType = editorManager.getJoinType(); // Gets either the table name or template SQL String lhs = null; String rhs = null; if(editorManager.tableRequiresTemplate(0)) { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(editorManager.getTemplateSQL(0)); sb.append(") AS A"); lhs = sb.toString(); } else { lhs = lhsTableName+" AS A"; //lhs = StringUtils.escapeSQLName(lhsTableName); } if(editorManager.tableRequiresTemplate(1)) { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(editorManager.getTemplateSQL(1)); sb.append(") AS B"); rhs = sb.toString(); } else { rhs = rhsTableName+" AS B"; //rhs = StringUtils.escapeSQLName(rhsTableName); } String viewDdl = DdlHelper.getODataViewJoinDdl(Constants.SERVICE_VIEW_NAME, lhs, lhsColNames, lhsColTypes, lhsCriteriaCol, rhs, rhsColNames, rhsColTypes, rhsCriteriaCol, jType); return viewDdl; } /** * Handles UiEvents from columnNamesTable * @param dEvent */ public void onUiEvent(@Observes UiEvent dEvent) { // checkbox change event from column names table if(dEvent.getType() == UiEventType.COLUMN_NAME_TABLE_CHECKBOX_CHANGED && dEvent.getEventSource().equals(this.getClass().getName())) { List<String> lhsCols = lhsJoinTable.getSelectedColumnNames(); List<String> rhsCols = rhsJoinTable.getSelectedColumnNames(); List<String> lhsColTypes = lhsJoinTable.getSelectedColumnTypes(); List<String> rhsColTypes = rhsJoinTable.getSelectedColumnTypes(); editorManager.setSelectedColumns(0, lhsCols); editorManager.setSelectedColumns(1, rhsCols); editorManager.setSelectedColumnTypes(0, lhsColTypes); editorManager.setSelectedColumnTypes(1, rhsColTypes); updateStatus(); } } /** * Get the Left table name * @return the left table name */ public String getLHTable() { return this.lhTableName; } /** * Get the Right table name * @return the right table name */ public String getRHTable() { return this.rhTableName; } /** * Get the Left table data source * @return the left table source */ public String getLHTableSource() { return this.lhTableSource; } /** * Get the Right table data source * @return the right table source */ public String getRHTableSource() { return this.rhTableSource; } /** * Update panel status */ private void updateStatus( ) { currentStatus = Constants.OK; // Ensure some columns are selected if(Constants.OK.equals(currentStatus)) { List<String> selectedLHColumns = editorManager.getSelectedColumns(0); List<String> selectedRHColumns = editorManager.getSelectedColumns(1); int nLHS = (selectedLHColumns==null) ? 0 : selectedLHColumns.size(); int nRHS = (selectedRHColumns==null) ? 0 : selectedRHColumns.size(); if(nLHS + nRHS == 0) { currentStatus = msgCheckOneOrMoreColumns; } } // Make sure LH Criteria is selected if(Constants.OK.equals(currentStatus)) { String lhCritColumn = getLHCriteriaSelection(); if(Constants.NO_CRITERIA_SELECTION.equals(lhCritColumn)) { currentStatus = msgSelectLeftJoinCriteria; } } // Make sure RH Criteria is selected if(Constants.OK.equals(currentStatus)) { String rhCritColumn = getRHCriteriaSelection(); if(Constants.NO_CRITERIA_SELECTION.equals(rhCritColumn)) { currentStatus = msgSelectRightJoinCriteria; } } // Enable setDdlButton button if OK if(Constants.OK.equals(currentStatus)) { messageLabel.setText(msgClickApplyWhenFinished); this.wizard.setNextOrReplaceButton(true); } else { messageLabel.setText(currentStatus); this.wizard.setNextOrReplaceButton(false); } } /** * Get the panel status * @return the status */ public String getStatus() { return this.currentStatus; } }
923168e7698bc10944b0987bfb845fb809054560
1,057
java
Java
src/main/java/com/immomo/momosec/utils/Str.java
r4b3rt/momo-code-sec-inspector-java
9f5c522beabfcb21e58b74d0dfa13ef6cc094701
[ "Apache-2.0" ]
719
2020-10-09T08:23:30.000Z
2022-03-31T10:18:33.000Z
src/main/java/com/immomo/momosec/utils/Str.java
paynexss/momo-code-sec-inspector-java
eaf76b661e08cb2f1d3e4ea9deef08ebe66a8603
[ "Apache-2.0" ]
13
2020-10-14T14:41:39.000Z
2022-03-25T01:53:30.000Z
src/main/java/com/immomo/momosec/utils/Str.java
paynexss/momo-code-sec-inspector-java
eaf76b661e08cb2f1d3e4ea9deef08ebe66a8603
[ "Apache-2.0" ]
105
2020-10-11T08:27:24.000Z
2022-03-25T11:56:27.000Z
30.2
75
0.639546
995,829
/* * Copyright 2020 momosecurity. * * 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.immomo.momosec.utils; public class Str { public static String ltrim(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } return s.substring(i); } public static String rtrim(String s) { int i = s.length()-1; while (i >= 0 && Character.isWhitespace(s.charAt(i))) { i--; } return s.substring(0,i+1); } }
9231697fb3e702f4e9e75cda33d5236b68f99595
727
java
Java
oauth/src/main/java/tw/idb/oauth/api/LoginApiService.java
powerbenson/oauth-server-simple-example
16cdc53745553d492299dc01cfa20505de609bbd
[ "RSA-MD", "CECILL-B" ]
null
null
null
oauth/src/main/java/tw/idb/oauth/api/LoginApiService.java
powerbenson/oauth-server-simple-example
16cdc53745553d492299dc01cfa20505de609bbd
[ "RSA-MD", "CECILL-B" ]
null
null
null
oauth/src/main/java/tw/idb/oauth/api/LoginApiService.java
powerbenson/oauth-server-simple-example
16cdc53745553d492299dc01cfa20505de609bbd
[ "RSA-MD", "CECILL-B" ]
null
null
null
34.619048
73
0.738652
995,830
package tw.idb.oauth.api; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /* * @FeignClient 使用註解跟標記的方式,結合了 httpClient * ${idb.domain.apiserver} 是要call的API的domain * callLogin會去call User Server的登入API */ @FeignClient(value = "loginApiService", url = "${idb.domain.apiserver}") public interface LoginApiService { @RequestMapping(value = "/user/login", method = RequestMethod.POST) public String callLogin(@RequestParam String username, @RequestParam String password); }
92316a3dcd25f83b7db51c560470956aeb89e45c
2,652
java
Java
src/main/java/org/sharedhealth/datasense/client/TrWebClient.java
SharedHealth/SHR-Datasense
8f08cd024050a93691df3246c78d244cd6c8c950
[ "Apache-2.0" ]
null
null
null
src/main/java/org/sharedhealth/datasense/client/TrWebClient.java
SharedHealth/SHR-Datasense
8f08cd024050a93691df3246c78d244cd6c8c950
[ "Apache-2.0" ]
null
null
null
src/main/java/org/sharedhealth/datasense/client/TrWebClient.java
SharedHealth/SHR-Datasense
8f08cd024050a93691df3246c78d244cd6c8c950
[ "Apache-2.0" ]
2
2020-12-10T15:52:54.000Z
2022-03-14T12:53:47.000Z
39.58209
113
0.728884
995,831
package org.sharedhealth.datasense.client; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.sharedhealth.datasense.client.exceptions.ConnectionException; import org.sharedhealth.datasense.config.DatasenseProperties; import org.sharedhealth.datasense.model.tr.TrConcept; import org.sharedhealth.datasense.model.tr.TrMedication; import org.sharedhealth.datasense.model.tr.TrReferenceTerm; import org.sharedhealth.datasense.util.MapperUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import static org.sharedhealth.datasense.util.HeaderUtil.getBase64Authentication; @Component public class TrWebClient { private DatasenseProperties datasenseProperties; private Logger log = Logger.getLogger(TrWebClient.class); @Autowired public TrWebClient(DatasenseProperties datasenseProperties) { this.datasenseProperties = datasenseProperties; } public TrMedication getTrMedication(String uri) throws IOException, URISyntaxException { String response = getResponse(new URI(uri)); if (response != null) { TrMedication trMedication = MapperUtil.readFrom(response, TrMedication.class); trMedication.setUuid(StringUtils.substringAfterLast(uri, "/")); return trMedication; } return null; } public String getResponse(URI uri) throws IOException, URISyntaxException { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", getBase64Authentication(datasenseProperties.getTrUser(), datasenseProperties .getTrPassword())); headers.put("Accept", "application/json"); String response; try { response = new WebClient().get(uri, headers); } catch (ConnectionException e) { log.error(String.format("Could not fetch feed for URI [%s] ", uri), e); throw new IOException(e); } return response; } public TrConcept getTrConcept(String uri) throws URISyntaxException, IOException { String response = getResponse(new URI(uri)); return response != null ? MapperUtil.readFrom(response, TrConcept.class) : null; } public TrReferenceTerm getTrReferenceTerm(String uri) throws URISyntaxException, IOException { String response = getResponse(new URI(uri)); return response != null ? MapperUtil.readFrom(response, TrReferenceTerm.class) : null; } }
92316b1bcbadacaf170a77818d01060df285064d
4,965
java
Java
src/dao/DAOEquivalenciaIngrediente.java
El-Kabs/Sistrans
0970dc1e6a9070ecdc39644cdac0c96fdc4706c6
[ "MIT" ]
null
null
null
src/dao/DAOEquivalenciaIngrediente.java
El-Kabs/Sistrans
0970dc1e6a9070ecdc39644cdac0c96fdc4706c6
[ "MIT" ]
null
null
null
src/dao/DAOEquivalenciaIngrediente.java
El-Kabs/Sistrans
0970dc1e6a9070ecdc39644cdac0c96fdc4706c6
[ "MIT" ]
null
null
null
32.24026
245
0.735146
995,832
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import vos.Categoria; import vos.Ingrediente; import vos.Producto; import vos.VOEquivalenciaIngrediente; import vos.VOEquivalenciaProducto; public class DAOEquivalenciaIngrediente { /** * Arraylits de recursos que se usan para la ejecución de sentencias SQL */ private ArrayList<Object> recursos; /** * Atributo que genera la conexión a la base de datos */ private Connection conn; /** * Metodo constructor que crea DAOVideo * <b>post: </b> Crea la instancia del DAO e inicializa el Arraylist de recursos */ public DAOEquivalenciaIngrediente() { recursos = new ArrayList<Object>(); } /** * Metodo que cierra todos los recursos que estan enel arreglo de recursos * <b>post: </b> Todos los recurso del arreglo de recursos han sido cerrados */ public void cerrarRecursos() { for(Object ob : recursos){ if(ob instanceof PreparedStatement) try { ((PreparedStatement) ob).close(); } catch (Exception ex) { ex.printStackTrace(); } } } /** * Metodo que inicializa la connection del DAO a la base de datos con la conexión que entra como parametro. * @param con - connection a la base de datos */ public void setConn(Connection con){ this.conn = con; } public ArrayList<VOEquivalenciaIngrediente> darEquivalenciaIngre() throws SQLException, Exception { ArrayList<VOEquivalenciaIngrediente> ingredientes = new ArrayList<VOEquivalenciaIngrediente>(); String sql = "SELECT * FROM EQUIVALENCIA_INGREDIENTE"; PreparedStatement prepStmt = conn.prepareStatement(sql); recursos.add(prepStmt); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { String ingre1 = rs.getString("NOMBRE_INGREDIENTE_1"); String ingre2 = rs.getString("NOMBRE_INGREDIENTE_2"); Long id = rs.getLong("ID"); Ingrediente prod1 = darIngrediente(ingre1); Ingrediente prod2 = darIngrediente(ingre1); VOEquivalenciaIngrediente vo = new VOEquivalenciaIngrediente(prod1, prod2, id); ingredientes.add(vo); } return ingredientes; } public Ingrediente darIngrediente(String nombreP) throws SQLException, Exception { String sql = "SELECT * FROM INGREDIENTE WHERE NOMBRE = '"+nombreP+"'"; Ingrediente retorno = null; PreparedStatement prepStmt = conn.prepareStatement(sql); recursos.add(prepStmt); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { String nombre = rs.getString("NOMBRE"); String descripcion = rs.getString("DESCRIPCION"); String traduccion = rs.getString("TRADUCCION"); retorno = new Ingrediente(nombre, descripcion, traduccion); } return retorno; } public VOEquivalenciaIngrediente buscarEquivIngrePorID(Long id) throws SQLException, Exception { VOEquivalenciaIngrediente ingreRetorno = null; String sql = "SELECT * FROM EQUIVALENCIA_INGREDIENTE WHERE ID ='" + id ; PreparedStatement prepStmt = conn.prepareStatement(sql); recursos.add(prepStmt); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { String nombreProd1 = rs.getString("NOMBRE_INGREDIENTE_1"); String nombreProd2 = rs.getString("NOMBRE_INGREDIENTE_2"); Long id2 = rs.getLong("ID"); Ingrediente prod1 = darIngrediente(nombreProd1); Ingrediente prod2 = darIngrediente(nombreProd2); ingreRetorno = new VOEquivalenciaIngrediente(prod1, prod2, id2); } return ingreRetorno; } public void addEquivIngre(VOEquivalenciaIngrediente equiv) throws SQLException, Exception { String sql2 = "INSERT INTO EQUIVALENCIA_INGREDIENTE VALUES ('"+equiv.getIngrediente1().getNombre()+"', '"+equiv.getIngrediente2().getNombre()+"', "+equiv.getId()+")"; //INSERT INTO EQUIVALENCIA_PRODUCTO VALUES('Ingrediente 1', 'Ingrediente 2', 1); PreparedStatement prepStmt = conn.prepareStatement(sql2); System.out.println("SQL 2:"+sql2); recursos.add(prepStmt); prepStmt.executeQuery(); } public boolean esEquivalenteIngrediente(Ingrediente p1, Ingrediente p2) throws SQLException, Exception { String sql = "SELECT * FROM EQUIVALENCIA_INGREDIENTE WHERE NOMBRE_INGREDIENTE_1 = '"+p1.getNombre()+"' AND NOMBRE_INGREDIENTE_2='"+p2.getNombre()+"' OR NOMBRE_INGREDIENTE_1 = '"+p2.getNombre()+"' AND NOMBRE_INGREDIENTE_2='"+p1.getNombre()+"'"; String n1 = ""; PreparedStatement prepStmt = conn.prepareStatement(sql); recursos.add(prepStmt); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { String nombre = rs.getString("NOMBRE_INGREDIENTE_1"); n1 = nombre; } if(!n1.equalsIgnoreCase("")) { return true; } else return false; } public void deleteEquivProd(VOEquivalenciaProducto equiv) throws SQLException, Exception { String sql = "DELETE FROM EQUIVALENCIA_INGREDIENTE"; sql += " WHERE ID = " + equiv.getId(); PreparedStatement prepStmt = conn.prepareStatement(sql); recursos.add(prepStmt); prepStmt.executeQuery(); } }
92316b58fe67409a1196de383ef1bd9883a58140
5,561
java
Java
server/impl/src/main/java/com/walmartlabs/concord/server/org/project/RepositoryEntry.java
ekmixon/concord
0e9380258d525c20fdc1fc8b8543b6fc0e5293c2
[ "Apache-2.0" ]
158
2018-11-21T12:54:58.000Z
2022-03-27T01:43:03.000Z
server/impl/src/main/java/com/walmartlabs/concord/server/org/project/RepositoryEntry.java
ekmixon/concord
0e9380258d525c20fdc1fc8b8543b6fc0e5293c2
[ "Apache-2.0" ]
232
2018-12-11T20:34:30.000Z
2022-03-25T11:23:59.000Z
server/impl/src/main/java/com/walmartlabs/concord/server/org/project/RepositoryEntry.java
samqws-marketing/walmartlabs-concord
b9420f3b9e73a9d381266ece72f7afb756f35a76
[ "Apache-2.0" ]
91
2018-12-11T21:01:42.000Z
2022-03-24T04:46:14.000Z
28.228426
165
0.568243
995,833
package com.walmartlabs.concord.server.org.project; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2018 Walmart 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. * ===== */ import com.fasterxml.jackson.annotation.*; import com.walmartlabs.concord.common.validation.ConcordKey; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Map; import java.util.UUID; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class RepositoryEntry implements Serializable { private static final long serialVersionUID = 1L; private final UUID id; private final UUID projectId; @ConcordKey private final String name; @NotNull @Size(max = 2048) private final String url; @Size(max = 255) private final String branch; @Size(max = 64) private final String commitId; @Size(max = 2048) private final String path; private final UUID secretId; @ConcordKey @JsonAlias("secret") private final String secretName; private final String secretStoreType; private final boolean disabled; private final Map<String, Object> meta; private final boolean triggersDisabled; public RepositoryEntry(String name, String url) { this(null, null, name, url, null, null, null, false, null, null, null, null, false); } public RepositoryEntry(String name, RepositoryEntry e) { this(e.id, e.projectId, name, e.url, e.branch, e.commitId, e.path, e.disabled, e.getSecretId(), e.secretName, e.secretStoreType, e.meta, e.triggersDisabled); } public RepositoryEntry(RepositoryEntry e, String branch, String commitId) { this(e.id, e.projectId, e.name, e.url, branch, commitId, e.path, e.disabled, e.getSecretId(), e.secretName, e.secretStoreType, e.meta, e.triggersDisabled); } @JsonCreator public RepositoryEntry(@JsonProperty("id") UUID id, @JsonProperty("projectId") UUID projectId, @JsonProperty("name") String name, @JsonProperty("url") String url, @JsonProperty("branch") String branch, @JsonProperty("commitId") String commitId, @JsonProperty("path") String path, @JsonProperty("disabled") boolean disabled, @JsonProperty("secretId") UUID secretId, @JsonProperty("secretName") String secretName, @JsonProperty("secretStoreType") String secretStoreType, @JsonProperty("meta") Map<String, Object> meta, @JsonProperty("triggersDisabled") boolean triggersDisabled) { this.id = id; this.projectId = projectId; this.name = name; this.url = url; this.branch = branch; this.commitId = commitId; this.path = path; this.secretId = secretId; this.secretName = secretName; this.secretStoreType = secretStoreType; this.disabled = disabled; this.meta = meta; this.triggersDisabled = triggersDisabled; } public UUID getId() { return id; } public UUID getProjectId() { return projectId; } public String getName() { return name; } public String getUrl() { return url; } public String getBranch() { return branch; } public String getCommitId() { return commitId; } public String getPath() { return path; } public UUID getSecretId() { return secretId; } public String getSecretName() { return secretName; } public String getSecretStoreType() { return secretStoreType; } public boolean isDisabled() { return disabled; } public Map<String, Object> getMeta() { return meta; } public boolean isTriggersDisabled() { return triggersDisabled; } @Override public String toString() { return "RepositoryEntry{" + "id=" + id + ", projectId=" + projectId + ", name='" + name + '\'' + ", url='" + url + '\'' + ", branch='" + branch + '\'' + ", commitId='" + commitId + '\'' + ", path='" + path + '\'' + ", secretId=" + secretId + ", secretName='" + secretName + '\'' + ", secretStoreType='" + secretStoreType + '\'' + ", disabled=" + disabled + '\'' + ", meta=" + meta + '\'' + ", triggersDisabled=" + triggersDisabled + '}'; } }
92316b9abcad68d17d4933bf7084f0bef7b8340d
5,937
java
Java
src/twg2/parser/codeParser/extractors/CommentAndWhitespaceExtractor.java
TeamworkGuy2/JParserTools
16de37b3016a35668bb4f43a48342b05eb311a4b
[ "MIT" ]
2
2017-05-14T09:31:13.000Z
2021-05-15T09:57:45.000Z
src/twg2/parser/codeParser/extractors/CommentAndWhitespaceExtractor.java
TeamworkGuy2/JParserTools
16de37b3016a35668bb4f43a48342b05eb311a4b
[ "MIT" ]
null
null
null
src/twg2/parser/codeParser/extractors/CommentAndWhitespaceExtractor.java
TeamworkGuy2/JParserTools
16de37b3016a35668bb4f43a48342b05eb311a4b
[ "MIT" ]
null
null
null
45.320611
215
0.756948
995,834
package twg2.parser.codeParser.extractors; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import twg2.collections.dataStructures.PairList; import twg2.collections.primitiveCollections.IntArrayList; import twg2.collections.primitiveCollections.IntListSorted; import twg2.parser.codeParser.CommentStyle; import twg2.parser.codeParser.codeStats.ParsedFileStats; import twg2.parser.fragment.CodeToken; import twg2.parser.fragment.CodeTokenType; import twg2.parser.language.CodeLanguage; import twg2.parser.textFragment.TextFragmentRef; import twg2.parser.textFragment.TextTransformer; import twg2.parser.tokenizers.CodeStringTokenizer; import twg2.parser.tokenizers.CodeTokenizer; import twg2.parser.tokenizers.CommentTokenizer; import twg2.parser.workflow.CodeFileSrc; import twg2.text.stringUtils.StringCheck; import twg2.text.tokenizer.CharParserFactory; import twg2.treeLike.TreeTraversalOrder; import twg2.treeLike.TreeTraverse; import twg2.treeLike.parameters.SimpleTreeTraverseParameters; import twg2.treeLike.simpleTree.SimpleTree; /** * @author TeamworkGuy2 * @since 2015-9-19 */ public class CommentAndWhitespaceExtractor { public static CodeFileSrc buildCommentsAndWhitespaceTreeFromFileExtension(String srcName, String fileExtension, boolean reusable, char[] src, int srcOff, int srcLen) throws IOException { EnumSet<CommentStyle> commentStyle = CommentStyle.fromFileExtension(fileExtension); return buildCommentsAndWhitespaceTree(reusable, commentStyle, srcName, src, srcOff, srcLen); } public static CodeFileSrc buildCommentsAndWhitespaceTree(boolean reusable, EnumSet<CommentStyle> style, String srcName, char[] src, int srcOff, int srcLen) throws IOException { CharParserFactory stringParser = CodeStringTokenizer.createStringTokenizerForJavascript(reusable); CharParserFactory commentParser = CommentTokenizer.createCommentTokenizer(reusable, style); var parsers = new PairList<CharParserFactory, TextTransformer<CodeTokenType>>(); parsers.add(commentParser, CodeTokenizer.ofType(CodeTokenType.COMMENT)); parsers.add(stringParser, CodeTokenizer.ofType(CodeTokenType.STRING)); var parser = CodeTokenizer.createTokenizer((CodeLanguage)null, parsers); return parser.tokenizeDocument(src, srcOff, srcLen, srcName, null); } public static ParsedFileStats calcCommentsAndWhitespaceLinesTreeStats(String srcId, char[] src, int srcOff, int srcLen, IntListSorted lineStartOffsets, SimpleTree<CodeToken> tree) { // flatten the document tree into a nested list of tokens per source line of text var tokensPerLine = documentTreeToTokensPerLine(tree); // find lines containing only comments (with optional whitespace) IntArrayList commentLines = new IntArrayList(); IntArrayList whitespaceLines = new IntArrayList(); for(int i = 0, size = lineStartOffsets.size(); i < size; i++) { int startIndex = lineStartOffsets.get(i); int endIndexExclusive = i + 1 < size ? lineStartOffsets.get(i + 1) : srcLen; int lineLen = endIndexExclusive - startIndex; if(tokensPerLine.size() <= i) { tokensPerLine.add(new ArrayList<>()); } var lineTokens = tokensPerLine.get(i); // TODO performance of stream + lambda for every line if(lineTokens.size() > 0 && lineTokens.stream().allMatch((t) -> t.getTokenType() == CodeTokenType.COMMENT)) { if(lineTokens.size() > 1) { // TODO this was causing issues parsing a particular project that had a number of multiple-comments-per-line files //throw new RuntimeException("not implemented support for checking if a line is to exclusively comments when more than one comment appears on the line, lineNum=" + (i + 1) + ", srcId='" + srcId + "'"); } else { TextFragmentRef comment = lineTokens.get(0).getToken(); var prefixLen = comment.getOffsetStart() - startIndex; var noneOrWhitespacePrefix = comment.getLineStart() < i || StringCheck.isWhitespace(src, startIndex, prefixLen); // if the token started on a previous line, there is no prefix text before it starts on this line var suffixLen = endIndexExclusive - comment.getOffsetEnd(); var noneOrWhitespaceSuffix = comment.getLineEnd() > i || StringCheck.isWhitespace(src, comment.getOffsetEnd(), suffixLen); if(noneOrWhitespacePrefix && noneOrWhitespaceSuffix) { if(StringCheck.isWhitespace(src, startIndex, lineLen)) { whitespaceLines.add(i); } else { commentLines.add(i); } } } } else if(StringCheck.isWhitespace(src, startIndex, lineLen)) { whitespaceLines.add(i); } //System.out.println("line " + i + " tokens: " + lineTokens); } System.out.println("line count: " + lineStartOffsets.size()); System.out.println("line counts: whitespace=" + whitespaceLines.size() + ", comment=" + commentLines.size() + ", total=" + (whitespaceLines.size() + commentLines.size())); System.out.println("line numbers:\nwhitespace: " + whitespaceLines + "\ncomments: " + commentLines); return new ParsedFileStats(srcId, srcLen, whitespaceLines, commentLines, lineStartOffsets.size()); } public static List<List<CodeToken>> documentTreeToTokensPerLine(SimpleTree<CodeToken> tree) { // flatten the document tree into a nested list of tokens per source line of text var tokensPerLine = new ArrayList<List<CodeToken>>(); var treeTraverseParams = SimpleTreeTraverseParameters.of(tree, false, TreeTraversalOrder.PRE_ORDER) .setSkipRoot(true) .setConsumerSimpleTree((branch, index, size, depth, parentBranch) -> { int startLine = branch.getToken().getLineStart(); int endLine = branch.getToken().getLineEnd(); while(tokensPerLine.size() <= endLine) { tokensPerLine.add(new ArrayList<>()); } for(int i = startLine; i <= endLine; i++) { tokensPerLine.get(i).add(branch); } }); TreeTraverse.Indexed.traverse(treeTraverseParams); return tokensPerLine; } }
92316c299efe56b47050636d50d3911b4b01c9e9
13,511
java
Java
source_files/cloudsim/container/schedulers/ContainerCloudletSchedulerTimeShared.java
fnandom96/optacloud-tfg
65d0442a4dc15f7f50f95776cb6f01493ab9eec0
[ "Apache-2.0" ]
44
2021-02-05T12:15:53.000Z
2022-03-18T10:14:31.000Z
source_files/cloudsim/container/schedulers/ContainerCloudletSchedulerTimeShared.java
fnandom96/optacloud-tfg
65d0442a4dc15f7f50f95776cb6f01493ab9eec0
[ "Apache-2.0" ]
2
2021-02-07T01:43:39.000Z
2021-02-08T05:23:23.000Z
source_files/cloudsim/container/schedulers/ContainerCloudletSchedulerTimeShared.java
fnandom96/optacloud-tfg
65d0442a4dc15f7f50f95776cb6f01493ab9eec0
[ "Apache-2.0" ]
28
2021-02-07T01:27:49.000Z
2021-07-07T11:26:01.000Z
28.993562
128
0.585893
995,835
package org.cloudbus.cloudsim.container.schedulers; import org.cloudbus.cloudsim.Cloudlet; import org.cloudbus.cloudsim.Consts; import org.cloudbus.cloudsim.ResCloudlet; import org.cloudbus.cloudsim.core.CloudSim; import java.util.ArrayList; import java.util.List; /** * Created by sareh on 10/07/15. */ public class ContainerCloudletSchedulerTimeShared extends ContainerCloudletScheduler { /** * The current cp us. */ protected int currentCPUs; /** * Creates a new ContainerCloudletSchedulerTimeShared object. This method must be invoked before starting * the actual simulation. * * @pre $none * @post $none */ public ContainerCloudletSchedulerTimeShared() { super(); currentCPUs = 0; } /** * Updates the processing of cloudlets running under management of this scheduler. * * @param currentTime current simulation time * @param mipsShare array with MIPS share of each processor available to the scheduler * @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is * no next events * @pre currentTime >= 0 * @post $none */ @Override public double updateContainerProcessing(double currentTime, List<Double> mipsShare) { setCurrentMipsShare(mipsShare); double timeSpam = currentTime - getPreviousTime(); for (ResCloudlet rcl : getCloudletExecList()) { rcl.updateCloudletFinishedSoFar((long) (getCapacity(mipsShare) * timeSpam * rcl.getNumberOfPes() * Consts.MILLION)); } if (getCloudletExecList().size() == 0) { setPreviousTime(currentTime); return 0.0; } // check finished cloudlets double nextEvent = Double.MAX_VALUE; List<ResCloudlet> toRemove = new ArrayList<>(); for (ResCloudlet rcl : getCloudletExecList()) { long remainingLength = rcl.getRemainingCloudletLength(); if (remainingLength == 0) {// finished: remove from the list toRemove.add(rcl); cloudletFinish(rcl); } } getCloudletExecList().removeAll(toRemove); // estimate finish time of cloudlets for (ResCloudlet rcl : getCloudletExecList()) { double estimatedFinishTime = currentTime + (rcl.getRemainingCloudletLength() / (getCapacity(mipsShare) * rcl.getNumberOfPes())); if (estimatedFinishTime - currentTime < CloudSim.getMinTimeBetweenEvents()) { estimatedFinishTime = currentTime + CloudSim.getMinTimeBetweenEvents(); } if (estimatedFinishTime < nextEvent) { nextEvent = estimatedFinishTime; } } toRemove.clear(); setPreviousTime(currentTime); return nextEvent; } /** * Gets the capacity. * * @param mipsShare the mips share * @return the capacity */ protected double getCapacity(List<Double> mipsShare) { double capacity = 0.0; int cpus = 0; for (Double mips : mipsShare) { capacity += mips; if (mips > 0.0) { cpus++; } } currentCPUs = cpus; int pesInUse = 0; for (ResCloudlet rcl : getCloudletExecList()) { pesInUse += rcl.getNumberOfPes(); } if (pesInUse > currentCPUs) { capacity /= pesInUse; } else { capacity /= currentCPUs; } return capacity; } /** * Cancels execution of a cloudlet. * * @param cloudletId ID of the cloudlet being cancealed * @return the canceled cloudlet, $null if not found * @pre $none * @post $none */ @Override public Cloudlet cloudletCancel(int cloudletId) { boolean found = false; int position = 0; // First, looks in the finished queue found = false; for (ResCloudlet rcl : getCloudletFinishedList()) { if (rcl.getCloudletId() == cloudletId) { found = true; break; } position++; } if (found) { return getCloudletFinishedList().remove(position).getCloudlet(); } // Then searches in the exec list position = 0; for (ResCloudlet rcl : getCloudletExecList()) { if (rcl.getCloudletId() == cloudletId) { found = true; break; } position++; } if (found) { ResCloudlet rcl = getCloudletExecList().remove(position); if (rcl.getRemainingCloudletLength() == 0) { cloudletFinish(rcl); } else { rcl.setCloudletStatus(Cloudlet.CANCELED); } return rcl.getCloudlet(); } // Now, looks in the paused queue found = false; position = 0; for (ResCloudlet rcl : getCloudletPausedList()) { if (rcl.getCloudletId() == cloudletId) { found = true; rcl.setCloudletStatus(Cloudlet.CANCELED); break; } position++; } if (found) { return getCloudletPausedList().remove(position).getCloudlet(); } return null; } /** * Pauses execution of a cloudlet. * * @param cloudletId ID of the cloudlet being paused * @return $true if cloudlet paused, $false otherwise * @pre $none * @post $none */ @Override public boolean cloudletPause(int cloudletId) { boolean found = false; int position = 0; for (ResCloudlet rcl : getCloudletExecList()) { if (rcl.getCloudletId() == cloudletId) { found = true; break; } position++; } if (found) { // remove cloudlet from the exec list and put it in the paused list ResCloudlet rcl = getCloudletExecList().remove(position); if (rcl.getRemainingCloudletLength() == 0) { cloudletFinish(rcl); } else { rcl.setCloudletStatus(Cloudlet.PAUSED); getCloudletPausedList().add(rcl); } return true; } return false; } /** * Processes a finished cloudlet. * * @param rcl finished cloudlet * @pre rgl != $null * @post $none */ @Override public void cloudletFinish(ResCloudlet rcl) { rcl.setCloudletStatus(Cloudlet.SUCCESS); rcl.finalizeCloudlet(); getCloudletFinishedList().add(rcl); } /** * Resumes execution of a paused cloudlet. * * @param cloudletId ID of the cloudlet being resumed * @return expected finish time of the cloudlet, 0.0 if queued * @pre $none * @post $none */ @Override public double cloudletResume(int cloudletId) { boolean found = false; int position = 0; // look for the cloudlet in the paused list for (ResCloudlet rcl : getCloudletPausedList()) { if (rcl.getCloudletId() == cloudletId) { found = true; break; } position++; } if (found) { ResCloudlet rgl = getCloudletPausedList().remove(position); rgl.setCloudletStatus(Cloudlet.INEXEC); getCloudletExecList().add(rgl); // calculate the expected time for cloudlet completion // first: how many PEs do we have? double remainingLength = rgl.getRemainingCloudletLength(); double estimatedFinishTime = CloudSim.clock() + (remainingLength / (getCapacity(getCurrentMipsShare()) * rgl.getNumberOfPes())); return estimatedFinishTime; } return 0.0; } /** * Receives an cloudlet to be executed in the VM managed by this scheduler. * * @param cloudlet the submited cloudlet * @param fileTransferTime time required to move the required files from the SAN to the VM * @return expected finish time of this cloudlet * @pre gl != null * @post $none */ @Override public double cloudletSubmit(Cloudlet cloudlet, double fileTransferTime) { ResCloudlet rcl = new ResCloudlet(cloudlet); rcl.setCloudletStatus(Cloudlet.INEXEC); for (int i = 0; i < cloudlet.getNumberOfPes(); i++) { rcl.setMachineAndPeId(0, i); } getCloudletExecList().add(rcl); // use the current capacity to estimate the extra amount of // time to file transferring. It must be added to the cloudlet length double extraSize = getCapacity(getCurrentMipsShare()) * fileTransferTime; long length = (long) (cloudlet.getCloudletLength() + extraSize); cloudlet.setCloudletLength(length); return cloudlet.getCloudletLength() / getCapacity(getCurrentMipsShare()); } /* * (non-Javadoc) * @see cloudsim.CloudletScheduler#cloudletSubmit(cloudsim.Cloudlet) */ @Override public double cloudletSubmit(Cloudlet cloudlet) { return cloudletSubmit(cloudlet, 0.0); } /** * Gets the status of a cloudlet. * * @param cloudletId ID of the cloudlet * @return status of the cloudlet, -1 if cloudlet not found * @pre $none * @post $none */ @Override public int getCloudletStatus(int cloudletId) { for (ResCloudlet rcl : getCloudletExecList()) { if (rcl.getCloudletId() == cloudletId) { return rcl.getCloudletStatus(); } } for (ResCloudlet rcl : getCloudletPausedList()) { if (rcl.getCloudletId() == cloudletId) { return rcl.getCloudletStatus(); } } return -1; } /** * Get utilization created by all cloudlets. * * @param time the time * @return total utilization */ @Override public double getTotalUtilizationOfCpu(double time) { double totalUtilization = 0; for (ResCloudlet gl : getCloudletExecList()) { totalUtilization += gl.getCloudlet().getUtilizationOfCpu(time); } return totalUtilization; } /** * Informs about completion of some cloudlet in the VM managed by this scheduler. * * @return $true if there is at least one finished cloudlet; $false otherwise * @pre $none * @post $none */ @Override public boolean isFinishedCloudlets() { return getCloudletFinishedList().size() > 0; } /** * Returns the next cloudlet in the finished list, $null if this list is empty. * * @return a finished cloudlet * @pre $none * @post $none */ @Override public Cloudlet getNextFinishedCloudlet() { if (getCloudletFinishedList().size() > 0) { return getCloudletFinishedList().remove(0).getCloudlet(); } return null; } /** * Returns the number of cloudlets runnning in the virtual machine. * * @return number of cloudlets runnning * @pre $none * @post $none */ @Override public int runningCloudlets() { return getCloudletExecList().size(); } /** * Returns one cloudlet to migrate to another vm. * * @return one running cloudlet * @pre $none * @post $none */ @Override public Cloudlet migrateCloudlet() { ResCloudlet rgl = getCloudletExecList().remove(0); rgl.finalizeCloudlet(); return rgl.getCloudlet(); } /* * (non-Javadoc) * @see cloudsim.CloudletScheduler#getCurrentRequestedMips() */ @Override public List<Double> getCurrentRequestedMips() { return new ArrayList<>(); } /* * (non-Javadoc) * @see cloudsim.CloudletScheduler#getTotalCurrentAvailableMipsForCloudlet(cloudsim.ResCloudlet, * java.util.List) */ @Override public double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare) { return getCapacity(getCurrentMipsShare()); } /* * (non-Javadoc) * @see cloudsim.CloudletScheduler#getTotalCurrentAllocatedMipsForCloudlet(cloudsim.ResCloudlet, * double) */ @Override public double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time) { return 0.0; } /* * (non-Javadoc) * @see cloudsim.CloudletScheduler#getTotalCurrentRequestedMipsForCloudlet(cloudsim.ResCloudlet, * double) */ @Override public double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time) { // TODO Auto-generated method stub return 0.0; } @Override public double getCurrentRequestedUtilizationOfRam() { double ram = 0; for (ResCloudlet cloudlet : cloudletExecList) { ram += cloudlet.getCloudlet().getUtilizationOfRam(CloudSim.clock()); } return ram; } @Override public double getCurrentRequestedUtilizationOfBw() { double bw = 0; for (ResCloudlet cloudlet : cloudletExecList) { bw += cloudlet.getCloudlet().getUtilizationOfBw(CloudSim.clock()); } return bw; } }
92316d9551158527abba223bb44a5a906d164c33
690
java
Java
src/main/java/com/jspxcms/core/repository/InfoAttributeDao.java
11676670/webmanager
b15baa51ed57d4b32a8e417f2d28c06108c06069
[ "MIT" ]
null
null
null
src/main/java/com/jspxcms/core/repository/InfoAttributeDao.java
11676670/webmanager
b15baa51ed57d4b32a8e417f2d28c06108c06069
[ "MIT" ]
null
null
null
src/main/java/com/jspxcms/core/repository/InfoAttributeDao.java
11676670/webmanager
b15baa51ed57d4b32a8e417f2d28c06108c06069
[ "MIT" ]
null
null
null
27.6
87
0.750725
995,836
package com.jspxcms.core.repository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import com.jspxcms.core.domain.InfoAttribute; import com.jspxcms.core.domain.InfoAttribute.InfoAttributeId; /** * InfoAttributeDao * * @author liufang * */ public interface InfoAttributeDao extends Repository<InfoAttribute, InfoAttributeId> { public InfoAttribute findOne(InfoAttributeId id); // -------------------- @Modifying @Query("delete from InfoAttribute t where t.attribute.id=?1") public int deleteByAttributeId(Integer attributeId); }
92316ea5245765666759795b258cfeaff42debcf
843
java
Java
grok-v107/src/ca/uwaterloo/cs/jgrok/interp/SyntaxTreeNode.java
makbn/eval-runner-docker
ed5650a3fe1c7d1c9a6d698608cb125d4aafd9dc
[ "Apache-2.0" ]
2
2021-06-03T14:27:27.000Z
2021-06-03T20:15:02.000Z
grok-v107/src/ca/uwaterloo/cs/jgrok/interp/SyntaxTreeNode.java
makbn/eval-runner-docker
ed5650a3fe1c7d1c9a6d698608cb125d4aafd9dc
[ "Apache-2.0" ]
null
null
null
grok-v107/src/ca/uwaterloo/cs/jgrok/interp/SyntaxTreeNode.java
makbn/eval-runner-docker
ed5650a3fe1c7d1c9a6d698608cb125d4aafd9dc
[ "Apache-2.0" ]
3
2021-06-03T20:14:29.000Z
2021-11-23T07:51:19.000Z
22.184211
59
0.628707
995,837
package ca.uwaterloo.cs.jgrok.interp; import ca.uwaterloo.cs.jgrok.env.Env; public abstract class SyntaxTreeNode { protected Location location; protected boolean evaluated; public SyntaxTreeNode() { location = null; evaluated = false; } public String strLocation() { if(location == null) return ""; else return location.toString(); } public Location getLocation() { return location; } public void setLocation(Location l) { this.location = l; } public void accept(SyntaxTreeNodeVisitor visitor) { visitor.visit(this); } public abstract void propagate(Env env, Object userObj) throws EvaluationException; public abstract Value evaluate(Env env) throws EvaluationException; }
92316ee39979e9ca4b2796ba1ba7a9108834c7ec
1,809
java
Java
src/main/java/org/gr1m/mc/mup/bugfix/mc83039/mixin/MixinTemplateManager.java
embeddedt/MUP
6f317818401c3c38b48b7c882dea69da623c38d9
[ "MIT" ]
41
2018-08-20T15:34:43.000Z
2022-01-14T08:13:21.000Z
src/main/java/org/gr1m/mc/mup/bugfix/mc83039/mixin/MixinTemplateManager.java
embeddedt/MUP
6f317818401c3c38b48b7c882dea69da623c38d9
[ "MIT" ]
26
2018-06-27T20:45:20.000Z
2022-03-23T17:47:11.000Z
src/main/java/org/gr1m/mc/mup/bugfix/mc83039/mixin/MixinTemplateManager.java
DeadlyMC/MUP
44eb1d2b68a0adfb2ecede4398e000f07993ece1
[ "MIT" ]
12
2018-06-17T23:21:49.000Z
2022-01-22T09:52:46.000Z
34.132075
112
0.630182
995,838
package org.gr1m.mc.mup.bugfix.mc83039.mixin; import net.minecraft.util.ResourceLocation; import net.minecraft.world.gen.structure.template.TemplateManager; import org.apache.commons.io.IOUtils; import org.gr1m.mc.mup.Mup; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.io.IOException; import java.io.InputStream; @Mixin(TemplateManager.class) public abstract class MixinTemplateManager { @Shadow protected abstract void readTemplateFromStream(String id, InputStream stream) throws IOException; // This is one ugly damn hack, but generalizing this would be overkill @Inject(method = "readTemplateFromJar", at = @At("HEAD"), cancellable = true) private void mc83039Override(ResourceLocation id, CallbackInfoReturnable<Boolean> cir) { if (id.getNamespace().equals("minecraft") && id.getPath().equals("endcity/tower_base")) { String s1 = id.getPath(); InputStream inputstream = null; boolean flag; try { inputstream = Mup.class.getResourceAsStream("/assets/mup/structures/overrides/" + s1 + ".nbt"); this.readTemplateFromStream(s1, inputstream); cir.setReturnValue(true); return; } catch (Throwable var10) { flag = false; } finally { IOUtils.closeQuietly(inputstream); } cir.setReturnValue(flag); } } }
92316fecaa01aa5ecc4937805d1ee6022ce72b99
1,743
java
Java
persistence/src/main/java/co/adun/mvnejb3jpa/persistence/eao/impl/MissionCodeUserEaoImpl.java
mikheladun/mvn-ejb3-jpa
38b70bd70b6ba1af57c7d28485ed0ee691224c3a
[ "Apache-2.0" ]
null
null
null
persistence/src/main/java/co/adun/mvnejb3jpa/persistence/eao/impl/MissionCodeUserEaoImpl.java
mikheladun/mvn-ejb3-jpa
38b70bd70b6ba1af57c7d28485ed0ee691224c3a
[ "Apache-2.0" ]
null
null
null
persistence/src/main/java/co/adun/mvnejb3jpa/persistence/eao/impl/MissionCodeUserEaoImpl.java
mikheladun/mvn-ejb3-jpa
38b70bd70b6ba1af57c7d28485ed0ee691224c3a
[ "Apache-2.0" ]
null
null
null
37.085106
181
0.776822
995,839
package co.adun.mvnejb3jpa.persistence.eao.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.ejb.Stateless; import org.hibernate.Query; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import co.adun.mvnejb3jpa.persistence.CustomSortField; import co.adun.mvnejb3jpa.persistence.eao.MissionCodeUserEao; import co.adun.mvnejb3jpa.persistence.entity.MissionCodeUser; /** * A entity access object class to provide persistent storage functions and CRUD operations for Member entity. Strongly-typed interface created since it could be used by @Autowired * * @author Mikhel Adun */ @Component @Stateless @Transactional public class MissionCodeUserEaoImpl extends BaseEaoImpl<MissionCodeUser> implements MissionCodeUserEao { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(MissionCodeEaoImpl.class.getName()); private static final String HQL_ALL_USERS = "FROM MissionCodeUser m JOIN FETCH m.ltUserByLtUserId u JOIN FETCH u.userRoleCode ORDER BY m.missionCode.description"; @Override public Class<MissionCodeUser> getEntityClass() { return MissionCodeUser.class; } @Override public List<MissionCodeUser> findAllUsers() { // set the column that needs to be sorted from the DB List<CustomSortField> sortFields = new ArrayList<CustomSortField>(); sortFields.add(new CustomSortField("missionCode", CustomSortField.ASCENDING)); Query query = this.createHqlQuery(HQL_ALL_USERS); List<MissionCodeUser> missionCodeUsers = (List<MissionCodeUser>) this.executeQuery(query); return missionCodeUsers; } }
923170315fb66b6e559f18036320c6681eb9c180
1,399
java
Java
Mage.Sets/src/mage/cards/t/TangleAngler.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/t/TangleAngler.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/t/TangleAngler.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
29.765957
138
0.736955
995,840
package mage.cards.t; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.combat.MustBeBlockedByTargetSourceEffect; import mage.abilities.keyword.InfectAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import mage.target.common.TargetCreaturePermanent; /** * * @author BetaSteward_at_googlemail.com */ public final class TangleAngler extends CardImpl { public TangleAngler(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{G}"); this.subtype.add(SubType.PHYREXIAN); this.subtype.add(SubType.HORROR); this.power = new MageInt(1); this.toughness = new MageInt(5); this.addAbility(InfectAbility.getInstance()); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new MustBeBlockedByTargetSourceEffect(), new ManaCostsImpl("{G}")); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); } private TangleAngler(final TangleAngler card) { super(card); } @Override public TangleAngler copy() { return new TangleAngler(this); } }
923170c5ca73171d658efeb688bb405cf52398c1
563
java
Java
Basics/AntAlgo/src/com/shiz/Main.java
cppshizoidS/Java
f842ac3988fef957b801dd58e64168ee66e39eb5
[ "Apache-2.0" ]
1
2022-03-22T08:07:26.000Z
2022-03-22T08:07:26.000Z
Basics/AntAlgo/src/com/shiz/Main.java
cppshizoidS/Java
f842ac3988fef957b801dd58e64168ee66e39eb5
[ "Apache-2.0" ]
null
null
null
Basics/AntAlgo/src/com/shiz/Main.java
cppshizoidS/Java
f842ac3988fef957b801dd58e64168ee66e39eb5
[ "Apache-2.0" ]
null
null
null
31.277778
95
0.660746
995,841
package com.shiz; import com.shiz.pathFindingAlgorithm.antAlgorithm.AntAlgorithm; public class Main { public static void main(String[] args) { final int[][] matrixOfDistance = MatrixDistanceGenerator.generate(150); // Arrays.stream(matrixOfDistance).forEach(e -> System.out.println(Arrays.toString(e))); final int[] shortestDistance = new AntAlgorithm(matrixOfDistance).getPath(); System.out.println("Path: "); for (int number : shortestDistance) { System.out.print(number + 1 + "->"); } } }
923170ce8e9a65212e16c14d9b86d18001703fb2
1,478
java
Java
libraries/controlP5/src/controlP5/ChartDataSet.java
snap10/processing-bouncing-circle-eq
143930f3a4471de9c635bc66476a0e22816dee84
[ "CC0-1.0" ]
287
2015-01-15T08:14:36.000Z
2022-02-17T02:50:39.000Z
libraries/controlP5/src/controlP5/ChartDataSet.java
snap10/processing-bouncing-circle-eq
143930f3a4471de9c635bc66476a0e22816dee84
[ "CC0-1.0" ]
95
2015-01-01T12:26:10.000Z
2022-01-31T13:00:52.000Z
libraries/controlP5/src/controlP5/ChartDataSet.java
snap10/processing-bouncing-circle-eq
143930f3a4471de9c635bc66476a0e22816dee84
[ "CC0-1.0" ]
156
2015-01-06T12:28:30.000Z
2022-03-25T05:50:57.000Z
18.02439
92
0.686739
995,842
package controlP5; import java.util.ArrayList; import java.util.ListIterator; import processing.core.PApplet; import processing.core.PGraphics; /** * Used by Chart, a chart data set is a container to store chart data. */ @SuppressWarnings("serial") public class ChartDataSet extends ArrayList<ChartData> { protected CColor _myColor; protected float _myStrokeWeight = 1; protected int[] colors = new int[0]; protected final String _myName; public ChartDataSet(String theName) { _myName = theName; _myColor = new CColor(); } public CColor getColor() { return _myColor; } public ChartDataSet setColors(int... theColors) { colors = theColors; return this; } public int[] getColors() { return colors; } public int getColor(int theIndex) { if (colors.length == 0) { return getColor().getForeground(); } if (colors.length == 2) { return PGraphics.lerpColor(colors[0], colors[1], theIndex / (float) size(), PApplet.RGB); } if (theIndex >= 0 && theIndex < colors.length) { return colors[theIndex]; } return getColor(0); } public ChartDataSet setStrokeWeight(float theStrokeWeight) { _myStrokeWeight = theStrokeWeight; return this; } public float getStrokeWeight() { return _myStrokeWeight; } public float[] getValues() { float[] v = new float[size()]; int n = 0; ListIterator<ChartData> litr = listIterator(); while (litr.hasNext()) { v[n++] = litr.next().getValue(); } return v; } }
9231714abd23aebff07b81ce2c6fa5ba2f1ffd1c
11,936
java
Java
src/projeto/gui/telas/TelaChangePassword.java
daienemelo/ClinicaVeterinaria
962e39bf9de0e9201e01c50dde9801e5e22d6894
[ "MIT" ]
2
2019-06-02T17:35:59.000Z
2021-10-04T16:34:08.000Z
src/projeto/gui/telas/TelaChangePassword.java
daienemelo/ClinicaVeterinaria
962e39bf9de0e9201e01c50dde9801e5e22d6894
[ "MIT" ]
null
null
null
src/projeto/gui/telas/TelaChangePassword.java
daienemelo/ClinicaVeterinaria
962e39bf9de0e9201e01c50dde9801e5e22d6894
[ "MIT" ]
1
2021-02-21T18:48:29.000Z
2021-02-21T18:48:29.000Z
50.362869
169
0.649129
995,843
/* * 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 projeto.gui.telas; import java.util.logging.Level; import java.util.logging.Logger; import projeto.erro.AutenticacaoException; import projeto.erro.ConexaoException; import projeto.erro.DaoException; import projeto.negocio.fachada.FachadaAutenticacao; import projeto.util.Msg; /** * * @author Mario */ public class TelaChangePassword extends javax.swing.JFrame { public static String cpfCli; /** * Creates new form NewJFrame * @param cpfCli */ public TelaChangePassword(String cpfCli) { initComponents(); this.cpfCli = cpfCli; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtAlterarSenha = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); txtOldPassword = new javax.swing.JPasswordField(); txtNewPassword = new javax.swing.JPasswordField(); txtConfirmPass = new javax.swing.JPasswordField(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setBackground(new java.awt.Color(51, 51, 255)); jPanel1.setBackground(new java.awt.Color(0, 102, 204)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel4.setText("New Password :"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setText("Confirm Password :"); txtAlterarSenha.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projeto/gui/icones/salvar_1.png"))); // NOI18N txtAlterarSenha.setText("Alterar a senha"); txtAlterarSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtAlterarSenhaActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setText("Old Password :"); txtConfirmPass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtConfirmPassActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(132, 132, 132) .addComponent(txtAlterarSenha)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(70, 70, 70) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtNewPassword, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtOldPassword, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtConfirmPass, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtOldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(txtNewPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtConfirmPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addComponent(txtAlterarSenha) .addGap(37, 37, 37)) ); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Alterar as Credenciais"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(85, 85, 85) .addComponent(jLabel1) .addContainerGap(57, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtAlterarSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAlterarSenhaActionPerformed String oldPassp = String.valueOf(txtOldPassword.getPassword()); String newPass = String.valueOf(txtNewPassword.getPassword()); String confirmPass = String.valueOf(txtConfirmPass.getPassword()); FachadaAutenticacao fachada = new FachadaAutenticacao(); try { if(newPass.equals(confirmPass)){ fachada.alterarSenha(oldPassp, newPass, cpfCli); new TelaPrincipal(cpfCli).setVisible(true); } } catch (AutenticacaoException ex) { Msg.msgErro("Erro ao alterar a senha!", "Erro ao alterar"); } catch (ConexaoException ex) { Msg.msgErro("Erro ao alterar a senha!", "Erro de Conexão ao banco!"); } catch (DaoException ex) { Msg.msgErro("Erro ao alterar a senha!", "Erro de SQL"); } }//GEN-LAST:event_txtAlterarSenhaActionPerformed private void txtConfirmPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtConfirmPassActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtConfirmPassActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaChangePassword.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaChangePassword.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaChangePassword.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaChangePassword.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new TelaChangePassword(cpfCli).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JButton txtAlterarSenha; private javax.swing.JPasswordField txtConfirmPass; private javax.swing.JPasswordField txtNewPassword; private javax.swing.JPasswordField txtOldPassword; // End of variables declaration//GEN-END:variables }
92317340fd07d5cba21ce1d50d2bc69ce6364cb3
1,877
java
Java
host-connector/src/test/java/com/intel/mtwilson/core/host/connector/HostConnectorFactoryTest.java
intel-secl/lib-host-connector
55ccf41f91346811ea499a29466636b8dae0ccbf
[ "BSD-3-Clause" ]
1
2019-07-04T06:43:42.000Z
2019-07-04T06:43:42.000Z
host-connector/src/test/java/com/intel/mtwilson/core/host/connector/HostConnectorFactoryTest.java
intel-secl/lib-host-connector
55ccf41f91346811ea499a29466636b8dae0ccbf
[ "BSD-3-Clause" ]
null
null
null
host-connector/src/test/java/com/intel/mtwilson/core/host/connector/HostConnectorFactoryTest.java
intel-secl/lib-host-connector
55ccf41f91346811ea499a29466636b8dae0ccbf
[ "BSD-3-Clause" ]
1
2019-07-04T06:43:45.000Z
2019-07-04T06:43:45.000Z
34.127273
154
0.748002
995,844
/* * Copyright (C) 2019 Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ package com.intel.mtwilson.core.host.connector; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.intel.mtwilson.jaxrs2.provider.JacksonObjectMapperProvider; import com.intel.mtwilson.core.common.model.HostManifest; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Use this class to instantiate the appropriate connector or client for a given * host. * @throws UnuspportedOperationException if the appropriate agent type cannot be determined from the given host * @author zaaquino */ public class HostConnectorFactoryTest { private static final Logger log = LoggerFactory.getLogger(HostConnectorFactoryTest.class); private final ObjectMapper mapper = JacksonObjectMapperProvider.createDefaultMapper(); @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void serializeHostManifest() throws Exception { String hostManifestAsJson = Resources.toString(Resources.getResource("host-manifest-rhel-tpm2.json"), Charsets.UTF_8); HostManifest hostManifest = mapper.readValue(hostManifestAsJson, HostManifest.class); System.out.println(String.format("Successfully deserialized file to host manifest with host name: %s", hostManifest.getHostInfo().getHostName())); System.out.println(String.format("Serialized host manifest:\n%s", mapper.writeValueAsString(hostManifest))); } }
92317362c61404b9fe4832aa47442233a3bdc0d3
2,967
java
Java
Java/Java Examples/JDBCTComplexExampleStarter/src/main/java/com/sg/jdbctcomplexexample/dao/RoomDaoDB.java
NacerSebtiMS/Mthree-Bootcamp-Java
a364912a171ce4d60463e08f444aa31d2132ba4a
[ "MIT" ]
1
2020-12-08T22:18:55.000Z
2020-12-08T22:18:55.000Z
Java/Java Examples/JDBCTComplexExampleStarter/src/main/java/com/sg/jdbctcomplexexample/dao/RoomDaoDB.java
NacerSebtiMS/Mthree-Bootcamp-Java
a364912a171ce4d60463e08f444aa31d2132ba4a
[ "MIT" ]
null
null
null
Java/Java Examples/JDBCTComplexExampleStarter/src/main/java/com/sg/jdbctcomplexexample/dao/RoomDaoDB.java
NacerSebtiMS/Mthree-Bootcamp-Java
a364912a171ce4d60463e08f444aa31d2132ba4a
[ "MIT" ]
null
null
null
31.903226
94
0.644422
995,845
/* * 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.sg.jdbctcomplexexample.dao; import com.sg.jdbctcomplexexample.entity.Room; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author nacer */ @Repository public class RoomDaoDB implements RoomDao { @Autowired JdbcTemplate jdbc; @Override public List<Room> getAllRooms() { final String SELECT_ALL_ROOMS = "SELECT * FROM room"; return jdbc.query(SELECT_ALL_ROOMS, new RoomMapper()); } @Override public Room getRoomById(int id) { try { final String SELECT_ROOM_BY_ID = "SELECT * FROM room WHERE id = ?"; return jdbc.queryForObject(SELECT_ROOM_BY_ID, new RoomMapper(), id); } catch(DataAccessException ex) { return null; } } @Override @Transactional public Room addRoom(Room room) { final String INSERT_ROOM = "INSERT INTO room(name, description) VALUES(?,?)"; jdbc.update(INSERT_ROOM, room.getName(), room.getDescription()); int newId = jdbc.queryForObject("SELECT LAST_INSERT_ID()", Integer.class); room.setId(newId); return room; } @Override public void updateRoom(Room room) { final String UPDATE_ROOM = "UPDATE room SET name = ?, description = ? WHERE id = ?"; jdbc.update(UPDATE_ROOM, room.getName(), room.getDescription(), room.getId()); } @Override @Transactional public void deleteRoomById(int id) { final String DELETE_MEETING_EMPLOYEE_BY_ROOM = "DELETE me.* FROM meeting_employee me " + "JOIN meeting m ON me.meetingId = m.id WHERE m.roomId = ?"; jdbc.update(DELETE_MEETING_EMPLOYEE_BY_ROOM, id); final String DELETE_MEETING_BY_ROOM = "DELETE FROM meeting WHERE roomId = ?"; jdbc.update(DELETE_MEETING_BY_ROOM, id); final String DELETE_ROOM = "DELETE FROM room WHERE id = ?"; jdbc.update(DELETE_ROOM, id); } public static final class RoomMapper implements RowMapper<Room> { @Override public Room mapRow(ResultSet rs, int index) throws SQLException { Room rm = new Room(); rm.setId(rs.getInt("id")); rm.setName(rs.getString("name")); rm.setDescription(rs.getString("description")); return rm; } } }
92317372e98ad08cb0b62bcf1c9625dfb6af0151
711
java
Java
app/src/main/java/com/cd/igitandroid/ui/test/TestingActivity.java
CrazyDudo/iGitAndroid
6c03f702b7a09ba530e30be1aa92bda3cdb9d2bb
[ "Apache-2.0" ]
1
2019-10-25T07:42:15.000Z
2019-10-25T07:42:15.000Z
app/src/main/java/com/cd/igitandroid/ui/test/TestingActivity.java
CrazyDudo/iGitAndroid
6c03f702b7a09ba530e30be1aa92bda3cdb9d2bb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/cd/igitandroid/ui/test/TestingActivity.java
CrazyDudo/iGitAndroid
6c03f702b7a09ba530e30be1aa92bda3cdb9d2bb
[ "Apache-2.0" ]
1
2019-10-25T03:49:55.000Z
2019-10-25T03:49:55.000Z
30.913043
84
0.739803
995,846
package com.cd.igitandroid.ui.test; import android.os.Bundle; import com.cd.igitandroid.R; import com.mukesh.MarkdownView; import androidx.appcompat.app.AppCompatActivity; public class TestingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_testing); MarkdownView markdownView = (MarkdownView) findViewById(R.id.markdown_view); markdownView.loadMarkdownFromAssets("README.md"); /* markdownView.setMarkDownText("# Hello World\nThis is a simple markdown\n" + "https://github.com/mukeshsolanki/MarkdownView-Android/");*/ } }
923173c98ea67b83692f19af43467be9747a7340
52,209
java
Java
apps/workflow/ofoverlay/app/src/main/java/org/onosproject/ofoverlay/impl/Ovs.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
apps/workflow/ofoverlay/app/src/main/java/org/onosproject/ofoverlay/impl/Ovs.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
apps/workflow/ofoverlay/app/src/main/java/org/onosproject/ofoverlay/impl/Ovs.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
39.642369
118
0.605164
995,847
/* * Copyright 2019-present Open Networking Foundation * * 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.onosproject.ofoverlay.impl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.onlab.packet.Ip4Address; import org.onlab.packet.Ip6Address; import org.onlab.packet.IpAddress; import org.onlab.packet.TpPort; import org.onosproject.cluster.ClusterService; import org.onosproject.event.Event; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.Port; import org.onosproject.net.behaviour.BridgeConfig; import org.onosproject.net.behaviour.BridgeDescription; import org.onosproject.net.behaviour.BridgeName; import org.onosproject.net.behaviour.ControlProtocolVersion; import org.onosproject.net.behaviour.ControllerInfo; import org.onosproject.net.behaviour.DefaultBridgeDescription; import org.onosproject.net.behaviour.DefaultTunnelDescription; import org.onosproject.net.behaviour.InterfaceConfig; import org.onosproject.net.behaviour.TunnelDescription; import org.onosproject.net.behaviour.TunnelEndPoints; import org.onosproject.net.behaviour.TunnelKeys; import org.onosproject.net.device.DeviceAdminService; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceService; import org.onosproject.net.driver.Behaviour; import org.onosproject.net.driver.DriverHandler; import org.onosproject.net.driver.DriverService; import org.onosproject.ofoverlay.impl.util.NetworkAddress; import org.onosproject.ofoverlay.impl.util.OvsDatapathType; import org.onosproject.ofoverlay.impl.util.OvsVersion; import org.onosproject.ofoverlay.impl.util.SshUtil; import org.onosproject.ovsdb.controller.OvsdbClientService; import org.onosproject.ovsdb.controller.OvsdbController; import org.onosproject.ovsdb.controller.OvsdbNodeId; import org.onosproject.workflow.api.AbstractWorklet; import org.onosproject.workflow.api.JsonDataModel; import org.onosproject.workflow.api.WorkflowContext; import org.onosproject.workflow.api.WorkflowException; import org.onosproject.workflow.api.StaticDataModel; import org.onosproject.workflow.model.accessinfo.SshAccessInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static org.onosproject.net.AnnotationKeys.PORT_NAME; import static org.onosproject.workflow.api.CheckCondition.check; /** * Class for defining OVS workflows. */ public final class Ovs { private static final Logger log = LoggerFactory.getLogger(Ovs.class); private static final String MODEL_MGMT_IP = "/mgmtIp"; private static final String BRIDGE_NAME = "/bridgeName"; private static final String MODEL_OVSDB_PORT = "/ovsdbPort"; private static final String MODEL_OVS_VERSION = "/ovsVersion"; private static final String MODEL_OVS_DATAPATH_TYPE = "/ovsDatapathType"; private static final String MODEL_SSH_ACCESSINFO = "/sshAccessInfo"; private static final String MODEL_OF_DEVID_BRIDGE = "/ofDevId"; private static final String MODEL_OF_DEVID_FOR_OVERLAY_UNDERLAY_BRIDGE = "/ofDevIdBrIntBrPhy"; private static final String MODEL_PHY_PORTS = "/physicalPorts"; private static final String MODEL_VTEP_IP = "/vtepIp"; private static final String BRIDGE_OVERLAY = "br-int"; private static final String BRIDGE_UNDERLAY = "br-phy"; private static final int DEVID_IDX_BRIDGE_OVERLAY = 0; private static final int DEVID_IDX_BRIDGE_UNDERLAY_NOVA = 1; private static final ControlProtocolVersion BRIDGE_DEFAULT_OF_VERSION = ControlProtocolVersion.OF_1_3; private static final int OPENFLOW_PORT = 6653; private static final String OPENFLOW_CHANNEL_PROTO = "tcp"; private static final String OVSDB_DEVICE_PREFIX = "ovsdb:"; private static final long TIMEOUT_DEVICE_CREATION_MS = 60000L; private static final long TIMEOUT_PORT_ADDITION_MS = 120000L; /** * Utility class for OVS workflow. */ public static final class OvsUtil { private OvsUtil() { } private static final String OPENFLOW_DEVID_FORMAT = "of:%08x%08x"; /** * Builds Open-flow device id with ip address, and index. * * @param addr ip address * @param index index * @return created device id */ public static DeviceId buildOfDeviceId(IpAddress addr, int index) { if (addr.isIp4()) { Ip4Address v4Addr = addr.getIp4Address(); return DeviceId.deviceId(String.format(OPENFLOW_DEVID_FORMAT, v4Addr.toInt(), index)); } else if (addr.isIp6()) { Ip6Address v6Addr = addr.getIp6Address(); return DeviceId.deviceId(String.format(OPENFLOW_DEVID_FORMAT, v6Addr.hashCode(), index)); } else { return DeviceId.deviceId(String.format(OPENFLOW_DEVID_FORMAT, addr.hashCode(), index)); } } /** * Builds OVS data path type. * * @param strOvsDatapathType string ovs data path type * @return ovs data path type * @throws WorkflowException workflow exception */ public static final OvsDatapathType buildOvsDatapathType(String strOvsDatapathType) throws WorkflowException { try { return OvsDatapathType.valueOf(strOvsDatapathType.toUpperCase()); } catch (IllegalArgumentException e) { throw new WorkflowException(e); } } /** * Gets OVSDB behavior. * * @param context workflow context * @param mgmtIp management ip * @param behaviourClass behavior class * @param <T> behavior class * @return OVSDB behavior * @throws WorkflowException workflow exception */ public static final <T extends Behaviour> T getOvsdbBehaviour(WorkflowContext context, String mgmtIp, Class<T> behaviourClass) throws WorkflowException { DriverService driverService = context.getService(DriverService.class); DeviceId devId = ovsdbDeviceId(mgmtIp); DriverHandler handler = driverService.createHandler(devId); if (Objects.isNull(handler)) { throw new WorkflowException("Failed to get DriverHandler for " + devId); } T behaviour; try { behaviour = handler.behaviour(behaviourClass); if (Objects.isNull(behaviour)) { throw new WorkflowException("Failed to get " + behaviourClass + " for " + devId + "-" + handler); } } catch (IllegalArgumentException e) { throw new WorkflowException("Failed to get " + behaviourClass + " for " + devId + "-" + handler); } return behaviour; } /** * Gets bridge description. * * @param bridgeConfig bridge config * @param bridgeName bridge name * @return bridge description optional */ public static final Optional<BridgeDescription> getBridgeDescription(BridgeConfig bridgeConfig, String bridgeName) { try { Collection<BridgeDescription> bridges = bridgeConfig.getBridges(); for (BridgeDescription br : bridges) { if (Objects.equals(bridgeName, br.name())) { return Optional.of(br); } } } catch (Exception e) { log.error("Exception : ", e); } return Optional.empty(); } public static BridgeDescription getBridgeNames(BridgeConfig bridgeConfig) { Collection<BridgeDescription> bridges = bridgeConfig.getBridges(); if (bridges.size() > 0) { for (BridgeDescription description : bridges) { return description; } } return null; } /** * Builds OVSDB device id. * * @param mgmtIp management ip address string * @return OVSDB device id */ public static final DeviceId ovsdbDeviceId(String mgmtIp) { return DeviceId.deviceId(OVSDB_DEVICE_PREFIX.concat(mgmtIp)); } /** * Returns {@code true} if this bridge is available; * returns {@code false} otherwise. * * @param context workflow context * @param devId device id * @return {@code true} if this bridge is available; {@code false} otherwise. * @throws WorkflowException workflow exception */ public static final boolean isAvailableBridge(WorkflowContext context, DeviceId devId) throws WorkflowException { if (Objects.isNull(devId)) { throw new WorkflowException("Invalid device id in data model"); } DeviceService deviceService = context.getService(DeviceService.class); Device dev = deviceService.getDevice(devId); if (Objects.isNull(dev)) { return false; } return deviceService.isAvailable(devId); } /** * Gets openflow controller information list. * * @param context workflow context * @return openflow controller information list * @throws WorkflowException workflow exception */ public static final List<ControllerInfo> getOpenflowControllerInfoList(WorkflowContext context) throws WorkflowException { ClusterService clusterService = context.getService(ClusterService.class); java.util.List<org.onosproject.net.behaviour.ControllerInfo> controllers = new ArrayList<>(); Sets.newHashSet(clusterService.getNodes()).forEach( controller -> { org.onosproject.net.behaviour.ControllerInfo ctrlInfo = new org.onosproject.net.behaviour.ControllerInfo(controller.ip(), OPENFLOW_PORT, OPENFLOW_CHANNEL_PROTO); controllers.add(ctrlInfo); } ); return controllers; } /** * Creates bridge. * * @param bridgeConfig bridge config * @param name bridge name to create * @param dpid openflow data path id of bridge to create * @param ofControllers openflow controller information list * @param datapathType OVS data path type */ public static final void createBridge(BridgeConfig bridgeConfig, String name, String dpid, List<ControllerInfo> ofControllers, OvsDatapathType datapathType) { BridgeDescription.Builder bridgeDescBuilder = DefaultBridgeDescription.builder() .name(name) .failMode(BridgeDescription.FailMode.SECURE) .datapathId(dpid) .disableInBand() .controlProtocols(Collections.singletonList(BRIDGE_DEFAULT_OF_VERSION)) .controllers(ofControllers); if (datapathType != null && !(datapathType.equals(OvsDatapathType.EMPTY))) { bridgeDescBuilder.datapathType(datapathType.toString()); log.info("create {} with dataPathType {}", name, datapathType); } BridgeDescription bridgeDesc = bridgeDescBuilder.build(); bridgeConfig.addBridge(bridgeDesc); } /** * Index of data path id in openflow device id. */ private static final int DPID_BEGIN_INDEX = 3; /** * Gets bridge data path id. * * @param devId device id * @return bridge data path id */ public static final String bridgeDatapathId(DeviceId devId) { return devId.toString().substring(DPID_BEGIN_INDEX); } /** * Gets OVSDB client. * * @param context workflow context * @param strMgmtIp management ip address * @param intOvsdbPort OVSDB port * @return ovsdb client * @throws WorkflowException workflow exception */ public static final OvsdbClientService getOvsdbClient( WorkflowContext context, String strMgmtIp, int intOvsdbPort) throws WorkflowException { IpAddress mgmtIp = IpAddress.valueOf(strMgmtIp); TpPort ovsdbPort = TpPort.tpPort(intOvsdbPort); OvsdbController ovsdbController = context.getService(OvsdbController.class); return ovsdbController.getOvsdbClient(new OvsdbNodeId(mgmtIp, ovsdbPort.toInt())); } /** * Checks whether 2 controller informations include same controller information. * * @param a controller information list * @param b controller information list * @return {@code true} if 2 controller informations include same controller information */ public static boolean isEqual(List<ControllerInfo> a, List<ControllerInfo> b) { if (a == b) { return true; } else if (a == null) { // equivalent to (a == null && b != null) return false; } else if (b == null) { // equivalent to (a != null && b == null) return false; } else if (a.size() != b.size()) { return false; } return a.containsAll(b); } /** * Gets the name of the port. * * @param port port * @return the name of the port */ public static final String portName(Port port) { return port.annotations().value(PORT_NAME); } } /** * Work-let class for creating OVSDB device. */ public static class CreateOvsdbDevice extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OVSDB_PORT) Integer intOvsdbPort; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { OvsdbClientService ovsdbClient = OvsUtil.getOvsdbClient(context, strMgmtIp, intOvsdbPort); return ovsdbClient == null || !ovsdbClient.isConnected(); } @Override public void process(WorkflowContext context) throws WorkflowException { IpAddress mgmtIp = IpAddress.valueOf(strMgmtIp); TpPort ovsdbPort = TpPort.tpPort(intOvsdbPort); OvsdbController ovsdbController = context.getService(OvsdbController.class); context.waitCompletion(DeviceEvent.class, OVSDB_DEVICE_PREFIX.concat(strMgmtIp), () -> ovsdbController.connect(mgmtIp, ovsdbPort), TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; Device device = deviceEvent.subject(); switch (deviceEvent.type()) { case DEVICE_ADDED: case DEVICE_AVAILABILITY_CHANGED: case DEVICE_UPDATED: return context.getService(DeviceService.class).isAvailable(device.id()); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for removing OVSDB device. */ public static class RemoveOvsdbDevice extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { DeviceId devId = DeviceId.deviceId(OVSDB_DEVICE_PREFIX.concat(strMgmtIp)); Device dev = context.getService(DeviceService.class).getDevice(devId); return dev != null; } @Override public void process(WorkflowContext context) throws WorkflowException { IpAddress mgmtIp = IpAddress.valueOf(strMgmtIp); check(mgmtIp != null, "mgmt ip is invalid"); DeviceId devId = DeviceId.deviceId(OVSDB_DEVICE_PREFIX.concat(strMgmtIp)); DeviceAdminService adminService = context.getService(DeviceAdminService.class); context.waitCompletion(DeviceEvent.class, devId.toString(), () -> adminService.removeDevice(devId), TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case DEVICE_REMOVED: return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for updating OVS version. */ public static class UpdateOvsVersion extends AbstractWorklet { @JsonDataModel(path = MODEL_OVS_VERSION, optional = true) String strOvsVersion; @JsonDataModel(path = MODEL_SSH_ACCESSINFO) JsonNode strSshAccessInfo; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { return strOvsVersion == null; } @Override public void process(WorkflowContext context) throws WorkflowException { SshAccessInfo sshAccessInfo = SshAccessInfo.valueOf(strSshAccessInfo); check(Objects.nonNull(sshAccessInfo), "Invalid ssh access info " + context.data()); OvsVersion ovsVersion = SshUtil.exec(sshAccessInfo, session -> SshUtil.fetchOvsVersion(session)); check(Objects.nonNull(ovsVersion), "Failed to fetch ovs version " + context.data()); strOvsVersion = ovsVersion.toString(); context.completed(); } } /** * Work-let class for updating overlay bridge device id. */ public static class UpdateBridgeId extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OF_DEVID_BRIDGE, optional = true) ObjectNode strOfDevId; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { return strOfDevId == null; } @Override public void process(WorkflowContext context) throws WorkflowException { BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); BridgeDescription bridgeName = OvsUtil.getBridgeNames(bridgeConfig); strOfDevId = JsonNodeFactory.instance.objectNode(); if (Objects.nonNull(bridgeName)) { Optional<BridgeDescription> optBd = OvsUtil.getBridgeDescription(bridgeConfig, bridgeName.name()); if (optBd.isPresent()) { String ofDevIdOverlay = strOfDevId.get(BRIDGE_OVERLAY).asText(); String ofDevIdUnderlay = strOfDevId.get(BRIDGE_UNDERLAY).asText(); if (Objects.nonNull(ofDevIdOverlay) || Objects.nonNull(ofDevIdUnderlay)) { strOfDevId.put(BRIDGE_OVERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY).toString()); strOfDevId.put(BRIDGE_UNDERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA).toString()); } else { strOfDevId.put(BRIDGE_OVERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY).toString()); strOfDevId.put(BRIDGE_UNDERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA).toString()); log.info("Failed to find devId. Updates of device id with new device id {}", strOfDevId); } } } else { strOfDevId.put(BRIDGE_OVERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY).toString()); strOfDevId.put(BRIDGE_UNDERLAY, OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA).toString()); log.info("Failed to find description. Updates of device id with new device id {}", strOfDevId); } context.completed(); } } public static class CreateBridge extends AbstractWorklet { @StaticDataModel(path = BRIDGE_NAME) String bridgeName; @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OVSDB_PORT) Integer intOvsdbPort; @JsonDataModel(path = MODEL_OVS_DATAPATH_TYPE) String strOvsDatapath; @JsonDataModel(path = MODEL_OF_DEVID_BRIDGE, optional = true) ObjectNode strOfDevId; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { check(strOfDevId != null, "invalid strOfDevIdUnderlay"); String bridgeId = strOfDevId.get(bridgeName).asText(); return !OvsUtil.isAvailableBridge(context, DeviceId.deviceId(bridgeId)); } @Override public void process(WorkflowContext context) throws WorkflowException { check(strOfDevId != null, "invalid strOfDevIdOverlay"); BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); List<ControllerInfo> ofControllers = OvsUtil.getOpenflowControllerInfoList(context); String bridge = strOfDevId.get(bridgeName).asText(); DeviceId ofDeviceId = DeviceId.deviceId(bridge); if (ofControllers == null || ofControllers.size() == 0) { throw new WorkflowException("Invalid of controllers"); } Optional<BridgeDescription> optBd = OvsUtil.getBridgeDescription(bridgeConfig, bridgeName); if (!optBd.isPresent()) { // If bridge does not exist, just creates a new bridge. context.waitCompletion(DeviceEvent.class, ofDeviceId.toString(), () -> OvsUtil.createBridge(bridgeConfig, bridgeName, OvsUtil.bridgeDatapathId(ofDeviceId), ofControllers, OvsUtil.buildOvsDatapathType(strOvsDatapath)), TIMEOUT_DEVICE_CREATION_MS ); return; } else { BridgeDescription bd = optBd.get(); if (OvsUtil.isEqual(ofControllers, bd.controllers())) { log.error("{} has valid controller setting({})", bridgeName, bd.controllers()); context.completed(); return; } OvsdbClientService ovsdbClient = OvsUtil.getOvsdbClient(context, strMgmtIp, intOvsdbPort); if (ovsdbClient == null || !ovsdbClient.isConnected()) { throw new WorkflowException("Invalid ovsdb client for " + strMgmtIp); } // If controller settings are not matched, set controller with valid controller information. context.waitCompletion(DeviceEvent.class, ofDeviceId.toString(), () -> ovsdbClient.setControllersWithDeviceId(bd.deviceId().get(), ofControllers), TIMEOUT_DEVICE_CREATION_MS ); return; } } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; Device device = deviceEvent.subject(); switch (deviceEvent.type()) { case DEVICE_ADDED: case DEVICE_AVAILABILITY_CHANGED: case DEVICE_UPDATED: return context.getService(DeviceService.class).isAvailable(device.id()); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for creating overlay openflow bridge. */ public static class CreateOverlayBridgeMultiEvent extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OVSDB_PORT) Integer intOvsdbPort; @JsonDataModel(path = MODEL_OVS_DATAPATH_TYPE) String strOvsDatapath; @JsonDataModel(path = MODEL_OF_DEVID_BRIDGE, optional = true) ObjectNode strOfDevIdOverlay; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { check(strOfDevIdOverlay != null, "invalid strOfDevIdOverlay"); String bridge = strOfDevIdOverlay.get(BRIDGE_OVERLAY).asText(); return !OvsUtil.isAvailableBridge(context, DeviceId.deviceId(bridge)); } @Override public void process(WorkflowContext context) throws WorkflowException { check(strOfDevIdOverlay != null, "invalid strOfDevIdOverlay"); BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); List<ControllerInfo> ofControllers = OvsUtil.getOpenflowControllerInfoList(context); String bridge = strOfDevIdOverlay.get(BRIDGE_OVERLAY).asText(); DeviceId ofDeviceId = DeviceId.deviceId(bridge); if (ofControllers == null || ofControllers.size() == 0) { throw new WorkflowException("Invalid of controllers"); } Optional<BridgeDescription> optBd = OvsUtil.getBridgeDescription(bridgeConfig, BRIDGE_OVERLAY); if (!optBd.isPresent()) { Set<String> eventHints = Sets.newHashSet(ofDeviceId.toString()); context.waitAnyCompletion(DeviceEvent.class, eventHints, () -> OvsUtil.createBridge(bridgeConfig, BRIDGE_OVERLAY, OvsUtil.bridgeDatapathId(ofDeviceId), ofControllers, OvsUtil.buildOvsDatapathType(strOvsDatapath)), TIMEOUT_DEVICE_CREATION_MS ); return; } else { BridgeDescription bd = optBd.get(); if (OvsUtil.isEqual(ofControllers, bd.controllers())) { log.error("{} has valid controller setting({})", BRIDGE_OVERLAY, bd.controllers()); context.completed(); return; } OvsdbClientService ovsdbClient = OvsUtil.getOvsdbClient(context, strMgmtIp, intOvsdbPort); if (ovsdbClient == null || !ovsdbClient.isConnected()) { throw new WorkflowException("Invalid ovsdb client for " + strMgmtIp); } // If controller settings are not matched, set controller with valid controller information. Set<String> eventHints = Sets.newHashSet(ofDeviceId.toString()); context.waitAnyCompletion(DeviceEvent.class, eventHints, () -> ovsdbClient.setControllersWithDeviceId(bd.deviceId().get(), ofControllers), TIMEOUT_DEVICE_CREATION_MS ); return; } } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; Device device = deviceEvent.subject(); switch (deviceEvent.type()) { case DEVICE_ADDED: case DEVICE_AVAILABILITY_CHANGED: case DEVICE_UPDATED: return context.getService(DeviceService.class).isAvailable(device.id()); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for creating vxlan port on the overlay bridge. */ public static class CreateOverlayBridgeVxlanPort extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OF_DEVID_BRIDGE, optional = true) ObjectNode strOfDevIdOverlay; private static final String OVS_VXLAN_PORTNAME = "vxlan"; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { check(strOfDevIdOverlay != null, "invalid strOfDevIdOverlay"); String bridge = strOfDevIdOverlay.get(BRIDGE_OVERLAY).asText(); DeviceId deviceId = DeviceId.deviceId(bridge); if (Objects.isNull(deviceId)) { throw new WorkflowException("Invalid br-int bridge, before creating VXLAN port"); } DeviceService deviceService = context.getService(DeviceService.class); return !deviceService.getPorts(deviceId) .stream() .filter(port -> OvsUtil.portName(port).contains(OVS_VXLAN_PORTNAME) && port.isEnabled()) .findAny().isPresent(); } @Override public void process(WorkflowContext context) throws WorkflowException { check(strOfDevIdOverlay != null, "invalid strOfDevIdOverlay"); TunnelDescription description = DefaultTunnelDescription.builder() .deviceId(BRIDGE_OVERLAY) .ifaceName(OVS_VXLAN_PORTNAME) .type(TunnelDescription.Type.VXLAN) .remote(TunnelEndPoints.flowTunnelEndpoint()) .key(TunnelKeys.flowTunnelKey()) .build(); String bridge = strOfDevIdOverlay.get(BRIDGE_OVERLAY).asText(); DeviceId ofDeviceId = DeviceId.deviceId(bridge); InterfaceConfig interfaceConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, InterfaceConfig.class); context.waitCompletion(DeviceEvent.class, ofDeviceId.toString(), () -> interfaceConfig.addTunnelMode(BRIDGE_OVERLAY, description), TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case PORT_ADDED: return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for adding physical ports on the underlay openflow bridge. */ public static class AddPhysicalPortsOnUnderlayBridge extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OVSDB_PORT) Integer intOvsdbPort; @JsonDataModel(path = MODEL_OF_DEVID_BRIDGE, optional = true) ObjectNode strOfDevIdUnderlay; @JsonDataModel(path = MODEL_OVS_DATAPATH_TYPE) String strOvsDatapath; @JsonDataModel(path = MODEL_PHY_PORTS) ArrayNode arrNodePhysicalPorts; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { check(strOfDevIdUnderlay != null, "invalid strOfDevIdUnderlay"); String bridge = strOfDevIdUnderlay.get(BRIDGE_UNDERLAY).asText(); DeviceId brphyDevId = DeviceId.deviceId(bridge); return !hasAllPhysicalPorts(context, brphyDevId); } @Override public void process(WorkflowContext context) throws WorkflowException { check(strOfDevIdUnderlay != null, "invalid strOfDevIdUnderlay"); String bridge = strOfDevIdUnderlay.get(BRIDGE_UNDERLAY).asText(); DeviceId brphyDevId = DeviceId.deviceId(bridge); context.waitCompletion(DeviceEvent.class, brphyDevId.toString(), () -> addPhysicalPorts(context, brphyDevId, BRIDGE_UNDERLAY, strOvsDatapath), TIMEOUT_PORT_ADDITION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case PORT_ADDED: return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } private final List<String> getPhysicalPorts(WorkflowContext context) throws WorkflowException { List<String> ports = Lists.newArrayList(); for (JsonNode jsonNode : arrNodePhysicalPorts) { check(jsonNode instanceof TextNode, "Invalid physical ports " + arrNodePhysicalPorts); ports.add(jsonNode.asText()); } return ports; } private final boolean hasAllPhysicalPorts(WorkflowContext context, DeviceId devId) throws WorkflowException { List<Port> devPorts = context.getService(DeviceService.class).getPorts(devId); check(devPorts != null, "Invalid device ports for " + devId); List<String> physicalPorts = getPhysicalPorts(context); check(physicalPorts != null, "Invalid physical ports" + context); log.info("physicalPorts: {} for {}", physicalPorts, devId); for (String port : physicalPorts) { if (devPorts.stream().noneMatch(p -> OvsUtil.portName(p).contains(port))) { return false; } } return true; } private final boolean hasPort(WorkflowContext context, DeviceId devId, String portName) throws WorkflowException { List<Port> devPorts = context.getService(DeviceService.class).getPorts(devId); check(devPorts != null, "Invalid device ports for " + devId); return devPorts.stream().anyMatch(p -> OvsUtil.portName(p).contains(portName)); } private final void addPhysicalPorts(WorkflowContext context, DeviceId devId, String bridgeName, String strOvsDatapathType) throws WorkflowException { OvsdbClientService ovsdbClient = OvsUtil.getOvsdbClient(context, strMgmtIp, intOvsdbPort); check(ovsdbClient != null, "Invalid ovsdb client"); List<String> physicalPorts = getPhysicalPorts(context); check(physicalPorts != null, "Invalid physical ports"); OvsDatapathType datapathType = OvsUtil.buildOvsDatapathType(strOvsDatapathType); check(datapathType != null, "Invalid data path type"); List<String> sortedPhyPorts = physicalPorts.stream().sorted().collect(Collectors.toList()); for (String port : sortedPhyPorts) { if (hasPort(context, devId, port)) { continue; } log.info("adding port {} on {}", port, devId); switch (datapathType) { case NETDEV: throw new WorkflowException("NETDEV datapathType are not supported"); //break; case SYSTEM: default: ovsdbClient.createPort(BridgeName.bridgeName(bridgeName).name(), port); } } } } /** * Work-let class for configure local ip of underlay openflow bridge. */ public static class ConfigureUnderlayBridgeLocalIp extends AbstractWorklet { @JsonDataModel(path = MODEL_SSH_ACCESSINFO) JsonNode strSshAccessInfo; @JsonDataModel(path = MODEL_VTEP_IP) String strVtepIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { SshAccessInfo sshAccessInfo = SshAccessInfo.valueOf(strSshAccessInfo); check(Objects.nonNull(sshAccessInfo), "Invalid ssh access info " + context.data()); NetworkAddress vtepIp = NetworkAddress.valueOf(strVtepIp); check(Objects.nonNull(vtepIp), "Invalid vtep ip " + context.data()); return !SshUtil.exec(sshAccessInfo, session -> SshUtil.hasIpAddrOnInterface(session, BRIDGE_UNDERLAY, vtepIp) && SshUtil.isIpLinkUpOnInterface(session, BRIDGE_UNDERLAY) ); } @Override public void process(WorkflowContext context) throws WorkflowException { SshAccessInfo sshAccessInfo = SshAccessInfo.valueOf(strSshAccessInfo); check(Objects.nonNull(sshAccessInfo), "Invalid ssh access info " + context.data()); NetworkAddress vtepIp = NetworkAddress.valueOf(strVtepIp); check(Objects.nonNull(vtepIp), "Invalid vtep ip " + context.data()); SshUtil.exec(sshAccessInfo, session -> { SshUtil.addIpAddrOnInterface(session, BRIDGE_UNDERLAY, vtepIp); SshUtil.setIpLinkUpOnInterface(session, BRIDGE_UNDERLAY); return ""; }); context.completed(); } } /** * Work-let class for deleting overlay bridge config. */ public static class DeleteOverlayBridgeConfig extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); Collection<BridgeDescription> bridges = bridgeConfig.getBridges(); return bridges.stream() .anyMatch(bd -> Objects.equals(bd.name(), BRIDGE_OVERLAY)); } @Override public void process(WorkflowContext context) throws WorkflowException { BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); bridgeConfig.deleteBridge(BridgeName.bridgeName(BRIDGE_OVERLAY)); for (int i = 0; i < 10; i++) { if (!isNext(context)) { context.completed(); return; } sleep(50); } throw new WorkflowException("Timeout happened for removing config"); } protected void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Work-let class for removing overlay bridge openflow device. */ public static class RemoveOverlayBridgeOfDevice extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { DeviceId devId = OvsUtil.buildOfDeviceId(IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY); Device dev = context.getService(DeviceService.class).getDevice(devId); return dev != null; } @Override public void process(WorkflowContext context) throws WorkflowException { DeviceId devId = OvsUtil.buildOfDeviceId(IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY); DeviceAdminService adminService = context.getService(DeviceAdminService.class); context.waitCompletion(DeviceEvent.class, devId.toString(), () -> adminService.removeDevice(devId), TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case DEVICE_REMOVED: return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for deleting underlay bridge config. */ public static class DeleteUnderlayBridgeConfig extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); Collection<BridgeDescription> bridges = bridgeConfig.getBridges(); return bridges.stream() .anyMatch(bd -> Objects.equals(bd.name(), BRIDGE_UNDERLAY)); } @Override public void process(WorkflowContext context) throws WorkflowException { BridgeConfig bridgeConfig = OvsUtil.getOvsdbBehaviour(context, strMgmtIp, BridgeConfig.class); bridgeConfig.deleteBridge(BridgeName.bridgeName(BRIDGE_UNDERLAY)); for (int i = 0; i < 10; i++) { if (!isNext(context)) { context.completed(); return; } sleep(50); } throw new WorkflowException("Timeout happened for removing config"); } protected void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Work-let class for removing underlay bridge openflow device. */ public static class RemoveUnderlayBridgeOfDevice extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { DeviceId devId = OvsUtil.buildOfDeviceId(IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA); Device dev = context.getService(DeviceService.class).getDevice(devId); return dev != null; } @Override public void process(WorkflowContext context) throws WorkflowException { DeviceId devId = OvsUtil.buildOfDeviceId(IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA); DeviceAdminService adminService = context.getService(DeviceAdminService.class); context.waitCompletion(DeviceEvent.class, devId.toString(), () -> adminService.removeDevice(devId), TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case DEVICE_REMOVED: return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } /** * Work-let class for removing underlay bridge and overlay openflow device. */ public static class RemoveBridgeOfDevice extends AbstractWorklet { @JsonDataModel(path = MODEL_MGMT_IP) String strMgmtIp; @JsonDataModel(path = MODEL_OF_DEVID_FOR_OVERLAY_UNDERLAY_BRIDGE, optional = true) ObjectNode ofDevId; @Override public boolean isNext(WorkflowContext context) throws WorkflowException { boolean isOfDevicePresent = true; if (ofDevId == null) { ofDevId = JsonNodeFactory.instance.objectNode(); ofDevId.put(String.valueOf(DEVID_IDX_BRIDGE_OVERLAY), OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY).toString()); ofDevId.put(String.valueOf(DEVID_IDX_BRIDGE_UNDERLAY_NOVA), OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA).toString()); } if (context.getService(DeviceService.class). getDevice(DeviceId.deviceId( ofDevId.get(String.valueOf(DEVID_IDX_BRIDGE_OVERLAY)).asText())) == null) { isOfDevicePresent = false; } if (context.getService(DeviceService.class). getDevice(DeviceId.deviceId( ofDevId.get(String.valueOf(DEVID_IDX_BRIDGE_UNDERLAY_NOVA)).asText())) == null) { isOfDevicePresent = false; } return isOfDevicePresent; } @Override public void process(WorkflowContext context) throws WorkflowException { DeviceAdminService adminService = context.getService(DeviceAdminService.class); String ofDevIdOverlay; String ofDevIdUnderlay; if (ofDevId == null) { ofDevId = JsonNodeFactory.instance.objectNode(); ofDevId.put(String.valueOf(DEVID_IDX_BRIDGE_OVERLAY), OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY).toString()); ofDevId.put(String.valueOf(DEVID_IDX_BRIDGE_UNDERLAY_NOVA), OvsUtil.buildOfDeviceId( IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_UNDERLAY_NOVA).toString()); } ofDevIdOverlay = ofDevId.get(String.valueOf(DEVID_IDX_BRIDGE_OVERLAY)).asText(); ofDevIdUnderlay = ofDevId.get(String.valueOf(DEVID_IDX_BRIDGE_UNDERLAY_NOVA)).asText(); Set<String> eventHints = Sets.newHashSet(ofDevIdOverlay, ofDevIdUnderlay); context.waitAnyCompletion(DeviceEvent.class, eventHints, () -> { adminService.removeDevice(DeviceId.deviceId(ofDevIdOverlay)); adminService.removeDevice(DeviceId.deviceId(ofDevIdUnderlay)); }, TIMEOUT_DEVICE_CREATION_MS ); } @Override public boolean isCompleted(WorkflowContext context, Event event) throws WorkflowException { if (!(event instanceof DeviceEvent)) { return false; } DeviceEvent deviceEvent = (DeviceEvent) event; switch (deviceEvent.type()) { case DEVICE_REMOVED: log.trace("GOT DEVICE REMOVED EVENT FOR DEVICE {}", event.subject()); return !isNext(context); default: return false; } } @Override public void timeout(WorkflowContext context) throws WorkflowException { if (!isNext(context)) { context.completed(); //Complete the job of worklet by timeout } else { super.timeout(context); } } } }
923173da68379bc4debf7f51f58f06815e31b0d0
1,982
java
Java
renfeid-core/src/main/java/net/renfei/services/system/QuartzServiceImpl.java
renfei/renfeid
a9813049143df7622e3a35becd98a92987a1540d
[ "Apache-2.0" ]
5
2021-11-12T08:05:26.000Z
2022-03-02T02:12:50.000Z
renfeid-core/src/main/java/net/renfei/services/system/QuartzServiceImpl.java
moutainhigh/renfeid
627fb36ae88b89e76486c79e97e14f560d09f823
[ "Apache-2.0" ]
24
2021-11-12T14:11:22.000Z
2022-03-31T11:23:28.000Z
renfeid-core/src/main/java/net/renfei/services/system/QuartzServiceImpl.java
moutainhigh/renfeid
627fb36ae88b89e76486c79e97e14f560d09f823
[ "Apache-2.0" ]
7
2021-11-12T14:08:38.000Z
2022-03-17T08:43:52.000Z
26.783784
140
0.685671
995,848
package net.renfei.services.system; import net.renfei.model.system.QuartzJob; import net.renfei.services.BaseService; import net.renfei.services.QuartzService; import net.renfei.utils.QuartzUtils; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.springframework.stereotype.Service; /** * Quartz 定时任务服务 * * @author renfei */ @Service public class QuartzServiceImpl extends BaseService implements QuartzService { private final Scheduler scheduler; public QuartzServiceImpl(Scheduler scheduler) { this.scheduler = scheduler; } /** * 添加一个定时任务 * * @param quartzJob * @throws ClassNotFoundException * @throws SchedulerException */ @Override public void addJob(QuartzJob quartzJob) throws ClassNotFoundException, SchedulerException { Class clazz = Class.forName(quartzJob.getReference()); QuartzUtils.createJob(scheduler, clazz, quartzJob.getJobName(), quartzJob.getJobGroup(), quartzJob.getCron(), quartzJob.getParam()); } /** * 暂停一个定时任务 * * @param jobName 任务名称 * @param jobGroup 任务组名称 * @throws SchedulerException */ @Override public void pauseJob(String jobName, String jobGroup) throws SchedulerException { QuartzUtils.pauseJob(scheduler, jobName, jobGroup); } /** * 继续一个定时任务 * * @param jobName 任务名称 * @param jobGroup 任务组名称 * @throws SchedulerException */ @Override public void resumeJob(String jobName, String jobGroup) throws SchedulerException { QuartzUtils.resumeJob(scheduler, jobName, jobGroup); } /** * 更新一个定时任务 * * @param jobName 任务名称 * @param jobGroup 任务组名称 * @param cron 定时表达式 * @throws SchedulerException */ @Override public void updateJob(String jobName, String jobGroup, String cron) throws SchedulerException { QuartzUtils.refreshJob(scheduler, jobName, jobGroup, cron); } }
92317487f2ed7d21bb880e41616ed9702fb2aa27
2,595
java
Java
src/main/java/svenhjol/charm/world/decorator/theme/VillageButcherTheme.java
yrsegal/Charm
f5f55f038bc302f538b37e72b0f7cfadd3bddada
[ "MIT" ]
null
null
null
src/main/java/svenhjol/charm/world/decorator/theme/VillageButcherTheme.java
yrsegal/Charm
f5f55f038bc302f538b37e72b0f7cfadd3bddada
[ "MIT" ]
null
null
null
src/main/java/svenhjol/charm/world/decorator/theme/VillageButcherTheme.java
yrsegal/Charm
f5f55f038bc302f538b37e72b0f7cfadd3bddada
[ "MIT" ]
null
null
null
31.646341
120
0.695568
995,849
package svenhjol.charm.world.decorator.theme; import net.minecraft.block.BlockCauldron; import net.minecraft.block.BlockStone; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import svenhjol.charm.base.CharmDecoratorTheme; import svenhjol.charm.base.CharmLootTables; import svenhjol.meson.decorator.MesonInnerDecorator; import java.util.ArrayList; import java.util.List; public class VillageButcherTheme extends CharmDecoratorTheme { public VillageButcherTheme(MesonInnerDecorator structure) { super(structure); } @Override public IBlockState getFunctionalBlock() { List<IBlockState> states = new ArrayList<>(); states.add(Blocks.CRAFTING_TABLE.getDefaultState()); states.add(Blocks.FURNACE.getDefaultState()); states.add(Blocks.CAULDRON.getDefaultState().withProperty(BlockCauldron.LEVEL, getRand().nextInt(3))); states.add(Blocks.HOPPER.getDefaultState()); return states.get(getRand().nextInt(states.size())); } @Override public IBlockState getDecorationBlock() { List<IBlockState> states = new ArrayList<>(); states.add(Blocks.STONE.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.DIORITE_SMOOTH)); states.add(Blocks.COAL_BLOCK.getDefaultState()); return states.get(getRand().nextInt(states.size())); } @Override public ItemStack getFramedItem() { List<Item> items = new ArrayList<>(); if (valuable()) items.add(Items.SADDLE); if (valuable()) items.add(Items.RABBIT_FOOT); if (uncommon()) items.add(Items.IRON_AXE); if (uncommon()) items.add(Items.IRON_SWORD); if (common()) items.add(Items.LEATHER_HELMET); if (common()) items.add(Items.LEATHER_CHESTPLATE); if (common()) items.add(Items.LEATHER_LEGGINGS); if (common()) items.add(Items.LEATHER_BOOTS); items.add(Items.LEATHER); items.add(Items.RABBIT_HIDE); items.add(Items.BEEF); items.add(Items.PORKCHOP); items.add(Items.COAL); return new ItemStack(items.get(getRand().nextInt(items.size()))); } @Override public ResourceLocation getLootTable() { List<ResourceLocation> locations = new ArrayList<>(); locations.add(CharmLootTables.VILLAGE_BUTCHER); return locations.get(getRand().nextInt(locations.size())); } }
923174b822cc01717800c91700556bef485fe6ef
12,118
java
Java
host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
host/ohosprofiler/src/main/java/ohos/devtools/services/memory/memorydao/MemoryDao.java
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
1
2021-09-13T11:17:44.000Z
2021-09-13T11:17:44.000Z
35.746313
118
0.570969
995,850
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ohos.devtools.services.memory.memorydao; import com.google.protobuf.InvalidProtocolBufferException; import ohos.devtools.datasources.databases.databaseapi.DataBaseApi; import ohos.devtools.datasources.databases.databasepool.AbstractDataStore; import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo; import ohos.devtools.datasources.transport.grpc.service.MemoryPluginResult; import ohos.devtools.datasources.utils.datahandler.datapoller.MemoryDataConsumer; import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager; import ohos.devtools.views.charts.model.ChartDataModel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_AFTER_TAIL; import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_ALL_APP_MEM_INFO; import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_APP_MEM_INFO; import static ohos.devtools.services.memory.memorydao.MemoryDao.MemorySelectStatements.SELECT_BEFORE_HEAD; /** * memory And Database Interaction Class */ public class MemoryDao extends AbstractDataStore { private static final Logger LOGGER = LogManager.getLogger(MemoryDao.class); private static volatile MemoryDao singleton; /** * get Instance * * @return MemoryDao */ public static MemoryDao getInstance() { if (singleton == null) { synchronized (MemoryDao.class) { if (singleton == null) { singleton = new MemoryDao(); } } } return singleton; } private Map<MemorySelectStatements, PreparedStatement> memorySelectMap = new HashMap<>(); /** * Memory Select Statements */ public enum MemorySelectStatements { SELECT_APP_MEM_INFO( "SELECT " + "timeStamp, " + "Data " + "from " + "processMemInfo " + "where " + "session = ? " + "and " + "timeStamp > ? " + "and " + "timeStamp < ?"), SELECT_ALL_APP_MEM_INFO( "SELECT " + "timeStamp, " + "Data " + "from " + "processMemInfo " + "where " + "session = ?"), DELETE_APP_MEM_INFO("delete from " + "processMemInfo " + "where " + "session = ?"), SELECT_BEFORE_HEAD( "SELECT " + "timeStamp, " + "Data " + "from " + "processMemInfo " + "where session = ? " + "and " + "timeStamp < ? " + "order by " + "timeStamp " + "desc limit 1"), SELECT_AFTER_TAIL( "SELECT " + "timeStamp, " + "Data " + "from " + "processMemInfo " + "where " + "session = ? " + "and " + "timeStamp > ? " + "order by " + "timeStamp " + "asc " + "limit 1"); private final String sqlStatement; MemorySelectStatements(String sqlStatement) { this.sqlStatement = sqlStatement; } /** * get Statement * * @return String */ public String getStatement() { return sqlStatement; } } private Connection conn; private MemoryDao() { if (conn == null) { Optional<Connection> connection = getConnectBydbName("memory"); if (connection.isPresent()) { conn = connection.get(); } createPrePareStatements(); } } private void createPrePareStatements() { if (ProfilerLogManager.isInfoEnabled()) { LOGGER.info("createPrePareStatements"); } MemorySelectStatements[] values = MemorySelectStatements.values(); for (MemorySelectStatements sta : values) { PreparedStatement psmt = null; try { psmt = conn.prepareStatement(sta.getStatement()); memorySelectMap.put(sta, psmt); } catch (SQLException throwAbles) { if (ProfilerLogManager.isErrorEnabled()) { LOGGER.error(" SQLException {}", throwAbles.getMessage()); } } } } /** * get All Data * * @param sessionId sessionId * @return List <ProcessMemInfo> */ public List<ProcessMemInfo> getAllData(long sessionId) { if (ProfilerLogManager.isInfoEnabled()) { LOGGER.info("getAllData"); } PreparedStatement pst = memorySelectMap.get(SELECT_ALL_APP_MEM_INFO); List<ProcessMemInfo> result = new ArrayList<>(); try { if (pst != null) { pst.setLong(1, sessionId); ResultSet rs = pst.executeQuery(); while (rs.next()) { long timeStamp = rs.getLong("timeStamp"); byte[] data = rs.getBytes("Data"); if (data == null) { continue; } ProcessMemInfo processMem = new ProcessMemInfo(); MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); processMem.setTimeStamp(timeStamp); processMem.setData(appSummary); processMem.setSession(sessionId); result.add(processMem); } } } catch (SQLException | InvalidProtocolBufferException throwables) { if (ProfilerLogManager.isErrorEnabled()) { LOGGER.error(" SQLException {}", throwables.getMessage()); } } return result; } /** * get Data * * @param sessionId sessionId * @param min min * @param max max * @param startTimeStamp startTimeStamp * @param isNeedHeadTail isNeedHeadTail * @return LinkedHashMap <Integer, List<ChartDataModel>> */ public LinkedHashMap<Integer, List<ChartDataModel>> getData(long sessionId, int min, int max, long startTimeStamp, boolean isNeedHeadTail) { if (ProfilerLogManager.isInfoEnabled()) { LOGGER.info("getData"); } PreparedStatement pst = memorySelectMap.get(SELECT_APP_MEM_INFO); LinkedHashMap<Integer, List<ChartDataModel>> result = new LinkedHashMap<>(); if (pst == null) { return result; } // 当startTime > 0时(Chart铺满界面时),需要取第一个点的前一个点用于Chart绘制,填充空白,解决边界闪烁 if (isNeedHeadTail && min > 0) { result.putAll(getTargetData(sessionId, min, startTimeStamp, true)); } try { pst.setLong(1, sessionId); pst.setLong(2, startTimeStamp + min); pst.setLong(3, startTimeStamp + max); ResultSet rs = pst.executeQuery(); if (rs != null) { while (rs.next()) { long timeStamp = rs.getLong("timeStamp"); byte[] data = rs.getBytes("Data"); if (data == null) { continue; } MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); result.put((int) (timeStamp - startTimeStamp), MemoryDataConsumer.processAppSummary(appSummary)); } } } catch (SQLException | InvalidProtocolBufferException throwAbles) { if (ProfilerLogManager.isErrorEnabled()) { LOGGER.error(" SQLException {}", throwAbles.getMessage()); } } // 取最后一个点的后一个点用于Chart绘制,填充空白,解决边界闪烁 if (isNeedHeadTail) { result.putAll(getTargetData(sessionId, max, startTimeStamp, false)); } return result; } /** * Get the data before head or after tail * * @param sessionId Session id * @param offset time offset * @param startTs start/first timestamp * @param beforeHead true: before head, false: after tail * @return LinkedHashMap <Integer, List<ChartDataModel>> */ private LinkedHashMap<Integer, List<ChartDataModel>> getTargetData(long sessionId, int offset, long startTs, boolean beforeHead) { if (ProfilerLogManager.isInfoEnabled()) { LOGGER.info("getTargetData"); } PreparedStatement pst; if (beforeHead) { pst = memorySelectMap.get(SELECT_BEFORE_HEAD); } else { pst = memorySelectMap.get(SELECT_AFTER_TAIL); } LinkedHashMap<Integer, List<ChartDataModel>> result = new LinkedHashMap<>(); if (pst == null) { return result; } try { pst.setLong(1, sessionId); pst.setLong(2, offset + startTs); ResultSet rs = pst.executeQuery(); if (rs != null) { while (rs.next()) { long timeStamp = rs.getLong("timeStamp"); byte[] data = rs.getBytes("Data"); if (data == null) { continue; } MemoryPluginResult.AppSummary.Builder builders = MemoryPluginResult.AppSummary.newBuilder(); MemoryPluginResult.AppSummary appSummary = builders.mergeFrom(data).build(); result.put((int) (timeStamp - startTs), MemoryDataConsumer.processAppSummary(appSummary)); } } } catch (SQLException | InvalidProtocolBufferException throwAbles) { if (ProfilerLogManager.isErrorEnabled()) { LOGGER.error(" SQLException {}", throwAbles.getMessage()); } } return result; } /** * deleteSessionData * * @param sessionId sessionId * @return boolean */ public boolean deleteSessionData(long sessionId) { if (ProfilerLogManager.isInfoEnabled()) { LOGGER.info("deleteSessionData"); } StringBuffer deleteSql = new StringBuffer("DELETE FROM "); deleteSql.append("processMemInfo").append(" WHERE session = ").append(sessionId); Optional<Connection> processMemInfo = DataBaseApi.getInstance().getConnectByTable("processMemInfo"); Connection connection = null; if (processMemInfo.isPresent()) { connection = processMemInfo.get(); } else { return false; } return execute(connection, deleteSql.toString()); } }