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
3e1ea5588f6a4bf319108b07e450b087b5678168
1,532
java
Java
src/main/java/module4/LandQuakeMarker.java
zeizeng/unfolding-maps
d15236495591fd78921404fb91c9289294f390d7
[ "MIT" ]
3
2017-12-24T11:37:54.000Z
2021-11-13T06:48:01.000Z
src/main/java/module4/LandQuakeMarker.java
zeizeng/unfolding-maps
d15236495591fd78921404fb91c9289294f390d7
[ "MIT" ]
1
2020-06-17T15:12:04.000Z
2020-06-17T15:12:04.000Z
src/main/java/module4/LandQuakeMarker.java
zeizeng/unfolding-maps
d15236495591fd78921404fb91c9289294f390d7
[ "MIT" ]
1
2019-02-20T08:42:25.000Z
2019-02-20T08:42:25.000Z
23.9375
92
0.701044
12,953
package module4; import de.fhpotsdam.unfolding.data.PointFeature; import processing.core.PGraphics; /** * Implements a visual marker for land earthquakes on an earthquake map * * @author UC San Diego Intermediate Software Development MOOC team * @author Solange U. Gasengayire * */ public class LandQuakeMarker extends EarthquakeMarker { /** * Constructor * @param quake point feature to create a marker for */ LandQuakeMarker(PointFeature quake) { // calling EarthquakeMarker constructor super(quake); // setting field in earthquake marker isOnLand = true; } /** * Draw marker * @param pg the graphics to draw on * @param x the x posiion coordinate * @param y the y position coordinate */ @Override public void drawEarthquake(PGraphics pg, float x, float y) { // Draw a centered circle for land quakes // DO NOT set the fill color here. // That will be set in the EarthquakeMarker class to indicate the depth of the earthquake. // Simply draw a centered circle. // HINT: Notice the radius variable in the EarthquakeMarker class // and how it is set in the EarthquakeMarker constructor. // DONE: Implement this method int radius = 20; if (getDepth() < THRESHOLD_INTERMEDIATE) { radius = 10; } else if (getDepth() < THRESHOLD_DEEP) { radius = 15; } pg.ellipse(x, y, radius, radius); } /** * Return the country this earthquake is in * @return country name */ public String getCountry() { return (String) getProperty("country"); } }
3e1ea6cce76995ce6774ec3baaa68bd9e335afef
1,571
java
Java
src/org/sosy_lab/cpachecker/appengine/io/DataStoreByteSink.java
45258E9F/IntPTI
e5dda55aafa2da3d977a9a62ad0857746dae3fe1
[ "Apache-2.0" ]
2
2017-08-28T09:14:11.000Z
2020-12-04T06:00:23.000Z
src/org/sosy_lab/cpachecker/appengine/io/DataStoreByteSink.java
45258E9F/IntPTI
e5dda55aafa2da3d977a9a62ad0857746dae3fe1
[ "Apache-2.0" ]
null
null
null
src/org/sosy_lab/cpachecker/appengine/io/DataStoreByteSink.java
45258E9F/IntPTI
e5dda55aafa2da3d977a9a62ad0857746dae3fe1
[ "Apache-2.0" ]
6
2017-08-03T13:06:55.000Z
2020-12-04T06:00:26.000Z
27.086207
76
0.726926
12,954
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.appengine.io; import com.google.common.io.ByteSink; import com.google.common.io.FileWriteMode; import org.sosy_lab.cpachecker.appengine.entity.TaskFile; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class DataStoreByteSink extends ByteSink { private TaskFile file; private FileWriteMode[] mode; public DataStoreByteSink(TaskFile file, FileWriteMode... mode) { this.file = file; this.mode = mode; } @Override public OutputStream openStream() throws IOException { OutputStream out = file.getContentOutputStream(); if (Arrays.asList(mode).contains(FileWriteMode.APPEND)) { out.write(file.getContent().getBytes()); } return out; } }
3e1ea777310d9a56fd7132ec99ceb4df9ae4464b
425
java
Java
jeecg-boot/jeecg-boot-module-system/src/main/java/hbvi/module/transcationsrecap/mapper/TblTranscationsRecapMapper.java
notszhang/HBVI
08fbbe5c63b4fc74773b0fbd449c8bcd9911e953
[ "Apache-2.0" ]
null
null
null
jeecg-boot/jeecg-boot-module-system/src/main/java/hbvi/module/transcationsrecap/mapper/TblTranscationsRecapMapper.java
notszhang/HBVI
08fbbe5c63b4fc74773b0fbd449c8bcd9911e953
[ "Apache-2.0" ]
null
null
null
jeecg-boot/jeecg-boot-module-system/src/main/java/hbvi/module/transcationsrecap/mapper/TblTranscationsRecapMapper.java
notszhang/HBVI
08fbbe5c63b4fc74773b0fbd449c8bcd9911e953
[ "Apache-2.0" ]
null
null
null
23.611111
86
0.788235
12,955
package hbvi.module.transcationsrecap.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import hbvi.module.transcationsrecap.entity.TblTranscationsRecap; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @Description: Recap流水 * @Author: jeecg-boot * @Date: 2022-04-20 * @Version: V1.0 */ public interface TblTranscationsRecapMapper extends BaseMapper<TblTranscationsRecap> { }
3e1ea78224b9d4c68c3d6723f5d34538aba15ae9
1,890
java
Java
demo/demo-spring-boot-provider/demo-spring-boot-jaxrs-client/src/main/java/org/apache/servicecomb/springboot/jaxrs/client/JaxrsClient.java
asifdxtreme/servicecomb-java-chassis
72cd0e137c4a0c3b899adfa6e19e2fd590743014
[ "Apache-2.0" ]
4
2018-01-08T01:39:35.000Z
2020-03-22T07:58:13.000Z
demo/demo-spring-boot-provider/demo-spring-boot-jaxrs-client/src/main/java/org/apache/servicecomb/springboot/jaxrs/client/JaxrsClient.java
asifdxtreme/servicecomb-java-chassis
72cd0e137c4a0c3b899adfa6e19e2fd590743014
[ "Apache-2.0" ]
3
2021-12-14T21:04:14.000Z
2022-02-01T01:08:24.000Z
demo/demo-spring-boot-provider/demo-spring-boot-jaxrs-client/src/main/java/org/apache/servicecomb/springboot/jaxrs/client/JaxrsClient.java
asifdxtreme/servicecomb-java-chassis
72cd0e137c4a0c3b899adfa6e19e2fd590743014
[ "Apache-2.0" ]
null
null
null
45
104
0.80582
12,956
/* * 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.servicecomb.springboot.jaxrs.client; import org.apache.servicecomb.common.rest.codec.RestObjectMapperFactory; import org.apache.servicecomb.demo.RestObjectMapperWithStringMapper; import org.apache.servicecomb.demo.RestObjectMapperWithStringMapperNotWriteNull; import org.apache.servicecomb.demo.TestMgr; import org.apache.servicecomb.foundation.common.utils.Log4jUtils; import org.apache.servicecomb.springboot.starter.provider.EnableServiceComb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableServiceComb public class JaxrsClient { public static void main(String[] args) throws Exception { RestObjectMapperFactory.setDefaultRestObjectMapper(new RestObjectMapperWithStringMapper()); RestObjectMapperFactory.setConsumerWriterMapper(new RestObjectMapperWithStringMapperNotWriteNull()); Log4jUtils.init(); SpringApplication.run(JaxrsClient.class, args); org.apache.servicecomb.demo.jaxrs.client.JaxrsClient.run(); TestMgr.summary(); } }
3e1ea78d3dab90e2aa496d74d923df5696b505da
4,256
java
Java
geode-core/src/main/java/org/apache/geode/internal/monitoring/ThreadsMonitoringProcess.java
GSSJacky/buildGeodeRedisAdapter
cd1859293b6b57b524125823230663927289fbc1
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
geode-core/src/main/java/org/apache/geode/internal/monitoring/ThreadsMonitoringProcess.java
GSSJacky/buildGeodeRedisAdapter
cd1859293b6b57b524125823230663927289fbc1
[ "Apache-2.0", "BSD-3-Clause" ]
3
2021-05-20T08:17:47.000Z
2022-03-31T01:50:40.000Z
geode-core/src/main/java/org/apache/geode/internal/monitoring/ThreadsMonitoringProcess.java
Krishnan-Raghavan/geode
708588659751c1213c467f5b200b2c36952af563
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
36.376068
100
0.728383
12,957
/* * 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.geode.internal.monitoring; import java.util.TimerTask; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.VisibleForTesting; import org.apache.geode.cache.CacheClosedException; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.control.ResourceManagerStats; import org.apache.geode.internal.monitoring.executor.AbstractExecutor; import org.apache.geode.logging.internal.log4j.api.LogService; public class ThreadsMonitoringProcess extends TimerTask { private static final Logger logger = LogService.getLogger(); private final ThreadsMonitoring threadsMonitoring; private final int timeLimitMillis; private final InternalDistributedSystem internalDistributedSystem; private ResourceManagerStats resourceManagerStats = null; protected ThreadsMonitoringProcess(ThreadsMonitoring tMonitoring, InternalDistributedSystem iDistributedSystem, int timeLimitMillis) { this.timeLimitMillis = timeLimitMillis; this.threadsMonitoring = tMonitoring; this.internalDistributedSystem = iDistributedSystem; } @VisibleForTesting /** * Returns true if a stuck thread was detected */ public boolean mapValidation() { int numOfStuck = 0; for (AbstractExecutor executor : threadsMonitoring.getMonitorMap().values()) { if (executor.isMonitoringSuspended()) { continue; } final long startTime = executor.getStartTime(); final long currentTime = System.currentTimeMillis(); if (startTime == 0) { executor.setStartTime(currentTime); continue; } long threadId = executor.getThreadID(); logger.trace("Checking thread {}", threadId); long delta = currentTime - startTime; if (delta >= timeLimitMillis) { numOfStuck++; logger.warn("Thread {} (0x{}) is stuck", threadId, Long.toHexString(threadId)); executor.handleExpiry(delta); } } updateNumThreadStuckStatistic(numOfStuck); if (numOfStuck == 0) { logger.trace("There are no stuck threads in the system"); } else if (numOfStuck != 1) { logger.warn("There are {} stuck threads in this node", numOfStuck); } else { logger.warn("There is 1 stuck thread in this node"); } return numOfStuck != 0; } private void updateNumThreadStuckStatistic(int numOfStuck) { ResourceManagerStats stats = getResourceManagerStats(); if (stats != null) { stats.setNumThreadStuck(numOfStuck); } } @Override public void run() { mapValidation(); } @VisibleForTesting public ResourceManagerStats getResourceManagerStats() { ResourceManagerStats result = resourceManagerStats; if (result == null) { try { if (internalDistributedSystem == null || !internalDistributedSystem.isConnected()) { return null; } DistributionManager distributionManager = internalDistributedSystem.getDistributionManager(); InternalCache cache = distributionManager.getExistingCache(); result = cache.getInternalResourceManager().getStats(); resourceManagerStats = result; } catch (CacheClosedException e1) { logger.trace("could not update statistic since cache is closed"); } } return result; } }
3e1ea96d17701923f163426dfe53dfcdcdd98fbd
1,080
java
Java
src/test/java/za/sabob/olive/jdbc/mixed/restore/TX_RestoreAutoCommit.java
sabob/olive
3e511665c2e5567611d21c6191fe9a2ea58d7837
[ "Apache-2.0" ]
null
null
null
src/test/java/za/sabob/olive/jdbc/mixed/restore/TX_RestoreAutoCommit.java
sabob/olive
3e511665c2e5567611d21c6191fe9a2ea58d7837
[ "Apache-2.0" ]
1
2018-05-09T18:27:52.000Z
2018-05-09T18:27:52.000Z
src/test/java/za/sabob/olive/jdbc/mixed/restore/TX_RestoreAutoCommit.java
sabob/olive
3e511665c2e5567611d21c6191fe9a2ea58d7837
[ "Apache-2.0" ]
null
null
null
31.764706
115
0.696296
12,958
package za.sabob.olive.jdbc.mixed.restore; import org.testng.*; import org.testng.annotations.*; import za.sabob.olive.jdbc.*; import za.sabob.olive.jdbc.context.*; import za.sabob.olive.postgres.*; public class TX_RestoreAutoCommit extends PostgresBaseTest { @Test public void closeConnectionTest() throws Exception { boolean isEmpty = DSF.getDataSourceContainer().isEmpty(); Assert.assertTrue( isEmpty ); JDBCContext tx = JDBC.beginTransaction( ds ); Assert.assertFalse( tx.getConnection().getAutoCommit() ); JDBCContext op = JDBC.beginOperation( ds ); Assert.assertFalse( op.getConnection().getAutoCommit() ); // beginning Operation doesn't change autoCommit JDBC.cleanupOperation( op ); Assert.assertFalse( op.getConnection().getAutoCommit() );// cleaning up Operation doesn't change autoCommit Assert.assertFalse( op.isOpen() ); Assert.assertFalse( op.isConnectionClosed() ); JDBC.cleanupTransaction( tx ); Assert.assertTrue( tx.isConnectionClosed() ); } }
3e1ea9a2dac2a8dddf57c8c3731403c59db5bef5
4,202
java
Java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DescribeProvisionedProductResult.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DescribeProvisionedProductResult.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DescribeProvisionedProductResult.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
2
2017-10-05T10:52:18.000Z
2018-10-19T09:13:12.000Z
33.349206
159
0.672775
12,959
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisionedProduct" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeProvisionedProductResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Detailed provisioned product information. * </p> */ private ProvisionedProductDetail provisionedProductDetail; /** * <p> * Detailed provisioned product information. * </p> * * @param provisionedProductDetail * Detailed provisioned product information. */ public void setProvisionedProductDetail(ProvisionedProductDetail provisionedProductDetail) { this.provisionedProductDetail = provisionedProductDetail; } /** * <p> * Detailed provisioned product information. * </p> * * @return Detailed provisioned product information. */ public ProvisionedProductDetail getProvisionedProductDetail() { return this.provisionedProductDetail; } /** * <p> * Detailed provisioned product information. * </p> * * @param provisionedProductDetail * Detailed provisioned product information. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeProvisionedProductResult withProvisionedProductDetail(ProvisionedProductDetail provisionedProductDetail) { setProvisionedProductDetail(provisionedProductDetail); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getProvisionedProductDetail() != null) sb.append("ProvisionedProductDetail: ").append(getProvisionedProductDetail()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeProvisionedProductResult == false) return false; DescribeProvisionedProductResult other = (DescribeProvisionedProductResult) obj; if (other.getProvisionedProductDetail() == null ^ this.getProvisionedProductDetail() == null) return false; if (other.getProvisionedProductDetail() != null && other.getProvisionedProductDetail().equals(this.getProvisionedProductDetail()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getProvisionedProductDetail() == null) ? 0 : getProvisionedProductDetail().hashCode()); return hashCode; } @Override public DescribeProvisionedProductResult clone() { try { return (DescribeProvisionedProductResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
3e1ea9e5b1151f5d233c7bbe7bfd1fa73f07bc9f
714
java
Java
Chapter_07_JavaFX/javafx-minimal/src/main/java/be/webtechie/App.java
FDelporte/JavaOnRaspberryPi
09a6a8f4cc30a638b1a95db7fd920cfb711850ad
[ "Apache-2.0" ]
43
2020-02-14T00:51:37.000Z
2022-03-01T15:50:21.000Z
Chapter_07_JavaFX/javafx-minimal/src/main/java/be/webtechie/App.java
FDelporte/JavaOnRaspberryPi
09a6a8f4cc30a638b1a95db7fd920cfb711850ad
[ "Apache-2.0" ]
null
null
null
Chapter_07_JavaFX/javafx-minimal/src/main/java/be/webtechie/App.java
FDelporte/JavaOnRaspberryPi
09a6a8f4cc30a638b1a95db7fd920cfb711850ad
[ "Apache-2.0" ]
10
2020-06-09T13:48:33.000Z
2022-02-27T21:12:40.000Z
24.62069
107
0.659664
12,960
package be.webtechie; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /** * JavaFX App */ public class App extends Application { @Override public void start(Stage stage) { var javaVersion = SystemInfo.javaVersion(); var javafxVersion = SystemInfo.javafxVersion(); var label = new Label("Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + "."); var scene = new Scene(new StackPane(label), 640, 480); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
3e1eabecdb51efa0353dcd49d071a2b0cfee414b
193
java
Java
src/test/java/com/flipkart/databuilderframework/flowtest/data/DPD.java
narendravardi/databuilderframework
7dae13c5e905eb16b24e1a366bddd2d03658cb82
[ "Apache-2.0" ]
19
2015-06-12T05:32:34.000Z
2021-09-14T23:15:02.000Z
src/test/java/com/flipkart/databuilderframework/flowtest/data/DPD.java
narendravardi/databuilderframework
7dae13c5e905eb16b24e1a366bddd2d03658cb82
[ "Apache-2.0" ]
25
2015-04-21T07:09:47.000Z
2021-05-04T19:23:21.000Z
src/test/java/com/flipkart/databuilderframework/flowtest/data/DPD.java
narendravardi/databuilderframework
7dae13c5e905eb16b24e1a366bddd2d03658cb82
[ "Apache-2.0" ]
27
2015-04-22T17:30:29.000Z
2022-02-17T11:59:51.000Z
19.3
56
0.715026
12,961
package com.flipkart.databuilderframework.flowtest.data; import com.flipkart.databuilderframework.model.Data; public class DPD extends Data { public DPD() { super("DPD"); } }
3e1eadd66a78596232981dac916cdbb364f0b675
432
java
Java
RXJavaDemo/app/src/main/java/com/rxjavademo/presenter/HomeContract.java
ernancythakkar/RxJavaDemo
ffcb95ecccb1a8edf57737364cd1263330dd16f1
[ "MIT" ]
null
null
null
RXJavaDemo/app/src/main/java/com/rxjavademo/presenter/HomeContract.java
ernancythakkar/RxJavaDemo
ffcb95ecccb1a8edf57737364cd1263330dd16f1
[ "MIT" ]
null
null
null
RXJavaDemo/app/src/main/java/com/rxjavademo/presenter/HomeContract.java
ernancythakkar/RxJavaDemo
ffcb95ecccb1a8edf57737364cd1263330dd16f1
[ "MIT" ]
null
null
null
20.571429
48
0.710648
12,962
package com.rxjavademo.presenter; import com.rxjavademo.model.AlbumsResponse; import com.rxjavademo.network.ApiService; import java.util.List; public class HomeContract { public interface View { void success(List<AlbumsResponse> data); void error(String message); } public interface HomeActionsListener { // processing to be done here void getAlbums(ApiService apiService); } }
3e1eae271b86aa70989da25c86120c6dd5acbbcd
3,522
java
Java
classpath/avian/Assembler.java
geeksville/avian
dfdd1f6e6c55ada96172f40d1256dc219637c492
[ "0BSD" ]
1
2022-02-02T23:44:49.000Z
2022-02-02T23:44:49.000Z
classpath/avian/Assembler.java
geeksville/avian
dfdd1f6e6c55ada96172f40d1256dc219637c492
[ "0BSD" ]
null
null
null
classpath/avian/Assembler.java
geeksville/avian
dfdd1f6e6c55ada96172f40d1256dc219637c492
[ "0BSD" ]
null
null
null
30.102564
77
0.655877
12,963
/* Copyright (c) 2011, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package avian; import static avian.Stream.write1; import static avian.Stream.write2; import static avian.Stream.write4; import avian.ConstantPool.PoolEntry; import java.util.List; import java.io.OutputStream; import java.io.IOException; public class Assembler { public static final int ACC_PUBLIC = 1 << 0; public static final int ACC_STATIC = 1 << 3; public static final int aaload = 0x32; public static final int aastore = 0x53; public static final int aload = 0x19; public static final int aload_0 = 0x2a; public static final int aload_1 = 0x2b; public static final int astore_0 = 0x4b; public static final int anewarray = 0xbd; public static final int areturn = 0xb0; public static final int dload = 0x18; public static final int dreturn = 0xaf; public static final int dup = 0x59; public static final int fload = 0x17; public static final int freturn = 0xae; public static final int getfield = 0xb4; public static final int goto_ = 0xa7; public static final int iload = 0x15; public static final int invokeinterface = 0xb9; public static final int invokespecial = 0xb7; public static final int invokestatic = 0xb8; public static final int invokevirtual = 0xb6; public static final int ireturn = 0xac; public static final int jsr = 0xa8; public static final int ldc_w = 0x13; public static final int lload = 0x16; public static final int lreturn = 0xad; public static final int new_ = 0xbb; public static final int pop = 0x57; public static final int putfield = 0xb5; public static final int ret = 0xa9; public static final int return_ = 0xb1; public static void writeClass(OutputStream out, List<PoolEntry> pool, int name, int super_, int[] interfaces, MethodData[] methods) throws IOException { int codeAttributeName = ConstantPool.addUtf8(pool, "Code"); write4(out, 0xCAFEBABE); write2(out, 0); // minor version write2(out, 0); // major version write2(out, pool.size() + 1); for (PoolEntry e: pool) { e.writeTo(out); } write2(out, ACC_PUBLIC); // flags write2(out, name + 1); write2(out, super_ + 1); write2(out, interfaces.length); for (int i: interfaces) { write2(out, i + 1); } write2(out, 0); // field count write2(out, methods.length); for (MethodData m: methods) { write2(out, m.flags); write2(out, m.nameIndex + 1); write2(out, m.specIndex + 1); write2(out, 1); // attribute count write2(out, codeAttributeName + 1); write4(out, m.code.length); out.write(m.code); } write2(out, 0); // attribute count } public static class MethodData { public final int flags; public final int nameIndex; public final int specIndex; public final byte[] code; public MethodData(int flags, int nameIndex, int specIndex, byte[] code) { this.flags = flags; this.nameIndex = nameIndex; this.specIndex = specIndex; this.code = code; } } }
3e1eae486e6e87316202f3ef065ba9bec7f3cfcc
3,680
java
Java
app/src/main/java/com/beziercurves/basic/PathOpView.java
WalterBryant/BezierCurves
8780f128b3d8061cd62691d31d2eb9571a14c3b6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/beziercurves/basic/PathOpView.java
WalterBryant/BezierCurves
8780f128b3d8061cd62691d31d2eb9571a14c3b6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/beziercurves/basic/PathOpView.java
WalterBryant/BezierCurves
8780f128b3d8061cd62691d31d2eb9571a14c3b6
[ "Apache-2.0" ]
null
null
null
31.452991
58
0.628261
12,964
package com.beziercurves.basic; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.os.Build; import android.view.View; @TargetApi(Build.VERSION_CODES.KITKAT) public class PathOpView extends View { private Paint mPaint; public PathOpView(Context context) { super(context); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(Color.GREEN); mPaint.setStrokeWidth(10); mPaint.setStyle(Paint.Style.STROKE); mPaint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // DIFFERENCE -- 减去Path2后Path1区域剩下的部分 // drawDifferenceOp(canvas); // INTERSECT --- 保留Path2 和 Path1 共同的部分 // drawIntersectOp(canvas); // UNION -- 保留Path1 和 Path 2 drawUnionOp(canvas); // XOR --- 保留Path1 和 Path2 还有共同的部分 // drawXorOp(canvas); // REVERSE_DIFFERENCE --- 减去Path1后Path2区域剩下的部分 // drawReverseDifferenceOp(canvas); } private void drawDifferenceOp(Canvas canvas) { Path path1 = new Path(); path1.addCircle(150, 150, 100, Path.Direction.CW); Path path2 = new Path(); path2.addCircle(200, 200, 100, Path.Direction.CW); path1.op(path2, Path.Op.DIFFERENCE); canvas.drawPath(path1, mPaint); mPaint.setColor(Color.DKGRAY); mPaint.setStrokeWidth(2); canvas.drawCircle(150, 150, 100, mPaint); canvas.drawCircle(200, 200, 100, mPaint); } private void drawIntersectOp(Canvas canvas) { Path path1 = new Path(); path1.addCircle(150, 150, 100, Path.Direction.CW); Path path2 = new Path(); path2.addCircle(200, 200, 100, Path.Direction.CW); path1.op(path2, Path.Op.INTERSECT); canvas.drawPath(path1, mPaint); mPaint.setColor(Color.DKGRAY); mPaint.setStrokeWidth(2); canvas.drawCircle(150, 150, 100, mPaint); canvas.drawCircle(200, 200, 100, mPaint); } private void drawUnionOp(Canvas canvas) { Path path1 = new Path(); path1.addCircle(150, 150, 100, Path.Direction.CW); Path path2 = new Path(); path2.addCircle(200, 200, 100, Path.Direction.CW); path1.op(path2, Path.Op.UNION); canvas.drawPath(path1, mPaint); mPaint.setColor(Color.DKGRAY); mPaint.setStrokeWidth(2); canvas.drawCircle(150, 150, 100, mPaint); canvas.drawCircle(200, 200, 100, mPaint); } private void drawXorOp(Canvas canvas) { Path path1 = new Path(); path1.addCircle(150, 150, 100, Path.Direction.CW); Path path2 = new Path(); path2.addCircle(200, 200, 100, Path.Direction.CW); path1.op(path2, Path.Op.XOR); canvas.drawPath(path1, mPaint); mPaint.setColor(Color.DKGRAY); mPaint.setStrokeWidth(2); canvas.drawCircle(150, 150, 100, mPaint); canvas.drawCircle(200, 200, 100, mPaint); } private void drawReverseDifferenceOp(Canvas canvas) { Path path1 = new Path(); path1.addCircle(150, 150, 100, Path.Direction.CW); Path path2 = new Path(); path2.addCircle(200, 200, 100, Path.Direction.CW); path1.op(path2, Path.Op.REVERSE_DIFFERENCE); canvas.drawPath(path1, mPaint); mPaint.setColor(Color.DKGRAY); mPaint.setStrokeWidth(2); canvas.drawCircle(150, 150, 100, mPaint); canvas.drawCircle(200, 200, 100, mPaint); } }
3e1eaf59554d3a6d202bdd3c61b7f4de5c90d5cc
2,674
java
Java
src/main/java/org/jf/smalidea/psi/stub/element/SmaliFileElementType.java
bugparty/smalidea
86017532653f3596df4000970fd1d3b6168958eb
[ "Apache-2.0" ]
401
2020-02-24T02:29:11.000Z
2022-03-31T02:52:46.000Z
src/main/java/org/jf/smalidea/psi/stub/element/SmaliFileElementType.java
bugparty/smalidea
86017532653f3596df4000970fd1d3b6168958eb
[ "Apache-2.0" ]
19
2020-03-09T20:29:41.000Z
2022-03-28T14:05:09.000Z
tools/SmaliEx/smalidea/src/main/java/org/jf/smalidea/psi/stub/element/SmaliFileElementType.java
xpierrohk/DigitalPaperApp
e0aae9e68325caa2dc3f42e4e013d2e39dac4b1c
[ "MIT" ]
57
2020-04-10T00:20:07.000Z
2022-03-08T09:37:49.000Z
42.444444
83
0.740838
12,965
/* * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 * OWNER 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. */ package org.jf.smalidea.psi.stub.element; import com.intellij.psi.PsiFile; import com.intellij.psi.StubBuilder; import com.intellij.psi.stubs.DefaultStubBuilder; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.IStubFileElementType; import org.jetbrains.annotations.NotNull; import org.jf.smalidea.SmaliLanguage; import org.jf.smalidea.psi.impl.SmaliFile; import org.jf.smalidea.psi.stub.SmaliFileStub; public class SmaliFileElementType extends IStubFileElementType<SmaliFileStub> { public static final SmaliFileElementType INSTANCE = new SmaliFileElementType(); private SmaliFileElementType() { super("smali.FILE", SmaliLanguage.INSTANCE); } @Override public StubBuilder getBuilder() { return new DefaultStubBuilder() { @Override protected StubElement createStubForFile(@NotNull PsiFile file) { if (file instanceof SmaliFile) { return new SmaliFileStub((SmaliFile)file); } throw new RuntimeException("Unexpected file type"); } }; } }
3e1eaf9dfd3424c2f14908d20c30dd84ca1f5769
10,015
java
Java
java-spiffe-core/src/main/java/io/spiffe/internal/CertificateUtils.java
srwaggon/java-spiffe
e33417b10b141cdc13f3ea7e48ea562fd9dd724a
[ "Apache-2.0" ]
19
2018-05-24T11:15:20.000Z
2021-11-23T21:45:25.000Z
java-spiffe-core/src/main/java/io/spiffe/internal/CertificateUtils.java
srwaggon/java-spiffe
e33417b10b141cdc13f3ea7e48ea562fd9dd724a
[ "Apache-2.0" ]
30
2018-05-23T17:53:59.000Z
2022-02-07T18:59:52.000Z
java-spiffe-core/src/main/java/io/spiffe/internal/CertificateUtils.java
srwaggon/java-spiffe
e33417b10b141cdc13f3ea7e48ea562fd9dd724a
[ "Apache-2.0" ]
13
2018-10-23T14:18:57.000Z
2021-08-04T22:01:58.000Z
41.384298
220
0.701048
12,966
package io.spiffe.internal; import io.spiffe.spiffeid.SpiffeId; import io.spiffe.spiffeid.TrustDomain; import lombok.val; import java.io.ByteArrayInputStream; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static io.spiffe.internal.AsymmetricKeyAlgorithm.EC; import static io.spiffe.internal.AsymmetricKeyAlgorithm.RSA; import static io.spiffe.internal.KeyUsage.CRL_SIGN; import static io.spiffe.internal.KeyUsage.DIGITAL_SIGNATURE; import static io.spiffe.internal.KeyUsage.KEY_CERT_SIGN; import static org.apache.commons.lang3.StringUtils.startsWith; /** * Common certificate utility methods. */ public class CertificateUtils { private static final String SPIFFE_PREFIX = "spiffe://"; private static final int SAN_VALUE_INDEX = 1; private static final String PUBLIC_KEY_INFRASTRUCTURE_ALGORITHM = "PKIX"; private static final String X509_CERTIFICATE_TYPE = "X.509"; private CertificateUtils() { } /** * Generates a list of X.509 certificates from a byte array. * * @param input as byte array representing a list of X.509 certificates, as a DER or PEM * @return a List of {@link X509Certificate} */ public static List<X509Certificate> generateCertificates(final byte[] input) throws CertificateParsingException { if (input.length == 0) { throw new CertificateParsingException("No certificates found"); } val certificateFactory = getCertificateFactory(); Collection<? extends Certificate> certificates; try { certificates = certificateFactory.generateCertificates(new ByteArrayInputStream(input)); } catch (CertificateException e) { throw new CertificateParsingException("Certificate could not be parsed from cert bytes", e); } return certificates.stream() .map(X509Certificate.class::cast) .collect(Collectors.toList()); } /** * Generates a private key from an array of bytes. * * @param privateKeyBytes is a PEM or DER PKCS#8 private key. * @return a instance of {@link PrivateKey} * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ public static PrivateKey generatePrivateKey(final byte[] privateKeyBytes, AsymmetricKeyAlgorithm algorithm, KeyFileFormat keyFileFormat) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException { EncodedKeySpec kspec = getEncodedKeySpec(privateKeyBytes, keyFileFormat); return generatePrivateKeyWithSpec(kspec, algorithm); } /** * Validate a certificate chain with a set of trusted certificates. * * @param chain the certificate chain * @param trustedCerts to validate the certificate chain * @throws CertificateException * @throws CertPathValidatorException */ public static void validate(final List<X509Certificate> chain, final Collection<X509Certificate> trustedCerts) throws CertificateException, CertPathValidatorException { if (chain == null || chain.size() == 0) { throw new IllegalArgumentException("Chain of certificates is empty"); } val certificateFactory = getCertificateFactory(); PKIXParameters pkixParameters; try { pkixParameters = toPkixParameters(trustedCerts); val certPath = certificateFactory.generateCertPath(chain); getCertPathValidator().validate(certPath, pkixParameters); } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException e) { throw new CertificateException(e); } } /** * Extracts the SPIFFE ID from an X.509 certificate. * <p> * It iterates over the list of SubjectAlternativesNames, read each entry, takes the value from the index * defined in SAN_VALUE_INDEX and filters the entries that starts with the SPIFFE_PREFIX and returns the first. * * @param certificate a {@link X509Certificate} * @return an instance of a {@link SpiffeId} * @throws CertificateException if the certificate contains multiple SPIFFE IDs, or does not contain any, or * the SAN extension cannot be decoded */ public static SpiffeId getSpiffeId(final X509Certificate certificate) throws CertificateException { val spiffeIds = getSpiffeIds(certificate); if (spiffeIds.size() > 1) { throw new CertificateException("Certificate contains multiple SPIFFE IDs"); } if (spiffeIds.size() < 1) { throw new CertificateException("Certificate does not contain SPIFFE ID in the URI SAN"); } return SpiffeId.parse(spiffeIds.get(0)); } /** * Extracts the trust domain of a chain of certificates. * * @param chain a list of {@link X509Certificate} * @return a {@link TrustDomain} * @throws CertificateException */ public static TrustDomain getTrustDomain(final List<X509Certificate> chain) throws CertificateException { val spiffeId = getSpiffeId(chain.get(0)); return spiffeId.getTrustDomain(); } public static boolean isCA(final X509Certificate cert) { return cert.getBasicConstraints() != -1; } public static boolean hasKeyUsageCertSign(final X509Certificate cert) { boolean[] keyUsage = cert.getKeyUsage(); return keyUsage[KEY_CERT_SIGN.index()]; } public static boolean hasKeyUsageDigitalSignature(final X509Certificate cert) { boolean[] keyUsage = cert.getKeyUsage(); return keyUsage[DIGITAL_SIGNATURE.index()]; } public static boolean hasKeyUsageCRLSign(final X509Certificate cert) { boolean[] keyUsage = cert.getKeyUsage(); return keyUsage[CRL_SIGN.index()]; } private static EncodedKeySpec getEncodedKeySpec(final byte[] privateKeyBytes, KeyFileFormat keyFileFormat) throws InvalidKeyException { EncodedKeySpec keySpec; if (keyFileFormat == KeyFileFormat.PEM) { byte[] keyDer = toDerFormat(privateKeyBytes); keySpec = new PKCS8EncodedKeySpec(keyDer); } else { keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); } return keySpec; } private static List<String> getSpiffeIds(final X509Certificate certificate) throws CertificateParsingException { if (certificate.getSubjectAlternativeNames() == null) { return Collections.emptyList(); } return certificate.getSubjectAlternativeNames() .stream() .map(san -> (String) san.get(SAN_VALUE_INDEX)) .filter(uri -> startsWith(uri, SPIFFE_PREFIX)) .collect(Collectors.toList()); } private static PrivateKey generatePrivateKeyWithSpec(final EncodedKeySpec keySpec, AsymmetricKeyAlgorithm algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException { PrivateKey privateKey = null; switch (algorithm) { case EC: privateKey = KeyFactory.getInstance(EC.value()).generatePrivate(keySpec); break; case RSA: privateKey = KeyFactory.getInstance(RSA.value()).generatePrivate(keySpec); } return privateKey; } // Create an instance of PKIXParameters used as input for the PKIX CertPathValidator private static PKIXParameters toPkixParameters(final Collection<X509Certificate> trustedCerts) throws CertificateException, InvalidAlgorithmParameterException { if (trustedCerts == null || trustedCerts.isEmpty()) { throw new CertificateException("No trusted Certs"); } val pkixParameters = new PKIXParameters(trustedCerts.stream() .map(c -> new TrustAnchor(c, null)) .collect(Collectors.toSet())); pkixParameters.setRevocationEnabled(false); return pkixParameters; } // Get the default PKIX CertPath Validator private static CertPathValidator getCertPathValidator() throws NoSuchAlgorithmException { return CertPathValidator.getInstance(PUBLIC_KEY_INFRASTRUCTURE_ALGORITHM); } // Get the X.509 Certificate Factory private static CertificateFactory getCertificateFactory() { try { return CertificateFactory.getInstance(X509_CERTIFICATE_TYPE); } catch (CertificateException e) { throw new IllegalStateException("Could not create Certificate Factory", e); } } // Given a private key in PEM format, encode it as DER private static byte[] toDerFormat(final byte[] privateKeyPem) throws InvalidKeyException { String privateKeyAsString = new String(privateKeyPem); privateKeyAsString = privateKeyAsString.replaceAll("(-+BEGIN PRIVATE KEY-+\\r?\\n|-+END PRIVATE KEY-+\\r?\\n?)", ""); privateKeyAsString = privateKeyAsString.replaceAll("\n", ""); val decoder = Base64.getDecoder(); try { return decoder.decode(privateKeyAsString); } catch (Exception e) { throw new InvalidKeyException(e); } } }
3e1eafdde7c5f8d002325f0465b943ebca7a6f35
10,981
java
Java
modules/core/src/main/java/org/apache/ignite/internal/managers/IgniteMBeansManager.java
AndyDem/ignite
5e70f1480c010f7eb423a7ba3750e0d0265db4fa
[ "Apache-2.0" ]
4,339
2015-08-21T21:13:25.000Z
2022-03-30T09:56:44.000Z
modules/core/src/main/java/org/apache/ignite/internal/managers/IgniteMBeansManager.java
AndyDem/ignite
5e70f1480c010f7eb423a7ba3750e0d0265db4fa
[ "Apache-2.0" ]
1,933
2015-08-24T11:37:40.000Z
2022-03-31T08:37:08.000Z
modules/core/src/main/java/org/apache/ignite/internal/managers/IgniteMBeansManager.java
AndyDem/ignite
5e70f1480c010f7eb423a7ba3750e0d0265db4fa
[ "Apache-2.0" ]
2,140
2015-08-21T22:09:00.000Z
2022-03-25T07:57:34.000Z
41.912214
137
0.723978
12,967
/* * 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.managers; import java.util.HashSet; import java.util.Set; import javax.management.JMException; import javax.management.ObjectName; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.ClusterLocalNodeMetricsMXBeanImpl; import org.apache.ignite.internal.ClusterMetricsMXBeanImpl; import org.apache.ignite.internal.ComputeMXBeanImpl; import org.apache.ignite.internal.GridKernalContextImpl; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.IgniteMXBeanImpl; import org.apache.ignite.internal.QueryMXBeanImpl; import org.apache.ignite.internal.ServiceMXBeanImpl; import org.apache.ignite.internal.TransactionMetricsMxBeanImpl; import org.apache.ignite.internal.TransactionsMXBeanImpl; import org.apache.ignite.internal.managers.encryption.EncryptionMXBeanImpl; import org.apache.ignite.internal.processors.cache.persistence.DataStorageMXBeanImpl; import org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationMXBeanImpl; import org.apache.ignite.internal.processors.cache.persistence.snapshot.SnapshotMXBeanImpl; import org.apache.ignite.internal.processors.cache.warmup.WarmUpMXBeanImpl; import org.apache.ignite.internal.processors.cluster.BaselineAutoAdjustMXBeanImpl; import org.apache.ignite.internal.processors.metric.MetricsMxBeanImpl; import org.apache.ignite.internal.processors.performancestatistics.PerformanceStatisticsMBeanImpl; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.FailureHandlingMxBeanImpl; import org.apache.ignite.internal.worker.WorkersControlMXBeanImpl; import org.apache.ignite.mxbean.BaselineAutoAdjustMXBean; import org.apache.ignite.mxbean.ClusterMetricsMXBean; import org.apache.ignite.mxbean.ComputeMXBean; import org.apache.ignite.mxbean.DataStorageMXBean; import org.apache.ignite.mxbean.DefragmentationMXBean; import org.apache.ignite.mxbean.EncryptionMXBean; import org.apache.ignite.mxbean.FailureHandlingMxBean; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.mxbean.MetricsMxBean; import org.apache.ignite.mxbean.PerformanceStatisticsMBean; import org.apache.ignite.mxbean.QueryMXBean; import org.apache.ignite.mxbean.ServiceMXBean; import org.apache.ignite.mxbean.SnapshotMXBean; import org.apache.ignite.mxbean.TransactionMetricsMxBean; import org.apache.ignite.mxbean.TransactionsMXBean; import org.apache.ignite.mxbean.WarmUpMXBean; import org.apache.ignite.mxbean.WorkersControlMXBean; /** * Class that registers and unregisters MBeans for kernal. */ public class IgniteMBeansManager { /** Ignite kernal */ private final IgniteKernal kernal; /** Ignite kernal context. */ private final GridKernalContextImpl ctx; /** Logger. */ private final IgniteLogger log; /** MBean names stored to be unregistered later. */ private final Set<ObjectName> mBeanNames = new HashSet<>(); /** * @param kernal Grid kernal. */ public IgniteMBeansManager(IgniteKernal kernal) { this.kernal = kernal; ctx = (GridKernalContextImpl)kernal.context(); log = ctx.log(IgniteMBeansManager.class); } /** * Registers kernal MBeans (for kernal, metrics, thread pools) after node start. * * @throws IgniteCheckedException if fails to register any of the MBeans. */ public void registerMBeansAfterNodeStarted() throws IgniteCheckedException { if (U.IGNITE_MBEANS_DISABLED) return; // Kernal IgniteMXBean kernalMXBean = new IgniteMXBeanImpl(kernal); registerMBean("Kernal", IgniteKernal.class.getSimpleName(), kernalMXBean, IgniteMXBean.class); // Metrics ClusterMetricsMXBean locMetricsBean = new ClusterLocalNodeMetricsMXBeanImpl(ctx.discovery()); registerMBean("Kernal", locMetricsBean.getClass().getSimpleName(), locMetricsBean, ClusterMetricsMXBean.class); ClusterMetricsMXBean metricsBean = new ClusterMetricsMXBeanImpl(kernal.cluster(), ctx); registerMBean("Kernal", metricsBean.getClass().getSimpleName(), metricsBean, ClusterMetricsMXBean.class); // Transaction metrics TransactionMetricsMxBean txMetricsMXBean = new TransactionMetricsMxBeanImpl(ctx.cache().transactions().metrics()); registerMBean("TransactionMetrics", txMetricsMXBean.getClass().getSimpleName(), txMetricsMXBean, TransactionMetricsMxBean.class); // Transactions TransactionsMXBean txMXBean = new TransactionsMXBeanImpl(ctx); registerMBean("Transactions", txMXBean.getClass().getSimpleName(), txMXBean, TransactionsMXBean.class); // Queries management QueryMXBean qryMXBean = new QueryMXBeanImpl(ctx); registerMBean("Query", qryMXBean.getClass().getSimpleName(), qryMXBean, QueryMXBean.class); // Compute task management ComputeMXBean computeMXBean = new ComputeMXBeanImpl(ctx); registerMBean("Compute", computeMXBean.getClass().getSimpleName(), computeMXBean, ComputeMXBean.class); // Service management ServiceMXBean serviceMXBean = new ServiceMXBeanImpl(ctx); registerMBean("Service", serviceMXBean.getClass().getSimpleName(), serviceMXBean, ServiceMXBean.class); // Data storage DataStorageMXBean dataStorageMXBean = new DataStorageMXBeanImpl(ctx); registerMBean("DataStorage", dataStorageMXBean.getClass().getSimpleName(), dataStorageMXBean, DataStorageMXBean.class); // Baseline configuration BaselineAutoAdjustMXBean baselineAutoAdjustMXBean = new BaselineAutoAdjustMXBeanImpl(ctx); registerMBean("Baseline", baselineAutoAdjustMXBean.getClass().getSimpleName(), baselineAutoAdjustMXBean, BaselineAutoAdjustMXBean.class); // Encryption EncryptionMXBean encryptionMXBean = new EncryptionMXBeanImpl(ctx); registerMBean("Encryption", encryptionMXBean.getClass().getSimpleName(), encryptionMXBean, EncryptionMXBean.class); // Snapshot. SnapshotMXBean snpMXBean = new SnapshotMXBeanImpl(ctx); registerMBean("Snapshot", snpMXBean.getClass().getSimpleName(), snpMXBean, SnapshotMXBean.class); // Defragmentation. DefragmentationMXBean defragMXBean = new DefragmentationMXBeanImpl(ctx); registerMBean("Defragmentation", defragMXBean.getClass().getSimpleName(), defragMXBean, DefragmentationMXBean.class); // Metrics configuration MetricsMxBean metricsMxBean = new MetricsMxBeanImpl(ctx.metric(), log); registerMBean("Metrics", metricsMxBean.getClass().getSimpleName(), metricsMxBean, MetricsMxBean.class); ctx.pools().registerMxBeans(this); if (U.IGNITE_TEST_FEATURES_ENABLED) { WorkersControlMXBean workerCtrlMXBean = new WorkersControlMXBeanImpl(ctx.workersRegistry()); registerMBean("Kernal", workerCtrlMXBean.getClass().getSimpleName(), workerCtrlMXBean, WorkersControlMXBean.class); } FailureHandlingMxBean blockOpCtrlMXBean = new FailureHandlingMxBeanImpl(ctx.workersRegistry(), ctx.cache().context().database()); registerMBean("Kernal", blockOpCtrlMXBean.getClass().getSimpleName(), blockOpCtrlMXBean, FailureHandlingMxBean.class); if (ctx.query().moduleEnabled()) ctx.query().getIndexing().registerMxBeans(this); PerformanceStatisticsMBeanImpl performanceStatMbean = new PerformanceStatisticsMBeanImpl(ctx); registerMBean("PerformanceStatistics", performanceStatMbean.getClass().getSimpleName(), performanceStatMbean, PerformanceStatisticsMBean.class); } /** * Registers kernal MBeans during init phase. * * @throws IgniteCheckedException if fails to register any of the MBeans. */ public void registerMBeansDuringInitPhase() throws IgniteCheckedException { if (U.IGNITE_MBEANS_DISABLED) return; // Warm-up. registerMBean("WarmUp", WarmUpMXBeanImpl.class.getSimpleName(), new WarmUpMXBeanImpl(ctx.cache()), WarmUpMXBean.class ); } /** * Register an Ignite MBean. * * @param grp bean group name * @param name bean name * @param impl bean implementation * @param itf bean interface * @param <T> bean type * @throws IgniteCheckedException if registration fails */ public <T> void registerMBean(String grp, String name, T impl, Class<T> itf) throws IgniteCheckedException { assert !U.IGNITE_MBEANS_DISABLED; try { ObjectName objName = U.registerMBean( ctx.config().getMBeanServer(), ctx.config().getIgniteInstanceName(), grp, name, impl, itf); if (log.isDebugEnabled()) log.debug("Registered MBean: " + objName); mBeanNames.add(objName); } catch (JMException e) { throw new IgniteCheckedException("Failed to register MBean " + name, e); } } /** * Unregisters all previously registered MBeans. * * @return {@code true} if all mbeans were unregistered successfully; {@code false} otherwise. */ public boolean unregisterAllMBeans() { boolean success = true; for (ObjectName name : mBeanNames) success = success && unregisterMBean(name); return success; } /** * Unregisters given MBean. * * @param mbean MBean to unregister. * @return {@code true} if successfully unregistered, {@code false} otherwise. */ private boolean unregisterMBean(ObjectName mbean) { assert !U.IGNITE_MBEANS_DISABLED; try { ctx.config().getMBeanServer().unregisterMBean(mbean); if (log.isDebugEnabled()) log.debug("Unregistered MBean: " + mbean); return true; } catch (JMException e) { U.error(log, "Failed to unregister MBean.", e); return false; } } }
3e1eb00346cc131d4e482e19d0f3ddf8f80ea05d
4,717
java
Java
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/samples/theming/api/GetCurrentSkin.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
607
2018-05-23T19:11:22.000Z
2022-03-28T17:11:34.000Z
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/samples/theming/api/GetCurrentSkin.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
379
2018-05-23T18:52:03.000Z
2022-03-28T11:07:05.000Z
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/samples/theming/api/GetCurrentSkin.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
96
2018-05-26T04:53:09.000Z
2022-03-09T03:25:16.000Z
42.116071
106
0.707017
12,968
/* * Copyright (c) 2005-2021 Radiance Kirill Grouchnikov. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 OWNER 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. */ package org.pushingpixels.radiance.demo.theming.main.samples.theming.api; import org.pushingpixels.radiance.theming.api.RadianceThemingCortex; import org.pushingpixels.radiance.theming.api.RadianceSkin; import org.pushingpixels.radiance.theming.api.skin.AutumnSkin; import org.pushingpixels.radiance.theming.api.skin.BusinessBlackSteelSkin; import org.pushingpixels.radiance.theming.api.skin.GraphiteSkin; import javax.swing.*; import java.awt.*; /** * Test application that shows the use of the * {@link RadianceThemingCortex.ComponentScope#getCurrentSkin(java.awt.Component)} API. * * @author Kirill Grouchnikov * @see RadianceThemingCortex.ComponentScope#getCurrentSkin(java.awt.Component) */ public class GetCurrentSkin extends JFrame { /** * Creates the main frame for <code>this</code> sample. */ public GetCurrentSkin() { super("Per-window skins"); this.setLayout(new FlowLayout()); JButton autumnSkin = new JButton("Autumn skin"); autumnSkin.addActionListener(actionEvent -> SwingUtilities .invokeLater(() -> openSampleFrame(new AutumnSkin()))); this.add(autumnSkin); JButton graphiteSkin = new JButton("Graphite skin"); graphiteSkin.addActionListener(actionEvent -> SwingUtilities .invokeLater(() -> openSampleFrame(new GraphiteSkin()))); this.add(graphiteSkin); this.setSize(400, 200); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * Opens a sample frame under the specified skin. * * @param skin * Skin. */ private void openSampleFrame(RadianceSkin skin) { final JFrame sampleFrame = new JFrame(skin.getDisplayName()); sampleFrame.setLayout(new FlowLayout()); final JButton button = new JButton("Get skin"); button.addActionListener(actionEvent -> SwingUtilities.invokeLater( () -> JOptionPane.showMessageDialog(sampleFrame, "Skin of this button is " + RadianceThemingCortex.ComponentScope.getCurrentSkin(button).getDisplayName()))); sampleFrame.add(button); sampleFrame.setVisible(true); sampleFrame.setSize(200, 100); sampleFrame.setLocationRelativeTo(null); sampleFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); RadianceThemingCortex.RootPaneScope.setSkin(sampleFrame.getRootPane(), skin); SwingUtilities.updateComponentTreeUI(sampleFrame); sampleFrame.repaint(); } /** * The main method for <code>this</code> sample. The arguments are ignored. * * @param args * Ignored. */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); SwingUtilities.invokeLater(() -> { RadianceThemingCortex.GlobalScope.setSkin(new BusinessBlackSteelSkin()); new GetCurrentSkin().setVisible(true); }); } }
3e1eb0a797cad39ffc6e5f8dbfc4147f1df14731
2,500
java
Java
Bingo Client/src/me/dylanmullen/bingo/gfx/ui/panel/UIPanel.java
DylanMullen/Bingo
a1e33dd0c88768474f496e7cc2119151761af7c9
[ "CC0-1.0" ]
1
2021-02-19T12:18:41.000Z
2021-02-19T12:18:41.000Z
Bingo Client/src/me/dylanmullen/bingo/gfx/ui/panel/UIPanel.java
DylanMullen/Bingo
a1e33dd0c88768474f496e7cc2119151761af7c9
[ "CC0-1.0" ]
null
null
null
Bingo Client/src/me/dylanmullen/bingo/gfx/ui/panel/UIPanel.java
DylanMullen/Bingo
a1e33dd0c88768474f496e7cc2119151761af7c9
[ "CC0-1.0" ]
null
null
null
22.727273
106
0.7012
12,969
package me.dylanmullen.bingo.gfx.ui.panel; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JPanel; import javax.swing.Scrollable; import javax.swing.SwingConstants; public abstract class UIPanel extends JPanel implements Scrollable, MouseMotionListener { private static final long serialVersionUID = -3182799998146452612L; protected int x, y; protected int width, height; private int maxUnitIncrement = 20; public UIPanel(int x, int y, int width, int height) { setBounds(x, y, width, height); setLayout(null); } @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); this.x = getX(); this.y = getY(); this.width = getWidth(); this.height = getHeight(); } public abstract void setup(); public abstract void create(); public void mouseMoved(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1); scrollRectToVisible(r); } @Override public Dimension getPreferredSize() { return new Dimension(getWidth(), getHeight()); } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { int currentPosition = 0; if (orientation == SwingConstants.HORIZONTAL) { currentPosition = visibleRect.x; } else { currentPosition = visibleRect.y; } if (direction < 0) { int newPosition = currentPosition - (currentPosition / this.maxUnitIncrement) * this.maxUnitIncrement; return (newPosition == 0) ? this.maxUnitIncrement : newPosition; } else { return ((currentPosition / this.maxUnitIncrement) + 1) * this.maxUnitIncrement - currentPosition; } } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { if (orientation == SwingConstants.HORIZONTAL) { return visibleRect.width - this.maxUnitIncrement; } else { return visibleRect.height - this.maxUnitIncrement; } } public boolean getScrollableTracksViewportWidth() { return false; } public boolean getScrollableTracksViewportHeight() { return false; } public void setMaxUnitIncrement(int pixels) { this.maxUnitIncrement = pixels; } }
3e1eb141f629314097b821a3bbfada45c5c21a56
1,538
java
Java
src/main/java/org/letustakearest/java/samples/halbuilder/UsingHalBuilder.java
flushdia/take-a-REST
87ef0fe8336129f48a1ea2412edacce621f7ef0b
[ "Apache-2.0" ]
1
2015-03-30T11:25:58.000Z
2015-03-30T11:25:58.000Z
src/main/java/org/letustakearest/java/samples/halbuilder/UsingHalBuilder.java
flushdia/take-a-REST
87ef0fe8336129f48a1ea2412edacce621f7ef0b
[ "Apache-2.0" ]
null
null
null
src/main/java/org/letustakearest/java/samples/halbuilder/UsingHalBuilder.java
flushdia/take-a-REST
87ef0fe8336129f48a1ea2412edacce621f7ef0b
[ "Apache-2.0" ]
null
null
null
45.235294
105
0.673602
12,970
package org.letustakearest.java.samples.halbuilder; import com.theoryinpractise.halbuilder.api.Representation; import com.theoryinpractise.halbuilder.api.RepresentationFactory; import org.letustakearest.infrastructure.jaxrs.CustomRepresentationFactory; import org.letustakearest.java.samples.BookingRepresentationProducer; /** * @author volodymyr.tsukur */ public class UsingHalBuilder { public static void main(final String[] args) { new UsingHalBuilder().demo(); } public void demo() { RepresentationFactory representationFactory = new CustomRepresentationFactory(); Representation representation = representationFactory.newRepresentation(). withNamespace("take-a-rest", "http://localhost:8080/api/doc/rels/{rel}"). withProperty("paid", false). withProperty("null", null). withLink("take-a-rest:hotel", "http://localhost:8080/api/hotels/12345"). withLink("take-a-rest:get-hotel", "http://localhost:8080/api/hotels/12345"). withRepresentation("take-a-rest:booking", representationFactory.newRepresentation(). withBean(new BookingRepresentationProducer().newSample()). withLink("take-a-rest:hotel", "http://localhost:8080/api/hotels/12345")). withBean(new BookingRepresentationProducer().newSample()); System.out.println(representation.toString(RepresentationFactory.HAL_JSON)); } }
3e1eb143384d8c0081891c99408b3435f98fd1a0
2,283
java
Java
sdk/src/main/java/com/vk/api/sdk/objects/board/responses/GetCommentsResponse.java
wtlgo/vk-java-sdk
2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2
[ "MIT" ]
332
2016-08-24T11:22:26.000Z
2022-03-30T16:33:31.000Z
sdk/src/main/java/com/vk/api/sdk/objects/board/responses/GetCommentsResponse.java
wtlgo/vk-java-sdk
2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2
[ "MIT" ]
199
2016-09-07T13:23:14.000Z
2022-03-24T06:30:19.000Z
sdk/src/main/java/com/vk/api/sdk/objects/board/responses/GetCommentsResponse.java
wtlgo/vk-java-sdk
2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2
[ "MIT" ]
249
2016-08-23T17:12:17.000Z
2022-03-26T13:35:42.000Z
25.943182
75
0.643014
12,971
// Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.objects.board.responses; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.vk.api.sdk.objects.Validable; import com.vk.api.sdk.objects.annotations.Required; import com.vk.api.sdk.objects.board.TopicComment; import com.vk.api.sdk.objects.board.TopicPoll; import java.util.List; import java.util.Objects; /** * GetCommentsResponse object */ public class GetCommentsResponse implements Validable { /** * Total number */ @SerializedName("count") @Required private Integer count; @SerializedName("items") @Required private List<TopicComment> items; @SerializedName("poll") private TopicPoll poll; public Integer getCount() { return count; } public GetCommentsResponse setCount(Integer count) { this.count = count; return this; } public List<TopicComment> getItems() { return items; } public GetCommentsResponse setItems(List<TopicComment> items) { this.items = items; return this; } public TopicPoll getPoll() { return poll; } public GetCommentsResponse setPoll(TopicPoll poll) { this.poll = poll; return this; } @Override public int hashCode() { return Objects.hash(count, poll, items); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetCommentsResponse getCommentsResponse = (GetCommentsResponse) o; return Objects.equals(count, getCommentsResponse.count) && Objects.equals(poll, getCommentsResponse.poll) && Objects.equals(items, getCommentsResponse.items); } @Override public String toString() { final Gson gson = new Gson(); return gson.toJson(this); } public String toPrettyString() { final StringBuilder sb = new StringBuilder("GetCommentsResponse{"); sb.append("count=").append(count); sb.append(", poll=").append(poll); sb.append(", items=").append(items); sb.append('}'); return sb.toString(); } }
3e1eb17285baf6fde9b708f63a2832d934438fe2
3,890
java
Java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/User.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/User.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
306
2019-09-27T06:41:56.000Z
2019-10-14T08:19:57.000Z
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/User.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2019-10-05T04:59:12.000Z
2019-10-05T04:59:12.000Z
25.933333
84
0.662982
12,972
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2016_09_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; /** * User credentials used for publishing activity. */ @JsonFlatten public class User extends ProxyOnlyResource { /** * Username. */ @JsonProperty(value = "properties.name") private String userName; /** * Username used for publishing. */ @JsonProperty(value = "properties.publishingUserName", required = true) private String publishingUserName; /** * Password used for publishing. */ @JsonProperty(value = "properties.publishingPassword") private String publishingPassword; /** * Password hash used for publishing. */ @JsonProperty(value = "properties.publishingPasswordHash") private String publishingPasswordHash; /** * Password hash salt used for publishing. */ @JsonProperty(value = "properties.publishingPasswordHashSalt") private String publishingPasswordHashSalt; /** * Get username. * * @return the userName value */ public String userName() { return this.userName; } /** * Set username. * * @param userName the userName value to set * @return the User object itself. */ public User withUserName(String userName) { this.userName = userName; return this; } /** * Get username used for publishing. * * @return the publishingUserName value */ public String publishingUserName() { return this.publishingUserName; } /** * Set username used for publishing. * * @param publishingUserName the publishingUserName value to set * @return the User object itself. */ public User withPublishingUserName(String publishingUserName) { this.publishingUserName = publishingUserName; return this; } /** * Get password used for publishing. * * @return the publishingPassword value */ public String publishingPassword() { return this.publishingPassword; } /** * Set password used for publishing. * * @param publishingPassword the publishingPassword value to set * @return the User object itself. */ public User withPublishingPassword(String publishingPassword) { this.publishingPassword = publishingPassword; return this; } /** * Get password hash used for publishing. * * @return the publishingPasswordHash value */ public String publishingPasswordHash() { return this.publishingPasswordHash; } /** * Set password hash used for publishing. * * @param publishingPasswordHash the publishingPasswordHash value to set * @return the User object itself. */ public User withPublishingPasswordHash(String publishingPasswordHash) { this.publishingPasswordHash = publishingPasswordHash; return this; } /** * Get password hash salt used for publishing. * * @return the publishingPasswordHashSalt value */ public String publishingPasswordHashSalt() { return this.publishingPasswordHashSalt; } /** * Set password hash salt used for publishing. * * @param publishingPasswordHashSalt the publishingPasswordHashSalt value to set * @return the User object itself. */ public User withPublishingPasswordHashSalt(String publishingPasswordHashSalt) { this.publishingPasswordHashSalt = publishingPasswordHashSalt; return this; } }
3e1eb1c5235a15d03033fd895a83b658cda6a441
1,388
java
Java
codingmore-demo/src/main/java/top/image/Yasuo.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
17
2022-01-12T08:14:38.000Z
2022-03-28T17:36:19.000Z
codingmore-demo/src/main/java/top/image/Yasuo.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
null
null
null
codingmore-demo/src/main/java/top/image/Yasuo.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
10
2022-02-08T15:47:23.000Z
2022-03-24T00:57:34.000Z
28.916667
87
0.662104
12,973
package top.image; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; public class Yasuo { public static void main(String[] args) { try { File input = new File("ceshi.jpg"); BufferedImage image = ImageIO.read(input); Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter) writers.next(); File compressedImageFile = new File("bbcompress.jpg"); OutputStream os = new FileOutputStream(compressedImageFile); ImageOutputStream ios = ImageIO.createImageOutputStream(os); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.01f); writer.write(null, new IIOImage(image, null, null), param); os.close(); ios.close(); writer.dispose(); } catch (IOException e) { e.printStackTrace(); } } }
3e1eb2046e2ec23fb02c3b2315fb45efb7bfa4ec
1,983
java
Java
vipr-portal/portal/app/models/datatable/ApplicationFullCopySetsDataTable.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
91
2015-06-06T01:40:34.000Z
2020-11-24T07:26:40.000Z
vipr-portal/portal/app/models/datatable/ApplicationFullCopySetsDataTable.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
3
2015-07-14T18:47:53.000Z
2015-07-14T18:50:16.000Z
vipr-portal/portal/app/models/datatable/ApplicationFullCopySetsDataTable.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
71
2015-06-05T21:35:31.000Z
2021-11-07T16:32:46.000Z
33.610169
120
0.751891
12,974
/* * Copyright (c) 2015 EMC Corporation * All Rights Reserved */ package models.datatable; import java.util.List; import com.emc.storageos.model.NamedRelatedResourceRep; import com.emc.storageos.model.RelatedResourceRep; import com.emc.storageos.model.block.VolumeRestRep; import com.google.common.collect.Lists; import util.BourneUtil; import util.datatable.DataTable; public class ApplicationFullCopySetsDataTable extends DataTable { public ApplicationFullCopySetsDataTable() { addColumn("cloneGroups").setRenderFunction("renderClones"); addColumn("createdTime").setRenderFunction("render.localDate"); addColumn("subGroup"); sortAll(); } //Suppressing sonar violation for need of accessor methods. Accessor methods are not needed and we use public variables @SuppressWarnings("ClassVariableVisibilityCheck") public static class ApplicationFullCopySets { public String cloneGroups; public long createdTime; public List<String> subGroup = Lists.newArrayList(); public RelatedResourceRep associatedSourceVolume; public String group; public ApplicationFullCopySets(String sets, List<NamedRelatedResourceRep> volumeDetailClone) { cloneGroups = sets; for (NamedRelatedResourceRep clone : volumeDetailClone) { VolumeRestRep blockVolume = BourneUtil.getViprClient() .blockVolumes().get((clone.getId())); if (blockVolume.getProtection() != null && blockVolume.getProtection().getFullCopyRep() != null) { associatedSourceVolume = blockVolume.getProtection() .getFullCopyRep().getAssociatedSourceVolume(); } if (associatedSourceVolume != null) { VolumeRestRep associatedVolume = BourneUtil.getViprClient() .blockVolumes().get(associatedSourceVolume.getId()); group = associatedVolume.getReplicationGroupInstance(); if (!subGroup.contains(group)) { subGroup.add(group); } } createdTime = blockVolume.getCreationTime().getTime().getTime(); ; } } } }
3e1eb2e347921decf2fae4c23bdf26cfdbd1e009
16,434
java
Java
core/data/src/main/java/imagej/data/overlay/ThresholdOverlay.java
jcarvalhogo/imagej
588bbd85637fa296455db3197f57ba5175b17581
[ "BSD-2-Clause" ]
null
null
null
core/data/src/main/java/imagej/data/overlay/ThresholdOverlay.java
jcarvalhogo/imagej
588bbd85637fa296455db3197f57ba5175b17581
[ "BSD-2-Clause" ]
null
null
null
core/data/src/main/java/imagej/data/overlay/ThresholdOverlay.java
jcarvalhogo/imagej
588bbd85637fa296455db3197f57ba5175b17581
[ "BSD-2-Clause" ]
null
null
null
30.890977
80
0.739808
12,975
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.data.overlay; import imagej.data.Dataset; import imagej.data.event.DatasetRestructuredEvent; import imagej.data.event.OverlayUpdatedEvent; import imagej.display.Displayable; import imagej.util.ColorRGB; import imagej.util.Colors; import net.imglib2.img.ImgPlus; import net.imglib2.meta.AxisType; import net.imglib2.ops.condition.Condition; import net.imglib2.ops.condition.FunctionGreaterCondition; import net.imglib2.ops.condition.FunctionLessCondition; import net.imglib2.ops.condition.OrCondition; import net.imglib2.ops.condition.WithinRangeCondition; import net.imglib2.ops.function.Function; import net.imglib2.ops.function.real.RealImageFunction; import net.imglib2.ops.pointset.ConditionalPointSet; import net.imglib2.ops.pointset.HyperVolumePointSet; import net.imglib2.ops.pointset.PointSet; import net.imglib2.ops.pointset.PointSetRegionOfInterest; import net.imglib2.roi.RegionOfInterest; import net.imglib2.type.numeric.RealType; import org.scijava.Context; import org.scijava.event.EventHandler; import org.scijava.event.EventService; /** * A {@link ThresholdOverlay} is an {@link Overlay} that represents the set of * points whose data values are in a range prescribed by API user. * * @author Barry DeZonia */ public class ThresholdOverlay extends AbstractOverlay { // -- instance variables -- private final Dataset dataset; private Function<long[], RealType<?>> function; private RealType<?> variable; private Displayable figure; private ConditionalPointSet pointsLess; private ConditionalPointSet pointsGreater; private ConditionalPointSet pointsWithin; private ConditionalPointSet pointsOutside; private FunctionLessCondition<? extends RealType<?>> conditionLess; private FunctionGreaterCondition<? extends RealType<?>> conditionGreater; private WithinRangeCondition<? extends RealType<?>> conditionWithin; private OrCondition<long[]> conditionOutside; private RegionOfInterest regionAdapter; private ColorRGB colorLess; private ColorRGB colorWithin; private ColorRGB colorGreater; private String defaultName; // -- ThresholdOverlay methods -- /** * Construct a {@link ThresholdOverlay} on a {@link Dataset} given an * {@link Context} context. */ public ThresholdOverlay(Context context, Dataset dataset) { setContext(context); this.dataset = dataset; this.figure = null; init(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); initAttributes(); resetThreshold(); setDefaultName(false); } /** * Construct a {@link ThresholdOverlay} on a {@link Dataset} given an * {@link Context} context, and a numeric range within which the data values of * interest exist. */ public ThresholdOverlay(Context context, Dataset ds, double min, double max) { this(context, ds); setRange(min,max); } /** * Helper method used by services to tie this overlay to its graphic * representation. Sometimes this overlay needs to redraw its graphics in * response to changes in the threshold values. Various services may use this * method but this method is not for general consumption. */ public void setFigure(Displayable figure) { this.figure = figure; } /** * Returns the {@link Displayable} figure associated with this overlay. */ public Displayable getFigure() { return figure; } /** * Sets the range of interest for this overlay. As a side effect the name of * the overlay is updated. */ public void setRange(double min, double max) { boolean changed = (min != conditionWithin.getMin() || max != conditionWithin.getMax()); conditionWithin.setMin(min); conditionWithin.setMax(max); conditionLess.setValue(min); conditionGreater.setValue(max); // make sure all pointsets know they've changed pointsGreater.setCondition(conditionGreater); pointsLess.setCondition(conditionLess); pointsWithin.setCondition(conditionWithin); pointsOutside.setCondition(conditionOutside); setDefaultName(changed); } /** * Gets the lower end of the range of interest for this overlay. */ public double getRangeMin() { return conditionWithin.getMin(); } /** * Gets the upper end of the range of interest for this overlay. */ public double getRangeMax() { return conditionWithin.getMax(); } /** * Resets the range of interest of this overlay to default values. */ public void resetThreshold() { // TODO - this is hacky. Maybe we need actual data values but scanning is // slow. Or maybe we delete threshold? No, we use it in constructor. RealType<?> type = dataset.getType(); double min = type.getMinValue(); double max = type.getMaxValue(); if (min < -20000) min = -20000; if (max > 20000) max = 20000; setRange(min, max / 2); } /** * Returns the set of points whose data values are within the range of * interest. */ public PointSet getPointsWithin() { return pointsWithin; } /** * Returns the set of points whose data values are less than the range of * interest. */ public PointSet getPointsLess() { return pointsLess; } /** * Returns the set of points whose data values are greater than the range of * interest. */ public PointSet getPointsGreater() { return pointsGreater; } /** * Returns the set of points whose data values are outside the range of * interest. */ public PointSet getPointsOutside() { return pointsOutside; } /** * Returns the {@link ThresholdOverlay}'s {@link Condition} used to determine * which points are within than the threshold. * <p> * By design the return value is not a specialized version of a Condition. * Users must not poke the threshold values via this Condition. This would * bypass internal communication. API users should call setRange(min, max) on * this {@link ThresholdOverlay} if they want to manipulate the display range. */ public Condition<long[]> getConditionWithin() { return conditionWithin; } /** * Returns the {@link ThresholdOverlay}'s {@link Condition} used to determine * which points are less than the threshold. * <p> * By design the return value is not a specialized version of a Condition. * Users must not poke the threshold values via this Condition. This would * bypass internal communication. API users should call setRange(min, max) on * this {@link ThresholdOverlay} if they want to manipulate the display range. */ public Condition<long[]> getConditionLess() { return conditionLess; } /** * Returns the {@link ThresholdOverlay}'s {@link Condition} used to determine * which points are greater than the threshold. * <p> * By design the return value is not a specialized version of a Condition. * Users must not poke the threshold values via this Condition. This would * bypass internal communication. API users should call setRange(min, max) on * this {@link ThresholdOverlay} if they want to manipulate the display range. */ public Condition<long[]> getConditionGreater() { return conditionGreater; } /** * Returns the {@link ThresholdOverlay}'s {@link Condition} used to determine * which points are outside than the threshold. * <p> * By design the return value is not a specialized version of a Condition. * Users must not poke the threshold values via this Condition. This would * bypass internal communication. API users should call setRange(min, max) on * this {@link ThresholdOverlay} if they want to manipulate the display range. */ public Condition<long[]> getConditionOutside() { return conditionOutside; } /** * Gets the color used when rendering points less than the threshold range. */ public ColorRGB getColorLess() { return colorLess; } /** * Gets the color used when rendering points greater than the threshold range. */ public ColorRGB getColorGreater() { return colorGreater; } /** * Gets the color used when rendering points within the threshold range. */ public ColorRGB getColorWithin() { return colorWithin; } /** * Sets the color used when rendering points less than the threshold range. */ public void setColorLess(ColorRGB c) { colorLess = c; } /** * Sets the color used when rendering points greater than the threshold range. */ public void setColorGreater(ColorRGB c) { colorGreater = c; } /** * Sets the color used when rendering points within the threshold range. */ public void setColorWithin(ColorRGB c) { colorWithin = c; } /** * Determines the relationship between the value of the underlying data and * the threshold range. The data is evaluated at the given point. Data points * whose value is less than the threshold range are classified as -1. Data * points whose value is within the threshold range are classified as 0. And * data points whose value is greater than the threshold range are classified * as 1. NaN data values are classified as Integer.MAX_VALUE. * <p> * This method is used by the renderers to quickly determine a point's status * and can be used generally by interested parties. * * @param point The coordinate point at which to test the underlying data * @return -1, 0, or 1 */ public int classify(long[] point) { function.compute(point, variable); double val = variable.getRealDouble(); if (Double.isNaN(val)) return Integer.MAX_VALUE; if (val < conditionWithin.getMin()) return -1; if (val > conditionWithin.getMax()) return 1; return 0; } // -- Overlay methods -- @Override public void update() { if (figure != null) figure.draw(); } @Override public void rebuild() { update(); // TODO - is this all we need to do? I think so. } @Override public boolean isDiscrete() { return true; } @Override public int getAxisIndex(AxisType axis) { return dataset.getAxisIndex(axis); } @Override public AxisType axis(int d) { return dataset.axis(d); } @Override public void axes(AxisType[] axes) { dataset.axes(axes); } @Override public void setAxis(AxisType axis, int d) { dataset.setAxis(axis, d); } // TODO these two calibration methods are inconsistent. Decide what is best. @Override public double calibration(int d) { return dataset.calibration(d); } @Override public void setCalibration(double cal, int d) { if (cal == 1 && (d == 0 || d == 1)) return; throw new IllegalArgumentException( "Cannot set calibration of a ThresholdOverlay"); } @Override public int numDimensions() { return pointsWithin.numDimensions(); } @Override public long min(int d) { return pointsWithin.min(d); } @Override public long max(int d) { return pointsWithin.max(d); } @Override public double realMin(int d) { return min(d); } @Override public double realMax(int d) { return max(d); } @Override public void dimensions(long[] dimensions) { pointsWithin.dimensions(dimensions); } @Override public long dimension(int d) { return pointsWithin.dimension(d); } @Override public RegionOfInterest getRegionOfInterest() { return regionAdapter; } @Override public ThresholdOverlay duplicate() { double min = getRangeMin(); double max = getRangeMax(); ThresholdOverlay overlay = new ThresholdOverlay(getContext(), dataset, min, max); overlay.setColorWithin(getColorWithin()); overlay.setColorLess(getColorLess()); overlay.setColorGreater(getColorGreater()); return overlay; } @Override public void move(double[] deltas) { // do nothing - thresholds don't move though space } @Override public String getName() { String name = super.getName(); if (name != null) return name; return defaultName; } // -- Event handlers -- @EventHandler protected void onEvent(DatasetRestructuredEvent evt) { if (evt.getObject() == dataset) { reinit(); rebuild(); } } // -- helpers -- @SuppressWarnings({ "unchecked", "rawtypes" }) private void init(double min, double max) { ImgPlus<? extends RealType<?>> imgPlus = dataset.getImgPlus(); function = new RealImageFunction(imgPlus, imgPlus.firstElement()); variable = function.createOutput(); conditionWithin = new WithinRangeCondition(function, min, max); conditionLess = new FunctionLessCondition(function, min); conditionGreater = new FunctionGreaterCondition(function, max); conditionOutside = new OrCondition<long[]>(conditionLess, conditionGreater); long[] dims = new long[imgPlus.numDimensions()]; imgPlus.dimensions(dims); HyperVolumePointSet volume = new HyperVolumePointSet(dims); pointsLess = new ConditionalPointSet(volume, conditionLess); pointsGreater = new ConditionalPointSet(volume, conditionGreater); pointsWithin = new ConditionalPointSet(volume, conditionWithin); pointsOutside = new ConditionalPointSet(volume, conditionOutside); regionAdapter = new PointSetRegionOfInterest(pointsWithin); setDefaultName(false); } // Updates the guts of the various members of this class to reflect a changed // Dataset. It makes sure that anyone using references from before should be // fine (as long as not concurrently accessing while changes made). @SuppressWarnings({ "unchecked", "rawtypes" }) private void reinit() { ImgPlus<? extends RealType<?>> imgPlus = dataset.getImgPlus(); function = new RealImageFunction(imgPlus, imgPlus.firstElement()); conditionWithin.setFunction( (Function) function); conditionLess.setFunction( (Function) function); conditionGreater.setFunction( (Function) function); // no change needed for conditionOutside long[] dims = new long[imgPlus.numDimensions()]; imgPlus.dimensions(dims); HyperVolumePointSet volume = new HyperVolumePointSet(dims); pointsWithin.setPointSet(volume); pointsLess.setPointSet(volume); pointsGreater.setPointSet(volume); // let ConditionalPointSets know they need bounds recalc via setCondition() pointsWithin.setCondition(conditionWithin); pointsLess.setCondition(conditionLess); pointsGreater.setCondition(conditionGreater); pointsOutside.setCondition(conditionOutside); // regionAdapter does not need any changes setDefaultName(false); } private void initAttributes() { setAlpha(255); setFillColor(Colors.RED); setLineColor(Colors.RED); setLineEndArrowStyle(ArrowStyle.NONE); setLineStartArrowStyle(ArrowStyle.NONE); setLineStyle(LineStyle.NONE); setLineWidth(1); setColorWithin(Colors.RED); setColorLess(null); setColorGreater(null); } private void setDefaultName(boolean emitEvent) { defaultName = "Threshold: " + conditionWithin.getMin() + " to " + conditionWithin.getMax(); if (emitEvent) { OverlayUpdatedEvent event = new OverlayUpdatedEvent(this); getContext().getService(EventService.class).publish(event); } } }
3e1eb33f251a2639043bd35dcfc827d0d8782bd8
307
java
Java
src/ml/mcos/itemcommand/action/ChatAction.java
myunco/ItemCommand
32fc6f6cc9c4627dc7cf197c02f2e7c032dfc068
[ "Apache-2.0" ]
null
null
null
src/ml/mcos/itemcommand/action/ChatAction.java
myunco/ItemCommand
32fc6f6cc9c4627dc7cf197c02f2e7c032dfc068
[ "Apache-2.0" ]
null
null
null
src/ml/mcos/itemcommand/action/ChatAction.java
myunco/ItemCommand
32fc6f6cc9c4627dc7cf197c02f2e7c032dfc068
[ "Apache-2.0" ]
null
null
null
19.1875
63
0.687296
12,976
package ml.mcos.itemcommand.action; import org.bukkit.entity.Player; public class ChatAction extends Action { public ChatAction(String value) { super(value); } @Override public void execute(Player player) { player.chat(plugin.replacePlaceholders(player, value)); } }
3e1eb3444957efaa3efdace3b1da976b66d137bd
1,451
java
Java
src/nam/tran/day13/Solution.java
NamTranDev/Hackerrank30Day
b2d95a6e2c825dfa789f8cae6fdae6019efa48b2
[ "Apache-2.0" ]
null
null
null
src/nam/tran/day13/Solution.java
NamTranDev/Hackerrank30Day
b2d95a6e2c825dfa789f8cae6fdae6019efa48b2
[ "Apache-2.0" ]
null
null
null
src/nam/tran/day13/Solution.java
NamTranDev/Hackerrank30Day
b2d95a6e2c825dfa789f8cae6fdae6019efa48b2
[ "Apache-2.0" ]
null
null
null
22.671875
68
0.589938
12,977
package nam.tran.day13; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String title = scanner.nextLine(); String author = scanner.nextLine(); int price = scanner.nextInt(); scanner.close(); Book book = new MyBook(title, author, price); book.display(); } } abstract class Book { String title; String author; Book(String title, String author) { this.title = title; this.author = author; } abstract void display(); } // Declare your class here. Do not use the 'public' access modifier. class MyBook extends Book { // Declare the price instance variable int price; /** * Class Constructor * * @param title The book's title. * @param author The book's author. * @param price The book's price. **/ // Write your constructor here MyBook(String title, String author,int price){ super(title, author); this.price = price; } /** * Method Name: display * * Print the title, author, and price in the specified format. **/ // Write your method here @java.lang.Override void display() { System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Price: " + price); } // End class }
3e1eb49caefee44c23d77cdff0bae0a069438838
461
java
Java
opensrp-web/src/test/java/org/opensrp/integration/ScheduleTrackingSchedulesJSONTest.java
fazries/opensrp-server
9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47
[ "Apache-2.0" ]
26
2015-03-05T15:44:34.000Z
2018-11-03T20:01:39.000Z
opensrp-web/src/test/java/org/opensrp/integration/ScheduleTrackingSchedulesJSONTest.java
fazries/opensrp-server
9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47
[ "Apache-2.0" ]
462
2015-02-23T17:10:38.000Z
2020-10-23T10:37:04.000Z
opensrp-web/src/test/java/org/opensrp/integration/ScheduleTrackingSchedulesJSONTest.java
fazries/opensrp-server
9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47
[ "Apache-2.0" ]
50
2015-02-20T12:07:52.000Z
2020-07-09T11:36:57.000Z
32.928571
106
0.813449
12,978
package org.opensrp.integration; import org.junit.Test; import org.motechproject.scheduletracking.api.repository.TrackedSchedulesJsonReaderImpl; public class ScheduleTrackingSchedulesJSONTest { @Test public void shouldNotFailWhileConvertingEveryScheduleFileToValidScheduleObject() throws Exception { TrackedSchedulesJsonReaderImpl schedulesReader = new TrackedSchedulesJsonReaderImpl("/schedules"); schedulesReader.records(); } }
3e1eb4d9ff6e6cdfb23955b8815b52cdd7c74ac3
2,581
java
Java
src/main/java/seedu/address/commons/util/FileUtil.java
yunchun-liu/FastTask
8ba26c493a29316cbe33675422120a151da263d9
[ "MIT" ]
6
2016-10-01T03:45:14.000Z
2016-11-07T16:45:56.000Z
src/main/java/seedu/address/commons/util/FileUtil.java
yunchun-liu/FastTask
8ba26c493a29316cbe33675422120a151da263d9
[ "MIT" ]
112
2016-10-01T16:23:06.000Z
2016-11-07T15:49:05.000Z
src/main/java/seedu/address/commons/util/FileUtil.java
yunchun-liu/FastTask
8ba26c493a29316cbe33675422120a151da263d9
[ "MIT" ]
140
2016-09-29T12:28:30.000Z
2018-09-09T08:33:27.000Z
29
99
0.639287
12,979
package seedu.address.commons.util; import java.io.File; import java.io.IOException; import java.nio.file.Files; /** * Writes and reads files */ public class FileUtil { private static final String CHARSET = "UTF-8"; public static boolean isFileExists(File file) { return file.exists() && file.isFile(); } public static void createIfMissing(File file) throws IOException { if (!isFileExists(file)) { createFile(file); } } /** * Creates a file if it does not exist along with its missing parent directories * * @return true if file is created, false if file already exists */ public static boolean createFile(File file) throws IOException { if (file.exists()) { return false; } createParentDirsOfFile(file); return file.createNewFile(); } /** * Creates the given directory along with its parent directories * * @param dir the directory to be created; assumed not null * @throws IOException if the directory or a parent directory cannot be created */ public static void createDirs(File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Failed to make directories of " + dir.getName()); } } /** * Creates parent directories of file if it has a parent directory */ public static void createParentDirsOfFile(File file) throws IOException { File parentDir = file.getParentFile(); if (parentDir != null) { createDirs(parentDir); } } /** * Assumes file exists */ public static String readFromFile(File file) throws IOException { return new String(Files.readAllBytes(file.toPath()), CHARSET); } /** * Writes given string to a file. * Will create the file if it does not exist yet. */ public static void writeToFile(File file, String content) throws IOException { Files.write(file.toPath(), content.getBytes(CHARSET)); } /** * Converts a string to a platform-specific file path * @param pathWithForwardSlash A String representing a file path but using '/' as the separator * @return {@code pathWithForwardSlash} but '/' replaced with {@code File.separator} */ public static String getPath(String pathWithForwardSlash) { assert pathWithForwardSlash != null; assert pathWithForwardSlash.contains("/"); return pathWithForwardSlash.replace("/", File.separator); } }
3e1eb50edcd78b067088f9c606f6a44708efd596
292
java
Java
statistics/src/main/java/cn/edu/nju/software/algorithm/kmeans/DijkstraResult.java
yzgqy/pinpoint
59eae56224a2f850c72c7cc22c443c9bf9ce9a24
[ "Apache-2.0" ]
null
null
null
statistics/src/main/java/cn/edu/nju/software/algorithm/kmeans/DijkstraResult.java
yzgqy/pinpoint
59eae56224a2f850c72c7cc22c443c9bf9ce9a24
[ "Apache-2.0" ]
null
null
null
statistics/src/main/java/cn/edu/nju/software/algorithm/kmeans/DijkstraResult.java
yzgqy/pinpoint
59eae56224a2f850c72c7cc22c443c9bf9ce9a24
[ "Apache-2.0" ]
null
null
null
19.466667
45
0.756849
12,980
package cn.edu.nju.software.algorithm.kmeans; import lombok.Getter; import lombok.Setter; //存放最短路径的实体 @Setter @Getter public class DijkstraResult { private String sourceData; private int sourceId; private String targetData; private int targetId; private double weigth; }
3e1eb5153e99c296377f3a43a5942beec67f823d
402
java
Java
spring-context/src/test/java/example/test/Object/ObjectB.java
minute5/Spring
e4fe4bed7aeb389e5b39ba486b19b5f3305515bc
[ "Apache-2.0" ]
null
null
null
spring-context/src/test/java/example/test/Object/ObjectB.java
minute5/Spring
e4fe4bed7aeb389e5b39ba486b19b5f3305515bc
[ "Apache-2.0" ]
null
null
null
spring-context/src/test/java/example/test/Object/ObjectB.java
minute5/Spring
e4fe4bed7aeb389e5b39ba486b19b5f3305515bc
[ "Apache-2.0" ]
null
null
null
16.16
62
0.725248
12,981
package example.test.Object; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author anpch@example.com * @since 2020/7/10 */ @Component("b") public class ObjectB { @Autowired private ObjectA a; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
3e1eb522738d20746a8231fb53a822f8a5588f1a
495
java
Java
web/src/main/java/com/navercorp/pinpoint/web/config/ExecutorFactory.java
qingyuan1232/pinpoint
ff689f1fa0589bd7469c78bc5dab08089c1098a3
[ "Apache-2.0" ]
1
2019-05-28T01:19:03.000Z
2019-05-28T01:19:03.000Z
web/src/main/java/com/navercorp/pinpoint/web/config/ExecutorFactory.java
qingyuan1232/pinpoint
ff689f1fa0589bd7469c78bc5dab08089c1098a3
[ "Apache-2.0" ]
1
2019-04-18T01:46:47.000Z
2019-04-18T01:46:47.000Z
web/src/main/java/com/navercorp/pinpoint/web/config/ExecutorFactory.java
qingyuan1232/pinpoint
ff689f1fa0589bd7469c78bc5dab08089c1098a3
[ "Apache-2.0" ]
null
null
null
22.5
88
0.719192
12,982
package com.navercorp.pinpoint.web.config; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author: zhao qingyuan * @date: 2018-11-23 9:04 */ public class ExecutorFactory { private ExecutorFactory() { } public static ExecutorService getInstance() { return ExecutorHolder.INSTANCE; } private static class ExecutorHolder { public static final ExecutorService INSTANCE = Executors.newFixedThreadPool(20); } }
3e1eb57cc19ae0b3602f9982afa9acc126ebe4f3
798
java
Java
Project0/src/main/java/com/revature/beans/Account.java
2004javausf/Project0CaseyYan
10229216753922afca29082ea9f7e63bedf856fc
[ "MIT" ]
null
null
null
Project0/src/main/java/com/revature/beans/Account.java
2004javausf/Project0CaseyYan
10229216753922afca29082ea9f7e63bedf856fc
[ "MIT" ]
null
null
null
Project0/src/main/java/com/revature/beans/Account.java
2004javausf/Project0CaseyYan
10229216753922afca29082ea9f7e63bedf856fc
[ "MIT" ]
null
null
null
16.625
72
0.694236
12,983
package com.revature.beans; import java.io.Serializable; public class Account implements Serializable{ /** * */ private static final long serialVersionUID = -498284351838735069L; private double balance; private boolean approved; public Account(double balance, boolean approved) { super(); this.balance = balance; this.approved = approved; } public Account() { balance = 0; approved = false; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } @Override public String toString() { return "Account [balance=" + balance + ", approved=" + approved + "]"; } }
3e1eb5dc7134a6999fb4d2ee0d63966a95fe7564
4,790
java
Java
land-services/src/main/java/org/egov/land/service/LandService.java
pmidc-digit/municipal-services
9c109055949bcaf5b23f73090d8b94964500c825
[ "MIT" ]
11
2021-04-22T13:18:00.000Z
2021-07-13T06:24:48.000Z
land-services/src/main/java/org/egov/land/service/LandService.java
pmidc-digit/municipal-services
9c109055949bcaf5b23f73090d8b94964500c825
[ "MIT" ]
940
2019-12-03T10:55:53.000Z
2022-03-16T18:37:25.000Z
land-services/src/main/java/org/egov/land/service/LandService.java
pmidc-digit/municipal-services
9c109055949bcaf5b23f73090d8b94964500c825
[ "MIT" ]
30
2019-12-06T09:35:45.000Z
2022-02-04T15:23:21.000Z
31.30719
106
0.757829
12,984
package org.egov.land.service; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.validation.Valid; import org.egov.common.contract.request.RequestInfo; import org.egov.land.repository.LandRepository; import org.egov.land.util.LandConstants; import org.egov.land.util.LandUtil; import org.egov.land.validator.LandValidator; import org.egov.land.web.models.LandInfo; import org.egov.land.web.models.LandInfoRequest; import org.egov.land.web.models.LandSearchCriteria; import org.egov.land.web.models.UserDetailResponse; import org.egov.tracer.model.CustomException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class LandService { @Autowired LandValidator landValidator; @Autowired private LandEnrichmentService enrichmentService; @Autowired private LandUserService userService; @Autowired private LandRepository repository; @Autowired private LandUtil util; public LandInfo create(@Valid LandInfoRequest landRequest) { Object mdmsData = util.mDMSCall(landRequest.getRequestInfo(), landRequest.getLandInfo().getTenantId()); if (landRequest.getLandInfo().getTenantId().split("\\.").length == 1) { throw new CustomException(LandConstants.INVALID_TENANT, " Application cannot be create at StateLevel"); } landValidator.validateLandInfo(landRequest,mdmsData); userService.manageUser(landRequest); enrichmentService.enrichLandInfoRequest(landRequest, false); repository.save(landRequest); return landRequest.getLandInfo(); } public LandInfo update(@Valid LandInfoRequest landRequest) { LandInfo landInfo = landRequest.getLandInfo(); Object mdmsData = util.mDMSCall(landRequest.getRequestInfo(), landRequest.getLandInfo().getTenantId()); if (landInfo.getId() == null) { throw new CustomException(LandConstants.UPDATE_ERROR, "Id is mandatory to update "); } landInfo.getOwners().forEach(owner -> { if (owner.getOwnerType() == null) { owner.setOwnerType("NONE"); } }); landValidator.validateLandInfo(landRequest, mdmsData); userService.manageUser(landRequest); enrichmentService.enrichLandInfoRequest(landRequest, true); repository.update(landRequest); return landRequest.getLandInfo(); } public List<LandInfo> search(LandSearchCriteria criteria, RequestInfo requestInfo) { List<LandInfo> landInfos; landValidator.validateSearch(requestInfo, criteria); if (criteria.getMobileNumber() != null) { landInfos = getLandFromMobileNumber(criteria, requestInfo); List<String> landIds = new ArrayList<String>(); for (LandInfo li : landInfos) { landIds.add(li.getId()); } criteria.setMobileNumber(null); criteria.setIds(landIds); } landInfos = fetchLandInfoData(criteria, requestInfo); if (!CollectionUtils.isEmpty(landInfos)) { log.debug("Received final landInfo response in service call.."); } return landInfos; } private List<LandInfo> getLandFromMobileNumber(LandSearchCriteria criteria, RequestInfo requestInfo) { List<LandInfo> landInfo = new LinkedList<>(); UserDetailResponse userDetailResponse = userService.getUser(criteria, requestInfo); // If user not found with given user fields return empty list if (userDetailResponse.getUser().size() == 0) { return Collections.emptyList(); }else{ List<String> ids = new ArrayList<String>(); for(int i=0; i<userDetailResponse.getUser().size();i++){ ids.add(userDetailResponse.getUser().get(i).getUuid()); } System.out.println(ids); criteria.setUserIds(ids); } landInfo = repository.getLandInfoData(criteria); if (landInfo.size() == 0) { return Collections.emptyList(); } enrichmentService.enrichLandInfoSearch(landInfo, criteria, requestInfo); return landInfo; } /** * Returns the landInfo with enriched owners from user service * * @param criteria * The object containing the parameters on which to search * @param requestInfo * The search request's requestInfo * @return List of landInfo for the given criteria */ public List<LandInfo> fetchLandInfoData(LandSearchCriteria criteria, RequestInfo requestInfo) { List<LandInfo> landInfos = repository.getLandInfoData(criteria); if (landInfos.isEmpty()) return Collections.emptyList(); if(!CollectionUtils.isEmpty(landInfos)){ log.debug("Received final landInfo response.."); } landInfos = enrichmentService.enrichLandInfoSearch(landInfos, criteria, requestInfo); if(!CollectionUtils.isEmpty(landInfos)){ log.debug("Received final landInfo response after enrichment.."); } return landInfos; } }
3e1eb6a81da2c6a61bf2532f031697216e52771e
1,828
java
Java
app/src/main/java/com/ys/yoosir/liveanimation/utils/GiftPathAnimator.java
LuoboDcom/LiveAnimation
d02080b0829094de04c9110c74c3ac96f488c117
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ys/yoosir/liveanimation/utils/GiftPathAnimator.java
LuoboDcom/LiveAnimation
d02080b0829094de04c9110c74c3ac96f488c117
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ys/yoosir/liveanimation/utils/GiftPathAnimator.java
LuoboDcom/LiveAnimation
d02080b0829094de04c9110c74c3ac96f488c117
[ "Apache-2.0" ]
null
null
null
32.070175
151
0.648249
12,985
package com.ys.yoosir.liveanimation.utils; import android.os.Handler; import android.os.Looper; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.TranslateAnimation; import java.util.concurrent.atomic.AtomicInteger; /** 礼物出现路径动画器 * Created by ys on 2016/8/31 0031. */ public class GiftPathAnimator extends AbstractGiftPathAnimator{ private final AtomicInteger mCounter = new AtomicInteger(0); private Handler mHandler; public GiftPathAnimator(AbstractGiftPathAnimator.Config config){ super(config); mHandler = new Handler(Looper.getMainLooper()); } @Override public void start(View child, ViewGroup parent) { parent.addView(child,new ViewGroup.LayoutParams(mConfig.giftWidth,mConfig.giftHeight)); TranslateAnimation anim = new TranslateAnimation(-mConfig.giftWidth,0,mCounter.get() * mConfig.giftHeight,mCounter.get() * mConfig.giftHeight); anim.setDuration(mConfig.animDuration); anim.setInterpolator(new LinearInterpolator()); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { //礼物总和加1 mCounter.incrementAndGet(); } @Override public void onAnimationEnd(Animation animation) { mHandler.post(new Runnable() { @Override public void run() { //礼物动画出现结束 } }); } @Override public void onAnimationRepeat(Animation animation) { } }); child.startAnimation(anim); } }
3e1eb7020a4d421c5b8c77099248ce017049a1a4
2,377
java
Java
src/main/java/org/valkyrienskies/addon/control/renderer/RotationAxleTileEntityRenderer.java
Rremis/Valkyrien-Skies-Control
6b23536a5c20a3d17fc8725c3c4eea101f4c695e
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-10T12:19:44.000Z
2021-09-07T16:43:31.000Z
src/main/java/org/valkyrienskies/addon/control/renderer/RotationAxleTileEntityRenderer.java
Rremis/Valkyrien-Skies-Control
6b23536a5c20a3d17fc8725c3c4eea101f4c695e
[ "Apache-2.0", "BSD-3-Clause" ]
4
2021-01-01T01:51:04.000Z
2022-01-16T21:07:55.000Z
src/main/java/org/valkyrienskies/addon/control/renderer/RotationAxleTileEntityRenderer.java
Rremis/Valkyrien-Skies-Control
6b23536a5c20a3d17fc8725c3c4eea101f4c695e
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-09-21T22:33:22.000Z
2021-09-17T13:47:31.000Z
38.967213
98
0.641144
12,986
package org.valkyrienskies.addon.control.renderer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.EnumFacing; import org.lwjgl.opengl.GL11; import org.valkyrienskies.addon.control.block.BlockRotationAxle; import org.valkyrienskies.addon.control.block.torque.TileEntityRotationAxle; public class RotationAxleTileEntityRenderer extends TileEntitySpecialRenderer<TileEntityRotationAxle> { @Override public void render(TileEntityRotationAxle tileentity, double x, double y, double z, float partialTick, int destroyStage, float alpha) { this.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); GlStateManager.pushMatrix(); GlStateManager.disableLighting(); GlStateManager.translate(x, y, z); GlStateManager.disableAlpha(); GlStateManager.disableBlend(); int brightness = tileentity.getWorld().getCombinedLight(tileentity.getPos(), 0); IBlockState gearState = Minecraft.getMinecraft().world.getBlockState(tileentity.getPos()); if (gearState.getBlock() instanceof BlockRotationAxle) { EnumFacing.Axis facingAxis = gearState.getValue(BlockRotationAxle.AXIS); GlStateManager.translate(0.5, 0.5, 0.5); switch (facingAxis) { case X: // Rotates (1, 0, 0) -> (1, 0, 0) break; case Y: // Rotates (1, 0, 0) -> (0, 1, 0) GL11.glRotated(90, 0, 0, 1); break; case Z: // Rotates (1, 0, 0) -> (0, 0, 1) GL11.glRotated(-90, 0, 1, 0); break; } GL11.glRotated(Math.toDegrees(tileentity.getRenderRotationRadians(partialTick)), 1, 0, 0); GlStateManager.translate(-0.5, -0.5, -0.5); } double keyframe = 1; GibsAtomAnimationRegistry.getAnimation("rotation_axle") .renderAnimation(keyframe, brightness); GlStateManager.popMatrix(); GlStateManager.enableLighting(); GlStateManager.resetColor(); } }
3e1eb7620b32b16e5b28d98fc58f2d5b608f8db5
870
java
Java
src/main/java/br/com/zupacademy/lucas/treinomercadolivre/requests/CaracteristicasRequest.java
LucasWilliam12/orange-talents-03-template-ecommerce
bb6b5257ea30dcbb2fc6358fabe527973e33c84c
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/lucas/treinomercadolivre/requests/CaracteristicasRequest.java
LucasWilliam12/orange-talents-03-template-ecommerce
bb6b5257ea30dcbb2fc6358fabe527973e33c84c
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/lucas/treinomercadolivre/requests/CaracteristicasRequest.java
LucasWilliam12/orange-talents-03-template-ecommerce
bb6b5257ea30dcbb2fc6358fabe527973e33c84c
[ "Apache-2.0" ]
null
null
null
23.513514
83
0.785057
12,987
package br.com.zupacademy.lucas.treinomercadolivre.requests; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import br.com.zupacademy.lucas.treinomercadolivre.models.CaracteristicaProduto; import br.com.zupacademy.lucas.treinomercadolivre.models.Produto; public class CaracteristicasRequest { // Atributos @NotBlank private String nome; @NotBlank private String descricao; // Construtores public CaracteristicasRequest(@NotBlank String nome, @NotBlank String descricao) { this.nome = nome; this.descricao = descricao; } // Getters public String getNome() { return nome; } public String getDescricao() { return descricao; } public CaracteristicaProduto toModel(@NotNull @Valid Produto produto) { return new CaracteristicaProduto(nome, descricao, produto); } }
3e1eb929ede6bba72d3b1a944056742dc929641c
3,570
java
Java
eventmesh-examples/src/main/java/org/apache/eventmesh/grpc/pub/cloudevents/CloudEventsRequestInstance.java
walleliu1016/incubator-eventmesh
d1b95604d074efcb619f93f824d1cd8328367995
[ "Apache-2.0" ]
null
null
null
eventmesh-examples/src/main/java/org/apache/eventmesh/grpc/pub/cloudevents/CloudEventsRequestInstance.java
walleliu1016/incubator-eventmesh
d1b95604d074efcb619f93f824d1cd8328367995
[ "Apache-2.0" ]
6
2022-02-17T09:17:17.000Z
2022-03-29T21:37:24.000Z
eventmesh-examples/src/main/java/org/apache/eventmesh/grpc/pub/cloudevents/CloudEventsRequestInstance.java
walleliu1016/incubator-eventmesh
d1b95604d074efcb619f93f824d1cd8328367995
[ "Apache-2.0" ]
null
null
null
41.511628
103
0.728571
12,988
/* * 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.eventmesh.grpc.pub.cloudevents; import org.apache.eventmesh.client.grpc.config.EventMeshGrpcClientConfig; import org.apache.eventmesh.client.grpc.producer.EventMeshGrpcProducer; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.common.Constants; import org.apache.eventmesh.common.ExampleConstants; import org.apache.eventmesh.common.utils.JsonUtils; import org.apache.eventmesh.util.Utils; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.UUID; import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import lombok.extern.slf4j.Slf4j; @Slf4j public class CloudEventsRequestInstance { // This messageSize is also used in SubService.java (Subscriber) public static int messageSize = 5; public static void main(String[] args) throws Exception { Properties properties = Utils.readPropertiesFile(ExampleConstants.CONFIG_FILE_NAME); final String eventMeshIp = properties.getProperty(ExampleConstants.EVENTMESH_IP); final String eventMeshGrpcPort = properties.getProperty(ExampleConstants.EVENTMESH_GRPC_PORT); EventMeshGrpcClientConfig eventMeshClientConfig = EventMeshGrpcClientConfig.builder() .serverAddr(eventMeshIp) .serverPort(Integer.parseInt(eventMeshGrpcPort)) .producerGroup(ExampleConstants.DEFAULT_EVENTMESH_TEST_PRODUCER_GROUP) .env("env").idc("idc") .sys("1234").build(); EventMeshGrpcProducer eventMeshGrpcProducer = new EventMeshGrpcProducer(eventMeshClientConfig); eventMeshGrpcProducer.init(); Map<String, String> content = new HashMap<>(); content.put("content", "testRequestReplyMessage"); for (int i = 0; i < messageSize; i++) { CloudEvent event = CloudEventBuilder.v1() .withId(UUID.randomUUID().toString()) .withSubject(ExampleConstants.EVENTMESH_GRPC_RR_TEST_TOPIC) .withSource(URI.create("/")) .withDataContentType(ExampleConstants.CLOUDEVENT_CONTENT_TYPE) .withType(EventMeshCommon.CLOUD_EVENTS_PROTOCOL_NAME) .withData(JsonUtils.serialize(content).getBytes(StandardCharsets.UTF_8)) .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4 * 1000)) .build(); eventMeshGrpcProducer.requestReply(event, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); Thread.sleep(1000); } Thread.sleep(30000); try (EventMeshGrpcProducer ignore = eventMeshGrpcProducer) { // ignore } } }
3e1eb95dcf1bbe275dca851b37503375c6d40430
3,130
java
Java
HangmanGame/Multiplayer.java
mantoomine/Amir_Projects
1386a0234b279884e743185b4072c0c3e01ebe87
[ "MIT" ]
null
null
null
HangmanGame/Multiplayer.java
mantoomine/Amir_Projects
1386a0234b279884e743185b4072c0c3e01ebe87
[ "MIT" ]
null
null
null
HangmanGame/Multiplayer.java
mantoomine/Amir_Projects
1386a0234b279884e743185b4072c0c3e01ebe87
[ "MIT" ]
null
null
null
32.604167
152
0.584345
12,989
package HangmanGame; import java.util.Scanner; /** * This is a main class<Multiplayer> that configure two player game. Ask a player * to enter a word and the other is able to play a game with this word. Display * result when game is over and then return to main menu. * * @author Amirhossein Soltaninejad * */ public class Multiplayer { private Configuration play; private Scanner sc; private boolean playHangMan; private String wr; public Multiplayer() { play = new Configuration(); sc = new Scanner(System.in); playHangMan = false; } /** * This is a method<twoPlayers> that two players can play the game. It ask one * player to enter a word and the other to play the game with that word. */ public void twoPlayers() { System.out.println( "Multiplayer game: first player should enter a word and the other is able to play the game with this word"); while (playHangMan == false) { System.out.print("Enter a word player 1: "); wr = sc.next(); while (listCheck(wr) == false) { System.out.println("Write a word that contain only letters!"); System.out.print("Enter a word player 1: "); wr = sc.next(); } System.out.println("Enter 1 to play with the word"); System.out.println("Enter 2 to change the word"); HangmanMain.intIn(sc); int input = sc.nextInt(); while (!(input == 1 | input == 2)) { System.out.print("Just enter a number from the menu: "); HangmanMain.intIn(sc); input = sc.nextInt(); } if (input == 1) { System.out.println("Player 2 , enter any character to play the game"); sc.next(); playHangMan = true; play.setList(wr); play.start(); } } if (play.win()) { System.out.println(); System.out.println("!*************"); System.out.println("!<<<PLAYER TWO>>> "); System.out.println("! *Y* *N*"); System.out.println("! *O* *O*"); System.out.println("! *U* *W*"); System.out.println("!*************"); System.out.println("!............."); } else { System.out.println(); System.out.println("!*************"); System.out.println("!<<<PLAYER ONE>>> "); System.out.println("! *Y* *N*"); System.out.println("! *O* *O*"); System.out.println("! *U* *W*"); System.out.println("!*************"); System.out.println("!............."); } System.out.println("Enter any character to continue the game"); sc.next(); } /** * This is a method<listCheck> that check the word with only letters and dash * * @param wr String that should be checked * @return true if the word is valid, otherwise return false */ public boolean listCheck(String wr) { for (int i = 0; i < wr.length(); i++) { if (!Character.isLetter(wr.charAt(i)) & wr.charAt(i) != '-') { //in order to get succeed result in the TestTwoPlayers you should replace return false; // if (!Character.isLetter(wr.charAt(i)) & wr.charAt(i) != '-') { } // with the code on line 89. } return true; } }
3e1eba030c4fe46632b05c3eae0b65c16e80ce15
1,784
java
Java
src/main/java/com/topolr/contenter/ContenterAdapter.java
topolr/topolr-service
05db5dba07a81ff4f427b15dd176c6ac7b91b432
[ "MIT" ]
1
2017-04-27T08:38:20.000Z
2017-04-27T08:38:20.000Z
src/main/java/com/topolr/contenter/ContenterAdapter.java
topolr/topolr-service
05db5dba07a81ff4f427b15dd176c6ac7b91b432
[ "MIT" ]
null
null
null
src/main/java/com/topolr/contenter/ContenterAdapter.java
topolr/topolr-service
05db5dba07a81ff4f427b15dd176c6ac7b91b432
[ "MIT" ]
null
null
null
40.545455
159
0.757287
12,990
package com.topolr.contenter; import com.topolr.contenter.data.ContentObjectModule; import com.topolr.util.jsonx.Jsonx; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ContenterAdapter { public static void renderPage(String pageId, HttpServletRequest request, HttpServletResponse response) throws Exception { Contenter.getContenter().renderPage(pageId, request, response); } public static void renderModule(String moduleId, HttpServletRequest request, HttpServletResponse response) throws Exception { Contenter.getContenter().renderModule(moduleId, request, response); } public static HashMap<String, Object> getNewClientModule(String moduleType, HttpServletRequest request) throws Exception { return Contenter.getContenter().getNewClientModule(moduleType, request); } public static HashMap<String, Object> getClientModuleInfo(String moduleId, HttpServletRequest request) throws Exception { return Contenter.getContenter().getClientModuleInfo(moduleId, request); } public static HashMap<String, Object> getClientMoudleInfo(String moduleId, String moduleType, String values, HttpServletRequest request) throws Exception { ContentObjectModule module = new ContentObjectModule(); module.setId(moduleId); module.setModuleType(moduleType); module.setValues(values); return Contenter.getContenter().getClientModuleInfo(module, request); } public static void refreshContenter() throws Exception { Contenter.getContenter().refresh(); } public static void save(String info) throws Exception{ Contenter.getContenter().save(Jsonx.create(info)); } }
3e1ebab3131d11d4d4a1316da536012264d1f598
871
java
Java
src/main/Main.java
mariecavallo/puissance4_binome5_MarieFrank
7b0ff497ecb72ecdbfc99ccd096a91130c5f3c80
[ "Unlicense" ]
null
null
null
src/main/Main.java
mariecavallo/puissance4_binome5_MarieFrank
7b0ff497ecb72ecdbfc99ccd096a91130c5f3c80
[ "Unlicense" ]
null
null
null
src/main/Main.java
mariecavallo/puissance4_binome5_MarieFrank
7b0ff497ecb72ecdbfc99ccd096a91130c5f3c80
[ "Unlicense" ]
null
null
null
36.291667
97
0.636051
12,991
import fr.formation.puissance4.Board.Board; import fr.formation.puissance4.Joueur.*; import fr.formation.puissance4.Piece.Jeton; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; public class Main { public static void main(String[] args) { Jeton[][] jetons = new Jeton[6][7]; for (int ligne = 0; ligne < jetons.length; ligne++) { for (int colonne = 0; colonne < jetons[ligne].length; colonne++) { Circle diskPreview = new Circle(40); diskPreview.setOpacity(1); diskPreview.setFill(Color.TRANSPARENT); jetons[ligne][colonne] = new Jeton(diskPreview); } } // Exemple pour réaliser des tests de fonctionalités des classes dérivées de class Joueur Joueur joueur = new JoueurHumain(Color.YELLOW, new Board(jetons)); } }
3e1ebb171bb0ef244a00d69ab5c8a331a52670c4
298
java
Java
runtime-commons/src/main/java/de/codecentric/reedelk/runtime/converter/types/doubletype/AsString.java
steftux/reedelk-runtime
cbcf6a48bab73b4f01e490ba4012e041a2417f96
[ "Apache-2.0" ]
null
null
null
runtime-commons/src/main/java/de/codecentric/reedelk/runtime/converter/types/doubletype/AsString.java
steftux/reedelk-runtime
cbcf6a48bab73b4f01e490ba4012e041a2417f96
[ "Apache-2.0" ]
null
null
null
runtime-commons/src/main/java/de/codecentric/reedelk/runtime/converter/types/doubletype/AsString.java
steftux/reedelk-runtime
cbcf6a48bab73b4f01e490ba4012e041a2417f96
[ "Apache-2.0" ]
null
null
null
24.833333
69
0.765101
12,992
package de.codecentric.reedelk.runtime.converter.types.doubletype; import de.codecentric.reedelk.runtime.converter.types.ValueConverter; class AsString implements ValueConverter<Double,String> { @Override public String from(Double value) { return Double.toString(value); } }
3e1ebc2a0d6788e3e8fd8a84cd870b9775147e12
732
java
Java
parking-system-api/parking-system-soap-api/src/main/java/pl/edu/agh/soa/parking_system/soap/ParkingWebServiceImpl.java
matkluska/soa-parking-system
517b44f54e78f8414bb052db40d0eff5d6919502
[ "MIT" ]
null
null
null
parking-system-api/parking-system-soap-api/src/main/java/pl/edu/agh/soa/parking_system/soap/ParkingWebServiceImpl.java
matkluska/soa-parking-system
517b44f54e78f8414bb052db40d0eff5d6919502
[ "MIT" ]
null
null
null
parking-system-api/parking-system-soap-api/src/main/java/pl/edu/agh/soa/parking_system/soap/ParkingWebServiceImpl.java
matkluska/soa-parking-system
517b44f54e78f8414bb052db40d0eff5d6919502
[ "MIT" ]
null
null
null
26.142857
115
0.75
12,993
package pl.edu.agh.soa.parking_system.soap; import pl.edu.agh.soa.contracts.AreaDTO; import pl.edu.agh.soa.parking_system.soap.service.ParkingService; import javax.inject.Inject; import javax.jws.WebService; import java.util.List; /** * @author Mateusz Kluska */ @WebService(name = "ParkingWebService", endpointInterface = "pl.edu.agh.soa.parking_system.soap.ParkingWebService") public class ParkingWebServiceImpl implements ParkingWebService { @Inject private ParkingService parkingService; @Override public List<AreaDTO> getParkingAreas() { return parkingService.getAreas(); } @Override public AreaDTO getParkingArea(long areaId) { return parkingService.getArea(areaId); } }
3e1ebd4202bc3512f30503e1952329abbe25522c
2,436
java
Java
src/main/java/org/javarosa/core/util/externalizable/ExtWrapNullable.java
neal0892/javarosa
72d1c1942f12548723e637c8c65e3efbd2a3f447
[ "Apache-2.0" ]
38
2017-04-05T18:11:27.000Z
2020-01-06T17:28:43.000Z
src/main/java/org/javarosa/core/util/externalizable/ExtWrapNullable.java
neal0892/javarosa
72d1c1942f12548723e637c8c65e3efbd2a3f447
[ "Apache-2.0" ]
428
2016-11-23T18:31:26.000Z
2020-04-18T02:29:21.000Z
src/main/java/org/javarosa/core/util/externalizable/ExtWrapNullable.java
GetODK/javarosa
adde512b7e7098e111f39eec1ae648f7e5d01475
[ "Apache-2.0" ]
105
2017-02-01T08:29:50.000Z
2020-04-15T10:16:27.000Z
29
120
0.662151
12,994
/* * Copyright (C) 2009 JavaRosa * * 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.javarosa.core.util.externalizable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class ExtWrapNullable extends ExternalizableWrapper { public ExternalizableWrapper type; /* serialization */ public ExtWrapNullable (Object val) { this.val = val; } /* deserialization */ public ExtWrapNullable () { } public ExtWrapNullable (Class type) { this.type = new ExtWrapBase(type); } /* serialization or deserialization, depending on context */ public ExtWrapNullable (ExternalizableWrapper type) { if (type instanceof ExtWrapNullable) { throw new IllegalArgumentException("Wrapping nullable with nullable is redundant"); } else if (type != null && type.isEmpty()) { this.type = type; } else { this.val = type; } } public ExternalizableWrapper clone (Object val) { return new ExtWrapNullable(val); } public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { if (in.readBoolean()) { val = ExtUtil.read(in, type, pf); } else { val = null; } } public void writeExternal(DataOutputStream out) throws IOException { if (val != null) { out.writeBoolean(true); ExtUtil.write(out, val); } else { out.writeBoolean(false); } } public void metaReadExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { type = ExtWrapTagged.readTag(in, pf); } public void metaWriteExternal(DataOutputStream out) throws IOException { ExtWrapTagged.writeTag(out, val == null ? new Object() : val); } }
3e1ebe21cd33053a1a3e5878c427f84b27e8a496
3,763
java
Java
src/main/java/org/pos/repository/logic/OrderNoRepository.java
BulkSecurityGeneratorProject/Simple-POS
b98da564584a23483bc64650378c7903a33d9637
[ "Apache-2.0" ]
3
2015-07-09T11:14:15.000Z
2018-09-11T19:33:04.000Z
src/main/java/org/pos/repository/logic/OrderNoRepository.java
BulkSecurityGeneratorProject/Simple-POS
b98da564584a23483bc64650378c7903a33d9637
[ "Apache-2.0" ]
2
2015-08-19T17:39:44.000Z
2015-09-12T06:45:52.000Z
src/main/java/org/pos/repository/logic/OrderNoRepository.java
BulkSecurityGeneratorProject/Simple-POS
b98da564584a23483bc64650378c7903a33d9637
[ "Apache-2.0" ]
2
2016-04-13T16:17:25.000Z
2020-09-18T09:38:18.000Z
61.688525
340
0.805209
12,995
package org.pos.repository.logic; import java.math.BigDecimal; import java.util.List; import org.joda.time.DateTime; import org.pos.domain.logic.OrderNo; import org.pos.web.rest.dto.logic.LineChartDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; /** * Spring Data JPA repository for the OrderNo entity. */ public interface OrderNoRepository extends JpaRepository<OrderNo, Long>, JpaSpecificationExecutor<OrderNo> { @EntityGraph(value = "orderWithDetails", type = EntityGraphType.LOAD) public Page<OrderNo> findByStatusIs(String status, Pageable pageable); public Page<OrderNo> findByStatusIsAndCreatedDateBetween(String status, DateTime from, DateTime to, Pageable pageable); public Page<OrderNo> findByStatusIsAndCreatedDateLessThanEqual(String status, DateTime createdDate, Pageable pageable); public Page<OrderNo> findByStatusIsAndCreatedDateGreaterThanEqual(String status, DateTime createdDate, Pageable pageable); @EntityGraph(value = "orderWithDetails", type = EntityGraphType.LOAD) public Page<OrderNo> findByTableNoIdIsAndStatusIs(Long tableId, String status, Pageable pageable); public Page<OrderNo> findByTableNoIdIsAndStatusIsAndCreatedDateBetween(Long tableId, String status, DateTime from, DateTime to, Pageable pageable); public Page<OrderNo> findByTableNoIdIsAndStatusIsAndCreatedDateLessThanEqual(Long tableId, String status, DateTime createdDate, Pageable pageable); public Page<OrderNo> findByTableNoIdIsAndStatusIsAndCreatedDateGreaterThanEqual(Long tableId, String status, DateTime createdDate, Pageable pageable); @Query(value = "select sum(a.receivableAmount) from OrderNo a where a.status = ?1 and a.createdDate between ?2 and ?3") public BigDecimal getSumReceivableAmountByStatusCreatedDateBetween(String status, DateTime from, DateTime to); @Query(value = "select sum(a.receivableAmount) from OrderNo a where a.status = ?1 and a.createdDate >= ?2") public BigDecimal getSumReceivableAmountByStatusCreatedDateAfterEqual(String status, DateTime createdDate); @Query(value = "select sum(a.receivableAmount) from OrderNo a where a.status = ?1 and a.createdDate <= ?2") public BigDecimal getSumReceivableAmountByStatusCreatedDateBeforeEqual(String status, DateTime createdDate); @EntityGraph(value = "orderWithDetails", type = EntityGraphType.LOAD) public OrderNo findById(Long id); @Query(value = "select new org.pos.web.rest.dto.logic.LineChartDTO(a.status, to_char(a.createdDate, 'yyyy-mm-dd'), sum(a.receivableAmount)) from OrderNo a where a.status = ?1 and a.createdDate between ?2 and ?3 group by to_char(a.createdDate, 'yyyy-mm-dd'), a.status order by to_char(a.createdDate, 'yyyy-mm-dd') asc") public List<LineChartDTO> getSaleByStatusIsAndCreatedDateBetween(String status, DateTime from, DateTime to); @Query(value = "select new org.pos.web.rest.dto.logic.LineChartDTO(a.status, to_char(a.createdDate, 'yyyy-mm-dd'), sum(a.receivableAmount)) from OrderNo a where a.status = ?1 and a.createdDate between ?2 and ?3 and a.createdBy = ?4 group by to_char(a.createdDate, 'yyyy-mm-dd'), a.status order by to_char(a.createdDate, 'yyyy-mm-dd') asc") public List<LineChartDTO> getSaleByStatusIsAndCreatedDateBetweenAndCreatedByIs(String status, DateTime from, DateTime to, String createdBy); public List<OrderNo> findByStatusIsAndCreatedDateBetween(String status, DateTime from, DateTime to); }
3e1ebe5a7e1f69d9753b2205c3e3639fb77c510e
1,197
java
Java
NaluReuseController/NaluReuseController-client/src/main/java/com/github/nalukit/example/nalureusecontroller/client/ui/application/content/list/IListComponent.java
FrankHossfeld/nalu-examples
e4551a5a53a89d521ddf2cf7c419970d923f5097
[ "Apache-2.0" ]
12
2018-09-29T23:16:11.000Z
2022-01-21T17:19:36.000Z
NaluReuseController/NaluReuseController-client/src/main/java/com/github/nalukit/example/nalureusecontroller/client/ui/application/content/list/IListComponent.java
FrankHossfeld/nalu-examples
e4551a5a53a89d521ddf2cf7c419970d923f5097
[ "Apache-2.0" ]
3
2020-10-11T07:26:22.000Z
2020-10-12T15:15:01.000Z
NaluReuseController/NaluReuseController-client/src/main/java/com/github/nalukit/example/nalureusecontroller/client/ui/application/content/list/IListComponent.java
FrankHossfeld/nalu-examples
e4551a5a53a89d521ddf2cf7c419970d923f5097
[ "Apache-2.0" ]
8
2018-11-20T21:12:24.000Z
2020-12-16T17:31:28.000Z
29.195122
90
0.745196
12,996
/* * Copyright (c) 2018 - 2019 - Frank Hossfeld * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package com.github.nalukit.example.nalureusecontroller.client.ui.application.content.list; import com.github.nalukit.example.nalureusecontroller.client.data.model.dto.Person; import com.github.nalukit.nalu.client.component.IsComponent; import elemental2.dom.HTMLElement; import java.util.List; public interface IListComponent extends IsComponent<IListComponent.Controller, HTMLElement> { void resetTable(); void setData(List<Person> result); interface Controller extends IsComponent.Controller { void doUpdate(Person object); } }
3e1ebe9fe26866b7ce248c95743635fa801ad019
180
java
Java
xiaoming-api/src/main/java/cn/codethink/xiaoming/event/GroupMemberMessageRecallEvent.java
XiaoMingProject/XiaoMingBot
7c153b93a850cf93d79e11492d885f409d0e7f49
[ "Apache-2.0" ]
2
2022-02-17T07:35:38.000Z
2022-03-06T08:02:05.000Z
xiaoming-api/src/main/java/cn/codethink/xiaoming/event/GroupMemberMessageRecallEvent.java
Chuanwise/XiaoMingBot
7c153b93a850cf93d79e11492d885f409d0e7f49
[ "Apache-2.0" ]
2
2022-02-14T10:19:40.000Z
2022-03-05T02:24:47.000Z
xiaoming-api/src/main/java/cn/codethink/xiaoming/event/GroupMemberMessageRecallEvent.java
XiaoMingProject/XiaoMingBot
7c153b93a850cf93d79e11492d885f409d0e7f49
[ "Apache-2.0" ]
3
2022-02-07T05:57:22.000Z
2022-03-05T02:01:50.000Z
16.363636
46
0.761111
12,997
package cn.codethink.xiaoming.event; /** * 群临时会话消息撤回事件 * * @author Chuanwise */ public interface GroupMemberMessageRecallEvent extends Event, MemberMessageRecallEvent { }
3e1ebeae2dc73fbf17e869cf39f9ebdc5cd1a287
165
java
Java
lib/src/main/java/com/walid/promise/interfaces/IReject.java
walid1992/JavaPromise
aef82255a6bb421b0e79b94b7ec14474ed3182c1
[ "MIT" ]
2
2019-07-10T07:11:57.000Z
2020-09-12T10:02:51.000Z
lib/src/main/java/com/walid/promise/interfaces/IReject.java
walid1992/JavaPromise
aef82255a6bb421b0e79b94b7ec14474ed3182c1
[ "MIT" ]
null
null
null
lib/src/main/java/com/walid/promise/interfaces/IReject.java
walid1992/JavaPromise
aef82255a6bb421b0e79b94b7ec14474ed3182c1
[ "MIT" ]
null
null
null
16.5
37
0.612121
12,998
package com.walid.promise.interfaces; /** * Author : walid * Data : 2017-04-07 18:53 * Describe : */ public interface IReject<T> { void run(T err); }
3e1ebf4d1b61bfd72f2201f07fcff2a46cd0bcef
12,927
java
Java
src/main/java/ome/codecs/LosslessJPEGCodec.java
LoopinFool/ome-codecs
af84eab0794cfa2b11c3ddc6fd528a4f1fdf6178
[ "BSD-2-Clause" ]
4
2017-07-05T18:17:11.000Z
2019-08-13T18:27:54.000Z
src/main/java/ome/codecs/LosslessJPEGCodec.java
LoopinFool/ome-codecs
af84eab0794cfa2b11c3ddc6fd528a4f1fdf6178
[ "BSD-2-Clause" ]
17
2017-06-29T07:20:58.000Z
2021-12-14T20:59:12.000Z
src/main/java/ome/codecs/LosslessJPEGCodec.java
LoopinFool/ome-codecs
af84eab0794cfa2b11c3ddc6fd528a4f1fdf6178
[ "BSD-2-Clause" ]
9
2017-06-28T16:21:49.000Z
2021-12-10T07:57:01.000Z
36.724432
91
0.59952
12,999
/* * #%L * Image encoding and decoding routines. * %% * Copyright (C) 2005 - 2017 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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 ome.codecs; import java.io.IOException; import java.util.Vector; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import ome.codecs.CodecException; import ome.codecs.UnsupportedCompressionException; /** * Decompresses lossless JPEG images. * * @author Melissa Linkert melissa at glencoesoftware.com */ public class LosslessJPEGCodec extends BaseCodec { // -- Constants -- // Start of Frame markers - non-differential, Huffman coding private static final int SOF0 = 0xffc0; // baseline DCT private static final int SOF1 = 0xffc1; // extended sequential DCT private static final int SOF2 = 0xffc2; // progressive DCT private static final int SOF3 = 0xffc3; // lossless (sequential) // Start of Frame markers - differential, Huffman coding private static final int SOF5 = 0xffc5; // differential sequential DCT private static final int SOF6 = 0xffc6; // differential progressive DCT private static final int SOF7 = 0xffc7; // differential lossless (sequential) // Start of Frame markers - non-differential, arithmetic coding private static final int JPG = 0xffc8; // reserved for JPEG extensions private static final int SOF9 = 0xffc9; // extended sequential DCT private static final int SOF10 = 0xffca; // progressive DCT private static final int SOF11 = 0xffcb; // lossless (sequential) // Start of Frame markers - differential, arithmetic coding private static final int SOF13 = 0xffcd; // differential sequential DCT private static final int SOF14 = 0xffce; // differential progressive DCT private static final int SOF15 = 0xffcf; // differential lossless (sequential) private static final int DHT = 0xffc4; // define Huffman table(s) private static final int DAC = 0xffcc; // define arithmetic coding conditions // Restart interval termination private static final int RST_0 = 0xffd0; private static final int RST_1 = 0xffd1; private static final int RST_2 = 0xffd2; private static final int RST_3 = 0xffd3; private static final int RST_4 = 0xffd4; private static final int RST_5 = 0xffd5; private static final int RST_6 = 0xffd6; private static final int RST_7 = 0xffd7; private static final int SOI = 0xffd8; // start of image private static final int EOI = 0xffd9; // end of image private static final int SOS = 0xffda; // start of scan private static final int DQT = 0xffdb; // define quantization table(s) private static final int DNL = 0xffdc; // define number of lines private static final int DRI = 0xffdd; // define restart interval private static final int DHP = 0xffde; // define hierarchical progression private static final int EXP = 0xffdf; // expand reference components private static final int COM = 0xfffe; // comment // -- Codec API methods -- /* @see Codec#compress(byte[], CodecOptions) */ @Override public byte[] compress(byte[] data, CodecOptions options) throws CodecException { throw new UnsupportedCompressionException( "Lossless JPEG compression not supported"); } /** * The CodecOptions parameter should have the following fields set: * {@link CodecOptions#interleaved interleaved} * {@link CodecOptions#littleEndian littleEndian} * * @see Codec#decompress(RandomAccessInputStream, CodecOptions) */ @Override public byte[] decompress(RandomAccessInputStream in, CodecOptions options) throws CodecException, IOException { if (in == null) throw new IllegalArgumentException("No data to decompress."); if (options == null) options = CodecOptions.getDefaultOptions(); byte[] buf = new byte[0]; int width = 0, height = 0; int bitsPerSample = 0, nComponents = 0, bytesPerSample = 0; int[] horizontalSampling = null, verticalSampling = null; int[] quantizationTable = null; short[][] huffmanTables = null; int startPredictor = 0, endPredictor = 0; int pointTransform = 0; int[] dcTable = null, acTable = null; while (in.getFilePointer() < in.length() - 1) { int code = in.readShort() & 0xffff; int length = in.readShort() & 0xffff; long fp = in.getFilePointer(); if (length > 0xff00) { length = 0; in.seek(fp - 2); } else if (code == SOS) { nComponents = in.read(); dcTable = new int[nComponents]; acTable = new int[nComponents]; for (int i=0; i<nComponents; i++) { int componentSelector = in.read(); int tableSelector = in.read(); dcTable[i] = (tableSelector & 0xf0) >> 4; acTable[i] = tableSelector & 0xf; } startPredictor = in.read(); endPredictor = in.read(); pointTransform = in.read() & 0xf; // read image data byte[] toDecode = new byte[(int) (in.length() - in.getFilePointer())]; in.read(toDecode); // scrub out byte stuffing ByteVector b = new ByteVector(); for (int i=0; i<toDecode.length; i++) { byte val = toDecode[i]; if (val == (byte) 0xff) { if (toDecode[i + 1] == 0) b.add(val); i++; } else { b.add(val); } } toDecode = b.toByteArray(); RandomAccessInputStream bb = new RandomAccessInputStream( new ByteArrayHandle(toDecode)); HuffmanCodec huffman = new HuffmanCodec(); HuffmanCodecOptions huffmanOptions = new HuffmanCodecOptions(); huffmanOptions.bitsPerSample = bitsPerSample; huffmanOptions.maxBytes = buf.length / nComponents; int nextSample = 0; while (nextSample < buf.length / nComponents) { for (int i=0; i<nComponents; i++) { huffmanOptions.table = huffmanTables[dcTable[i]]; int v = 0; if (huffmanTables != null) { v = huffman.getSample(bb, huffmanOptions); if (nextSample == 0) { v += (int) Math.pow(2, bitsPerSample - pointTransform - 1); } } else { throw new UnsupportedCompressionException( "Arithmetic coding not supported"); } // apply predictor to the sample int predictor = startPredictor; if (nextSample < width * bytesPerSample) predictor = 1; else if ((nextSample % (width * bytesPerSample)) == 0) { predictor = 2; } int componentOffset = i * (buf.length / nComponents); int indexA = nextSample - bytesPerSample + componentOffset; int indexB = nextSample - width * bytesPerSample + componentOffset; int indexC = nextSample - (width + 1) * bytesPerSample + componentOffset; int sampleA = indexA < 0 ? 0 : DataTools.bytesToInt(buf, indexA, bytesPerSample, false) >> pointTransform; int sampleB = indexB < 0 ? 0 : DataTools.bytesToInt(buf, indexB, bytesPerSample, false) >> pointTransform; int sampleC = indexC < 0 ? 0 : DataTools.bytesToInt(buf, indexC, bytesPerSample, false) >> pointTransform; if (nextSample > 0) { int pred = 0; switch (predictor) { case 1: pred = sampleA; break; case 2: pred = sampleB; break; case 3: pred = sampleC; break; case 4: pred = sampleA + sampleB + sampleC; break; case 5: pred = sampleA + ((sampleB - sampleC) >> 1); break; case 6: pred = sampleB + ((sampleA - sampleC) >> 1); break; case 7: pred = (sampleA + sampleB) >> 1; break; } v += pred; } int offset = componentOffset + nextSample; DataTools.unpackBytes(v << pointTransform, buf, offset, bytesPerSample, false); } nextSample += bytesPerSample; } bb.close(); } else { length -= 2; // stored length includes length param if (length == 0) continue; if (code == EOI) { } else if (code == SOF3) { // lossless w/Huffman coding bitsPerSample = in.read(); height = in.readShort(); width = in.readShort(); nComponents = in.read(); horizontalSampling = new int[nComponents]; verticalSampling = new int[nComponents]; quantizationTable = new int[nComponents]; for (int i=0; i<nComponents; i++) { in.skipBytes(1); int s = in.read(); horizontalSampling[i] = (s & 0xf0) >> 4; verticalSampling[i] = s & 0x0f; quantizationTable[i] = in.read(); } bytesPerSample = bitsPerSample / 8; if ((bitsPerSample % 8) != 0) bytesPerSample++; buf = new byte[width * height * nComponents * bytesPerSample]; } else if (code == SOF11) { throw new UnsupportedCompressionException( "Arithmetic coding is not yet supported"); } else if (code == DHT) { if (huffmanTables == null) { huffmanTables = new short[4][]; } int bytesRead = 0; while (bytesRead < length) { int s = in.read(); byte tableClass = (byte) ((s & 0xf0) >> 4); byte destination = (byte) (s & 0xf); int[] nCodes = new int[16]; Vector table = new Vector(); for (int i=0; i<nCodes.length; i++) { nCodes[i] = in.read(); table.add(new Short((short) nCodes[i])); } for (int i=0; i<nCodes.length; i++) { for (int j=0; j<nCodes[i]; j++) { table.add(new Short((short) (in.read() & 0xff))); } } huffmanTables[destination] = new short[table.size()]; for (int i=0; i<huffmanTables[destination].length; i++) { huffmanTables[destination][i] = ((Short) table.get(i)).shortValue(); } bytesRead += table.size() + 1; } } in.seek(fp + length); } } if (options.interleaved && nComponents > 1) { // data is stored in planar (RRR...GGG...BBB...) order byte[] newBuf = new byte[buf.length]; for (int i=0; i<buf.length; i+=nComponents*bytesPerSample) { for (int c=0; c<nComponents; c++) { int src = c * (buf.length / nComponents) + (i / nComponents); int dst = i + c * bytesPerSample; System.arraycopy(buf, src, newBuf, dst, bytesPerSample); } } buf = newBuf; } if (options.littleEndian && bytesPerSample > 1) { // data is stored in big endian order // reverse the bytes in each sample byte[] newBuf = new byte[buf.length]; for (int i=0; i<buf.length; i+=bytesPerSample) { for (int q=0; q<bytesPerSample; q++) { newBuf[i + bytesPerSample - q - 1] = buf[i + q]; } } buf = newBuf; } return buf; } }
3e1ebf4e5183cbb1890a21c0e52afd12611a24a6
882
java
Java
src/main/java/javax/persistence/spi/PersistenceUnitTransactionType.java
jakobk/hibernate-jpa-api-async
7b4da4e2fd1d4b67c907a61c9e09583099c9e6f9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/javax/persistence/spi/PersistenceUnitTransactionType.java
jakobk/hibernate-jpa-api-async
7b4da4e2fd1d4b67c907a61c9e09583099c9e6f9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/javax/persistence/spi/PersistenceUnitTransactionType.java
jakobk/hibernate-jpa-api-async
7b4da4e2fd1d4b67c907a61c9e09583099c9e6f9
[ "BSD-3-Clause" ]
null
null
null
29.4
84
0.740363
13,000
/* * Copyright (c) 2008, 2009, 2011 Oracle, Inc. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. The Eclipse Public License is available * at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License * is available at http://www.eclipse.org/org/documents/edl-v10.php. */ package javax.persistence.spi; /** * Specifies whether entity managers created by the {@link * javax.persistence.EntityManagerFactory} will be JTA or * resource-local entity managers. * * @since Java Persistence 1.0 */ public enum PersistenceUnitTransactionType { /** * JTA entity managers will be created. */ JTA, /** * Resource-local entity managers will be created. */ RESOURCE_LOCAL }
3e1ebfce865dc802f84e44fdf599a9dd1d804bc3
1,905
java
Java
src/lingua/ui/gtk/main_window/widgets/commandslist/CommandsListItem.java
cyberpython/lingua
8d437bdc4fd9c1eb1e025391770d6e86d33ec389
[ "MIT" ]
1
2018-10-03T12:20:02.000Z
2018-10-03T12:20:02.000Z
src/lingua/ui/gtk/main_window/widgets/commandslist/CommandsListItem.java
cyberpython/lingua
8d437bdc4fd9c1eb1e025391770d6e86d33ec389
[ "MIT" ]
3
2015-08-18T12:08:00.000Z
2015-08-26T17:21:01.000Z
src/lingua/ui/gtk/main_window/widgets/commandslist/CommandsListItem.java
cyberpython/lingua
8d437bdc4fd9c1eb1e025391770d6e86d33ec389
[ "MIT" ]
null
null
null
34.089286
101
0.716082
13,001
/* * The MIT License * * Copyright 2012 Georgios Migdos <envkt@example.com>. * * 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 lingua.ui.gtk.main_window.widgets.commandslist; /** * * @author cyberpython */ public abstract class CommandsListItem { private String label; private String textBefore; private String textAfter; public CommandsListItem(String label, String textBefore, String textAfter) { this.label = label; this.textBefore = textBefore; this.textAfter = textAfter; } public String getLabel() { return label; } public String getTextBefore() { return textBefore; } public String getTextAfter() { return textAfter; } public abstract String getText(String encapsulatedText, String indentation, boolean isLineEmpty); }
3e1ebffc77460dce87e7e5492a722c8dd249b488
349
java
Java
app/src/main/java/com/fx/coolweather/gson/Now.java
fx109138/coolweather
67261b605687386963c7213c734437846cd5f378
[ "Apache-2.0" ]
2
2018-06-04T09:41:17.000Z
2018-06-04T09:41:22.000Z
app/src/main/java/com/fx/coolweather/gson/Now.java
fx109138/coolweather
67261b605687386963c7213c734437846cd5f378
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/fx/coolweather/gson/Now.java
fx109138/coolweather
67261b605687386963c7213c734437846cd5f378
[ "Apache-2.0" ]
null
null
null
13.96
50
0.644699
13,002
package com.fx.coolweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by fx on 2017/4/19. */ public class Now { @SerializedName("tmp") public String temperature; @SerializedName("cond") public More more; public class More{ @SerializedName("txt") public String info; } }
3e1ec1c0ccdde8677e48ea70d3f7d47d66747595
14,389
java
Java
bundles/api/src/main/java/org/apache/sling/api/resource/ResourceMetadata.java
peterkir/sling
554656dc509d2d81200cb6a73715e93937761462
[ "Apache-2.0" ]
null
null
null
bundles/api/src/main/java/org/apache/sling/api/resource/ResourceMetadata.java
peterkir/sling
554656dc509d2d81200cb6a73715e93937761462
[ "Apache-2.0" ]
null
null
null
bundles/api/src/main/java/org/apache/sling/api/resource/ResourceMetadata.java
peterkir/sling
554656dc509d2d81200cb6a73715e93937761462
[ "Apache-2.0" ]
null
null
null
34.016548
118
0.644868
13,003
/* * 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.sling.api.resource; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * The <code>ResourceMetadata</code> interface defines the API for the * metadata of a Sling {@link Resource}. Essentially the resource's metadata is * just a map of objects indexed by string keys. * <p> * The actual contents of the meta data map is implementation specific with the * exception of the {@link #RESOLUTION_PATH sling.resolutionPath} property which * must be provided by all implementations and contain the part of the request * URI used to resolve the resource. The type of this property value is defined * to be <code>String</code>. * <p> * Note, that the prefix <em>sling.</em> to key names is reserved for the * Sling implementation. * * Once a resource is returned by the {@link ResourceResolver}, the resource * metadata is made read-only and therefore can't be changed by client code! */ public class ResourceMetadata extends HashMap<String, Object> { private static final long serialVersionUID = 4692666752269523738L; /** * The name of the required property providing the part of the request URI * which was used to the resolve the resource to which the meta data * instance belongs (value is "sling.resolutionPath"). */ public static final String RESOLUTION_PATH = "sling.resolutionPath"; /** * The name of the required property providing the part of the request URI * which was not used to the resolve the resource to which the meta data * instance belongs (value is "sling.resolutionPathInfo"). The value of this * property concatenated to the value of the * {@link #RESOLUTION_PATH sling.resolutionPath} property returns the * original request URI leading to the resource. * <p> * This property is optional. If missing, it should be assumed equal to an * empty string. * * @since 2.0.4 (Sling API Bundle 2.0.4) */ public static final String RESOLUTION_PATH_INFO = "sling.resolutionPathInfo"; /** * The name of the optional property providing the content type of the * resource if the resource is streamable (value is "sling.contentType"). * This property may be missing if the resource is not streamable or if the * content type is not known. */ public static final String CONTENT_TYPE = "sling.contentType"; /** * The name of the optional property providing the content length of the * resource if the resource is streamable (value is "sling.contentLength"). * This property may be missing if the resource is not streamable or if the * content length is not known. * <p> * Note, that unlike the other properties, this property may be set only * after the resource has successfully been adapted to an * <code>InputStream</code> for performance reasons. */ public static final String CONTENT_LENGTH = "sling.contentLength"; /** * The name of the optional property providing the character encoding of the * resource if the resource is streamable and contains character data (value * is "sling.characterEncoding"). This property may be missing if the * resource is not streamable or if the character encoding is not known. */ public static final String CHARACTER_ENCODING = "sling.characterEncoding"; /** * Returns the creation time of this resource in the repository in * milliseconds (value is "sling.creationTime"). The type of this property * is <code>java.lang.Long</code>. The property may be missing if the * resource is not streamable or if the creation time is not known. */ public static final String CREATION_TIME = "sling.creationTime"; /** * Returns the last modification time of this resource in the repository in * milliseconds (value is "sling.modificationTime"). The type of this * property is <code>java.lang.Long</code>. The property may be missing * if the resource is not streamable or if the last modification time is not * known. */ public static final String MODIFICATION_TIME = "sling.modificationTime"; /** * Returns whether the resource resolver should continue to search for a * resource. * A resource provider can set this flag to indicate that the resource * resolver should search for a provider with a lower priority. If it * finds a resource using such a provider, that resource is returned * instead. If none is found this resource is returned. * This flag should never be manipulated by application code! * The value of this property has no meaning, the resource resolver * just checks whether this flag is set or not. * @since 2.2 (Sling API Bundle 2.2.0) */ public static final String INTERNAL_CONTINUE_RESOLVING = ":org.apache.sling.resource.internal.continue.resolving"; /** * Returns a map containing parameters added to path after semicolon. * For instance, map for path <code>/content/test;v='1.2.3'.html</code> * will contain one entry key <code>v</code> and value <code>1.2.3</code>. */ public static final String PARAMETER_MAP = "sling.parameterMap"; private boolean isReadOnly = false; /** * Sets the {@link #CHARACTER_ENCODING} property to <code>encoding</code> * if not <code>null</code>. */ public void setCharacterEncoding(String encoding) { if (encoding != null) { put(CHARACTER_ENCODING, encoding); } } /** * Returns the {@link #CHARACTER_ENCODING} property if not <code>null</code> * and a <code>String</code> instance. Otherwise <code>null</code> is * returned. */ public @CheckForNull String getCharacterEncoding() { Object value = get(CHARACTER_ENCODING); if (value instanceof String) { return (String) value; } return null; } /** * Sets the {@link #CONTENT_TYPE} property to <code>contentType</code> if * not <code>null</code>. */ public void setContentType(String contentType) { if (contentType != null) { put(CONTENT_TYPE, contentType); } } /** * Returns the {@link #CONTENT_TYPE} property if not <code>null</code> and * a <code>String</code> instance. Otherwise <code>null</code> is * returned. */ public @CheckForNull String getContentType() { Object value = get(CONTENT_TYPE); if (value instanceof String) { return (String) value; } return null; } /** * Sets the {@link #CONTENT_LENGTH} property to <code>contentType</code> * if not <code>null</code>. */ public void setContentLength(long contentLength) { if (contentLength > 0) { put(CONTENT_LENGTH, contentLength); } } /** * Returns the {@link #CONTENT_LENGTH} property if not <code>null</code> * and a <code>long</code>. Otherwise <code>-1</code> is returned. */ public long getContentLength() { Object value = get(CONTENT_LENGTH); if (value instanceof Long) { return (Long) value; } return -1; } /** * Sets the {@link #CREATION_TIME} property to <code>creationTime</code> * if not negative. */ public void setCreationTime(long creationTime) { if (creationTime >= 0) { put(CREATION_TIME, creationTime); } } /** * Returns the {@link #CREATION_TIME} property if not <code>null</code> * and a <code>long</code>. Otherwise <code>-1</code> is returned. */ public long getCreationTime() { Object value = get(CREATION_TIME); if (value instanceof Long) { return (Long) value; } return -1; } /** * Sets the {@link #MODIFICATION_TIME} property to * <code>modificationTime</code> if not negative. */ public void setModificationTime(long modificationTime) { if (modificationTime >= 0) { put(MODIFICATION_TIME, modificationTime); } } /** * Returns the {@link #MODIFICATION_TIME} property if not <code>null</code> * and a <code>long</code>. Otherwise <code>-1</code> is returned. */ public long getModificationTime() { Object value = get(MODIFICATION_TIME); if (value instanceof Long) { return (Long) value; } return -1; } /** * Sets the {@link #RESOLUTION_PATH} property to <code>resolutionPath</code> * if not <code>null</code>. */ public void setResolutionPath(String resolutionPath) { if (resolutionPath != null) { put(RESOLUTION_PATH, resolutionPath); } } /** * Returns the {@link #RESOLUTION_PATH} property if not <code>null</code> * and a <code>String</code> instance. Otherwise <code>null</code> is * returned. */ public @CheckForNull String getResolutionPath() { Object value = get(RESOLUTION_PATH); if (value instanceof String) { return (String) value; } return null; } /** * Sets the {@link #RESOLUTION_PATH_INFO} property to * <code>resolutionPathInfo</code> if not <code>null</code>. */ public void setResolutionPathInfo(String resolutionPathInfo) { if (resolutionPathInfo != null) { put(RESOLUTION_PATH_INFO, resolutionPathInfo); } } /** * Returns the {@link #RESOLUTION_PATH_INFO} property if not * <code>null</code> and a <code>String</code> instance. Otherwise * <code>null</code> is returned. */ public @CheckForNull String getResolutionPathInfo() { Object value = get(RESOLUTION_PATH_INFO); if (value instanceof String) { return (String) value; } return null; } /** * Sets the {@link #PARAMETER_MAP} property to * <code>parameterMap</code> if not <code>null</code>. */ public void setParameterMap(Map<String, String> parameterMap) { if (parameterMap != null) { put(PARAMETER_MAP, new LinkedHashMap<String, String>(parameterMap)); } } /** * Returns the {@link #PARAMETER_MAP} property if not * <code>null</code> and a <code>Map</code> instance. Otherwise * <code>null</code> is returned. */ @SuppressWarnings("unchecked") public @CheckForNull Map<String, String> getParameterMap() { Object value = get(PARAMETER_MAP); if (value instanceof Map) { return (Map<String, String>) value; } return null; } /** * Make this object read-only. All method calls trying to modify this object * result in an exception! * @since 2.3 (Sling API Bundle 2.4.0) */ public void lock() { this.isReadOnly = true; } /** * Check if this object is read only and if so throw an unsupported operation exception. */ private void checkReadOnly() { if ( this.isReadOnly ) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is locked"); } } @Override public void clear() { this.checkReadOnly(); super.clear(); } @Override public Object put(@Nonnull final String key, final Object value) { this.checkReadOnly(); return super.put(key, value); } @Override public void putAll(@Nonnull final Map<? extends String, ? extends Object> m) { this.checkReadOnly(); super.putAll(m); } @Override public Object remove(@Nonnull final Object key) { this.checkReadOnly(); return super.remove(key); } protected void internalPut(@Nonnull String key, Object value) { super.put(key, value); } @Override public Object clone() { ResourceMetadata result = (ResourceMetadata) super.clone(); result.lockedEntrySet = null; result.lockedKeySet = null; result.lockedValues = null; return result; } // volatile for correct double-checked locking in getLockedData() private transient volatile Set<Map.Entry<String, Object>> lockedEntrySet; private transient Set<String> lockedKeySet; private transient Collection<Object> lockedValues; private void getLockedData() { if(isReadOnly && lockedEntrySet == null) { synchronized (this) { if(isReadOnly && lockedEntrySet == null) { lockedEntrySet = Collections.unmodifiableSet(super.entrySet()); lockedKeySet = Collections.unmodifiableSet(super.keySet()); lockedValues = Collections.unmodifiableCollection(super.values()); } } } } @Override public @Nonnull Set<Map.Entry<String, Object>> entrySet() { getLockedData(); return lockedEntrySet != null ? lockedEntrySet : super.entrySet(); } @Override public @Nonnull Set<String> keySet() { getLockedData(); return lockedKeySet != null ? lockedKeySet : super.keySet(); } @Override public @Nonnull Collection<Object> values() { getLockedData(); return lockedValues != null ? lockedValues : super.values(); } }
3e1ec210df6aadd831bef77509f54724c86f537d
7,628
java
Java
app/src/main/java/gr/kalymnos/sk3m3l10/ddosdroid/mvc_controllers/connectivity/client/wifi/wifi_p2p/WifiDirectReceiver.java
tomasmichael995/DDoSDroid
8c14d67c7e1f8d3587d2bc4b1555a46fef9870b8
[ "MIT" ]
3
2021-02-21T17:58:28.000Z
2022-03-09T02:57:43.000Z
app/src/main/java/gr/kalymnos/sk3m3l10/ddosdroid/mvc_controllers/connectivity/client/wifi/wifi_p2p/WifiDirectReceiver.java
tomasmichael995/DDoSDroid
8c14d67c7e1f8d3587d2bc4b1555a46fef9870b8
[ "MIT" ]
null
null
null
app/src/main/java/gr/kalymnos/sk3m3l10/ddosdroid/mvc_controllers/connectivity/client/wifi/wifi_p2p/WifiDirectReceiver.java
tomasmichael995/DDoSDroid
8c14d67c7e1f8d3587d2bc4b1555a46fef9870b8
[ "MIT" ]
2
2020-02-03T19:31:51.000Z
2020-04-01T02:14:54.000Z
39.319588
129
0.673964
13,004
package gr.kalymnos.sk3m3l10.ddosdroid.mvc_controllers.connectivity.client.wifi.wifi_p2p; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.support.annotation.NonNull; import android.util.Log; import java.net.InetAddress; import gr.kalymnos.sk3m3l10.ddosdroid.mvc_controllers.connectivity.client.wifi.SocketConnectionThread; import gr.kalymnos.sk3m3l10.ddosdroid.pojos.attack.Attacks; import static android.net.wifi.p2p.WifiP2pManager.EXTRA_WIFI_STATE; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION; import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_ENABLED; import static gr.kalymnos.sk3m3l10.ddosdroid.utils.connectivity.WifiP2pUtil.failureTextFrom; public class WifiDirectReceiver extends BroadcastReceiver implements SocketConnectionThread.OnServerResponseListener { private static final String TAG = "WifiDirectReceiver"; private WifiP2PServerConnection serverConnection; private WifiP2pManager manager; private WifiP2pManager.Channel channel; public WifiDirectReceiver(WifiP2PServerConnection serverConnection, WifiP2pManager manager, WifiP2pManager.Channel channel) { this.serverConnection = serverConnection; this.manager = manager; this.channel = channel; } @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case WIFI_P2P_STATE_CHANGED_ACTION: Log.d(TAG, "WIFI_P2P_STATE_CHANGED_ACTION"); int state = intent.getIntExtra(EXTRA_WIFI_STATE, -1); handleWifiState(state); break; case WIFI_P2P_PEERS_CHANGED_ACTION: Log.d(TAG, "WIFI_P2P_PEERS_CHANGED_ACTION"); manager.requestPeers(channel, getPeerListListener()); break; case WIFI_P2P_CONNECTION_CHANGED_ACTION: Log.d(TAG, "WIFI_P2P_CONNECTION_CHANGED_ACTION"); handleConnectionChange(intent); break; default: throw new IllegalArgumentException(TAG + ": Unknown action"); } } private void handleWifiState(int state) { if (state == WIFI_P2P_STATE_ENABLED) { manager.discoverPeers(channel, getPeerDiscoveryActionListener()); } else { serverConnection.connectionListener.onServerConnectionError(); } } @NonNull private WifiP2pManager.ActionListener getPeerDiscoveryActionListener() { return new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "Initiating discovering peers process..."); } @Override public void onFailure(int reason) { Log.d(TAG, "Initiating discovering peers process: " + failureTextFrom(reason)); serverConnection.connectionListener.onServerConnectionError(); } }; } @NonNull private WifiP2pManager.PeerListListener getPeerListListener() { return wifiP2pDeviceList -> { for (WifiP2pDevice device : wifiP2pDeviceList.getDeviceList()) { if (isServer(device)) { Log.d(TAG, "Found server peer with name: " + device.deviceName + " and address: " + device.deviceAddress); connectTo(device); return; } } if (serverConnection.connectionListener != null) serverConnection.connectionListener.onServerConnectionError(); }; } private boolean isServer(WifiP2pDevice device) { String address = device.deviceAddress; String serverAddress = Attacks.getHostMacAddress(serverConnection.attack); return address.equals(serverAddress) && device.isGroupOwner(); } private void connectTo(WifiP2pDevice device) { WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; manager.connect(channel, config, getDeviceConnectionActionListener()); } @NonNull private WifiP2pManager.ActionListener getDeviceConnectionActionListener() { return new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "Initiated connection with server device..."); } @Override public void onFailure(int reason) { Log.d(TAG, "Connection initiation with server device failed: " + failureTextFrom(reason)); // Don't broadcast a server connection error here, onReceive() may called again to establish a connection. } }; } private void handleConnectionChange(Intent intent) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if (networkInfo.isConnected()) { Log.d(TAG, "Local device is connected with server device, requesting connection info"); manager.requestConnectionInfo(channel, getConnectionInfoListener()); } else { Log.d(TAG, "NetworkInfo.isConnected() returned false."); } } @NonNull private WifiP2pManager.ConnectionInfoListener getConnectionInfoListener() { return wifiP2pInfo -> { if (wifiP2pInfo.groupFormed) { Log.d(TAG, "Starting a connection thread"); SocketConnectionThread thread = createConnectionThread(wifiP2pInfo); thread.start(); } }; } @NonNull private SocketConnectionThread createConnectionThread(WifiP2pInfo wifiP2pInfo) { InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress; int hostLocalPort = Attacks.getHostLocalPort(serverConnection.attack); SocketConnectionThread thread = new SocketConnectionThread(groupOwnerAddress, hostLocalPort); thread.setServerResponseListener(this); return thread; } @Override public void onValidServerResponse() { Log.d(TAG, "Received server response"); serverConnection.connectionListener.onServerConnection(); } @Override public void onErrorServerResponse() { Log.d(TAG, "Did not receive response from server"); serverConnection.connectionListener.onServerConnectionError(); } public void releaseWifiP2pResources() { manager.removeGroup(channel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "Initiated group removal"); } @Override public void onFailure(int reason) { Log.d(TAG, "Failed to initiate group removal: " + failureTextFrom(reason)); } }); } @NonNull public static IntentFilter getIntentFilter() { IntentFilter filter = new IntentFilter(); filter.addAction(WIFI_P2P_STATE_CHANGED_ACTION); filter.addAction(WIFI_P2P_PEERS_CHANGED_ACTION); filter.addAction(WIFI_P2P_CONNECTION_CHANGED_ACTION); return filter; } }
3e1ec389333eb4c801d99cd473575aa0b070b110
2,555
java
Java
app/src/main/java/com/sdsmdg/harjot/MusicDNA/LocalTrackListAdapter.java
alan896/MusicStreamer
805d59240d34d75a3a3fe6617e03ec30d8a3be60
[ "MIT" ]
3
2017-02-06T07:53:31.000Z
2019-07-22T14:01:58.000Z
app/src/main/java/com/sdsmdg/harjot/MusicDNA/LocalTrackListAdapter.java
MrRight1990/MusicStreamer
805d59240d34d75a3a3fe6617e03ec30d8a3be60
[ "MIT" ]
null
null
null
app/src/main/java/com/sdsmdg/harjot/MusicDNA/LocalTrackListAdapter.java
MrRight1990/MusicStreamer
805d59240d34d75a3a3fe6617e03ec30d8a3be60
[ "MIT" ]
2
2017-01-10T04:09:05.000Z
2021-02-21T15:35:54.000Z
30.783133
102
0.662231
13,005
package com.sdsmdg.harjot.MusicDNA; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.sdsmdg.harjot.MusicDNA.Models.LocalTrack; import com.sdsmdg.harjot.MusicDNA.imageLoader.ImageLoader; import java.util.List; /** * Created by Harjot on 09-May-16. */ public class LocalTrackListAdapter extends RecyclerView.Adapter<LocalTrackListAdapter.MyViewHolder> { private List<LocalTrack> localTracks; private Context ctx; ImageLoader imgLoader; public class MyViewHolder extends RecyclerView.ViewHolder { ImageView art; TextView title, artist; public MyViewHolder(View view) { super(view); art = (ImageView) view.findViewById(R.id.img_2); title = (TextView) view.findViewById(R.id.title_2); artist = (TextView) view.findViewById(R.id.url_2); } } public LocalTrackListAdapter(List<LocalTrack> localTracks, Context ctx) { this.localTracks = localTracks; this.ctx = ctx; imgLoader = new ImageLoader(ctx); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_2, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { LocalTrack track = localTracks.get(position); holder.title.setText(track.getTitle()); holder.artist.setText(track.getArtist()); imgLoader.DisplayImage(track.getPath(), holder.art); } @Override public int getItemCount() { return localTracks.size(); } public static Bitmap getAlbumArt(String path) { android.media.MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(path); Bitmap bitmap = null; byte[] data = mmr.getEmbeddedPicture(); if (data != null) { bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); return bitmap; } else { return null; } } }
3e1ec4834ad9c449da3ac5bcb5af25e3b683e89c
21,966
java
Java
java/org.apache.derby.engine/org/apache/derby/iapi/sql/dictionary/ConstraintDescriptor.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
282
2015-01-06T02:30:11.000Z
2022-03-23T06:40:17.000Z
java/org.apache.derby.engine/org/apache/derby/iapi/sql/dictionary/ConstraintDescriptor.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
null
null
null
java/org.apache.derby.engine/org/apache/derby/iapi/sql/dictionary/ConstraintDescriptor.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
163
2015-01-07T00:07:53.000Z
2022-03-07T08:35:03.000Z
29.09404
114
0.679232
13,006
/* Derby - Class org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor 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.derby.iapi.sql.dictionary; import java.util.Arrays; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.iapi.sql.depend.Provider; import org.apache.derby.iapi.sql.depend.Dependent; import org.apache.derby.catalog.UUID; import org.apache.derby.shared.common.reference.SQLState; import org.apache.derby.shared.common.util.ArrayUtil; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.catalog.DependableFinder; import org.apache.derby.catalog.Dependable; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.sql.depend.DependencyManager; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.store.access.TransactionController; /** * This class is used to get information from a ConstraintDescriptor. * A ConstraintDescriptor can represent a constraint on a table or on a * column. * * @version 0.1 */ public abstract class ConstraintDescriptor extends UniqueTupleDescriptor implements Provider, Dependent { // used to indicate what type of constraints we // are interested in public static final int ENABLED = 1; public static final int DISABLED = 2; public static final int ALL = 3; // field that we want users to be able to know about public static final int SYSCONSTRAINTS_STATE_FIELD = 6; TableDescriptor table; final String constraintName; private boolean deferrable; private boolean initiallyDeferred; private boolean enforced; private final int[] referencedColumns; final UUID constraintId; private final SchemaDescriptor schemaDesc; private ColumnDescriptorList colDL; /** * Constructor for a ConstraintDescriptor * * @param dataDictionary The data dictionary that this descriptor lives in * @param table The descriptor of the table the constraint is on * @param constraintName The name of the constraint. * @param deferrable If the constraint can be deferred. * @param initiallyDeferred If the constraint starts life deferred. * @param referencedColumns columns that the constraint references * @param constraintId UUID of constraint * @param schemaDesc SchemaDescriptor * @param enforced Is the constraint enforced? */ ConstraintDescriptor( DataDictionary dataDictionary, TableDescriptor table, String constraintName, boolean deferrable, boolean initiallyDeferred, int[] referencedColumns, UUID constraintId, SchemaDescriptor schemaDesc, boolean enforced ) { super( dataDictionary ); this.table = table; this.constraintName = constraintName; this.deferrable = deferrable; this.initiallyDeferred = initiallyDeferred; this.referencedColumns = referencedColumns; this.constraintId = constraintId; this.schemaDesc = schemaDesc; this.enforced = enforced; } /** * Gets the UUID of the table the constraint is on. * * @return The UUID of the table the constraint is on. */ public UUID getTableId() { return table.getUUID(); } /** * Gets the UUID of the constraint. * * @return The UUID of the constraint. */ public UUID getUUID() { return constraintId; } /** * Gets the name of the constraint. * * @return A String containing the name of the constraint. */ public String getConstraintName() { return constraintName; } /** * Gets an identifier telling what type of descriptor it is * (UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK). * * @return An identifier telling what type of descriptor it is * (UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK). */ public abstract int getConstraintType(); public abstract UUID getConglomerateId(); /** * Get the text of the constraint. (Only non-null/meaningful for check * constraints.) * @return The constraint text. */ public String getConstraintText() { return null; } /** * Returns TRUE if the constraint is deferrable * * @return TRUE if the constraint is DEFERRABLE, FALSE if it is * NOT DEFERRABLE. */ public boolean deferrable() { return deferrable; } public void setDeferrable(boolean b) { deferrable = b; } /** * Returns TRUE if the constraint is initially deferred * * @return TRUE if the constraint is initially DEFERRED, * FALSE if the constraint is initially IMMEDIATE */ public boolean initiallyDeferred() { return initiallyDeferred; } public void setInitiallyDeferred(boolean b) { initiallyDeferred = b; } /** * Returns an array of column ids (i.e. ordinal positions) for * the columns referenced in this table for a primary key, unique * key, referential, or check constraint. * * @return An array of column ids for those constraints that can * be on columns (primary, unique key, referential * constraints, and check constraints). For check and * unique constraints, it returns an array of columns ids * that are referenced in the constraint. For primary key * and referential constraints, it returns an array of * column ids for the columns in this table (i.e. the * primary key columns for a primary key constraint, * and the foreign key columns for a foreign key * constraint. */ public int[] getReferencedColumns() { return ArrayUtil.copy( referencedColumns ); } /** * Does this constraint have a backing index? * * @return boolean Whether or not there is a backing index for this constraint. */ public abstract boolean hasBackingIndex(); /** * Get the SchemaDescriptor for the schema that this constraint * belongs to. * * @return SchemaDescriptor The SchemaDescriptor for this constraint. */ public SchemaDescriptor getSchemaDescriptor() { return schemaDesc; } /** RESOLVE: For now the ConstraintDescriptor code stores the array of key columns in the field 'otherColumns'. Jerry plans to re-organize things. For now to minimize his rototill I've implemented this function on the old structures. All new code should use getKeyColumns to get a constraint's key columns. @see org.apache.derby.iapi.sql.dictionary.KeyConstraintDescriptor#getKeyColumns */ public int[] getKeyColumns() { return getReferencedColumns(); } /** * Is this constraint enforced? * * @return true/false */ public boolean enforced() { return enforced; } public void setEnforced(boolean b) { enforced = b; } /** * Is this constraint referenced? Return * false. Overridden by ReferencedKeyConstraints. * * @return false */ public boolean isReferenced() { return false; } /** * Get the number of enforced fks that * reference this key. Overriden by * ReferencedKeyConstraints. * * @return the number of fks */ public int getReferenceCount() { return 0; } /** * Does this constraint need to fire on this type of * DML? * * @param stmtType the type of DML * (StatementType.INSERT|StatementType.UPDATE|StatementType.DELETE) * @param modifiedCols the columns modified, or null for all * * @return true/false */ public abstract boolean needsToFire(int stmtType, int[] modifiedCols); /** * Get the table descriptor upon which this constraint * is declared. * * @return the table descriptor */ public TableDescriptor getTableDescriptor() { return table; } /** * Get the column descriptors for all the columns * referenced by this constraint. * * @return the column descriptor list * * @exception StandardException on error */ public ColumnDescriptorList getColumnDescriptors() throws StandardException { if (colDL == null) { colDL = new ColumnDescriptorList(); int[] refCols = getReferencedColumns(); for (int i = 0; i < refCols.length; i++) { colDL.add(table.getColumnDescriptor(refCols[i])); } } return colDL; } /** * Indicates whether the column descriptor list is * type comparable with the constraints columns. The * types have to be identical AND in the same order * to succeed. * * @param otherColumns the columns to compare * * @return true/false * * @exception StandardException on error */ public boolean areColumnsComparable(ColumnDescriptorList otherColumns) throws StandardException { ColumnDescriptor myColumn; ColumnDescriptor otherColumn; ColumnDescriptorList myColDl = getColumnDescriptors(); /* ** Check the lenghts of the lists */ if (otherColumns.size() != myColDl.size()) { return false; } int mySize = myColDl.size(); int otherSize = otherColumns.size(); int index; for (index = 0; index < mySize && index < otherSize; index++) { myColumn = myColDl.elementAt(index); otherColumn = otherColumns.elementAt(index); /* ** Just compare the types. Note that this will ** say a decimal(x,y) != numeric(x,y) even though ** it does. */ if (!(myColumn.getType()).isExactTypeAndLengthMatch( (otherColumn.getType()))) { break; } } return (index == mySize && index == otherSize); } /** * Does a column intersect with our referenced columns * @param columnArray columns to check * * Note-- this is not a static method. */ public boolean columnIntersects(int columnArray[]) { // call static method. return doColumnsIntersect(getReferencedColumns(), columnArray); } /** * Does a column in the input set intersect with * our referenced columns? * * @param otherColumns the columns to compare. If * null, asssumed to mean all columns * * @param referencedColumns the columns referenced by the caller * * @return true/false */ static boolean doColumnsIntersect(int[] otherColumns, int[] referencedColumns) { /* ** It is assumed that if otherColumns is null, then ** all other columns are modified. In this case, ** it is assumed that it intersects with some column ** of ours, so just return true. */ if ((otherColumns == null) || (referencedColumns == null)) { return true; } for (int outer = 0; outer < referencedColumns.length; outer++) { for (int inner = 0; inner < otherColumns.length; inner++) { if (referencedColumns[outer] == otherColumns[inner]) { return true; } } } return false; } /** * Convert the ColumnDescriptor to a String. * * @return A String representation of this ColumnDescriptor */ @Override public String toString() { if (SanityManager.DEBUG) { String tableDesc = "table: " + table.getQualifiedName() + "(" + table.getUUID()+","+ table.getTableType()+")"; return tableDesc + "\n"+ "constraintName: " + constraintName + "\n" + "constraintId: " + constraintId + "\n" + "deferrable: " + deferrable + "\n" + "initiallyDeferred: " + initiallyDeferred + "\n" + "referencedColumns: " + Arrays.toString(referencedColumns) + "\n" + "schemaDesc: " + schemaDesc + "\n" ; } else { return ""; } } //////////////////////////////////////////////////////////////////// // // PROVIDER INTERFACE // //////////////////////////////////////////////////////////////////// /** @return the stored form of this provider @see Dependable#getDependableFinder */ public DependableFinder getDependableFinder() { return getDependableFinder(StoredFormatIds.CONSTRAINT_DESCRIPTOR_FINDER_V01_ID); } /** * Return the name of this Provider. (Useful for errors.) * * @return String The name of this provider. */ public String getObjectName() { return constraintName; } /** * Get the provider's UUID * * @return The provider's UUID */ public UUID getObjectID() { return constraintId; } /** * Get the provider's type. * * @return char The provider's type. */ public String getClassType() { return Dependable.CONSTRAINT; } ////////////////////////////////////////////////////// // // DEPENDENT INTERFACE // ////////////////////////////////////////////////////// /** * Check that all of the dependent's dependencies are valid. * * @return true if the dependent is currently valid */ public synchronized boolean isValid() { return true; } /** * Prepare to mark the dependent as invalid (due to at least one of * its dependencies being invalid). * * @param action The action causing the invalidation * @param p the provider * * @exception StandardException thrown if unable to make it invalid */ public void prepareToInvalidate(Provider p, int action, LanguageConnectionContext lcc) throws StandardException { DependencyManager dm = getDataDictionary().getDependencyManager(); switch (action) { /* ** A SET CONSTRAINT stmt will throw an SET_CONSTRAINTS action ** when enabling/disabling constraints. We'll ignore it. ** Same for SET TRIGGERS */ case DependencyManager.SET_CONSTRAINTS_ENABLE: case DependencyManager.SET_CONSTRAINTS_DISABLE: case DependencyManager.SET_TRIGGERS_ENABLE: case DependencyManager.SET_TRIGGERS_DISABLE: case DependencyManager.RENAME: //When REVOKE_PRIVILEGE gets sent (this happens for privilege //types SELECT, UPDATE, DELETE, INSERT, REFERENCES, TRIGGER), we //don't do anything here. Later in makeInvalid method, we make //the ConstraintDescriptor drop itself. //Ditto for role grant conferring a privilege. case DependencyManager.REVOKE_PRIVILEGE: case DependencyManager.REVOKE_ROLE: case DependencyManager.INTERNAL_RECOMPILE_REQUEST: // Only used by Activations case DependencyManager.RECHECK_PRIVILEGES: break; /* ** Currently, the only thing we are depenedent ** on is another constraint or an alias.. */ //Notice that REVOKE_PRIVILEGE_RESTRICT is not caught earlier. //It gets handled in this default: action where an exception //will be thrown. This is because, if such an invalidation //action type is ever received by a dependent, the dependent //should throw an exception. //In Derby, at this point, REVOKE_PRIVILEGE_RESTRICT gets sent //when execute privilege on a routine is getting revoked. //Currently, in Derby, a constraint can't depend on a routine //and hence a REVOKE_PRIVILEGE_RESTRICT invalidation action //should never be received by a ConstraintDescriptor. But this //may change in future and when it does, the code to do the right //thing is already here. default: throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(action), p.getObjectName(), "CONSTRAINT", constraintName); } } /** * Mark the dependent as invalid (due to at least one of * its dependencies being invalid). Always an error * for a constraint -- should never have gotten here. * * @param action The action causing the invalidation * * @exception StandardException thrown if called in sanity mode */ public void makeInvalid(int action, LanguageConnectionContext lcc) throws StandardException { /* ** For ConstraintDescriptor, SET_CONSTRAINTS/TRIGGERS and * REVOKE_PRIVILEGE are the only valid actions */ //Let's handle REVOKE_PRIVILEGE and REVOKE_ROLE first if (action == DependencyManager.REVOKE_PRIVILEGE || action == DependencyManager.REVOKE_ROLE) { //At this point (Derby 10.2), only a FOREIGN KEY key constraint can //depend on a privilege. None of the other constraint types //can be dependent on a privilege becuse those constraint types //can not reference a table/routine. ConglomerateDescriptor newBackingConglomCD = drop(lcc, true); // // Invalidate every statement which depends on the table. // This causes us to follow the same code path which we pursue // when the CHECK constraint is dropped explicitly. // getDataDictionary().getDependencyManager().invalidateFor( table, DependencyManager.ALTER_TABLE, lcc ); lcc.getLastActivation().addWarning( StandardException.newWarning( SQLState.LANG_CONSTRAINT_DROPPED, getConstraintName(), getTableDescriptor().getName())); if (newBackingConglomCD != null) { /* Since foreign keys can never be unique, and since * we only (currently) share conglomerates if two * constraints/indexes have identical columns, dropping * a foreign key should not necessitate the creation of * another physical conglomerate. That will change if * DERBY-2204 is implemented, but for now we don't expect * it to happen... */ if (SanityManager.DEBUG) { SanityManager.THROWASSERT( "Dropped shared conglomerate due to a REVOKE " + "and found that a new conglomerate was needed " + "to replace it...but that shouldn't happen!"); } } return; } /* ** Now, handle SET_CONSTRAINTS/TRIGGERS */ if ((action != DependencyManager.SET_CONSTRAINTS_DISABLE) && (action != DependencyManager.SET_CONSTRAINTS_ENABLE) && (action != DependencyManager.SET_TRIGGERS_ENABLE) && (action != DependencyManager.SET_TRIGGERS_DISABLE) && (action != DependencyManager.INTERNAL_RECOMPILE_REQUEST) && (action != DependencyManager.RECHECK_PRIVILEGES) && (action != DependencyManager.RENAME) ) { /* ** We should never get here, we should have barfed on ** prepareToInvalidate(). */ if (SanityManager.DEBUG) { DependencyManager dm; dm = getDataDictionary().getDependencyManager(); SanityManager.THROWASSERT("makeInvalid("+ dm.getActionString(action)+ ") not expected to get called"); } } } /** * Drop the constraint. Clears dependencies, drops * the backing index and removes the constraint * from the list on the table descriptor. Does NOT * do an dm.invalidateFor() * * @return If the backing conglomerate for this constraint * was a) dropped and b) shared by other constraints/indexes, * then this method will return a ConglomerateDescriptor that * describes what a new backing conglomerate must look like * to stay "sharable" across the remaining constraints/indexes. * It is then up to the caller to create a corresponding * conglomerate. We don't create the conglomerate here * because depending on who called us, it might not make * sense to create it--ex. if we get here because of a DROP * TABLE, the DropTable action doesn't need to create a * new backing conglomerate since the table (and all of * its constraints/indexes) are going to disappear anyway. */ public ConglomerateDescriptor drop(LanguageConnectionContext lcc, boolean clearDependencies) throws StandardException { DataDictionary dd = getDataDictionary(); TransactionController tc = lcc.getTransactionExecute(); if (clearDependencies) { DependencyManager dm = dd.getDependencyManager(); dm.clearDependencies(lcc, this); } /* Drop the constraint. * NOTE: This must occur before dropping any backing index, since * a user is not allowed to drop a backing index without dropping * the constraint. */ dd.dropConstraintDescriptor(this, tc); /* Drop the index, if there's one for this constraint. * NOTE: There will always be an indexAction. We don't * force the constraint to exist at bind time, so we always * generate one. */ ConglomerateDescriptor newBackingConglomCD = null; if (hasBackingIndex()) { // it may have duplicates, and we drop a backing index // Bug 4307 // We need to get the conglomerate descriptors from the // dd in case we dropped other constraints in a cascade operation. ConglomerateDescriptor[]conglomDescs = dd.getConglomerateDescriptors(getConglomerateId()); // Typically there is only one ConglomerateDescriptor // for a given UUID, but due to an old bug // there may be more than one. If there is more // than one then which one is remvoed does not // matter since they will all have the same critical // information since they point to the same physical index. for (ConglomerateDescriptor cd : conglomDescs) { if (cd.isConstraint()) { newBackingConglomCD = cd.drop(lcc, table); break; } } } table.removeConstraintDescriptor(this); return newBackingConglomCD; } /** @see TupleDescriptor#getDescriptorName */ @Override public String getDescriptorName() { return constraintName; } @Override public String getDescriptorType() { return "Constraint"; } }
3e1ec48dc0fa6c771a0fba5faad0719679f10779
1,190
java
Java
app/src/main/java/io/moku/davide/sideproject/utils/assets/ImagesUtils.java
davidecastello/side-project
35e59937ba893358693f9c410793954317b4a267
[ "MIT" ]
null
null
null
app/src/main/java/io/moku/davide/sideproject/utils/assets/ImagesUtils.java
davidecastello/side-project
35e59937ba893358693f9c410793954317b4a267
[ "MIT" ]
null
null
null
app/src/main/java/io/moku/davide/sideproject/utils/assets/ImagesUtils.java
davidecastello/side-project
35e59937ba893358693f9c410793954317b4a267
[ "MIT" ]
null
null
null
36.060606
130
0.730252
13,007
package io.moku.davide.sideproject.utils.assets; import android.content.Context; import android.text.TextUtils; import android.widget.ImageView; import com.pkmmte.view.CircularImageView; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; /** * Created by Davide Castello on 01/02/18. * Project: side-project * Copyright © 2018 Moku S.r.l. All rights reserved. */ public class ImagesUtils { public static void loadUrlIntoImageView(String url, Context context, ImageView imageView, int placeholderId) { loadUrlIntoImageView(url, context, imageView, placeholderId, true); } public static void loadUrlIntoImageView(String url, Context context, ImageView imageView, int placeholderId, boolean resize) { boolean validUrl = !TextUtils.isEmpty(url); Picasso picasso = Picasso.with(context); RequestCreator creator = (validUrl) ? picasso.load(url) : picasso.load(placeholderId); if (resize) { creator = creator.resize(1200, 1200).centerCrop(); } creator = creator.placeholder(placeholderId); if (validUrl) { creator = creator.error(placeholderId); } creator.into(imageView); } }
3e1ec4ca72cd9ec9df30e5eb24ec0b6bd14b9569
2,597
java
Java
spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/InvalidBindingConfigurationTests.java
fangjian0423/spring-cloud-stream
df645ecbd0a032455ac2f7fc33850878fc365dcb
[ "Apache-2.0" ]
1
2020-04-07T08:34:04.000Z
2020-04-07T08:34:04.000Z
spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/InvalidBindingConfigurationTests.java
fangjian0423/spring-cloud-stream
df645ecbd0a032455ac2f7fc33850878fc365dcb
[ "Apache-2.0" ]
null
null
null
spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/InvalidBindingConfigurationTests.java
fangjian0423/spring-cloud-stream
df645ecbd0a032455ac2f7fc33850878fc365dcb
[ "Apache-2.0" ]
null
null
null
30.916667
75
0.789757
13,008
/* * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.stream.binding; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.Input; import org.springframework.cloud.stream.annotation.Output; import org.springframework.cloud.stream.messaging.Processor; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Artem Bilan * @since 1.3 */ public class InvalidBindingConfigurationTests { @Test @Ignore public void testDuplicateBeanByBindingConfig() { assertThatThrownBy(() -> SpringApplication.run(TestBindingConfig.class)) .isInstanceOf(BeanDefinitionStoreException.class) .hasMessageContaining("bean definition with this name already exists") .hasMessageContaining(TestInvalidBinding.NAME).hasNoCause(); } @Test public void testSameDestinationByBindingConfig() { assertThatThrownBy(() -> SpringApplication.run( InvalidBindingConfigurationTests.TestProcessorSameDestination.class, "--spring.cloud.stream.bindings.output.destination=topic", "--spring.cloud.stream.bindings.input.destination=topic", "--spring.cloud.stream.bindings.input.group=testGroup")) .hasRootCauseInstanceOf(IllegalArgumentException.class); } public interface TestInvalidBinding { String NAME = "testName"; @Input(NAME) SubscribableChannel in(); @Output(NAME) MessageChannel out(); } @EnableBinding(TestInvalidBinding.class) @EnableAutoConfiguration public static class TestBindingConfig { } @EnableBinding(Processor.class) @EnableAutoConfiguration public static class TestProcessorSameDestination { } }
3e1ec4e5507a9554392bc73fc679254d2c40f25d
8,510
java
Java
base.core/src/main/java/eapli/base/antlr/formulario/ValidacaoFormVisitor.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
base.core/src/main/java/eapli/base/antlr/formulario/ValidacaoFormVisitor.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
base.core/src/main/java/eapli/base/antlr/formulario/ValidacaoFormVisitor.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
36.212766
123
0.737133
13,009
// Generated from C:/lei20_21_s4_2di_02/base.core/src/main/java/eapli/base/antlr/formulario\ValidacaoForm.g4 by ANTLR 4.9.1 package eapli.base.antlr.formulario; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link ValidacaoFormParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface ValidacaoFormVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by the {@code endResult} * labeled alternative in {@link ValidacaoFormParser#start}. * @param ctx the parse tree * @return the visitor result */ T visitEndResult(ValidacaoFormParser.EndResultContext ctx); /** * Visit a parse tree produced by the {@code inst} * labeled alternative in {@link ValidacaoFormParser#form}. * @param ctx the parse tree * @return the visitor result */ T visitInst(ValidacaoFormParser.InstContext ctx); /** * Visit a parse tree produced by the {@code instRec} * labeled alternative in {@link ValidacaoFormParser#form}. * @param ctx the parse tree * @return the visitor result */ T visitInstRec(ValidacaoFormParser.InstRecContext ctx); /** * Visit a parse tree produced by the {@code opVerifyInstrucaoForm} * labeled alternative in {@link ValidacaoFormParser#instrucao_form}. * @param ctx the parse tree * @return the visitor result */ T visitOpVerifyInstrucaoForm(ValidacaoFormParser.OpVerifyInstrucaoFormContext ctx); /** * Visit a parse tree produced by the {@code opAndVerif} * labeled alternative in {@link ValidacaoFormParser#cond_verificacao}. * @param ctx the parse tree * @return the visitor result */ T visitOpAndVerif(ValidacaoFormParser.OpAndVerifContext ctx); /** * Visit a parse tree produced by the {@code opBoolVerif} * labeled alternative in {@link ValidacaoFormParser#cond_verificacao}. * @param ctx the parse tree * @return the visitor result */ T visitOpBoolVerif(ValidacaoFormParser.OpBoolVerifContext ctx); /** * Visit a parse tree produced by the {@code opOrVerif} * labeled alternative in {@link ValidacaoFormParser#cond_verificacao}. * @param ctx the parse tree * @return the visitor result */ T visitOpOrVerif(ValidacaoFormParser.OpOrVerifContext ctx); /** * Visit a parse tree produced by the {@code opValid} * labeled alternative in {@link ValidacaoFormParser#validacoes}. * @param ctx the parse tree * @return the visitor result */ T visitOpValid(ValidacaoFormParser.OpValidContext ctx); /** * Visit a parse tree produced by the {@code opValidRec} * labeled alternative in {@link ValidacaoFormParser#validacoes}. * @param ctx the parse tree * @return the visitor result */ T visitOpValidRec(ValidacaoFormParser.OpValidRecContext ctx); /** * Visit a parse tree produced by {@link ValidacaoFormParser#validacao}. * @param ctx the parse tree * @return the visitor result */ T visitValidacao(ValidacaoFormParser.ValidacaoContext ctx); /** * Visit a parse tree produced by the {@code instForm} * labeled alternative in {@link ValidacaoFormParser#operacoes_logicas}. * @param ctx the parse tree * @return the visitor result */ T visitInstForm(ValidacaoFormParser.InstFormContext ctx); /** * Visit a parse tree produced by the {@code opAndLogic} * labeled alternative in {@link ValidacaoFormParser#operacoes_logicas}. * @param ctx the parse tree * @return the visitor result */ T visitOpAndLogic(ValidacaoFormParser.OpAndLogicContext ctx); /** * Visit a parse tree produced by the {@code funcBool} * labeled alternative in {@link ValidacaoFormParser#operacoes_logicas}. * @param ctx the parse tree * @return the visitor result */ T visitFuncBool(ValidacaoFormParser.FuncBoolContext ctx); /** * Visit a parse tree produced by the {@code opBoolLogic} * labeled alternative in {@link ValidacaoFormParser#operacoes_logicas}. * @param ctx the parse tree * @return the visitor result */ T visitOpBoolLogic(ValidacaoFormParser.OpBoolLogicContext ctx); /** * Visit a parse tree produced by the {@code opOrLogic} * labeled alternative in {@link ValidacaoFormParser#operacoes_logicas}. * @param ctx the parse tree * @return the visitor result */ T visitOpOrLogic(ValidacaoFormParser.OpOrLogicContext ctx); /** * Visit a parse tree produced by the {@code empty} * labeled alternative in {@link ValidacaoFormParser#funcao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitEmpty(ValidacaoFormParser.EmptyContext ctx); /** * Visit a parse tree produced by the {@code notEmpty} * labeled alternative in {@link ValidacaoFormParser#funcao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitNotEmpty(ValidacaoFormParser.NotEmptyContext ctx); /** * Visit a parse tree produced by the {@code match} * labeled alternative in {@link ValidacaoFormParser#funcao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitMatch(ValidacaoFormParser.MatchContext ctx); /** * Visit a parse tree produced by the {@code notMatch} * labeled alternative in {@link ValidacaoFormParser#funcao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitNotMatch(ValidacaoFormParser.NotMatchContext ctx); /** * Visit a parse tree produced by the {@code opStr} * labeled alternative in {@link ValidacaoFormParser#operacao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitOpStr(ValidacaoFormParser.OpStrContext ctx); /** * Visit a parse tree produced by the {@code opBoolAtr} * labeled alternative in {@link ValidacaoFormParser#operacao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitOpBoolAtr(ValidacaoFormParser.OpBoolAtrContext ctx); /** * Visit a parse tree produced by the {@code opBool} * labeled alternative in {@link ValidacaoFormParser#operacao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitOpBool(ValidacaoFormParser.OpBoolContext ctx); /** * Visit a parse tree produced by the {@code opInt} * labeled alternative in {@link ValidacaoFormParser#operacao_bool}. * @param ctx the parse tree * @return the visitor result */ T visitOpInt(ValidacaoFormParser.OpIntContext ctx); /** * Visit a parse tree produced by the {@code opLen} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpLen(ValidacaoFormParser.OpLenContext ctx); /** * Visit a parse tree produced by the {@code operr} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOperr(ValidacaoFormParser.OperrContext ctx); /** * Visit a parse tree produced by the {@code opNum} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpNum(ValidacaoFormParser.OpNumContext ctx); /** * Visit a parse tree produced by the {@code opSS} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpSS(ValidacaoFormParser.OpSSContext ctx); /** * Visit a parse tree produced by the {@code opMD} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpMD(ValidacaoFormParser.OpMDContext ctx); /** * Visit a parse tree produced by the {@code opParen} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpParen(ValidacaoFormParser.OpParenContext ctx); /** * Visit a parse tree produced by the {@code opAtr} * labeled alternative in {@link ValidacaoFormParser#inteiro}. * @param ctx the parse tree * @return the visitor result */ T visitOpAtr(ValidacaoFormParser.OpAtrContext ctx); /** * Visit a parse tree produced by the {@code attribute} * labeled alternative in {@link ValidacaoFormParser#atributo}. * @param ctx the parse tree * @return the visitor result */ T visitAttribute(ValidacaoFormParser.AttributeContext ctx); /** * Visit a parse tree produced by {@link ValidacaoFormParser#regex}. * @param ctx the parse tree * @return the visitor result */ T visitRegex(ValidacaoFormParser.RegexContext ctx); }
3e1ec4e7dce637a0e36dfeb02601eeb8a0f3cf66
11,862
java
Java
contrib/storage-hive/core/src/main/codegen/templates/ObjectInspectorHelper.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
1,510
2015-01-04T01:35:19.000Z
2022-03-28T23:36:02.000Z
contrib/storage-hive/core/src/main/codegen/templates/ObjectInspectorHelper.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
1,979
2015-01-28T03:18:38.000Z
2022-03-31T13:49:32.000Z
contrib/storage-hive/core/src/main/codegen/templates/ObjectInspectorHelper.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
940
2015-01-01T01:39:39.000Z
2022-03-25T08:46:59.000Z
47.830645
148
0.656045
13,010
/* * 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. */ <@pp.dropOutputFile /> <@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/hive/ObjectInspectorHelper.java" /> <#include "/@includes/license.ftl" /> package org.apache.drill.exec.expr.fn.impl.hive; import com.sun.codemodel.*; import org.apache.drill.common.types.TypeProtos; import org.apache.drill.common.types.TypeProtos.DataMode; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.exec.expr.ClassGenerator; import org.apache.drill.exec.expr.DirectExpression; import org.apache.drill.exec.expr.TypeHelper; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.*; import java.lang.UnsupportedOperationException; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; import org.apache.drill.shaded.guava.com.google.common.collect.Multimap; import org.apache.drill.shaded.guava.com.google.common.collect.ArrayListMultimap; public class ObjectInspectorHelper { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ObjectInspectorHelper.class); private static Multimap<MinorType, Class> OIMAP_REQUIRED = ArrayListMultimap.create(); private static Multimap<MinorType, Class> OIMAP_OPTIONAL = ArrayListMultimap.create(); static { <#assign entries = drillDataType.map + drillOI.map /> <#list entries as entry> <#if entry.needOIForDrillType == true> OIMAP_REQUIRED.put(MinorType.${entry.drillType?upper_case}, Drill${entry.drillType}${entry.hiveOI}.Required.class); OIMAP_OPTIONAL.put(MinorType.${entry.drillType?upper_case}, Drill${entry.drillType}${entry.hiveOI}.Optional.class); </#if> </#list> } public static ObjectInspector getDrillObjectInspector(DataMode mode, MinorType minorType, boolean varCharToStringReplacement) { try { if (mode == DataMode.REQUIRED) { if (OIMAP_REQUIRED.containsKey(minorType)) { if (varCharToStringReplacement && minorType == MinorType.VARCHAR) { return (ObjectInspector) ((Class) OIMAP_REQUIRED.get(minorType).toArray()[1]).newInstance(); } else { return (ObjectInspector) ((Class) OIMAP_REQUIRED.get(minorType).toArray()[0]).newInstance(); } } } else if (mode == DataMode.OPTIONAL) { if (OIMAP_OPTIONAL.containsKey(minorType)) { if (varCharToStringReplacement && minorType == MinorType.VARCHAR) { return (ObjectInspector) ((Class) OIMAP_OPTIONAL.get(minorType).toArray()[1]).newInstance(); } else { return (ObjectInspector) ((Class) OIMAP_OPTIONAL.get(minorType).toArray()[0]).newInstance(); } } } else { throw new UnsupportedOperationException("Repeated types are not supported as arguement to Hive UDFs"); } } catch(InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to instantiate ObjectInspector", e); } throw new UnsupportedOperationException( String.format("Type %s[%s] not supported as arguement to Hive UDFs", minorType.toString(), mode.toString())); } public static JBlock initReturnValueHolder(ClassGenerator<?> g, JCodeModel m, JVar returnValueHolder, ObjectInspector oi, MinorType returnType) { JBlock block = new JBlock(false, false); switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; switch(poi.getPrimitiveCategory()) { <#assign entries = drillDataType.map + drillOI.map /> <#list entries as entry> case ${entry.hiveType}:{ JType holderClass = TypeHelper.getHolderType(m, returnType, TypeProtos.DataMode.OPTIONAL); block.assign(returnValueHolder, JExpr._new(holderClass)); <#if entry.hiveType == "VARCHAR" || entry.hiveType == "STRING" || entry.hiveType == "BINARY" || entry.hiveType == "CHAR"> block.assign( // returnValueHolder.ref("buffer"), // g .getMappingSet() .getIncoming() .invoke("getContext") .invoke("getManagedBuffer") .invoke("reallocIfNeeded") .arg(JExpr.lit(1024)) ); </#if> return block; } </#list> default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", poi.getPrimitiveCategory().toString())); } } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", oi.getCategory().toString())); } } private static Map<PrimitiveCategory, MinorType> TYPE_HIVE2DRILL = new HashMap<>(); static { <#assign entries = drillDataType.map + drillOI.map /> <#list entries as entry> TYPE_HIVE2DRILL.put(PrimitiveCategory.${entry.hiveType}, MinorType.${entry.drillType?upper_case}); </#list> } public static MinorType getDrillType(ObjectInspector oi) { switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; if (TYPE_HIVE2DRILL.containsKey(poi.getPrimitiveCategory())) { return TYPE_HIVE2DRILL.get(poi.getPrimitiveCategory()); } throw new UnsupportedOperationException(); } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(); } } public static JBlock getDrillObject(JCodeModel m, ObjectInspector oi, JVar returnOI, JVar returnValueHolder, JVar returnValue) { JBlock block = new JBlock(false, false); switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; switch(poi.getPrimitiveCategory()) { <#assign entries = drillDataType.map + drillOI.map /> <#list entries as entry> case ${entry.hiveType}:{ JConditional jc = block._if(returnValue.eq(JExpr._null())); jc._then().assign(returnValueHolder.ref("isSet"), JExpr.lit(0)); jc._else().assign(returnValueHolder.ref("isSet"), JExpr.lit(1)); JVar castedOI = jc._else().decl( m.directClass(${entry.hiveOI}.class.getCanonicalName()), "castOI", JExpr._null()); jc._else().assign(castedOI, JExpr.cast(m.directClass(${entry.hiveOI}.class.getCanonicalName()), returnOI)); <#if entry.hiveType == "BOOLEAN"> JConditional booleanJC = jc._else()._if(castedOI.invoke("get").arg(returnValue)); booleanJC._then().assign(returnValueHolder.ref("value"), JExpr.lit(1)); booleanJC._else().assign(returnValueHolder.ref("value"), JExpr.lit(0)); <#elseif entry.hiveType == "VARCHAR" || entry.hiveType == "CHAR" || entry.hiveType == "STRING" || entry.hiveType == "BINARY"> <#if entry.hiveType == "VARCHAR"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getValue") .invoke("getBytes")); <#elseif entry.hiveType == "CHAR"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getStrippedValue") .invoke("getBytes")); <#elseif entry.hiveType == "STRING"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getBytes")); <#elseif entry.hiveType == "BINARY"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); </#if> JConditional jnullif = jc._else()._if(data.eq(JExpr._null())); jnullif._then().assign(returnValueHolder.ref("isSet"), JExpr.lit(0)); jnullif._else().add(returnValueHolder.ref("buffer") .invoke("setBytes").arg(JExpr.lit(0)).arg(data)); jnullif._else().assign(returnValueHolder.ref("start"), JExpr.lit(0)); jnullif._else().assign(returnValueHolder.ref("end"), data.ref("length")); jnullif._else().add(returnValueHolder.ref("buffer").invoke("setIndex").arg(JExpr.lit(0)).arg(data.ref("length"))); <#elseif entry.hiveType == "TIMESTAMP"> JVar tsVar = jc._else().decl(m.directClass(${entry.javaType}.class.getCanonicalName()), "ts", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); <#if entry.javaType == "org.apache.hadoop.hive.common.type.Timestamp"> jc._else().assign(returnValueHolder.ref("value"), tsVar.invoke("toEpochMilli")); <#else> // Bringing relative timestamp value without timezone info to timestamp value in UTC, since Drill keeps date-time values in UTC JVar localDateTimeVar = jc._else().decl(m.directClass(org.joda.time.LocalDateTime.class.getCanonicalName()), "localDateTime", JExpr._new(m.directClass(org.joda.time.LocalDateTime.class.getCanonicalName())).arg(tsVar)); jc._else().assign(returnValueHolder.ref("value"), localDateTimeVar.invoke("toDateTime") .arg(m.directClass(org.joda.time.DateTimeZone.class.getCanonicalName()).staticRef("UTC")).invoke("getMillis")); </#if> <#elseif entry.hiveType == "DATE"> JVar dVar = jc._else().decl(m.directClass(${entry.javaType}.class.getCanonicalName()), "d", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); <#if entry.javaType == "org.apache.hadoop.hive.common.type.Date"> jc._else().assign(returnValueHolder.ref("value"), dVar.invoke("toEpochMilli")); <#else> jc._else().assign(returnValueHolder.ref("value"), dVar.invoke("getTime")); </#if> <#else> jc._else().assign(returnValueHolder.ref("value"), castedOI.invoke("get").arg(returnValue)); </#if> return block; } </#list> default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", poi.getPrimitiveCategory().toString())); } } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", oi.getCategory().toString())); } } }
3e1ec62c64094044488fe4f8a537284dc59928be
1,009
java
Java
src/main/java/com/dao/newsentry/JpaNewsEntryDao.java
Mumuksia/Web-Starter
4685b682bb6c6b737ad2063254e73f56b9fe8496
[ "Apache-2.0" ]
null
null
null
src/main/java/com/dao/newsentry/JpaNewsEntryDao.java
Mumuksia/Web-Starter
4685b682bb6c6b737ad2063254e73f56b9fe8496
[ "Apache-2.0" ]
null
null
null
src/main/java/com/dao/newsentry/JpaNewsEntryDao.java
Mumuksia/Web-Starter
4685b682bb6c6b737ad2063254e73f56b9fe8496
[ "Apache-2.0" ]
null
null
null
25.225
88
0.796829
13,011
package com.dao.newsentry; import java.util.List; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.transaction.annotation.Transactional; import com.dao.JpaDao; import com.dao.model.entity.NewsEntry; public class JpaNewsEntryDao extends JpaDao<NewsEntry, Long> implements NewsEntryDao { public JpaNewsEntryDao() { super(NewsEntry.class); } @Override @Transactional(readOnly = true) public List<NewsEntry> findAll() { final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); final CriteriaQuery<NewsEntry> criteriaQuery = builder.createQuery(NewsEntry.class); Root<NewsEntry> root = criteriaQuery.from(NewsEntry.class); criteriaQuery.orderBy(builder.desc(root.get("date"))); TypedQuery<NewsEntry> typedQuery = this.getEntityManager().createQuery(criteriaQuery); return typedQuery.getResultList(); } }
3e1ec6d1121f14c2605c8b765ba96ff81cf9790b
1,720
java
Java
src/main/java/byow/bitcoinwallet/controllers/CreateWatchOnlyWalletDialogController.java
humbcezar/byow-bitcoin-wallet
d4eea9fc3368e1ef1dcc03a5c82235d628704c38
[ "MIT" ]
null
null
null
src/main/java/byow/bitcoinwallet/controllers/CreateWatchOnlyWalletDialogController.java
humbcezar/byow-bitcoin-wallet
d4eea9fc3368e1ef1dcc03a5c82235d628704c38
[ "MIT" ]
null
null
null
src/main/java/byow/bitcoinwallet/controllers/CreateWatchOnlyWalletDialogController.java
humbcezar/byow-bitcoin-wallet
d4eea9fc3368e1ef1dcc03a5c82235d628704c38
[ "MIT" ]
null
null
null
32.45283
132
0.725
13,012
package byow.bitcoinwallet.controllers; import byow.bitcoinwallet.exceptions.WrongPasswordException; import byow.bitcoinwallet.services.AuthenticationService; import byow.bitcoinwallet.services.gui.CurrentWallet; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.scene.control.PasswordField; import org.springframework.stereotype.Component; @Component public class CreateWatchOnlyWalletDialogController extends GenerateWalletDialogController { private final CurrentWallet currentWallet; private final AuthenticationService authenticationService; @FXML public PasswordField currentWalletPassword; @FXML public PasswordField watchOnlyWalletPassword; public CreateWatchOnlyWalletDialogController( CurrentWallet currentWallet, AuthenticationService authenticationService ) { this.currentWallet = currentWallet; this.authenticationService = authenticationService; } @Override public void createWallet() { if (!authenticationService.checkPassword(currentWalletPassword.getText(), currentWallet.getCurrentWallet().getPassword())) { throw new WrongPasswordException("Could not create watch only wallet: wrong password for current wallet."); } walletCreator.createWatchOnly( currentWallet.getWalletName().concat("(watch only)"), watchOnlyWalletPassword.getText(), currentWallet.getCurrentWallet() ); } @Override public void initialize() { allInputsAreFull = new BooleanBinding() { @Override protected boolean computeValue() { return true; } }; } }
3e1ec7974f220f36774b1e6b467212d589f3ab40
10,935
java
Java
lib/src/main/java/com/google/samples/apps/iosched/debug/DebugFragment.java
liaoqingmo/iosched
6540760a278c111f311ca53db220f3afab8b9687
[ "Apache-2.0" ]
1
2018-05-10T00:34:29.000Z
2018-05-10T00:34:29.000Z
lib/src/main/java/com/google/samples/apps/iosched/debug/DebugFragment.java
liaoqingmo/iosched
6540760a278c111f311ca53db220f3afab8b9687
[ "Apache-2.0" ]
null
null
null
lib/src/main/java/com/google/samples/apps/iosched/debug/DebugFragment.java
liaoqingmo/iosched
6540760a278c111f311ca53db220f3afab8b9687
[ "Apache-2.0" ]
1
2018-09-05T11:54:12.000Z
2018-09-05T11:54:12.000Z
39.476534
99
0.633379
13,013
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.debug; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.samples.apps.iosched.debug.actions.DisplayUserDataDebugAction; import com.google.samples.apps.iosched.debug.actions.ForceAppDataSyncNowAction; import com.google.samples.apps.iosched.debug.actions.ForceSyncNowAction; import com.google.samples.apps.iosched.debug.actions.ScheduleStarredSessionAlarmsAction; import com.google.samples.apps.iosched.debug.actions.ShowSessionNotificationDebugAction; import com.google.samples.apps.iosched.debug.actions.TestScheduleHelperAction; import com.google.samples.apps.iosched.info.BaseInfoFragment; import com.google.samples.apps.iosched.lib.R; import com.google.samples.apps.iosched.schedule.ScheduleActivity; import com.google.samples.apps.iosched.service.SessionAlarmService; import com.google.samples.apps.iosched.settings.ConfMessageCardUtils; import com.google.samples.apps.iosched.settings.SettingsUtils; import com.google.samples.apps.iosched.util.AccountUtils; import com.google.samples.apps.iosched.util.RegistrationUtils; import com.google.samples.apps.iosched.util.TimeUtils; import com.google.samples.apps.iosched.util.WiFiUtils; import com.google.samples.apps.iosched.welcome.WelcomeActivity; import static com.google.samples.apps.iosched.util.LogUtils.LOGW; import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.Activity} displaying debug options so a developer can debug and test. This * functionality is only enabled when {@link com.google.samples.apps.iosched.lib.BuildConfig}.DEBUG * is true. */ public class DebugFragment extends BaseInfoFragment { private static final String TAG = makeLogTag(DebugFragment.class); /** * Area of screen used to display log log messages. */ private TextView mLogArea; private ViewGroup mTestActionsList; @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.debug_frag, container, false); mLogArea = (TextView) rootView.findViewById(R.id.logArea); mTestActionsList = (ViewGroup) rootView.findViewById(R.id.debug_action_list); createTestAction(new ForceSyncNowAction()); createTestAction(new DisplayUserDataDebugAction()); createTestAction(new ForceAppDataSyncNowAction()); createTestAction(new TestScheduleHelperAction()); createTestAction(new ScheduleStarredSessionAlarmsAction()); createTestAction(new DebugAction() { @Override public void run(final Context context, final Callback callback) { final String sessionId = SessionAlarmService.DEBUG_SESSION_ID; final String sessionTitle = "Debugging with Placeholder Text"; Intent intent = new Intent( SessionAlarmService.ACTION_NOTIFY_SESSION_FEEDBACK, null, context, SessionAlarmService.class); intent.putExtra(SessionAlarmService.EXTRA_SESSION_ID, sessionId); intent.putExtra(SessionAlarmService.EXTRA_SESSION_START, System.currentTimeMillis() - 30 * 60 * 1000); intent.putExtra(SessionAlarmService.EXTRA_SESSION_END, System.currentTimeMillis()); intent.putExtra(SessionAlarmService.EXTRA_SESSION_TITLE, sessionTitle); context.startService(intent); Toast.makeText(context, "Showing DEBUG session feedback notification.", Toast.LENGTH_LONG).show(); } @Override public String getLabel() { return "Show session feedback notification"; } }); createTestAction(new ShowSessionNotificationDebugAction()); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { RegistrationUtils.setRegisteredAttendee(context, false); AccountUtils.setActiveAccount(context, null); context.startActivity(new Intent(context, WelcomeActivity.class)); } @Override public String getLabel() { return "Display Welcome Activity"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { RegistrationUtils.setRegisteredAttendee(context, false); AccountUtils.setActiveAccount(context, null); ConfMessageCardUtils.unsetStateForAllCards(context); } @Override public String getLabel() { return "Reset Welcome Flags"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { Intent intent = new Intent(context, ScheduleActivity.class); intent.putExtra(ScheduleActivity.EXTRA_FILTER_TAG, "TRACK_ANDROID"); context.startActivity(intent); } @Override public String getLabel() { return "Show filtered Schedule (Android Topic)"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { LOGW(TAG, "Unsetting all Explore I/O message card answers."); ConfMessageCardUtils.markAnsweredConfMessageCardsPrompt(context, null); ConfMessageCardUtils.setConfMessageCardsEnabled(context, null); ConfMessageCardUtils.unsetStateForAllCards(context); } @Override public String getLabel() { return "Unset all My I/O-based card answers"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.setCurrentTimeRelativeToStartOfConference(context, -TimeUtils.HOUR * 3); } @Override public String getLabel() { return "Set time to 3 hours before Conf"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.setCurrentTimeRelativeToStartOfConference(context, -TimeUtils.DAY); } @Override public String getLabel() { return "Set time to day before Conf"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.setCurrentTimeRelativeToStartOfConference(context, TimeUtils.HOUR * 3); LOGW(TAG, "Unsetting all Explore I/O card answers and settings."); ConfMessageCardUtils.markAnsweredConfMessageCardsPrompt(context, null); ConfMessageCardUtils.setConfMessageCardsEnabled(context, null); SettingsUtils.markDeclinedWifiSetup(context, false); WiFiUtils.uninstallConferenceWiFi(context); } @Override public String getLabel() { return "Set time to 3 hours after Conf start"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.setCurrentTimeRelativeToStartOfSecondDayOfConference(context, TimeUtils.HOUR * 3); } @Override public String getLabel() { return "Set time to 3 hours after 2nd day start"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.setCurrentTimeRelativeToEndOfConference(context, TimeUtils.HOUR * 3); } @Override public String getLabel() { return "Set time to 3 hours after Conf end"; } }); createTestAction(new DebugAction() { @Override public void run(Context context, Callback callback) { TimeUtils.clearMockCurrentTime(context); } @Override public String getLabel() { return "Clear mock current time"; } }); return rootView; } protected void createTestAction(final DebugAction test) { Button testButton = new Button(mTestActionsList.getContext()); testButton.setText(test.getLabel()); testButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final long start = System.currentTimeMillis(); mLogArea.setText(""); test.run(view.getContext(), new DebugAction.Callback() { @Override public void done(boolean success, String message) { logTimed((System.currentTimeMillis() - start), (success ? "[OK] " : "[FAIL] ") + message); } }); } }); mTestActionsList.addView(testButton); } protected void logTimed(long time, String message) { message = "[" + time + "ms] " + message; Log.d(TAG, message); mLogArea.append(message + "\n"); } @Override public String getTitle(Resources resources) { return "DEBUG"; } @Override public void updateInfo(Object info) { // } @Override protected void showInfo() { // } }
3e1ec91b8ce2f22b60b3d0eb15163cdd67e1f8e9
6,482
java
Java
service-userlayer/src/test/java/org/oskari/map/userlayer/input/KMLParserTest.java
WTurunen/oskari-server
80ca7ac3f0ca263c29438b3e2e3215889905022a
[ "MIT" ]
23
2017-05-09T23:17:06.000Z
2022-03-18T02:02:13.000Z
service-userlayer/src/test/java/org/oskari/map/userlayer/input/KMLParserTest.java
WTurunen/oskari-server
80ca7ac3f0ca263c29438b3e2e3215889905022a
[ "MIT" ]
402
2017-03-15T12:51:56.000Z
2022-03-21T11:19:43.000Z
service-userlayer/src/test/java/org/oskari/map/userlayer/input/KMLParserTest.java
WTurunen/oskari-server
80ca7ac3f0ca263c29438b3e2e3215889905022a
[ "MIT" ]
36
2017-03-21T13:32:47.000Z
2022-02-24T12:48:54.000Z
48.014815
120
0.638846
13,014
package org.oskari.map.userlayer.input; import static org.junit.Assert.assertEquals; import java.io.File; import java.net.URISyntaxException; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.referencing.CRS; import org.junit.Test; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.oskari.map.userlayer.input.KMLParser; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; import fi.nls.oskari.service.ServiceException; public class KMLParserTest { @Test public void testParseExtendedData() throws ServiceException, URISyntaxException, FactoryException { File file = new File(getClass().getResource("user_data.kml").toURI()); KMLParser kml = new KMLParser(); SimpleFeatureCollection fc = kml.parse(file, null, CRS.decode("EPSG:3067")); SimpleFeatureType schema = fc.getSchema(); boolean found = false; // test schema assertEquals(5, schema.getAttributeCount()); assertEquals(Geometry.class, schema.getDescriptor(KMLParser.KML_GEOM).getType().getBinding()); assertEquals(String.class, schema.getDescriptor("Opening hours").getType().getBinding()); // test feature count assertEquals(5, fc.size()); // loop features SimpleFeatureIterator it = fc.features(); while (it.hasNext()){ SimpleFeature feature = it.next(); assertEquals(5, feature.getAttributeCount()); if ("Ruskeasuo".equals(feature.getAttribute(KMLParser.KML_NAME))){ found = true; Point p = (Point) feature.getDefaultGeometry(); Coordinate c = p.getCoordinate(); assertEquals(383726.9520816681, c.x, 1e-6); assertEquals(6676234.520781213, c.y, 1e-6); assertEquals(0.0, c.z, 0.0); assertEquals("Floorball arena", feature.getAttribute(KMLParser.KML_DESC)); assertEquals("9-20", feature.getAttribute("Opening hours")); // should be empty string instead of null, to get feature which matches schema assertEquals("", feature.getAttribute("Additional info")); } else if ("Route".equals(feature.getAttribute(KMLParser.KML_NAME))) { LineString line = (LineString) feature.getDefaultGeometry(); assertEquals(157, line.getCoordinates().length); assertEquals("Route from the Arena center to the Codecorner", feature.getAttribute(KMLParser.KML_DESC)); } } assertEquals("Failed to parse feature Ruskeasuo", true, found); } @Test public void testParseSampleData() throws ServiceException, URISyntaxException, FactoryException { File file = new File(getClass().getResource("samples.kml").toURI()); KMLParser kml = new KMLParser(); SimpleFeatureCollection fc = kml.parse(file, null, CRS.decode("EPSG:4326")); boolean foundHidden = false; boolean foundPentagon = false; // test schema SimpleFeatureType schema = fc.getSchema(); assertEquals(3, schema.getAttributeCount()); // test feature count assertEquals(20, fc.size()); // loop features SimpleFeatureIterator it = fc.features(); while (it.hasNext()){ SimpleFeature feature = it.next(); assertEquals(3, feature.getAttributeCount()); // hidden placemark with no geometry if (feature.getDefaultGeometry() == null){ foundHidden = true; assertEquals("Descriptive HTML", feature.getAttribute(KMLParser.KML_NAME)); } else if ("The Pentagon".equals(feature.getAttribute(KMLParser.KML_NAME))) { foundPentagon = true; assertEquals("Shouldn't have kml LookAt attribute", null, feature.getAttribute("LookAt")); Polygon p = (Polygon) feature.getDefaultGeometry(); assertEquals(1, p.getNumInteriorRing()); LineString ring = p.getExteriorRing(); assertEquals (6, ring.getNumPoints()); Coordinate c = ring.getCoordinateN(0); // KML has always lonlat 4326, but 4326 has latlon ordering assertEquals(38.87253259892824, c.x, 1e-6); assertEquals(-77.05788457660967, c.y, 1e-6); assertEquals(100.0, c.z, 0); ring = p.getInteriorRingN(0); assertEquals (6, ring.getNumPoints()); c = ring.getCoordinateN(0); assertEquals(38.87154239798456, c.x, 1e-6); assertEquals(-77.05668055019126, c.y, 1e-6); assertEquals(100.0, c.z, 0); } } assertEquals(true, foundHidden); assertEquals("Can't find The Pentagon. Has plane chrashed or just the test failed", true, foundPentagon); } //@Test PARSER DOESN'T SUPPORT TYPED EXTENDED DATA (types are defined in Schema element) public void testParseTypedUserData() throws ServiceException, URISyntaxException, FactoryException { // file is converted from shape File file = new File(getClass().getResource("hki.kml").toURI()); KMLParser kml = new KMLParser(); SimpleFeatureCollection fc = kml.parse(file, null, CRS.decode("EPSG:3067")); boolean found = false; // test schema SimpleFeatureType schema = fc.getSchema(); assertEquals(5, schema.getAttributeCount()); // test feature count assertEquals(2, fc.size()); // loop features SimpleFeatureIterator it = fc.features(); while (it.hasNext()){ SimpleFeature feature = it.next(); assertEquals(5, feature.getAttributeCount()); if ("Kauniainen".equals(feature.getAttribute("NIMI"))) { found = true; assertEquals("505", feature.getAttribute("KUNTA")); assertEquals(Polygon.class, feature.getDefaultGeometry().getClass()); } } assertEquals(true, found); } }
3e1ec9a6ec6f72c6cb99fe5e1d83573ef4838de5
1,651
java
Java
module_news/src/main/java/com/fly/news/config/JwtConfiguration.java
zouyu0008/spring-cloud-flycloud
d5507da91c146661ffdd395d3d15d25ad351a5a2
[ "Apache-2.0" ]
1,228
2019-08-01T01:47:07.000Z
2022-03-26T16:00:04.000Z
module_news/src/main/java/com/fly/news/config/JwtConfiguration.java
liusg110/spring-cloud-flycloud
6cafd8835b24cada6917f40d14e25aeff2a2f9d0
[ "Apache-2.0" ]
5
2019-09-19T09:07:20.000Z
2022-02-20T16:03:37.000Z
module_news/src/main/java/com/fly/news/config/JwtConfiguration.java
liusg110/spring-cloud-flycloud
6cafd8835b24cada6917f40d14e25aeff2a2f9d0
[ "Apache-2.0" ]
398
2019-08-01T12:12:11.000Z
2022-03-11T10:30:50.000Z
33.02
93
0.739552
13,015
package com.fly.news.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.util.FileCopyUtils; import java.io.IOException; /** * Description: <JwtConfiguration><br> * Author:    mxdl<br> * Date:     2019/2/19<br> * Version:   V1.0.0<br> * Update:     <br> */ @Configuration public class JwtConfiguration { @Autowired JwtAccessTokenConverter jwtAccessTokenConverter; @Bean @Qualifier("tokenStore") public TokenStore tokenStore() { System.out.println("Created JwtTokenStore"); return new JwtTokenStore(jwtAccessTokenConverter); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource("public.cert"); String publicKey ; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } converter.setVerifierKey(publicKey); return converter; } }
3e1ec9cb074c58bdd3877a566920f53a8e9421b7
2,035
java
Java
src/main/java/creational/builder/type_two/Student.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
src/main/java/creational/builder/type_two/Student.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
src/main/java/creational/builder/type_two/Student.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
18.333333
64
0.507617
13,016
package creational.builder.type_two; /** * Created by zhuyanan on 17/7/21. */ public class Student { public Student(Builder builder) { this.age = builder.age; this.sex = builder.sex; this.name = builder.name; this.grade = builder.grade; this.gradeName = builder.gradeName; } public static class Builder { private int age; private int sex; private String name; private int grade; private String gradeName; public Builder baseInfo(String name, int age, int sex) { this.name = name; this.age = age; this.sex = sex; return this; } public Builder grade(int grade, String gradeName) { this.grade = grade; this.gradeName = gradeName; return this; } public Student build() { return new Student(this); } } private int age; private int sex; private String name; private int grade; private String gradeName; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } @Override public String toString() { return "Student{" + "age=" + age + ", sex=" + sex + ", name='" + name + '\'' + ", grade=" + grade + ", gradeName='" + gradeName + '\'' + '}'; } }
3e1ec9d3f93e522ecfc80842c81c747901891b77
2,584
java
Java
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/event/world/GetCollisionBoxesEvent.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
22
2021-01-10T20:58:45.000Z
2021-12-19T18:11:35.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/event/world/GetCollisionBoxesEvent.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
3
2021-01-10T20:59:19.000Z
2021-01-13T14:00:58.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/event/world/GetCollisionBoxesEvent.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
4
2020-12-20T02:10:44.000Z
2022-01-25T19:38:53.000Z
35.39726
207
0.73065
13,017
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.event.world; import net.minecraft.entity.Entity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Cancelable; import javax.annotation.Nullable; import java.util.List; /** * This event is fired during {@link World#collidesWithAnyBlock(AxisAlignedBB)} * and before returning the list in {@link World#getCollisionBoxes(Entity, AxisAlignedBB)}<br> * <br> * {@link #entity} contains the entity passed in the {@link World#getCollisionBoxes(Entity, AxisAlignedBB)}. <b>Can be null.</b> Calls from {@link World#collidesWithAnyBlock(AxisAlignedBB)} will be null.<br> * {@link #aabb} contains the AxisAlignedBB passed in the method.<br> * {@link #collisionBoxesList} contains the list of detected collision boxes intersecting with {@link #aabb}. The list can be modified.<br> * <br> * This event is not {@link Cancelable}.<br> * <br> * This event does not have a result. {@link HasResult} <br> * <br> * This event is fired on the {@link MinecraftForge#EVENT_BUS}.<br> **/ public class GetCollisionBoxesEvent extends WorldEvent { private final Entity entity; private final AxisAlignedBB aabb; private final List<AxisAlignedBB> collisionBoxesList; public GetCollisionBoxesEvent(World world, @Nullable Entity entity, AxisAlignedBB aabb, List<AxisAlignedBB> collisionBoxesList) { super(world); this.entity = entity; this.aabb = aabb; this.collisionBoxesList = collisionBoxesList; } public Entity getEntity() { return entity; } public AxisAlignedBB getAabb() { return aabb; } public List<AxisAlignedBB> getCollisionBoxesList() { return collisionBoxesList; } }
3e1ec9fdce4ce40bddf21dafdd33420d46ea72f9
20,834
java
Java
src/main/java/epicsquid/roots/model/ModelWildwoodArmor.java
Radient-Sora/Roots
10992b0ad76f7a246077975e7bb7fd51bd63cf68
[ "MIT" ]
null
null
null
src/main/java/epicsquid/roots/model/ModelWildwoodArmor.java
Radient-Sora/Roots
10992b0ad76f7a246077975e7bb7fd51bd63cf68
[ "MIT" ]
null
null
null
src/main/java/epicsquid/roots/model/ModelWildwoodArmor.java
Radient-Sora/Roots
10992b0ad76f7a246077975e7bb7fd51bd63cf68
[ "MIT" ]
null
null
null
39.835564
65
0.583805
13,018
package epicsquid.roots.model; import net.minecraft.client.model.ModelRenderer; import net.minecraft.inventory.EntityEquipmentSlot; public class ModelWildwoodArmor extends ModelArmorBase { public EntityEquipmentSlot slot; ModelRenderer head1; ModelRenderer head2; ModelRenderer head3; ModelRenderer head4; ModelRenderer head5; ModelRenderer head6; ModelRenderer head7; ModelRenderer head8; ModelRenderer head9; ModelRenderer head10; ModelRenderer head11; ModelRenderer head12; ModelRenderer head13; ModelRenderer head14; ModelRenderer head15; ModelRenderer head16; ModelRenderer head17; ModelRenderer chest1; ModelRenderer chest2; ModelRenderer chest3; ModelRenderer chest4; ModelRenderer chest5; ModelRenderer chest6; ModelRenderer chest7; ModelRenderer chest8; ModelRenderer chest9; ModelRenderer chest10; ModelRenderer chest11; ModelRenderer chest12; ModelRenderer chest13; ModelRenderer armR1; ModelRenderer armR2; ModelRenderer armR3; ModelRenderer armR4; ModelRenderer armR5; ModelRenderer armR6; ModelRenderer armL1; ModelRenderer armL2; ModelRenderer armL3; ModelRenderer armL4; ModelRenderer armL5; ModelRenderer armL6; ModelRenderer legR1; ModelRenderer legR2; ModelRenderer legR3; ModelRenderer legR4; ModelRenderer legR5; ModelRenderer legR6; ModelRenderer legL1; ModelRenderer legL2; ModelRenderer legL3; ModelRenderer legL4; ModelRenderer legL5; ModelRenderer legL6; ModelRenderer bootR1; ModelRenderer bootR2; ModelRenderer bootR3; ModelRenderer bootL1; ModelRenderer bootL2; ModelRenderer bootL3; public ModelWildwoodArmor(EntityEquipmentSlot slot) { super(slot); head1 = new ModelRenderer(this, 48, 16); head1.addBox(-1F, -8F, -1F, 2, 8, 2); head1.setRotationPoint(0F, -1F, -6F); head1.setTextureSize(64, 64); head1.mirror = true; setRotation(head1, 0.1308997F, 0F, 0F); head2 = new ModelRenderer(this, 0, 16); head2.addBox(-1F, -8F, -1F, 2, 8, 2); head2.setRotationPoint(2F, -6.5F, -5F); head2.setTextureSize(64, 64); head2.mirror = true; setRotation(head2, -1.047198F, 0.2617994F, 0F); head3 = new ModelRenderer(this, 0, 32); head3.addBox(-1F, -1F, -1F, 2, 2, 2); head3.setRotationPoint(-2F, -1F, -5F); head3.setTextureSize(64, 64); head3.mirror = true; setRotation(head3, 0F, 0F, 0F); head4 = new ModelRenderer(this, 0, 32); head4.addBox(-1F, -1F, -1F, 2, 2, 2); head4.setRotationPoint(0F, -0F, -6F); head4.setTextureSize(64, 64); head4.mirror = true; setRotation(head4, 0F, 0F, 0F); head5 = new ModelRenderer(this, 48, 16); head5.addBox(-1F, -4F, -1F, 2, 6, 2); head5.setRotationPoint(-3.8F, -3F, -1F); head5.setTextureSize(64, 64); head5.mirror = true; setRotation(head5, 0.1308997F, 1.308997F, -0.5235988F); head6 = new ModelRenderer(this, 32, 0); head6.addBox(-6F, -1F, -2F, 6, 2, 4); head6.setRotationPoint(0F, -7F, -5F); head6.setTextureSize(64, 64); head6.mirror = true; setRotation(head6, 0F, 1.570796F, 0.7853982F); head7 = new ModelRenderer(this, 48, 16); head7.addBox(-1F, -6F, -1F, 2, 4, 2); head7.setRotationPoint(-2F, -1F, -5F); head7.setTextureSize(64, 64); head7.mirror = true; setRotation(head7, 0.1308997F, 0.2617994F, 0F); head8 = new ModelRenderer(this, 48, 16); head8.addBox(-1F, -7F, -1F, 2, 7, 2); head8.setRotationPoint(2.933333F, -1F, -4F); head8.setTextureSize(64, 64); head8.mirror = true; setRotation(head8, 0.1308997F, -0.7853982F, 0F); head9 = new ModelRenderer(this, 0, 32); head9.addBox(-1F, -1F, -1F, 2, 2, 2); head9.setRotationPoint(2F, -1F, -5F); head9.setTextureSize(64, 64); head9.mirror = true; setRotation(head9, 0F, 0F, 0F); head10 = new ModelRenderer(this, 0, 16); head10.addBox(-1F, -6F, -1F, 2, 6, 2); head10.setRotationPoint(4F, -1.5F, -1F); head10.setTextureSize(64, 64); head10.mirror = true; setRotation(head10, -1.308997F, 0.1308997F, 0F); head11 = new ModelRenderer(this, 48, 16); head11.addBox(-1F, -7F, -1F, 2, 7, 2); head11.setRotationPoint(-3F, -1F, -4F); head11.setTextureSize(64, 64); head11.mirror = true; setRotation(head11, 0.1308997F, 0.7853982F, 0F); head12 = new ModelRenderer(this, 56, 16); head12.addBox(-1F, -6F, -1F, 2, 4, 2); head12.setRotationPoint(-3.5F, 1F, -3F); head12.setTextureSize(64, 64); head12.mirror = true; setRotation(head12, 0.1308997F, 1.047198F, -0.2617994F); head13 = new ModelRenderer(this, 56, 16); head13.addBox(-1F, -6F, -1F, 2, 4, 2); head13.setRotationPoint(3.5F, 1F, -3F); head13.setTextureSize(64, 64); head13.mirror = true; setRotation(head13, 0.1308997F, -1.047198F, 0.2617994F); head14 = new ModelRenderer(this, 48, 16); head14.addBox(-1F, -4F, -1F, 2, 6, 2); head14.setRotationPoint(3.75F, -3F, -1F); head14.setTextureSize(64, 64); head14.mirror = true; setRotation(head14, 0.1308997F, -1.308997F, 0.5235988F); head15 = new ModelRenderer(this, 48, 16); head15.addBox(-1F, -6F, -1F, 2, 4, 2); head15.setRotationPoint(2F, -1F, -5F); head15.setTextureSize(64, 64); head15.mirror = true; setRotation(head15, 0.1308997F, -0.2617994F, 0F); head16 = new ModelRenderer(this, 0, 16); head16.addBox(-1F, -6F, -1F, 2, 6, 2); head16.setRotationPoint(-4F, -1.5F, -1F); head16.setTextureSize(64, 64); head16.mirror = true; setRotation(head16, -1.308997F, -0.1308997F, 0F); head17 = new ModelRenderer(this, 0, 16); head17.addBox(-1F, -8F, -1F, 2, 8, 2); head17.setRotationPoint(-2F, -6.5F, -5F); head17.setTextureSize(64, 64); head17.mirror = true; setRotation(head17, -1.047198F, -0.2617994F, 0F); chest1 = new ModelRenderer(this, 16, 16); chest1.addBox(-2F, -4F, -1F, 4, 4, 2); chest1.setRotationPoint(3F, 11F, 0F); chest1.setTextureSize(64, 64); chest1.mirror = true; setRotation(chest1, 0.5235988F, -1.570796F, 0F); chest2 = new ModelRenderer(this, 16, 16); chest2.addBox(-2F, -8F, -1F, 4, 8, 2); chest2.setRotationPoint(-1F, 10F, 2F); chest2.setTextureSize(64, 64); chest2.mirror = true; setRotation(chest2, 0.1308997F, 2.879793F, 0.3926991F); chest3 = new ModelRenderer(this, 16, 16); chest3.addBox(-2F, -8F, -1F, 4, 8, 2); chest3.setRotationPoint(1F, 10F, 2F); chest3.setTextureSize(64, 64); chest3.mirror = true; setRotation(chest3, 0.1308997F, -2.879793F, -0.3926991F); chest4 = new ModelRenderer(this, 16, 16); chest4.addBox(-2F, -4F, -1F, 4, 4, 2); chest4.setRotationPoint(-3F, 11F, 0F); chest4.setTextureSize(64, 64); chest4.mirror = true; setRotation(chest4, 0.5235988F, 1.570796F, 0F); chest5 = new ModelRenderer(this, 16, 16); chest5.addBox(-2F, -8F, -1F, 4, 8, 2); chest5.setRotationPoint(-1F, 10F, -2F); chest5.setTextureSize(64, 64); chest5.mirror = true; setRotation(chest5, 0.1308997F, 0.2617994F, -0.3926991F); chest6 = new ModelRenderer(this, 16, 16); chest6.addBox(-2F, -8F, -1F, 4, 8, 2); chest6.setRotationPoint(0F, 9F, -2F); chest6.setTextureSize(64, 64); chest6.mirror = true; setRotation(chest6, 0.2617994F, 0F, 0F); chest7 = new ModelRenderer(this, 16, 16); chest7.addBox(-2F, -4F, -1F, 4, 4, 2); chest7.setRotationPoint(0F, 11F, 2F); chest7.setTextureSize(64, 64); chest7.mirror = true; setRotation(chest7, 0.5235988F, 3.141593F, 0F); chest8 = new ModelRenderer(this, 16, 16); chest8.addBox(-2F, -8F, -1F, 4, 8, 2); chest8.setRotationPoint(1F, 10F, -2F); chest8.setTextureSize(64, 64); chest8.mirror = true; setRotation(chest8, 0.1308997F, -0.2617994F, 0.3926991F); chest9 = new ModelRenderer(this, 16, 16); chest9.addBox(-2F, -4F, -1F, 4, 4, 2); chest9.setRotationPoint(0F, 11F, -2F); chest9.setTextureSize(64, 64); chest9.mirror = true; setRotation(chest9, 0.5235988F, 0F, 0F); chest10 = new ModelRenderer(this, 8, 16); chest10.addBox(-1F, -4F, -1F, 2, 4, 2); chest10.setRotationPoint(-2.5F, 7F, -1F); chest10.setTextureSize(64, 64); chest10.mirror = true; setRotation(chest10, -1.832596F, -2.879793F, 0F); chest11 = new ModelRenderer(this, 8, 16); chest11.addBox(-1F, -4F, -1F, 2, 4, 2); chest11.setRotationPoint(-2.5F, 5F, -2F); chest11.setTextureSize(64, 64); chest11.mirror = true; setRotation(chest11, -1.308997F, -2.879793F, 0F); chest12 = new ModelRenderer(this, 8, 16); chest12.addBox(-1F, -4F, -1F, 2, 4, 2); chest12.setRotationPoint(2.5F, 5F, -2F); chest12.setTextureSize(64, 64); chest12.mirror = true; setRotation(chest12, -1.308997F, 2.879793F, 0F); chest13 = new ModelRenderer(this, 8, 16); chest13.addBox(-1F, -4F, -1F, 2, 4, 2); chest13.setRotationPoint(2.5F, 7F, -1F); chest13.setTextureSize(64, 64); chest13.mirror = true; setRotation(chest13, -1.832596F, 2.879793F, 0F); armR1 = new ModelRenderer(this, 32, 16); armR1.addBox(-2F, -4F, -1F, 4, 4, 2); armR1.setRotationPoint(-7.5F, 8F, 0F); armR1.setTextureSize(64, 64); armR1.mirror = true; setRotation(armR1, 0F, 1.570796F, 0F); armR2 = new ModelRenderer(this, 8, 16); armR2.addBox(-1F, -4F, -1F, 2, 4, 2); armR2.setRotationPoint(-6F, 0F, 0F); armR2.setTextureSize(64, 64); armR2.mirror = true; setRotation(armR2, -0.7853982F, 0F, -0.3926991F); armR3 = new ModelRenderer(this, 8, 16); armR3.addBox(-1F, -4F, -1F, 2, 4, 2); armR3.setRotationPoint(-6F, 0F, -1F); armR3.setTextureSize(64, 64); armR3.mirror = true; setRotation(armR3, -0.2617994F, 0F, -0.1308997F); armR4 = new ModelRenderer(this, 48, 16); armR4.addBox(-1F, 0F, -1F, 2, 7, 2); armR4.setRotationPoint(-7F, 9F, 0F); armR4.setTextureSize(64, 64); armR4.mirror = true; setRotation(armR4, 0.1308997F, 1.570796F, 3.141593F); armR5 = new ModelRenderer(this, 16, 32); armR5.addBox(-2F, -4F, -2F, 4, 4, 4); armR5.setRotationPoint(-5F, 3F, 0F); armR5.setTextureSize(64, 64); armR5.mirror = true; setRotation(armR5, 0.2617994F, 1.570796F, 0F); armR6 = new ModelRenderer(this, 0, 16); armR6.addBox(-1F, -6F, -1F, 2, 6, 2); armR6.setRotationPoint(-6.5F, 4F, 0F); armR6.setTextureSize(64, 64); armR6.mirror = true; setRotation(armR6, -1.047198F, -0.3926991F, 0F); armL1 = new ModelRenderer(this, 16, 32); armL1.addBox(-2F, -4F, -2F, 4, 4, 4); armL1.setRotationPoint(5F, 3F, 0F); armL1.setTextureSize(64, 64); armL1.mirror = true; setRotation(armL1, -0.2617994F, 1.570796F, 0F); armL2 = new ModelRenderer(this, 48, 16); armL2.addBox(-1F, 0F, -1F, 2, 7, 2); armL2.setRotationPoint(7F, 9F, 0F); armL2.setTextureSize(64, 64); armL2.mirror = true; setRotation(armL2, -0.1308997F, 1.570796F, 3.141593F); armL3 = new ModelRenderer(this, 32, 16); armL3.addBox(-2F, -4F, -1F, 4, 4, 2); armL3.setRotationPoint(7.5F, 8F, 0F); armL3.setTextureSize(64, 64); armL3.mirror = true; setRotation(armL3, 0F, -1.570796F, 0F); armL4 = new ModelRenderer(this, 0, 16); armL4.addBox(-1F, -6F, -1F, 2, 6, 2); armL4.setRotationPoint(6.5F, 4F, 0F); armL4.setTextureSize(64, 64); armL4.mirror = true; setRotation(armL4, -1.047198F, 0.3926991F, 0F); armL5 = new ModelRenderer(this, 8, 16); armL5.addBox(-1F, -4F, -1F, 2, 4, 2); armL5.setRotationPoint(6F, 0F, 0F); armL5.setTextureSize(64, 64); armL5.mirror = true; setRotation(armL5, -0.7853982F, 0F, 0.3926991F); armL6 = new ModelRenderer(this, 8, 16); armL6.addBox(-1F, -4F, -1F, 2, 4, 2); armL6.setRotationPoint(6F, 0F, -1F); armL6.setTextureSize(64, 64); armL6.mirror = true; setRotation(armL6, -0.2617994F, 0F, 0.1308997F); legR1 = new ModelRenderer(this, 32, 16); legR1.addBox(-2F, -4F, -1F, 4, 4, 2); legR1.setRotationPoint(-2.5F, 16F, -2.5F); legR1.setTextureSize(64, 64); legR1.mirror = true; setRotation(legR1, 0.1308997F, 0F, 0F); legR2 = new ModelRenderer(this, 32, 16); legR2.addBox(-1F, 0F, -1F, 2, 4, 2); legR2.setRotationPoint(-2.5F, 19F, -2F); legR2.setTextureSize(64, 64); legR2.mirror = true; setRotation(legR2, 0F, 0F, 3.141593F); legR3 = new ModelRenderer(this, 32, 16); legR3.addBox(-1F, -4F, -1F, 2, 4, 2); legR3.setRotationPoint(-2.5F, 13F, -2F); legR3.setTextureSize(64, 64); legR3.mirror = true; setRotation(legR3, 0.1308997F, 0F, 0F); legR4 = new ModelRenderer(this, 8, 16); legR4.addBox(-1F, -4F, -1F, 2, 4, 2); legR4.setRotationPoint(-3F, 12F, -2F); legR4.setTextureSize(64, 64); legR4.mirror = true; setRotation(legR4, -1.047198F, -2.617994F, 0F); legR5 = new ModelRenderer(this, 8, 16); legR5.addBox(-1F, -4F, -1F, 2, 4, 2); legR5.setRotationPoint(-3F, 12F, -1F); legR5.setTextureSize(64, 64); legR5.mirror = true; setRotation(legR5, -1.047198F, -1.832596F, 0F); legR6 = new ModelRenderer(this, 32, 16); legR6.addBox(-2F, 0F, -1F, 4, 4, 2); legR6.setRotationPoint(-4F, 12F, -0.5F); legR6.setTextureSize(64, 64); legR6.mirror = true; setRotation(legR6, -0.2617994F, 1.570796F, 0F); legL1 = new ModelRenderer(this, 32, 16); legL1.addBox(-2F, -4F, -1F, 4, 4, 2); legL1.setRotationPoint(2.5F, 16F, -2.5F); legL1.setTextureSize(64, 64); legL1.mirror = true; setRotation(legL1, 0.1308997F, 0F, 0F); legL2 = new ModelRenderer(this, 32, 16); legL2.addBox(-1F, 0F, -1F, 2, 4, 2); legL2.setRotationPoint(2.5F, 19F, -2F); legL2.setTextureSize(64, 64); legL2.mirror = true; setRotation(legL2, 0F, 0F, 3.141593F); legL3 = new ModelRenderer(this, 32, 16); legL3.addBox(-1F, -4F, -1F, 2, 4, 2); legL3.setRotationPoint(2.5F, 13F, -2F); legL3.setTextureSize(64, 64); legL3.mirror = true; setRotation(legL3, 0.1308997F, 0F, 0F); legL4 = new ModelRenderer(this, 8, 16); legL4.addBox(-1F, -4F, -1F, 2, 4, 2); legL4.setRotationPoint(3F, 12F, -2F); legL4.setTextureSize(64, 64); legL4.mirror = true; setRotation(legL4, -1.047198F, 2.617994F, 0F); legL5 = new ModelRenderer(this, 8, 16); legL5.addBox(-1F, -4F, -1F, 2, 4, 2); legL5.setRotationPoint(3F, 12F, -1F); legL5.setTextureSize(64, 64); legL5.mirror = true; setRotation(legL5, -1.047198F, 1.832596F, 0F); legL6 = new ModelRenderer(this, 32, 16); legL6.addBox(-2F, 0F, -1F, 4, 4, 2); legL6.setRotationPoint(4F, 12F, -0.5F); legL6.setTextureSize(64, 64); legL6.mirror = true; setRotation(legL6, -0.2617994F, -1.570796F, 0F); bootR1 = new ModelRenderer(this, 16, 32); bootR1.addBox(-2F, -4F, -2F, 4, 4, 4); bootR1.setRotationPoint(-2F, 22F, -2F); bootR1.setTextureSize(64, 64); bootR1.mirror = true; setRotation(bootR1, 0F, 0F, 0F); bootR2 = new ModelRenderer(this, 32, 16); bootR2.addBox(-1F, -4F, -1F, 2, 4, 2); bootR2.setRotationPoint(-3F, 19F, -1F); bootR2.setTextureSize(64, 64); bootR2.mirror = true; setRotation(bootR2, -1.047198F, -0.5235988F, 0F); bootR3 = new ModelRenderer(this, 32, 16); bootR3.addBox(-1F, -4F, -1F, 2, 4, 2); bootR3.setRotationPoint(-3F, 19F, -1F); bootR3.setTextureSize(64, 64); bootR3.mirror = true; setRotation(bootR3, -1.832596F, -0.7853982F, 0F); bootL1 = new ModelRenderer(this, 16, 32); bootL1.addBox(-2F, -4F, -2F, 4, 4, 4); bootL1.setRotationPoint(2F, 22F, -2F); bootL1.setTextureSize(64, 64); bootL1.mirror = true; setRotation(bootL1, 0F, 0F, 0F); bootL2 = new ModelRenderer(this, 32, 16); bootL2.addBox(-1F, -4F, -1F, 2, 4, 2); bootL2.setRotationPoint(3F, 19F, -1F); bootL2.setTextureSize(64, 64); bootL2.mirror = true; setRotation(bootL2, -1.047198F, 0.5235988F, 0F); bootL3 = new ModelRenderer(this, 32, 16); bootL3.addBox(-1F, -4F, -1F, 2, 4, 2); bootL3.setRotationPoint(3F, 19F, -1F); bootL3.setTextureSize(64, 64); bootL3.mirror = true; setRotation(bootL3, -1.832596F, 0.7853982F, 0F); head = new ModelRenderer(this); head.addChild(head1); head.addChild(head2); head.addChild(head3); head.addChild(head4); head.addChild(head5); head.addChild(head6); head.addChild(head7); head.addChild(head8); head.addChild(head9); head.addChild(head10); head.addChild(head11); head.addChild(head12); head.addChild(head13); head.addChild(head14); head.addChild(head15); head.addChild(head16); head.addChild(head17); chest = new ModelRenderer(this); chest.addChild(chest1); chest.addChild(chest2); chest.addChild(chest3); chest.addChild(chest4); chest.addChild(chest5); chest.addChild(chest6); chest.addChild(chest7); chest.addChild(chest8); chest.addChild(chest9); chest.addChild(chest10); chest.addChild(chest11); chest.addChild(chest12); chest.addChild(chest13); for (int i = 0; i < chest.childModels.size(); i++) { chest.childModels.get(i).rotationPointY -= 1; } armR = new ModelRenderer(this); armR.addChild(armR1); armR.addChild(armR2); armR.addChild(armR3); armR.addChild(armR4); armR.addChild(armR5); armR.addChild(armR6); armL = new ModelRenderer(this); armL.addChild(armL1); armL.addChild(armL2); armL.addChild(armL3); armL.addChild(armL4); armL.addChild(armL5); armL.addChild(armL6); legR = new ModelRenderer(this); legR.setRotationPoint(0, -12, 0); legR.addChild(legR1); legR.addChild(legR2); legR.addChild(legR3); legR.addChild(legR4); legR.addChild(legR5); legR.addChild(legR6); for (int i = 0; i < legR.childModels.size(); i++) { legR.childModels.get(i).rotationPointY -= 12; } legL = new ModelRenderer(this); legL.setRotationPoint(0, -12, 0); legL.addChild(legL1); legL.addChild(legL2); legL.addChild(legL3); legL.addChild(legL4); legL.addChild(legL5); legL.addChild(legL6); for (int i = 0; i < legL.childModels.size(); i++) { legL.childModels.get(i).rotationPointY -= 12; } bootR = new ModelRenderer(this); bootR.setRotationPoint(0, -12, 0); bootR.addChild(bootR1); bootR.addChild(bootR2); bootR.addChild(bootR3); for (int i = 0; i < bootR.childModels.size(); i++) { bootR.childModels.get(i).rotationPointY -= 12; } bootL = new ModelRenderer(this); bootL.setRotationPoint(0, -12, 0); bootL.addChild(bootL1); bootL.addChild(bootL2); bootL.addChild(bootL3); for (int i = 0; i < bootL.childModels.size(); i++) { bootL.childModels.get(i).rotationPointY -= 12; } this.armorScale = 1.2f; } }
3e1eca2b1fd3bfe41ebd3208a5aae88dd188ee1f
4,640
java
Java
server/src/main/help/applyextra/commons/action/ListArrangementsAction.java
saalk/cards
ffef920efb2dbf7391958c3494c8cb126729777d
[ "MIT" ]
null
null
null
server/src/main/help/applyextra/commons/action/ListArrangementsAction.java
saalk/cards
ffef920efb2dbf7391958c3494c8cb126729777d
[ "MIT" ]
13
2019-12-30T23:18:23.000Z
2022-01-21T23:35:46.000Z
server/src/main/help/applyextra/commons/action/ListArrangementsAction.java
saalk/cards
ffef920efb2dbf7391958c3494c8cb126729777d
[ "MIT" ]
1
2022-01-09T07:43:21.000Z
2022-01-09T07:43:21.000Z
38.991597
175
0.670259
13,019
package applyextra.commons.action; import lombok.extern.slf4j.Slf4j; import applyextra.commons.activity.ActivityException; import applyextra.commons.event.EventOutput; import applyextra.commons.orchestration.Action; import applyextra.operations.model.ArrangementStatus; import nl.ing.riaf.ix.serviceclient.ServiceOperationTask; import nl.ing.sc.arrangementretrieval.listarrangements2.ListArrangementsServiceOperationClient; import nl.ing.sc.arrangementretrieval.listarrangements2.value.ListArrangementsBusinessRequest; import nl.ing.sc.arrangementretrieval.listarrangements2.value.ListArrangementsBusinessResponse; import nl.ing.sc.arrangementretrieval.listarrangements2.value.RoleWithArrangement; import org.apache.commons.lang3.StringUtils; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * New suppliedMove to make a tailored call to list arrangements. * The arrangements can be searched by category codes, arrangement status. If there is a next, * then the next can also be searched. * Please check the comments for the default methods below */ @Component @Lazy @Slf4j public class ListArrangementsAction implements Action<ListArrangementsAction.ListArrangementsActionDTO, EventOutput.Result> { private static final int MAX_NEXT_COUNT = 20; @Resource private ListArrangementsServiceOperationClient resourceClient; @Override public EventOutput.Result perform(ListArrangementsActionDTO dto) { int numberOfPages = 0; String partyID = dto.getCustomerId(); //Please check the comments below for the arrangement status and categorycodes ListArrangementsBusinessRequest request = new ListArrangementsBusinessRequest(partyID, ListArrangementsBusinessRequest.PartyType.PRIVATE, dto.getArrangementStatus()); //If CategoryCodes is set, then populate the biz request with the categorycodes if (!dto.getCategoryCodes().isEmpty()) { request.getCategoryCodes().addAll(dto.getCategoryCodes()); } ServiceOperationTask<ListArrangementsBusinessResponse> response = null; //Logic for calling list arrangements multiple times. do { if (canSetNext(response)) { request.setNext(response.getResponse().getNext()); } try { response = resourceClient.execute(request); if (response.getResult().isOk()) { dto.getRoleWithArrangements().addAll((response.getResponse()).getRoleWithArrangementList()); } else { throw new ActivityException("ListArrangements", response.getResult().getError().getErrorCode(), "Cannot fetch role list from list arrangements", null); } } catch (Exception ex) { if (!dto.getRoleWithArrangements().isEmpty()) { log.warn("Got an exception during call for NEXT page. Returning the arrangments obtained till now."); return EventOutput.Result.SUCCESS; } else { throw ex; } } //To avoid memory leak if (numberOfPages >= MAX_NEXT_COUNT) break; numberOfPages++; } while (canSetNext(response)); //Loop as long as there is a next in the response return EventOutput.Result.SUCCESS; } private boolean canSetNext(ServiceOperationTask<ListArrangementsBusinessResponse> response) { return response!=null && response.getResponse() != null && StringUtils.isNotEmpty(response.getResponse().getNext()); } public interface ListArrangementsActionDTO { String getCustomerId(); List<RoleWithArrangement> getRoleWithArrangements(); /** * 1 is the default which returns active arrangments * Ensure that you return null if you want both closed and active arrangements. * 2 is for closed arrangements * @return */ default Integer getArrangementStatus() { return ArrangementStatus.ACTIVE.getArrangementStatus(); } /** * Ensure that you overrride this method to set the list of category codes that you need to filer * @return */ default List<Integer> getCategoryCodes() { return new ArrayList(); } } }
3e1ecb442b864a05fa8f447df703bdd10c6ff787
6,167
java
Java
aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/DescribePackagesResult.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
1
2020-08-27T17:36:34.000Z
2020-08-27T17:36:34.000Z
aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/DescribePackagesResult.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
3
2020-04-15T20:08:15.000Z
2021-06-30T19:58:16.000Z
aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/DescribePackagesResult.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
1
2020-10-10T15:59:17.000Z
2020-10-10T15:59:17.000Z
32.119792
149
0.634344
13,020
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticsearch.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Container for response returned by <code> <a>DescribePackages</a> </code> operation. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribePackagesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * List of <code>PackageDetails</code> objects. * </p> */ private java.util.List<PackageDetails> packageDetailsList; private String nextToken; /** * <p> * List of <code>PackageDetails</code> objects. * </p> * * @return List of <code>PackageDetails</code> objects. */ public java.util.List<PackageDetails> getPackageDetailsList() { return packageDetailsList; } /** * <p> * List of <code>PackageDetails</code> objects. * </p> * * @param packageDetailsList * List of <code>PackageDetails</code> objects. */ public void setPackageDetailsList(java.util.Collection<PackageDetails> packageDetailsList) { if (packageDetailsList == null) { this.packageDetailsList = null; return; } this.packageDetailsList = new java.util.ArrayList<PackageDetails>(packageDetailsList); } /** * <p> * List of <code>PackageDetails</code> objects. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setPackageDetailsList(java.util.Collection)} or {@link #withPackageDetailsList(java.util.Collection)} if * you want to override the existing values. * </p> * * @param packageDetailsList * List of <code>PackageDetails</code> objects. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePackagesResult withPackageDetailsList(PackageDetails... packageDetailsList) { if (this.packageDetailsList == null) { setPackageDetailsList(new java.util.ArrayList<PackageDetails>(packageDetailsList.length)); } for (PackageDetails ele : packageDetailsList) { this.packageDetailsList.add(ele); } return this; } /** * <p> * List of <code>PackageDetails</code> objects. * </p> * * @param packageDetailsList * List of <code>PackageDetails</code> objects. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePackagesResult withPackageDetailsList(java.util.Collection<PackageDetails> packageDetailsList) { setPackageDetailsList(packageDetailsList); return this; } /** * @param nextToken */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * @return */ public String getNextToken() { return this.nextToken; } /** * @param nextToken * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePackagesResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPackageDetailsList() != null) sb.append("PackageDetailsList: ").append(getPackageDetailsList()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribePackagesResult == false) return false; DescribePackagesResult other = (DescribePackagesResult) obj; if (other.getPackageDetailsList() == null ^ this.getPackageDetailsList() == null) return false; if (other.getPackageDetailsList() != null && other.getPackageDetailsList().equals(this.getPackageDetailsList()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPackageDetailsList() == null) ? 0 : getPackageDetailsList().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public DescribePackagesResult clone() { try { return (DescribePackagesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
3e1eccbd1168b2500c8ec5f5e080c7f288382c8b
6,921
java
Java
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/facebook/common/R$id.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
4
2019-10-07T05:17:21.000Z
2020-11-02T08:29:13.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/facebook/common/R$id.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
38
2019-10-07T02:40:35.000Z
2019-12-12T09:15:24.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/facebook/common/R$id.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
5
2019-10-07T02:41:15.000Z
2020-10-30T01:36:08.000Z
54.070313
83
0.751481
13,021
package com.facebook.common; public final class R$id { public static final int action0 = 2131361817; public static final int action_bar = 2131361819; public static final int action_bar_activity_content = 2131361820; public static final int action_bar_container = 2131361821; public static final int action_bar_root = 2131361822; public static final int action_bar_spinner = 2131361823; public static final int action_bar_subtitle = 2131361824; public static final int action_bar_title = 2131361825; public static final int action_container = 2131361826; public static final int action_context_bar = 2131361827; public static final int action_divider = 2131361828; public static final int action_image = 2131361829; public static final int action_menu_divider = 2131361830; public static final int action_menu_presenter = 2131361831; public static final int action_mode_bar = 2131361832; public static final int action_mode_bar_stub = 2131361833; public static final int action_mode_close_button = 2131361834; public static final int action_text = 2131361835; public static final int actions = 2131361836; public static final int activity_chooser_view_content = 2131361837; public static final int add = 2131361838; public static final int alertTitle = 2131361850; public static final int async = 2131361864; public static final int blocking = 2131361885; public static final int bottom = 2131361900; public static final int box_count = 2131361929; public static final int button = 2131361936; public static final int buttonPanel = 2131361983; public static final int cancel_action = 2131362000; public static final int cancel_button = 2131362001; public static final int center = 2131362009; public static final int checkbox = 2131362021; public static final int chronometer = 2131362022; public static final int com_facebook_device_auth_instructions = 2131362034; public static final int com_facebook_fragment_container = 2131362035; public static final int com_facebook_login_fragment_progress_bar = 2131362036; public static final int com_facebook_smart_instructions_0 = 2131362037; public static final int com_facebook_smart_instructions_or = 2131362038; public static final int confirmation_code = 2131362055; public static final int contentPanel = 2131362074; public static final int custom = 2131362105; public static final int customPanel = 2131362106; public static final int decor_content_parent = 2131362113; public static final int default_activity_button = 2131362114; public static final int edit_query = 2131362167; public static final int end_padder = 2131362181; public static final int expand_activities_button = 2131362202; public static final int expanded_menu = 2131362203; public static final int forever = 2131362244; public static final int home = 2131362282; public static final int icon = 2131362294; public static final int icon_group = 2131362308; public static final int image = 2131362313; public static final int info = 2131362360; public static final int inline = 2131362361; public static final int italic = 2131362372; public static final int left = 2131362448; public static final int line1 = 2131362463; public static final int line3 = 2131362464; public static final int listMode = 2131362475; public static final int list_item = 2131362478; public static final int media_actions = 2131362501; public static final int message = 2131362503; public static final int multiply = 2131362521; public static final int none = 2131362545; public static final int normal = 2131362546; public static final int notification_background = 2131362557; public static final int notification_main_column = 2131362558; public static final int notification_main_column_container = 2131362559; public static final int open_graph = 2131362565; public static final int page = 2131362583; public static final int parentPanel = 2131362588; public static final int progress_bar = 2131362735; public static final int progress_circular = 2131362736; public static final int progress_horizontal = 2131362737; public static final int radio = 2131362738; public static final int right = 2131362807; public static final int right_icon = 2131362816; public static final int right_side = 2131362817; public static final int screen = 2131362826; public static final int scrollIndicatorDown = 2131362828; public static final int scrollIndicatorUp = 2131362829; public static final int scrollView = 2131362830; public static final int search_badge = 2131362845; public static final int search_bar = 2131362846; public static final int search_button = 2131362847; public static final int search_close_btn = 2131362848; public static final int search_edit_frame = 2131362849; public static final int search_go_btn = 2131362850; public static final int search_mag_icon = 2131362851; public static final int search_plate = 2131362852; public static final int search_src_text = 2131362854; public static final int search_voice_btn = 2131362855; public static final int select_dialog_listview = 2131362856; public static final int shortcut = 2131362920; public static final int spacer = 2131362948; public static final int split_action_bar = 2131362956; public static final int src_atop = 2131362960; public static final int src_in = 2131362961; public static final int src_over = 2131362962; public static final int standard = 2131362963; public static final int status_bar_latest_event_content = 2131362976; public static final int submenuarrow = 2131363008; public static final int submit_area = 2131363009; public static final int tabMode = 2131363014; public static final int tag_transition_group = 2131363028; public static final int text = 2131363045; public static final int text2 = 2131363046; public static final int textSpacerNoButtons = 2131363195; public static final int textSpacerNoTitle = 2131363196; public static final int time = 2131363243; public static final int title = 2131363245; public static final int titleDividerNoCustom = 2131363247; public static final int title_template = 2131363250; public static final int top = 2131363257; public static final int topPanel = 2131363263; public static final int uniform = 2131363354; public static final int unknown = 2131363355; public static final int up = 2131363357; public static final int wrap_content = 2131363452; private R$id() { } }
3e1ecda2d72da7c84301713f5f35dd9233d4ccfb
1,687
java
Java
java_src/src/main/java/com/google/crypto/tink/internal/PrimitiveFactory.java
yoavamit/tink
d7a0c2ae9266d54eac721ab6776e9939160fdff7
[ "Apache-2.0" ]
null
null
null
java_src/src/main/java/com/google/crypto/tink/internal/PrimitiveFactory.java
yoavamit/tink
d7a0c2ae9266d54eac721ab6776e9939160fdff7
[ "Apache-2.0" ]
null
null
null
java_src/src/main/java/com/google/crypto/tink/internal/PrimitiveFactory.java
yoavamit/tink
d7a0c2ae9266d54eac721ab6776e9939160fdff7
[ "Apache-2.0" ]
null
null
null
38.340909
98
0.703616
13,022
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package com.google.crypto.tink.internal; import com.google.protobuf.MessageLite; import java.security.GeneralSecurityException; /** A PrimitiveFactory knows how to create primitives from a given key. */ public abstract class PrimitiveFactory<PrimitiveT, KeyProtoT extends MessageLite> { private final Class<PrimitiveT> clazz; public PrimitiveFactory(Class<PrimitiveT> clazz) { this.clazz = clazz; } /** Returns the class object corresponding to the generic parameter {@code PrimitiveT}. */ final Class<PrimitiveT> getPrimitiveClass() { return clazz; } /** * Creates a new instance of {@code PrimitiveT}. * * <p>For primitives of type {@code Mac}, {@code Aead}, {@code PublicKeySign}, {@code * PublicKeyVerify}, {@code DeterministicAead}, {@code HybridEncrypt}, and {@code HybridDecrypt} * this should be a primitive which <b>ignores</b> the output prefix and assumes "RAW". */ public abstract PrimitiveT getPrimitive(KeyProtoT key) throws GeneralSecurityException; }
3e1ecda49e4c1ae12b91121f6b54fb40e1a85256
12,503
java
Java
src/tools/android/java/com/google/devtools/build/android/ResourcesZip.java
nowens03/bazel
d0a3c5eb67320906e4b937df5434f0e673cb6dce
[ "Apache-2.0" ]
8
2015-12-25T16:16:53.000Z
2021-07-13T09:58:53.000Z
src/tools/android/java/com/google/devtools/build/android/ResourcesZip.java
dilbrent/bazel
7b73c5f6abc9e9b574849f760873252ee987e184
[ "Apache-2.0" ]
1
2016-02-10T20:14:53.000Z
2016-02-10T20:14:53.000Z
src/tools/android/java/com/google/devtools/build/android/ResourcesZip.java
dilbrent/bazel
7b73c5f6abc9e9b574849f760873252ee987e184
[ "Apache-2.0" ]
6
2016-02-10T20:07:36.000Z
2020-11-18T17:44:05.000Z
37.10089
98
0.689914
13,023
// 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.android; import static com.google.common.base.Predicates.not; import static java.util.stream.Collectors.toMap; import com.android.SdkConstants; import com.android.annotations.VisibleForTesting; import com.android.build.gradle.tasks.ResourceUsageAnalyzer; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteStreams; import com.google.devtools.build.android.AndroidResourceOutputs.ZipBuilder; import com.google.devtools.build.android.AndroidResourceOutputs.ZipBuilderVisitorWithDirectories; import com.google.devtools.build.android.aapt2.CompiledResources; import com.google.devtools.build.android.aapt2.ProtoApk; import com.google.devtools.build.android.aapt2.ProtoResourceUsageAnalyzer; import com.google.devtools.build.android.aapt2.ResourceCompiler; import com.google.devtools.build.android.aapt2.ResourceLinker; import com.google.devtools.build.android.proto.SerializeFormat.ToolAttributes; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.annotation.Nullable; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** Represents a collection of raw, merged resources with an optional id list. */ public class ResourcesZip { static final Logger logger = Logger.getLogger(ResourcesZip.class.toString()); @Nullable private final Path resourcesRoot; @Nullable private final Path assetsRoot; @Nullable private final Path apkWithAssets; @Nullable private final Path proto; @Nullable private final Path attributes; @Nullable private final Path ids; private ResourcesZip( @Nullable Path resourcesRoot, @Nullable Path assetsRoot, @Nullable Path ids, @Nullable Path apkWithAssets, @Nullable Path proto, @Nullable Path attributes) { this.resourcesRoot = resourcesRoot; this.assetsRoot = assetsRoot; this.ids = ids; this.apkWithAssets = apkWithAssets; this.proto = proto; this.attributes = attributes; } /** * @param resourcesRoot The root of the raw resources. * @param assetsRoot The root of the raw assets. */ public static ResourcesZip from(Path resourcesRoot, Path assetsRoot) { return new ResourcesZip(resourcesRoot, assetsRoot, null, null, null, null); } /** * @param resourcesRoot The root of the raw resources. * @param assetsRoot The root of the raw assets. * @param resourceIds Optional path to a file containing the resource ids. */ public static ResourcesZip from(Path resourcesRoot, Path assetsRoot, Path resourceIds) { return new ResourcesZip( resourcesRoot, assetsRoot, resourceIds != null && Files.exists(resourceIds) ? resourceIds : null, null, null, null); } /** * @param resourcesRoot The root of the raw resources. * @param apkWithAssets The apk containing assets. * @param resourceIds Optional path to a file containing the resource ids. */ public static ResourcesZip fromApk(Path resourcesRoot, Path apkWithAssets, Path resourceIds) { return new ResourcesZip( resourcesRoot, /* assetsRoot= */ null, resourceIds != null && Files.exists(resourceIds) ? resourceIds : null, apkWithAssets, null, null); } /** * @param proto apk in proto format. * @param attributes Tooling attributes. * @param resourcesRoot The root of the raw resources. * @param apkWithAssets The apk containing assets. * @param resourceIds Optional path to a file containing the resource ids. */ public static ResourcesZip fromApkWithProto( Path proto, Path attributes, Path resourcesRoot, Path apkWithAssets, Path resourceIds) { return new ResourcesZip( resourcesRoot, /* assetsRoot= */ null, resourceIds != null && Files.exists(resourceIds) ? resourceIds : null, apkWithAssets, proto, attributes); } /** Creates a ResourcesZip from an archive by expanding into the workingDirectory. */ public static ResourcesZip createFrom(Path resourcesZip, Path workingDirectory) throws IOException { // Expand resource files zip into working directory. final ZipFile zipFile = new ZipFile(resourcesZip.toFile()); zipFile .stream() .filter(not(ZipEntry::isDirectory)) .forEach( entry -> { Path output = workingDirectory.resolve(entry.getName()); try { Files.createDirectories(output.getParent()); try (FileOutputStream fos = new FileOutputStream(output.toFile())) { ByteStreams.copy(zipFile.getInputStream(entry), fos); } } catch (IOException e) { throw new RuntimeException(e); } }); return new ResourcesZip( Files.createDirectories(workingDirectory.resolve("res")), Files.createDirectories(workingDirectory.resolve("assets")), workingDirectory.resolve("ids.txt"), null, workingDirectory.resolve("apk.pb"), workingDirectory.resolve("tools.attributes.pb")); } /** * Creates a zip file containing the provided android resources and assets. * * @param output The path to write the zip file * @param compress Whether or not to compress the content * @throws IOException */ public void writeTo(Path output, boolean compress) throws IOException { try (final ZipBuilder zip = ZipBuilder.createFor(output)) { if (Files.exists(resourcesRoot)) { ZipBuilderVisitorWithDirectories visitor = new ZipBuilderVisitorWithDirectories(zip, resourcesRoot, "res"); visitor.setCompress(compress); Files.walkFileTree(resourcesRoot, visitor); if (!Files.exists(resourcesRoot.resolve("values/public.xml"))) { // add an empty public xml, if one doesn't exist. The ResourceUsageAnalyzer expects one. visitor.addEntry( resourcesRoot.resolve("values").resolve("public.xml"), "<resources></resources>".getBytes(StandardCharsets.UTF_8)); } visitor.writeEntries(); } if (apkWithAssets != null) { ZipFile apkZip = new ZipFile(apkWithAssets.toString()); apkZip .stream() .filter(entry -> entry.getName().startsWith("assets/")) .forEach( entry -> { try { zip.addEntry(entry, ByteStreams.toByteArray(apkZip.getInputStream(entry))); } catch (IOException e) { throw new RuntimeException(e); } }); zip.addEntry("assets/", new byte[0], compress ? ZipEntry.DEFLATED : ZipEntry.STORED); } else if (Files.exists(assetsRoot)) { ZipBuilderVisitorWithDirectories visitor = new ZipBuilderVisitorWithDirectories(zip, assetsRoot, "assets"); visitor.setCompress(compress); Files.walkFileTree(assetsRoot, visitor); visitor.writeEntries(); } try { if (ids != null) { zip.addEntry("ids.txt", Files.readAllBytes(ids), ZipEntry.STORED); } if (proto != null && Files.exists(proto)) { zip.addEntry("apk.pb", Files.readAllBytes(proto), ZipEntry.STORED); } if (attributes != null && Files.exists(attributes)) { zip.addEntry("tools.attributes.pb", Files.readAllBytes(attributes), ZipEntry.STORED); } } catch (IOException e) { throw new RuntimeException(e); } } } /** Removes unused resources from the archived resources. */ public ShrunkResources shrink( Set<String> packages, Path rTxt, Path classJar, Path manifest, @Nullable Path proguardMapping, Path logFile, Path workingDirectory) throws ParserConfigurationException, IOException, SAXException { new ResourceUsageAnalyzer( packages, rTxt, classJar, manifest, proguardMapping, resourcesRoot, logFile) .shrink(workingDirectory); return ShrunkResources.of( new ResourcesZip(workingDirectory, assetsRoot, ids, null, null, attributes), new UnvalidatedAndroidData( ImmutableList.of(workingDirectory), ImmutableList.of(assetsRoot), manifest)); } public ShrunkProtoApk shrinkUsingProto( Set<String> packages, Path classJar, Path proguardMapping, Path logFile, Path workingDirectory) throws ParserConfigurationException, IOException, SAXException { final Path shrunkApkProto = workingDirectory.resolve("shrunk.apk.pb"); try (final ProtoApk apk = ProtoApk.readFrom(proto)) { final Map<String, Set<String>> toolAttributes = toAttributes(); // record resources and manifest new ProtoResourceUsageAnalyzer(packages, proguardMapping, logFile) .shrink( apk, classJar, shrunkApkProto, toolAttributes.getOrDefault(SdkConstants.ATTR_KEEP, ImmutableSet.of()), toolAttributes.getOrDefault(SdkConstants.ATTR_DISCARD, ImmutableSet.of())); return new ShrunkProtoApk(shrunkApkProto, logFile); } } @VisibleForTesting public Map<String, Set<String>> toAttributes() throws IOException { return ToolAttributes.parseFrom(Files.readAllBytes(attributes)) .getAttributesMap() .entrySet() .stream() .collect(toMap(Entry::getKey, e -> ImmutableSet.copyOf(e.getValue().getValuesList()))); } static class ShrunkProtoApk { private final Path apk; private final Path report; ShrunkProtoApk(Path apk, Path report) { this.apk = apk; this.report = report; } ShrunkProtoApk writeBinaryTo(ResourceLinker linker, Path binaryOut, boolean writeAsProto) throws IOException { Files.copy( writeAsProto ? apk : linker.optimizeApk(linker.convertToBinary(apk)), binaryOut, StandardCopyOption.REPLACE_EXISTING); return this; } ShrunkProtoApk writeReportTo(Path reportOut) throws IOException { Files.copy(report, reportOut); return this; } ShrunkProtoApk writeResourcesToZip(Path resourcesZip) throws IOException { try (final ZipBuilder zip = ZipBuilder.createFor(resourcesZip)) { zip.addEntry("apk.pb", Files.readAllBytes(apk), ZipEntry.STORED); } return this; } } static class ShrunkResources { private ResourcesZip resourcesZip; private UnvalidatedAndroidData unvalidatedAndroidData; private ShrunkResources( ResourcesZip resourcesZip, UnvalidatedAndroidData unvalidatedAndroidData) { this.resourcesZip = resourcesZip; this.unvalidatedAndroidData = unvalidatedAndroidData; } public static ShrunkResources of( ResourcesZip resourcesZip, UnvalidatedAndroidData unvalidatedAndroidData) { return new ShrunkResources(resourcesZip, unvalidatedAndroidData); } public ShrunkResources writeArchiveTo(Path archivePath, boolean compress) throws IOException { resourcesZip.writeTo(archivePath, compress); return this; } public CompiledResources compile(ResourceCompiler compiler, Path workingDirectory) throws InterruptedException, ExecutionException, IOException { return unvalidatedAndroidData .compile(compiler, workingDirectory) .addStableIds(resourcesZip.ids); } } }
3e1ecda93001636aa3827e191321e557616b9def
682
java
Java
src/com/cc/mode/observer/jdk/WeathData.java
CC-Beelzebub/design-mode
6d3ea8ad188aafe5471c678fdc4eb0df00b627ba
[ "Apache-2.0" ]
null
null
null
src/com/cc/mode/observer/jdk/WeathData.java
CC-Beelzebub/design-mode
6d3ea8ad188aafe5471c678fdc4eb0df00b627ba
[ "Apache-2.0" ]
null
null
null
src/com/cc/mode/observer/jdk/WeathData.java
CC-Beelzebub/design-mode
6d3ea8ad188aafe5471c678fdc4eb0df00b627ba
[ "Apache-2.0" ]
null
null
null
20.058824
54
0.602639
13,024
package com.cc.mode.observer.jdk; import java.util.Observable; /** * @ClassName com.cc.mode.observer.jdk * @Description: * @Author chenjie * @Date Created in 星期日 2018/7/1 * @Version 1.0 */ public class WeathData extends Observable { private String temperature; /** * 方便测试,天气状态变化时 * * @param temperature */ public void setMeasurements(String temperature) { this.temperature = temperature; this.measurementsChanged(); } public void measurementsChanged() { setChanged(); notifyObservers(); } public String getTemperature() { return temperature; } }
3e1ecdfb3c9ab1e519690ee962db2c54bcf0c718
2,224
java
Java
micro-deps/micro-deps/src/main/java/com/ofg/infrastructure/discovery/util/DependencyCreator.java
vrachieru/micro-infra-spring
94277657743d26d9e0a5bd19423b24fa537906d6
[ "Apache-2.0" ]
193
2015-01-02T23:22:59.000Z
2021-06-11T07:52:28.000Z
micro-deps/micro-deps/src/main/java/com/ofg/infrastructure/discovery/util/DependencyCreator.java
vrachieru/micro-infra-spring
94277657743d26d9e0a5bd19423b24fa537906d6
[ "Apache-2.0" ]
504
2015-01-02T08:45:02.000Z
2018-08-16T13:03:52.000Z
micro-deps/micro-deps/src/main/java/com/ofg/infrastructure/discovery/util/DependencyCreator.java
vrachieru/micro-infra-spring
94277657743d26d9e0a5bd19423b24fa537906d6
[ "Apache-2.0" ]
58
2015-01-13T23:11:37.000Z
2019-06-25T03:20:55.000Z
48.347826
155
0.6875
13,025
package com.ofg.infrastructure.discovery.util; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.Collections2; import com.ofg.infrastructure.discovery.MicroserviceConfiguration; import com.ofg.infrastructure.discovery.MicroserviceConfiguration.Dependency.StubsConfiguration; import com.ofg.infrastructure.discovery.ServiceAlias; import com.ofg.infrastructure.discovery.ServicePath; import org.apache.commons.lang.StringUtils; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class DependencyCreator { public static Collection<MicroserviceConfiguration.Dependency> fromMap(Map<String, Map<String, Object>> dependency) { return Collections2.transform(dependency.entrySet(), new Function<Map.Entry<String, Map<String, Object>>, MicroserviceConfiguration.Dependency>() { @Override public MicroserviceConfiguration.Dependency apply(Map.Entry<String, Map<String, Object>> input) { String key = input.getKey(); Map<String, Object> value = input.getValue(); return new MicroserviceConfiguration.Dependency(new ServiceAlias(key), new ServicePath((String) value.get("path")), Boolean.valueOf((String) value.get("required")), LoadBalancerType.fromName((String) value.get("load-balancer-type")), MoreObjects.firstNonNull((String) value.get("contentTypeTemplate"), StringUtils.EMPTY), MoreObjects.firstNonNull((String) value.get("version"), StringUtils.EMPTY), MoreObjects.firstNonNull((Map<String, String>) value.get("headers"), new HashMap<String, String>()), parseStubConfiguration(value)); } }); } private static StubsConfiguration parseStubConfiguration(Map<String, Object> value) { Map<String, String> stubs = (Map<String, String>) value.get("stubs"); if (stubs != null) { return new StubsConfiguration(stubs.get("stubsGroupId"), stubs.get("stubsArtifactId"), stubs.get("stubsClassifier")); } return null; } }
3e1ece046cfb5cb98bfd5b6e7d1a3277eda8385d
2,381
java
Java
univocity-trader-binance/src/main/java/com/univocity/trader/exchange/binance/api/client/BinanceApiClientFactory.java
hlevel/univocity-trader
a02bc24fb17a542c47bfbd3800106982502d1298
[ "Apache-2.0" ]
571
2019-11-15T19:42:43.000Z
2022-03-30T08:07:46.000Z
univocity-trader-binance/src/main/java/com/univocity/trader/exchange/binance/api/client/BinanceApiClientFactory.java
hlevel/univocity-trader
a02bc24fb17a542c47bfbd3800106982502d1298
[ "Apache-2.0" ]
75
2019-11-15T19:05:48.000Z
2022-02-09T01:19:42.000Z
univocity-trader-binance/src/main/java/com/univocity/trader/exchange/binance/api/client/BinanceApiClientFactory.java
hlevel/univocity-trader
a02bc24fb17a542c47bfbd3800106982502d1298
[ "Apache-2.0" ]
150
2019-11-15T16:43:02.000Z
2022-03-28T20:22:30.000Z
28.011765
126
0.724066
13,026
package com.univocity.trader.exchange.binance.api.client; import com.univocity.trader.exchange.binance.api.client.impl.*; import com.univocity.trader.exchange.binance.api.client.config.*; import org.asynchttpclient.*; /** * A factory for creating BinanceApi client objects. */ public class BinanceApiClientFactory { /** * Api Configuration to create the clients */ private final BinanceApiConfig apiConfig; /** * Instantiates a new binance api client factory. * * @param apiKey the API key * @param secret the Secret */ private BinanceApiClientFactory(String apiKey, String secret, AsyncHttpClient client, boolean isTestNet) { this.apiConfig = new BinanceApiConfig(apiKey, secret, client, isTestNet); } /** * New instance. * * @param apiKey the API key * @param secret the Secret * @param client the httpClient * @param isTestNet if it uses the Test Network or Real Network * * @return the binance api client factory */ public static BinanceApiClientFactory newInstance(String apiKey, String secret, AsyncHttpClient client, boolean isTestNet) { return new BinanceApiClientFactory(apiKey, secret, client, isTestNet); } /** * New instance. * * @param apiKey the API key * @param secret the Secret * @param client the httpClient * * @return the binance api client factory */ public static BinanceApiClientFactory newInstance(String apiKey, String secret, AsyncHttpClient client) { return newInstance(apiKey, secret, client, false); } /** * New instance without authentication. * * @return the binance api client factory */ public static BinanceApiClientFactory newInstance(AsyncHttpClient client) { return new BinanceApiClientFactory(null, null, client, false); } /** * Creates a new synchronous/blocking REST client. */ public BinanceApiRestClient newRestClient() { return new BinanceApiRestClientImpl(apiConfig); } /** * Creates a new asynchronous/non-blocking REST client. */ public BinanceApiAsyncRestClient newAsyncRestClient() {return new BinanceApiAsyncRestClientImpl(apiConfig); } /** * Creates a new web socket client used for handling data streams. */ public BinanceApiWebSocketClient newWebSocketClient() { return new BinanceApiWebSocketClientImpl(apiConfig.getAsyncHttpClient()); } }
3e1ece9b3d6062061289ab46741f10737911688c
1,961
java
Java
ecmall-product/src/main/java/com/immor/ecmall/product/service/impl/AttrGroupServiceImpl.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
1
2021-01-06T03:30:28.000Z
2021-01-06T03:30:28.000Z
ecmall-product/src/main/java/com/immor/ecmall/product/service/impl/AttrGroupServiceImpl.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
null
null
null
ecmall-product/src/main/java/com/immor/ecmall/product/service/impl/AttrGroupServiceImpl.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
null
null
null
39.22
114
0.689954
13,027
package com.immor.ecmall.product.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.immor.common.utils.PageUtils; import com.immor.common.utils.Query; import com.immor.ecmall.product.dao.AttrGroupDao; import com.immor.ecmall.product.entity.AttrGroupEntity; import com.immor.ecmall.product.service.AttrGroupService; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import java.util.Map; @Service("attrGroupService") public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<AttrGroupEntity> page = this.page( new Query<AttrGroupEntity>().getPage(params), new QueryWrapper<AttrGroupEntity>() ); return new PageUtils(page); } @Override public PageUtils queryPage(Map<String, Object> params, Long catelogId) { String key = (String) params.get("key"); //select * from pms_attr_group where catelogId = ? and ( attr_group_id = ? or attr_group_name like ? ) QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>(); if (StringUtils.isNotBlank(key)) { wrapper.and(obj -> { obj.eq("attr_group_id", key).or().like("attr_group_name", key); }); } if (catelogId == 0) { IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper); return new PageUtils(page); } else { wrapper.eq("catelog_id", catelogId); IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper); return new PageUtils(page); } } }
3e1ecf3846f1fb8862fb8269c64eb8fc08b02c00
6,907
java
Java
admin-web/src/java/org/jppf/admin/web/tabletree/JPPFTableTree.java
jppf-grid/JPPF
b98ee419e8d6bbf47ebb31e26ad4ef7c8f93c6e8
[ "Apache-2.0" ]
44
2018-09-13T02:31:00.000Z
2022-03-24T01:18:49.000Z
admin-web/src/java/org/jppf/admin/web/tabletree/JPPFTableTree.java
ParaSatellite/JPPF
b6a23dddb0393a8908c71b441fb214b148648cea
[ "Apache-2.0" ]
18
2019-03-17T21:40:53.000Z
2021-11-20T06:57:32.000Z
admin-web/src/java/org/jppf/admin/web/tabletree/JPPFTableTree.java
ParaSatellite/JPPF
b6a23dddb0393a8908c71b441fb214b148648cea
[ "Apache-2.0" ]
14
2019-07-02T09:26:50.000Z
2022-01-12T07:39:57.000Z
35.239796
183
0.719849
13,028
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.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.jppf.admin.web.tabletree; import java.util.*; import javax.swing.tree.*; import org.apache.wicket.*; import org.apache.wicket.ajax.*; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.tree.TableTree; import org.apache.wicket.extensions.markup.html.repeater.util.TreeModelProvider; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.repeater.*; import org.apache.wicket.model.*; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.cycle.RequestCycle; import org.jppf.admin.web.JPPFWebSession; import org.jppf.client.monitoring.AbstractComponent; import org.jppf.ui.treetable.*; import org.jppf.ui.utils.TreeTableUtils; import org.jppf.utils.TypedProperties; /** * */ public class JPPFTableTree extends TableTree<DefaultMutableTreeNode, String> { /** * */ private transient final SelectionHandler selectionHandler; /** * Provides the content for rendering tree nodes, i.e. icon and text. */ private transient final TreeNodeRenderer nodeRenderer; /** * The backing tree data model. */ private transient final AbstractJPPFTreeTableModel nodeTreeModel; /** * */ private transient final List<Component> updateTargets = new ArrayList<>(); /** * The type of view this table tree is in. */ private transient final TreeViewType type; /** * * @param type the type of view this table tree is in. * @param id . * @param columns . * @param nodeTreeModel . * @param rowsPerPage . * @param selectionHandler handles selection events. * @param nodeRenderer provides the content for rendering tree nodes, i.e. icon and text. * @param expansionModel keeps tabs on the expanded nodes in the tree. */ public JPPFTableTree(final TreeViewType type, final String id, final List<? extends IColumn<DefaultMutableTreeNode, String>> columns, final AbstractJPPFTreeTableModel nodeTreeModel, final long rowsPerPage, final SelectionHandler selectionHandler, final TreeNodeRenderer nodeRenderer, final IModel<Set<DefaultMutableTreeNode>> expansionModel) { super(id, columns, new JPPFModelProvider(nodeTreeModel), rowsPerPage, expansionModel); this.type = type; this.selectionHandler = selectionHandler; this.nodeRenderer = nodeRenderer; this.nodeTreeModel = nodeTreeModel; //if (selectionHandler instanceof AbstractSelectionHandler) ((AbstractSelectionHandler) selectionHandler).setTableTree(this); getTable().setTableBodyCss("scrollable"); } @Override protected Component newContentComponent(final String id, final IModel<DefaultMutableTreeNode> model) { final DefaultMutableTreeNode node = model.getObject(); final WebMarkupContainer panel = new NodeContent(id, node, nodeRenderer, JPPFWebSession.get().isShowIP()); return panel; } @Override protected Item<DefaultMutableTreeNode> newRowItem(final String id, final int index, final IModel<DefaultMutableTreeNode> model) { final Item<DefaultMutableTreeNode> item = new OddEvenItem<>(id, index, model); if (selectionHandler != null) { item.add(new SelectionBehavior(model.getObject(), type)); } return item; } /** * @return the selection handler for this table tree. */ public SelectionHandler getSelectionHandler() { return selectionHandler; } /** * @return the backing tree data model. */ public AbstractJPPFTreeTableModel getNodeTreeModel() { return nodeTreeModel; } /** * Add a component to update upon selection changes. * @param comp the component to add. */ public void addUpdateTarget(final Component comp) { updateTargets.add(comp); } /** * */ public static class JPPFModelProvider extends TreeModelProvider<DefaultMutableTreeNode> { /** * * @param treeModel the backing tree data model. */ public JPPFModelProvider(final TreeModel treeModel) { super(treeModel, false); } @Override public IModel<DefaultMutableTreeNode> model(final DefaultMutableTreeNode object) { return Model.of(object); } } /** * */ public static class SelectionBehavior extends AjaxEventBehavior { /** * Uuid of the tree node to which the selection event applies. */ private final String uuid; /** * The type of view. */ private final TreeViewType type; /** * * @param node the tree node to which the selection applies. * @param type the type of view. */ public SelectionBehavior(final DefaultMutableTreeNode node, final TreeViewType type) { super("click"); this.uuid = ((AbstractComponent<?>) node.getUserObject()).getUuid(); this.type = type; } @Override protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.getDynamicExtraParameters().add("return {'ctrl' : attrs.event.ctrlKey, 'shift' : attrs.event.shiftKey}"); } @Override protected void onEvent(final AjaxRequestTarget target) { final JPPFWebSession session = (JPPFWebSession) target.getPage().getSession(); final TableTreeData data = session.getTableTreeData(type); final SelectionHandler selectionHandler = data.getSelectionHandler(); final DefaultMutableTreeNode node = TreeTableUtils.findTreeNode((DefaultMutableTreeNode) data.getModel().getRoot(), uuid, selectionHandler.getFilter()); if (node != null) { final IRequestParameters params = RequestCycle.get().getRequest().getRequestParameters(); final TypedProperties props = new TypedProperties() .setBoolean("ctrl", params.getParameterValue("ctrl").toBoolean(false)) .setBoolean("shift", params.getParameterValue("shift").toBoolean(false)); final Page page = target.getPage(); if (selectionHandler.handle(target, node, props) && (page instanceof TableTreeHolder)) { final TableTreeHolder holder = (TableTreeHolder) page; target.add(holder.getTableTree()); target.add(holder.getToolbar()); } } } } }
3e1ecf9623bedcb6a35b191e731d12d1bc8fc259
4,986
java
Java
src/main/java/cs/f10/t1/nursetraverse/logic/parser/appointment/AddAppointmentCommandParser.java
gabrielchao/main
20ca4847592f4a55b87ff1c21882d17c531980b3
[ "MIT" ]
1
2019-10-16T07:16:04.000Z
2019-10-16T07:16:04.000Z
src/main/java/cs/f10/t1/nursetraverse/logic/parser/appointment/AddAppointmentCommandParser.java
crazoter/main
b823e819020013b1e2a93ea26ad7652e71bd7ed7
[ "MIT" ]
150
2019-09-20T05:12:21.000Z
2019-11-15T12:18:53.000Z
src/main/java/cs/f10/t1/nursetraverse/logic/parser/appointment/AddAppointmentCommandParser.java
crazoter/main
b823e819020013b1e2a93ea26ad7652e71bd7ed7
[ "MIT" ]
5
2019-09-15T14:08:50.000Z
2019-09-24T18:47:21.000Z
54.791209
116
0.764741
13,029
// @@author sandydays package cs.f10.t1.nursetraverse.logic.parser.appointment; import static cs.f10.t1.nursetraverse.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_APPOINTMENT_DESCRIPTION; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_APPOINTMENT_END_DATE_AND_TIME; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_APPOINTMENT_START_DATE_AND_TIME; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_PATIENT_INDEX; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_DAYS; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_HOURS; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_MINUTES; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_MONTHS; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_WEEKS; import static cs.f10.t1.nursetraverse.logic.parser.CliSyntax.PREFIX_RECUR_YEARS; import java.util.stream.Stream; import cs.f10.t1.nursetraverse.commons.core.index.Index; import cs.f10.t1.nursetraverse.logic.commands.appointment.AddAppointmentCommand; import cs.f10.t1.nursetraverse.logic.parser.ArgumentMultimap; import cs.f10.t1.nursetraverse.logic.parser.ArgumentTokenizer; import cs.f10.t1.nursetraverse.logic.parser.Parser; import cs.f10.t1.nursetraverse.logic.parser.ParserUtil; import cs.f10.t1.nursetraverse.logic.parser.Prefix; import cs.f10.t1.nursetraverse.logic.parser.exceptions.ParseException; import cs.f10.t1.nursetraverse.model.appointment.Appointment; import cs.f10.t1.nursetraverse.model.datetime.EndDateTime; import cs.f10.t1.nursetraverse.model.datetime.RecurringDateTime; import cs.f10.t1.nursetraverse.model.datetime.StartDateTime; /** * Parses input arguments and creates a new AddAppointmentCommand object */ public class AddAppointmentCommandParser implements Parser<AddAppointmentCommand> { /** * Parses the given {@code String} of arguments in the context of the AddAppointmentCommand * and returns an AddAppointmentCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public AddAppointmentCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_PATIENT_INDEX, PREFIX_APPOINTMENT_START_DATE_AND_TIME, PREFIX_APPOINTMENT_END_DATE_AND_TIME, PREFIX_RECUR_YEARS, PREFIX_RECUR_MONTHS, PREFIX_RECUR_WEEKS, PREFIX_RECUR_DAYS, PREFIX_RECUR_HOURS, PREFIX_RECUR_MINUTES, PREFIX_APPOINTMENT_DESCRIPTION); if (!arePrefixesPresent(argMultimap, PREFIX_PATIENT_INDEX, PREFIX_APPOINTMENT_START_DATE_AND_TIME, PREFIX_APPOINTMENT_END_DATE_AND_TIME)) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddAppointmentCommand.MESSAGE_USAGE)); } StartDateTime startDateTime = ParserUtil.parseStartDateTime(argMultimap .getValue(PREFIX_APPOINTMENT_START_DATE_AND_TIME).get()); EndDateTime endDateTime = ParserUtil.parseEndDateTime(argMultimap .getValue(PREFIX_APPOINTMENT_END_DATE_AND_TIME).get(), argMultimap .getValue(PREFIX_APPOINTMENT_START_DATE_AND_TIME).get()); Long years = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_YEARS)); Long months = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_MONTHS)); Long weeks = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_WEEKS)); Long days = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_DAYS)); Long hours = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_HOURS)); Long minutes = ParserUtil.parseFrequency(argMultimap.getValue(PREFIX_RECUR_MINUTES)); Long[] freqArray = {years, months, weeks, days, hours, minutes}; RecurringDateTime frequency = new RecurringDateTime(freqArray); Index indexPatient = ParserUtil.parseIndex(argMultimap.getValue(PREFIX_PATIENT_INDEX).get()); String description = ParserUtil.parseDescription(argMultimap .getValue(PREFIX_APPOINTMENT_DESCRIPTION)); Appointment appointment = new Appointment(startDateTime, endDateTime, frequency, indexPatient, description); return new AddAppointmentCommand(appointment); } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
3e1ed019232d75f64f79aac16ab2313bf0b90bfa
15,224
java
Java
rx-extensions/src/test/java/com/appunite/detector/ChangesDetectorTest.java
jacek-marchwicki/rx-java-extensions
22c02517055153aecc6d99c9543e6c3ac5b2a4af
[ "Apache-2.0" ]
43
2015-04-01T11:52:40.000Z
2019-04-20T06:11:24.000Z
rx-extensions/src/test/java/com/appunite/detector/ChangesDetectorTest.java
jacek-marchwicki/rx-java-extensions
22c02517055153aecc6d99c9543e6c3ac5b2a4af
[ "Apache-2.0" ]
75
2015-04-29T09:59:49.000Z
2021-06-01T21:44:51.000Z
rx-extensions/src/test/java/com/appunite/detector/ChangesDetectorTest.java
jacek-marchwicki/rx-java-extensions
22c02517055153aecc6d99c9543e6c3ac5b2a4af
[ "Apache-2.0" ]
17
2015-04-20T09:40:08.000Z
2017-07-29T11:50:56.000Z
38.760814
142
0.640714
13,030
/* * Copyright 2015 Jacek Marchwicki <upchh@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.appunite.detector; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import javax.annotation.Nonnull; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class ChangesDetectorTest { private ChangesDetector<Cat, Cat> detector; private ChangesDetector.ChangesAdapter adapter; private static class Cat { private final int id; private final String name; private Cat(int id, String name) { this.id = id; this.name = name; } Cat(int id) { this.id = id; name = generateName(id); } Cat withName(String name) { return new Cat(id, name); } @Nonnull private String generateName(int id) { switch (id) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; case 3: return "tree"; case 4: return "four"; case 5: return "five"; default: throw new RuntimeException("Unknown id: " + id); } } @Override public String toString() { return "Cat{" + "id=" + id + ", name='" + name + '\'' + '}'; } } @Before public void setUp() throws Exception { detector = new ChangesDetector<>(new ChangesDetector.Detector<Cat, Cat>() { @Nonnull @Override public Cat apply(@Nonnull Cat item) { return item; } @Override public boolean matches(@Nonnull Cat item, @Nonnull Cat newOne) { return item.id == newOne.id; } @Override public boolean same(@Nonnull Cat item, @Nonnull Cat newOne) { return item.id == newOne.id && Objects.equal(item.name, newOne.name); } }); adapter = mock(ChangesDetector.ChangesAdapter.class); } @Test public void testStart() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); verify(adapter).notifyItemRangeInserted(0, 1); } @Test public void testAfterChangeOrder_orderIsChangeIsNotified1() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(0)), false); verify(adapter).notifyItemMoved(1, 0); verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrder_orderIsChangeIsNotified2() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(0), new Cat(2)), false); verify(adapter).notifyItemMoved(1, 0); verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrder_orderIsChangeIsNotified3() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(0)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemMoved(1, 0); // 1, 0, 2 inOrder.verify(adapter).notifyItemMoved(2, 1); // 1, 2, 0 verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrderAndModifyItem_orderAndChangeAreNotified() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(0).withName("zero_")), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemMoved(1, 0); // one, zero inOrder.verify(adapter).notifyItemRangeChanged(1, 1); // one, zero_ verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrderAndDeleteSomeItem_orderAndDeleteAreNotified1() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(0)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemMoved(1, 0); inOrder.verify(adapter).notifyItemRangeRemoved(2, 1); verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrderAndDeleteSomeItem_orderAndDeleteAreNotified2() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), false); verify(adapter).notifyItemRangeRemoved(0, 1); verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrderAndDeleteSomeItem_orderAndDeleteAreNotified3() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(2), new Cat(0)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemMoved(2, 0); // 2, 0, 1 inOrder.verify(adapter).notifyItemRangeRemoved(2, 1); // 2, 0 verifyNoMoreInteractions(adapter); } @Test public void testAfterChangeOrderAndDeleteSomeItem_orderAndDeleteAreNotified4() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1), new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(2), new Cat(1), new Cat(0)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemMoved(2, 0); // 2, 0, 1 inOrder.verify(adapter).notifyItemMoved(2, 1); // 2, 1, 0 verifyNoMoreInteractions(adapter); } @Test public void testAfterInsertAtFirstPlace_firstPlaceIsMarkedAsInserted() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(0), new Cat(1)), true); verify(adapter).notifyItemRangeInserted(0, 1); } @Test public void testForce() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1)), true); verify(adapter).notifyItemRangeChanged(0, 1); } @Test public void testForce2() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), true); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemRangeChanged(0, 1); inOrder.verify(adapter).notifyItemRangeInserted(1, 1); } @Test public void testAddItemAtTheEnd() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), false); verify(adapter).notifyItemRangeInserted(1, 1); } @Test public void testAddTwoItemsAtTheEnd() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); verify(adapter).notifyItemRangeInserted(1, 2); } @Test public void testAddItemAtTheBegining() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(2)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), false); verify(adapter).notifyItemRangeInserted(0, 1); } @Test public void testAddTwoItemsAtTheBegining() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); verify(adapter).notifyItemRangeInserted(0, 2); } @Test public void testAddItemInTheMiddle() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); verify(adapter).notifyItemRangeInserted(1, 1); } @Test public void testAddTwoItemsInTheMiddle() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3), new Cat(4)), false); verify(adapter).notifyItemRangeInserted(1, 2); } @Test public void testItemChanged() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1).withName("one1"), new Cat(3)), false); verify(adapter).notifyItemRangeChanged(0, 1); } @Test public void testTwoItemsChangedAtStart() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1).withName("one1"), new Cat(2).withName("two1"), new Cat(3)), false); verify(adapter).notifyItemRangeChanged(0, 2); } @Test public void testTwoItemsChangedInMiddle() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2).withName("two1"), new Cat(3).withName("tree1"), new Cat(4)), false); verify(adapter).notifyItemRangeChanged(1, 2); } @Test public void testTwoItemsChangedAtTheEnd() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2).withName("two1"), new Cat(3).withName("tree1")), false); verify(adapter).notifyItemRangeChanged(1, 2); } @Test public void testItemDeleted1() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(2), new Cat(3)), false); verify(adapter).notifyItemRangeRemoved(0, 1); } @Test public void testItemDeleted2() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(3)), false); verify(adapter).notifyItemRangeRemoved(1, 1); } @Test public void testItemDeleted4() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(3), new Cat(4)), false); verify(adapter).notifyItemRangeRemoved(0, 2); } @Test public void testItemDeleted5() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(4)), false); verify(adapter).notifyItemRangeRemoved(1, 2); } @Test public void testItemDeleted6() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), false); verify(adapter).notifyItemRangeRemoved(2, 2); } @Test public void testItemDeleted3() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2)), false); verify(adapter).notifyItemRangeRemoved(2, 1); } @Test public void testItemSwapped() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(3)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(2), new Cat(3)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemRangeInserted(0, 1); // 2, 1, 3 inOrder.verify(adapter).notifyItemRangeRemoved(1, 1); // 2, 3 } @Test public void testItemSwappedTwo() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(5)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(3), new Cat(4), new Cat(5)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemRangeInserted(0, 2); // 3, 4, 1, 2, 5 inOrder.verify(adapter).notifyItemRangeRemoved(2, 2); // 3, 4, 5 } @Test public void testItemRemovedAndAdded() throws Exception { detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(4)), false); reset(adapter); detector.newData(adapter, ImmutableList.of(new Cat(2), new Cat(3), new Cat(4)), false); final InOrder inOrder = inOrder(adapter); inOrder.verify(adapter).notifyItemRangeInserted(0, 2); // 2, 1, 4, than // 2, 3, 1, 4 inOrder.verify(adapter).notifyItemRangeRemoved(2, 1); // 2, 3, 4 } }
3e1ed0989848dc9ee92bfe8c18d305f5091296db
3,674
java
Java
app/src/main/java/com/alaskalany/careershowcase/AppExecutors.java
AlAskalany/CareerShowcase
dfeac613756ef22e5de62d6d09b3b54607a7f729
[ "MIT" ]
1
2019-05-10T14:38:34.000Z
2019-05-10T14:38:34.000Z
app/src/main/java/com/alaskalany/careershowcase/AppExecutors.java
AlAskalany/CareerShowcase
dfeac613756ef22e5de62d6d09b3b54607a7f729
[ "MIT" ]
22
2018-11-03T11:55:59.000Z
2018-11-19T08:39:05.000Z
app/src/main/java/com/alaskalany/careershowcase/AppExecutors.java
AlAskalany/CareerShowcase
dfeac613756ef22e5de62d6d09b3b54607a7f729
[ "MIT" ]
1
2018-12-06T23:08:48.000Z
2018-12-06T23:08:48.000Z
28.703125
109
0.655144
13,031
/* * MIT License * * Copyright (c) 2018 Ahmed AlAskalany * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.alaskalany.careershowcase; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; /** * App {@link Executor}s */ public class AppExecutors { /** * Disk IO {@link Executor} */ private final Executor diskIoExecutor; /** * Network IO {@link Executor} */ private final Executor networkIoExecutor; /** * Main thread {@link Executor} */ private final Executor mainThreadExecutor; /** * App {@link Executor}s */ public AppExecutors() { this(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThreadExecutor()); } /** * @param diskIO Disk IO {@link Executor} * @param networkIO Network IO {@link Executor} * @param mainThread Main thread {@link Executor} */ private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) { this.diskIoExecutor = diskIO; this.networkIoExecutor = networkIO; this.mainThreadExecutor = mainThread; } /** * @return DisK IO {@link Executor} */ public Executor diskIO() { return diskIoExecutor; } /** * @return Network IO {@link Executor} */ public Executor networkIO() { return networkIoExecutor; } /** * @return Main thread {@link Executor} */ public Executor mainThread() { return mainThreadExecutor; } /** * Main thread {@link Executor} */ private static class MainThreadExecutor implements Executor { /** * Main thread handler */ private Handler mainThreadHandler = new Handler(Looper.getMainLooper()); /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the {@code Executor} implementation. * * @param command the runnable task * * @throws RejectedExecutionException if this task cannot be * accepted for execution * @throws NullPointerException if command is null */ @Override public void execute(@NonNull Runnable command) { mainThreadHandler.post(command); } } }
3e1ed0bc800d9b97a83d50383b3e9d0629c694b9
4,514
java
Java
testes_caso_uso/testes_use_case3/ControladorMetasTest.java
pedrohos/p2-psquiza
60463f4ce24d8764292167335e3ca44abd815b6c
[ "MIT" ]
1
2019-10-24T16:45:52.000Z
2019-10-24T16:45:52.000Z
testes_caso_uso/testes_use_case3/ControladorMetasTest.java
pedrohos/p2-psquiza
60463f4ce24d8764292167335e3ca44abd815b6c
[ "MIT" ]
3
2020-04-03T03:42:29.000Z
2020-04-03T03:42:39.000Z
testes_caso_uso/testes_use_case3/ControladorMetasTest.java
pedrohos/p2-psquiza
60463f4ce24d8764292167335e3ca44abd815b6c
[ "MIT" ]
null
null
null
22.913706
135
0.66615
13,032
package testes_use_case3; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import psquiza.controladores.ControladorMetas; class ControladorMetasTest { @Test void testCadastraProblemaDescricaoInvalida() { ControladorMetas cm = new ControladorMetas(); // Problema descricao vazia. try { cm.cadastraProblema("", 5); fail(""); } catch (Exception e) { assertTrue(true); } // Problema descricao nula. try { cm.cadastraProblema(null, 5); fail(""); } catch (Exception e) { assertTrue(true); } } @Test void testCadastraViabilidadeInvalida() { ControladorMetas cm = new ControladorMetas(); // Valor de viabilidade inválido abaixo. try { cm.cadastraProblema("Preconceito contra racistas", 0); fail(""); } catch (Exception e) { assertTrue(true); } // Valor de viabilidade inválido acima. try { cm.cadastraProblema("Preconceito contra racistas", 6); fail(""); } catch (Exception e) { assertTrue(true); } } @Test void testConstroiObjetivoTipoInvalido() { ControladorMetas cm = new ControladorMetas(); // Objetivo com tipo vazio try { cm.cadastraObjetivo("", "Ajudar animais ameacados pelo vazamento de petroleo", 3, 4); fail(""); } catch (Exception e) { } // Objetivo com tipo nulo try { cm.cadastraObjetivo(null, "Ajudar animais ameacados pelo vazamento de petroleo", 3, 4); fail(""); } catch (Exception e) { } } @Test void testConstroiObjetivoDescricaoInvalido() { ControladorMetas cm = new ControladorMetas(); // Objetivo com descicao vazia try { cm.cadastraObjetivo("ESPECIFICO", "", 3, 4); fail(""); } catch (Exception e) { } // Objetivo com descricao nula try { cm.cadastraObjetivo("ESPECIFICO", null, 3, 4); fail(""); } catch (Exception e) { } } @Test void testConstroiObjetivoAderenciaInvalida() { ControladorMetas cm = new ControladorMetas(); // Objetivo com aderencia abaixo do limite try { cm.cadastraObjetivo("ESPECIFICO", "Ajudar animais ameacados pelo vazamento de petroleo", 0, 4); fail(""); } catch (Exception e) { } // Objetivo com aderencia acima do limite try { cm.cadastraObjetivo("ESPECIFICO", "Ajudar animais ameacados pelo vazamento de petroleo", 6, 4); fail(""); } catch (Exception e) { } } @Test void testConstroiObjetivoViabilidadeInvalido() { ControladorMetas cm = new ControladorMetas(); // Objetivo com viabilidade abaixo do limite try { cm.cadastraObjetivo("ESPECIFICO", "Ajudar animais ameacados pelo vazamento de petroleo", 3, 0); fail(""); } catch (Exception e) { } // Objetivo com viabilidade acima do limite try { cm.cadastraObjetivo("ESPECIFICO", "Ajudar animais ameacados pelo vazamento de petroleo", 3, 6); fail(""); } catch (Exception e) { } } @Test void testCadastraProblema() { ControladorMetas cm = new ControladorMetas(); cm.cadastraProblema("Racismo", 5); cm.cadastraProblema("Preconceito racial", 4); cm.cadastraProblema("Intolerancia contra pessoas negras", 3); cm.cadastraProblema("Preocupacao por classes oprimidas pelo seu status social marcado pelo nascimento oprimido", 3); cm.cadastraProblema("Falta de consciencia sobre o estado social vivenciado pelas pessoas com cor de pele diferente da dominante", 1); } @Test void exibeProblema() { ControladorMetas cm = new ControladorMetas(); cm.cadastraProblema("Desligar freezer por 12h", 3); assertEquals(cm.exibeProblema("P1"), "P1 - Desligar freezer por 12h - 3"); } @Test void exibeObjetivo() { ControladorMetas cm = new ControladorMetas(); cm.cadastraObjetivo("GERAL", "Trocar a placa Saborear", 5, 4); assertEquals(cm.exibeObjetivo("O1"), "O1 - GERAL - Trocar a placa Saborear - 9"); } @Test void apagaProblema() { ControladorMetas cm = new ControladorMetas(); cm.cadastraProblema("Desligar freezer por 12h", 3); try { cm.exibeProblema("P1"); } catch (Exception e) { fail(""); } cm.apagarProblema("P1"); try { cm.exibeProblema("P1"); fail(""); } catch (Exception e) { } } @Test void apagaObjetivo() { ControladorMetas cm = new ControladorMetas(); cm.cadastraObjetivo("GERAL", "Trocar a placa Saborear", 5, 4); try { cm.exibeObjetivo("O1"); } catch (Exception e) { fail(""); } cm.apagarObjetivo("O1"); try { cm.exibeObjetivo("O1"); fail(""); } catch (Exception e) { } } }
3e1ed0e100daac906e92f7d1eee03e55689071b4
1,184
java
Java
leetcode/src/com/github/extermania/leetcode/$0155_Min_Stack_18_63.java
extremania/leetcode
70e1b01127c6f8a24cc521526befc5bea214f93f
[ "Apache-2.0" ]
1
2019-02-28T14:36:03.000Z
2019-02-28T14:36:03.000Z
leetcode/src/com/github/extermania/leetcode/$0155_Min_Stack_18_63.java
extremania/leetcode
70e1b01127c6f8a24cc521526befc5bea214f93f
[ "Apache-2.0" ]
null
null
null
leetcode/src/com/github/extermania/leetcode/$0155_Min_Stack_18_63.java
extremania/leetcode
70e1b01127c6f8a24cc521526befc5bea214f93f
[ "Apache-2.0" ]
null
null
null
21.142857
49
0.414696
13,033
package com.github.extermania.leetcode; import java.util.ArrayList; import java.util.List; public class $0155_Min_Stack_18_63 { class MinStack { List<Integer> list = new ArrayList<>(); int min=Integer.MAX_VALUE; int minCnt=0; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(list.size()==0){ min = x; minCnt=1; }else{ if(x==min) minCnt++; else if(x<min){ min=x; minCnt=1; } } list.add(x); } public void pop() { if(list.size()==0) return; int r = list.remove(list.size()-1); if(r==min){ minCnt--; } if(minCnt==0){ min=Integer.MAX_VALUE; minCnt=1; for(int i:list){ min=Math.min(min, i); } } } public int top() { return list.get(list.size()-1); } public int getMin() { return min; } } }
3e1ed30ef9f9d99c18133980455ca8384569c23d
323
java
Java
ttscoupe-boot-module-system/src/main/java/org/ttscoupe/modules/system/mapper/SysPositionMapper.java
ttscoupe/springboot
019d4a036bd4a47a6ee676952d592bbdcb936b6f
[ "MIT" ]
null
null
null
ttscoupe-boot-module-system/src/main/java/org/ttscoupe/modules/system/mapper/SysPositionMapper.java
ttscoupe/springboot
019d4a036bd4a47a6ee676952d592bbdcb936b6f
[ "MIT" ]
1
2022-02-16T01:03:33.000Z
2022-02-16T01:03:33.000Z
ttscoupe-boot-module-system/src/main/java/org/ttscoupe/modules/system/mapper/SysPositionMapper.java
ttscoupe/springboot
019d4a036bd4a47a6ee676952d592bbdcb936b6f
[ "MIT" ]
null
null
null
21.533333
68
0.76161
13,034
package org.ttscoupe.modules.system.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.ttscoupe.modules.system.entity.SysPosition; /** * @Description: 职务表 * @Author: ttscoupe-boot * @Date: 2019-09-19 * @Version: V1.0 */ public interface SysPositionMapper extends BaseMapper<SysPosition> { }
3e1ed431a4a92c12b769a561dd6699a8dc1aff2d
1,159
java
Java
officefloor/core/officeframe/src/main/test/net/officefloor/frame/test/TestSupport.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
17
2019-09-30T08:23:01.000Z
2021-12-20T04:51:03.000Z
officefloor/core/officeframe/src/main/test/net/officefloor/frame/test/TestSupport.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
880
2019-07-08T04:31:14.000Z
2022-03-16T20:16:03.000Z
officefloor/core/officeframe/src/main/test/net/officefloor/frame/test/TestSupport.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
3
2019-09-30T08:22:37.000Z
2021-10-13T10:05:24.000Z
25.755556
75
0.709232
13,035
/*- * #%L * OfficeFrame * %% * Copyright (C) 2005 - 2020 Daniel Sagenschneider * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package net.officefloor.frame.test; import org.junit.jupiter.api.extension.ExtensionContext; /** * <p> * Test support object. * <p> * {@link TestSupportExtension} will invoke this to enable the * {@link TestSupport} instance to initialise itself. * * @author Daniel Sagenschneider */ public interface TestSupport { /** * Intialise. * * @param context {@link ExtensionContext}. * @throws Exception If fails to init. */ void init(ExtensionContext context) throws Exception; }
3e1ed4a9bc978bd2b5fb1386c1931ab142c12bc2
2,925
java
Java
Ghidra/Features/Base/ghidra_scripts/BatchSegregate64bit.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Features/Base/ghidra_scripts/BatchSegregate64bit.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Features/Base/ghidra_scripts/BatchSegregate64bit.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
3
2019-12-02T13:36:50.000Z
2019-12-04T05:40:12.000Z
30.154639
76
0.705983
13,036
/* ### * IP: GHIDRA * * 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. */ //Separates co-mingled n-bit and 64-bit binaries into two folder trees. //@category Project //@menupath import java.io.IOException; import java.util.Map; import ghidra.app.script.GhidraScript; import ghidra.framework.model.*; import ghidra.util.InvalidNameException; public class BatchSegregate64bit extends GhidraScript { public BatchSegregate64bit() { } @Override public void run() throws Exception { if (currentProgram != null) { popup("This script should be run from a tool with no open programs"); return; } DomainFolder rootFolder32 = askProjectFolder("Choose root folder to recursively 'segregate'"); DomainFolder projRoot = rootFolder32.getProjectData().getRootFolder(); String rootFolder32Str = rootFolder32.getPathname() + "/"; String rootFolder64Str = rootFolder32.getPathname() + "-x64/"; long start_ts = System.currentTimeMillis(); monitor.initialize(0); monitor.setIndeterminate(true); int filesProcessed = 0; for (DomainFile file : ProjectDataUtils.descendantFiles(rootFolder32)) { if (monitor.isCancelled()) { break; } Map<String, String> metadata = file.getMetadata(); String langId = metadata.get("Language ID"); if (langId != null && langId.indexOf(":64:") != -1) { String origName = file.getPathname(); DomainFolder destFolder = resolvePath(projRoot, rootFolder64Str + file.getParent().getPathname().substring(rootFolder32Str.length()), true); DomainFile newFile = file.moveTo(destFolder); println("Moved " + origName + " to " + newFile.getPathname()); filesProcessed++; } } long end_ts = System.currentTimeMillis(); println("Finished segregating for folder: " + rootFolder32.getPathname()); println("Total files: " + filesProcessed); println("Total time: " + (end_ts - start_ts)); } public static DomainFolder resolvePath(DomainFolder folder, String path, boolean createIfMissing) throws InvalidNameException, IOException { String[] pathParts = path.split("/"); for (String part : pathParts) { if (part.isEmpty()) { continue; } DomainFolder subfolder = folder.getFolder(part); if (subfolder == null && createIfMissing) { subfolder = folder.createFolder(part); } if (subfolder == null) { return null; } folder = subfolder; } return folder; } }
3e1ed636823108fe302c321028ab98948ef91d18
34,249
java
Java
modeshape-jcr/src/main/java/org/modeshape/jcr/cache/document/ImmutableChildReferences.java
mbklein/modeshape
25064c2345bafbe7c313e3a3f5d95ef9bcbc0837
[ "Apache-2.0" ]
120
2015-01-05T06:30:23.000Z
2022-03-22T12:25:33.000Z
modeshape-jcr/src/main/java/org/modeshape/jcr/cache/document/ImmutableChildReferences.java
mbklein/modeshape
25064c2345bafbe7c313e3a3f5d95ef9bcbc0837
[ "Apache-2.0" ]
286
2015-01-02T15:17:09.000Z
2022-01-21T23:22:14.000Z
modeshape-jcr/src/main/java/org/modeshape/jcr/cache/document/ImmutableChildReferences.java
mbklein/modeshape
25064c2345bafbe7c313e3a3f5d95ef9bcbc0837
[ "Apache-2.0" ]
131
2015-01-07T17:45:46.000Z
2021-11-11T14:11:30.000Z
38.096774
164
0.499314
13,037
/* * ModeShape (http://www.modeshape.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.modeshape.jcr.cache.document; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.modeshape.schematic.document.Document; import org.modeshape.common.annotation.Immutable; import org.modeshape.common.collection.EmptyIterator; import org.modeshape.jcr.cache.ChildReference; import org.modeshape.jcr.cache.ChildReferences; import org.modeshape.jcr.cache.DocumentNotFoundException; import org.modeshape.jcr.cache.NodeKey; import org.modeshape.jcr.cache.document.DocumentTranslator.ChildReferencesInfo; import org.modeshape.jcr.value.Name; import org.modeshape.jcr.value.NamespaceRegistry; /** * */ public class ImmutableChildReferences { protected static final ChildReferences EMPTY_CHILD_REFERENCES = EmptyChildReferences.INSTANCE; protected static final Iterator<ChildReference> EMPTY_ITERATOR = new EmptyIterator<ChildReference>(); protected static final Iterator<NodeKey> EMPTY_KEY_ITERATOR = new EmptyIterator<NodeKey>(); public static ChildReferences create( DocumentTranslator documentTranslator, Document document, String childrenFieldName, boolean allowsSNS) { return new Medium(documentTranslator, document, childrenFieldName, allowsSNS); } public static ChildReferences union( ChildReferences first, ChildReferences second ) { long firstSize = first.size(); long secondSize = second.size(); if (firstSize == 0 && secondSize == 0) { return EMPTY_CHILD_REFERENCES; } else if (firstSize == 0) { return second; } else if (secondSize == 0) { return first; } return new ReferencesUnion(first, second); } public static ChildReferences create( ChildReferences first, ChildReferencesInfo firstSegmentingInfo, WorkspaceCache cache, boolean allowsSNS) { if (firstSegmentingInfo == null || firstSegmentingInfo.nextKey == null) return first; return new Segmented(cache, first, firstSegmentingInfo, allowsSNS); } public static ChildReferences create( ChildReferences first, ChildReferencesInfo firstSegmentingInfo, ChildReferences second, WorkspaceCache cache, boolean allowsSNS) { if (firstSegmentingInfo == null || firstSegmentingInfo.nextKey == null) return union(first, second); Segmented segmentedReferences = new Segmented(cache, first, firstSegmentingInfo, allowsSNS); return union(segmentedReferences, second); } @Immutable protected final static class EmptyChildReferences implements ChildReferences { public static final ChildReferences INSTANCE = new EmptyChildReferences(); private EmptyChildReferences() { } @Override public boolean supportsGetChildReferenceByKey() { return true; } @Override public long size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public int getChildCount( Name name ) { return 0; } @Override public ChildReference getChild( Name name ) { return null; } @Override public ChildReference getChild( Name name, int snsIndex ) { return null; } @Override public ChildReference getChild( Name name, int snsIndex, Context context ) { return null; } @Override public ChildReference getChild( org.modeshape.jcr.value.Path.Segment segment ) { return null; } @Override public ChildReference getChild( NodeKey key ) { return null; } @Override public ChildReference getChild( NodeKey key, Context context ) { return null; } @Override public boolean hasChild( NodeKey key ) { return false; } @Override public Iterator<ChildReference> iterator() { return EMPTY_ITERATOR; } @Override public Iterator<ChildReference> iterator( Name name ) { return EMPTY_ITERATOR; } @Override public Iterator<ChildReference> iterator( Name name, Context context ) { return EMPTY_ITERATOR; } @Override public Iterator<ChildReference> iterator( Context context ) { return EMPTY_ITERATOR; } @Override public Iterator<ChildReference> iterator( Collection<?> namePatterns, NamespaceRegistry registry ) { return EMPTY_ITERATOR; } @Override public Iterator<ChildReference> iterator( Context context, Collection<?> namePatterns, NamespaceRegistry registry ) { return EMPTY_ITERATOR; } @Override public Iterator<NodeKey> getAllKeys() { return EMPTY_KEY_ITERATOR; } @Override public boolean allowsSNS() { return false; } } @Immutable protected static final class Medium extends AbstractChildReferences { private final Map<NodeKey, ChildReference> childReferencesByKey; private final Map<Name, List<NodeKey>> childKeysByName; private final boolean allowsSNS; protected Medium( DocumentTranslator documentTranslator, Document document, String childrenFieldName, boolean allowsSNS) { this.allowsSNS = allowsSNS; this.childKeysByName = new HashMap<>(); this.childReferencesByKey = new LinkedHashMap<>(); final List<?> documentArray = document.getArray(childrenFieldName); if (documentArray == null || documentArray.isEmpty()) { return; } for (Object value : documentArray) { ChildReference ref = documentTranslator.childReferenceFrom(value); if (ref == null) { continue; } Name refName = ref.getName(); NodeKey refKey = ref.getKey(); ChildReference old = this.childReferencesByKey.get(refKey); if (old != null && old.getName().equals(ref.getName())) { // We already have this key/name pair, so we don't need to add it again ... continue; } // We've not seen this NodeKey/Name combination yet, so it is okay. In fact, we should not see any // node key more than once, since that is clearly an unexpected condition (as a child may not appear // more than once in its parent's list of child nodes). See MODE-2120. // we can precompute the SNS index up front List<NodeKey> keysWithName = this.childKeysByName.get(refName); if (allowsSNS) { int currentSNS = keysWithName != null ? this.childKeysByName.get(refName).size() : 0; ChildReference refWithSNS = ref.with(currentSNS + 1); this.childReferencesByKey.put(refKey, refWithSNS); } else { this.childReferencesByKey.put(refKey, ref); } if (keysWithName == null) { keysWithName = new ArrayList<>(); this.childKeysByName.put(refName, keysWithName); } keysWithName.add(refKey); } } @Override public long size() { return childReferencesByKey.size(); } @Override public int getChildCount( Name name ) { List<NodeKey> nodeKeys = childKeysByName.get(name); return nodeKeys != null ? nodeKeys.size() : 0; } @Override public ChildReference getChild( Name name, int snsIndex, Context context ) { if (!allowsSNS && snsIndex > 1) { return null; } Changes changes = null; Iterator<ChildInsertions> insertions = null; boolean includeRenames = false; if (context == null) { context = new SingleNameContext(); } else { changes = context.changes(); // may still be null if (changes != null) { insertions = changes.insertions(name); includeRenames = changes.isRenamed(name); } } List<NodeKey> childrenWithSameName = this.childKeysByName.get(name); if (changes == null) { if (childrenWithSameName == null) { return null; } // there are no changes, so we can take advantage of the fact that we precomputed the SNS indexes up front... if (snsIndex > childrenWithSameName.size()) { return null; } NodeKey childKey = childrenWithSameName.get(snsIndex - 1); return childReferencesByKey.get(childKey); } // there are changes, so there is some extra processing to be done... if (childrenWithSameName == null && !includeRenames) { // This segment contains no nodes with the supplied name ... if (insertions == null) { // and no nodes with this name were inserted ... return null; } // But there is at least one inserted node with this name ... while (insertions.hasNext()) { ChildInsertions inserted = insertions.next(); Iterator<ChildReference> iter = inserted.inserted().iterator(); while (iter.hasNext()) { ChildReference result = iter.next(); int index = context.consume(result.getName(), result.getKey()); if (index == snsIndex) return result.with(index); } } return null; } // This collection contains at least one node with the same name ... if (insertions != null || includeRenames) { // The logic for this would involve iteration to find the indexes, so we may as well just iterate ... Iterator<ChildReference> iter = iterator(context, name); while (iter.hasNext()) { ChildReference ref = iter.next(); if (ref.getSnsIndex() == snsIndex) return ref; } return null; } // We have at least one SNS in this list (and still potentially some removals) ... for (NodeKey key : childrenWithSameName) { ChildReference childWithSameName = childReferencesByKey.get(key); if (changes.isRemoved(childWithSameName)) { continue; } if (changes.isRenamed(childWithSameName)) { continue; } // we've already precomputed the SNS index if (snsIndex == childWithSameName.getSnsIndex()) { return childWithSameName; } } return null; } @Override public ChildReference getChild( NodeKey key, Context context ) { ChildReference ref = childReferencesByKey.get(key); if (ref == null) { // Not in our list, so check the context for changes ... if (context != null) { Changes changes = context.changes(); if (changes != null) { ref = changes.inserted(key); if (ref != null) { // The requested node was inserted, so figure out the SNS index. // Unfortunately, this would require iteration (to figure out the indexes), so the // easiest/fastest way is (surprisingly) to just iterate ... Iterator<ChildReference> iter = iterator(context, ref.getName()); while (iter.hasNext()) { ChildReference child = iter.next(); if (child.getKey().equals(key)) return child; } // Shouldn't really happen ... } } // Not in list and no changes, so return ... } } else { // It's in our list, but if there are changes we need to use the context ... if (context != null) { Changes changes = context.changes(); if (changes != null) { boolean renamed = false; if (changes.isRenamed(ref)) { // The node was renamed, so get the new name ... Name newName = changes.renamed(key); ref = ref.with(newName, 1); renamed = true; } Iterator<ChildInsertions> insertions = changes.insertions(ref.getName()); if (insertions != null || renamed) { // We're looking for a node that was not inserted but has the same name as those that are // (perhaps have renaming). As painful as it is, the easiest and most-efficient way to get // this is to iterate ... Iterator<ChildReference> iter = iterator(context, ref.getName()); while (iter.hasNext()) { ChildReference child = iter.next(); if (child.getKey().equals(key)) return child; } } // check if the node was removed only at the end to that insertions before can be processed first if (changes.isRemoved(ref)) { // The node was removed ... return null; } } } } return ref; } @Override public ChildReference getChild( NodeKey key ) { // we should already have precomputed the correct SNS at the beginning return childReferencesByKey.get(key); } @Override public boolean hasChild( NodeKey key ) { return childReferencesByKey.containsKey(key); } @Override public Iterator<ChildReference> iterator( Name name ) { // the child references should already have the correct SNS precomputed List<NodeKey> childKeys = childKeysByName.get(name); if (childKeys == null || childKeys.isEmpty()) { return Collections.emptyIterator(); } final Iterator<NodeKey> childKeysIterator = childKeys.iterator(); return new Iterator<ChildReference>() { @Override public boolean hasNext() { return childKeysIterator.hasNext(); } @Override public ChildReference next() { return childReferencesByKey.get(childKeysIterator.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Iterator<ChildReference> iterator() { // the child references should already have the correct SNS precomputed return childReferencesByKey.values().iterator(); } @Override public Iterator<ChildReference> iterator( Name name, Context context ) { if (context != null && context.changes() != null) { // we only want the context-sensitive behavior if there are changes. Otherwise we've already precomputed the SNS // index return super.iterator(name, context); } return iterator(name); } @Override public Iterator<ChildReference> iterator( Context context ) { if (context != null && context.changes() != null) { // we only want the context-sensitive behavior if there are changes. Otherwise we've already precomputed the SNS // index return super.iterator(context); } return iterator(); } @Override public Iterator<NodeKey> getAllKeys() { return childReferencesByKey.keySet().iterator(); } @Override public StringBuilder toString( StringBuilder sb ) { Iterator<ChildReference> iter = childReferencesByKey.values().iterator(); if (iter.hasNext()) { sb.append(iter.next()); while (iter.hasNext()) { sb.append(", "); sb.append(iter.next()); } } return sb; } @Override public boolean allowsSNS() { return allowsSNS; } } @Immutable public static class Segmented extends AbstractChildReferences { protected final WorkspaceCache cache; protected final long totalSize; protected final boolean allowsSNS; private Segment firstSegment; public Segmented( WorkspaceCache cache, ChildReferences firstSegment, ChildReferencesInfo info, boolean allowsSNS) { this.cache = cache; this.totalSize = info.totalSize; this.firstSegment = new Segment(firstSegment, info.nextKey, allowsSNS); this.allowsSNS = allowsSNS; } @Override public long size() { return totalSize; } @Override public boolean supportsGetChildReferenceByKey() { return size() != ChildReferences.UNKNOWN_SIZE; } @Override public int getChildCount( Name name ) { int result = 0; Segment segment = this.firstSegment; while (segment != null) { result += segment.getReferences().getChildCount(name); segment = segment.next(cache); } return result; } @Override public ChildReference getChild( Name name, int snsIndex, Context context ) { ChildReference result = null; Segment segment = this.firstSegment; while (segment != null) { result = segment.getReferences().getChild(name, snsIndex, context); if (result != null) { return result; } segment = segment.next(cache); } return result; } @Override public boolean hasChild( NodeKey key ) { Segment segment = this.firstSegment; while (segment != null) { if (segment.getReferences().hasChild(key)) { return true; } segment = segment.next(cache); } return false; } @Override public ChildReference getChild( NodeKey key ) { return getChild(key, defaultContext()); } @Override public ChildReference getChild( NodeKey key, Context context ) { ChildReference result = null; Segment segment = this.firstSegment; while (segment != null) { result = segment.getReferences().getChild(key, context); if (result != null) { return result; } segment = segment.next(cache); } return result; } @Override public Iterator<ChildReference> iterator( final Name name, final Context context ) { final Segment firstSegment = this.firstSegment; return new Iterator<ChildReference>() { private Segment segment = firstSegment; private Iterator<ChildReference> iter = segment != null ? segment.getReferences().iterator(name, context) : ImmutableChildReferences.EMPTY_ITERATOR; private ChildReference next; @Override public boolean hasNext() { if (next != null) { // Called 'hasNext()' multiple times in a row ... return true; } if (!iter.hasNext()) { while (segment != null) { segment = segment.next(cache); if (segment != null) { iter = segment.getReferences().iterator(name, context); if (iter.hasNext()) { next = iter.next(); return true; } } } return false; } next = iter.next(); return true; } @Override public ChildReference next() { try { if (next == null) { if (hasNext()) return next; throw new NoSuchElementException(); } return next; } finally { next = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Iterator<ChildReference> iterator( final Context context ) { final Segment firstSegment = this.firstSegment; return new Iterator<ChildReference>() { private Segment segment = firstSegment; private Iterator<ChildReference> iter = segment != null ? segment.getReferences().iterator(context) : ImmutableChildReferences.EMPTY_ITERATOR; private ChildReference next; @Override public boolean hasNext() { if (next != null) { // Called 'hasNext()' multiple times in a row ... return true; } if (!iter.hasNext()) { while (segment != null) { segment = segment.next(cache); if (segment != null) { iter = segment.getReferences().iterator(context); if (iter.hasNext()) { next = iter.next(); return true; } } } return false; } next = iter.next(); return true; } @Override public ChildReference next() { try { if (next == null) { if (hasNext()) return next; throw new NoSuchElementException(); } return next; } finally { next = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Iterator<NodeKey> getAllKeys() { final Segment firstSegment = this.firstSegment; return new Iterator<NodeKey>() { private Segment segment = firstSegment; private Iterator<NodeKey> iter = segment != null ? segment.keys() : ImmutableChildReferences.EMPTY_KEY_ITERATOR; private NodeKey next; @Override public boolean hasNext() { if (!iter.hasNext()) { while (segment != null) { segment = segment.next(cache); if (segment != null) { iter = segment.keys(); if (iter.hasNext()) { next = iter.next(); return true; } } } return false; } next = iter.next(); return true; } @Override public NodeKey next() { try { if (next == null) { if (hasNext()) return next; throw new NoSuchElementException(); } return next; } finally { next = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @SuppressWarnings( "synthetic-access" ) @Override public StringBuilder toString( StringBuilder sb ) { Segment segment = firstSegment; while (segment != null) { segment.toString(sb); if (segment.next != null) { // there is already a loaded segment ... sb.append(", "); } else if (segment.nextKey != null) { // there is a segment, but it hasn't yet been loaded ... sb.append(", <segment=").append(segment.nextKey).append('>'); } segment = segment.next; } return sb; } @Override public boolean allowsSNS() { return allowsSNS; } } public static class ReferencesUnion extends AbstractChildReferences { private final ChildReferences firstReferences; protected final ChildReferences secondReferences; ReferencesUnion( ChildReferences firstReferences, ChildReferences secondReferences ) { this.firstReferences = firstReferences; this.secondReferences = secondReferences; } @Override public long size() { return secondReferences.size() + firstReferences.size(); } @Override public int getChildCount( Name name ) { return secondReferences.getChildCount(name) + firstReferences.getChildCount(name); } @Override public ChildReference getChild( Name name, int snsIndex, Context context ) { ChildReference firstReferencesChild = firstReferences.getChild(name, snsIndex, context); if (firstReferencesChild != null) { return firstReferencesChild; } return secondReferences.getChild(name, snsIndex, context); } @Override public boolean hasChild( NodeKey key ) { return secondReferences.hasChild(key) || firstReferences.hasChild(key); } @Override public ChildReference getChild( NodeKey key ) { return getChild(key, defaultContext()); } @Override public ChildReference getChild( NodeKey key, Context context ) { ChildReference firstReferencesChild = firstReferences.getChild(key, context); if (firstReferencesChild != null) { return firstReferencesChild; } return secondReferences.getChild(key, context); } @Override public Iterator<ChildReference> iterator() { return new UnionIterator<ChildReference>(firstReferences.iterator(), secondReferences); } @Override public Iterator<ChildReference> iterator( final Name name ) { Iterable<ChildReference> second = new Iterable<ChildReference>() { @Override public Iterator<ChildReference> iterator() { return secondReferences.iterator(name); } }; return new UnionIterator<ChildReference>(firstReferences.iterator(name), second); } @Override public Iterator<NodeKey> getAllKeys() { Set<NodeKey> externalKeys = new HashSet<NodeKey>(); for (Iterator<NodeKey> externalKeysIterator = secondReferences.getAllKeys(); externalKeysIterator.hasNext();) { externalKeys.add(externalKeysIterator.next()); } return new UnionIterator<NodeKey>(firstReferences.getAllKeys(), externalKeys); } @Override public StringBuilder toString( StringBuilder sb ) { sb.append("<second references=").append(secondReferences.toString()); sb.append(">, <first references=").append(firstReferences.toString()).append(">"); return sb; } @Override public boolean allowsSNS() { return firstReferences.allowsSNS() || secondReferences.allowsSNS(); } } protected static class Segment { private final ChildReferences references; private final String nextKey; private final boolean allowsSNS; private Segment next; protected Segment( ChildReferences references, String nextKey, boolean allowsSNS) { this.nextKey = nextKey; this.references = references; this.allowsSNS = allowsSNS; } public ChildReferences getReferences() { return this.references; } public Segment next( WorkspaceCache cache ) { if (next == null && nextKey != null) { Document blockDoc = cache.blockFor(nextKey); if (blockDoc == null) { throw new DocumentNotFoundException(nextKey); } // we only need the direct children of the block to avoid nesting ChildReferences refs = cache.translator().getChildReferencesFromBlock(blockDoc, allowsSNS); ChildReferencesInfo nextNextKey = cache.translator().getChildReferencesInfo(blockDoc); next = new Segment(refs, nextNextKey != null ? nextNextKey.nextKey : null, allowsSNS); } return next; } public Iterator<NodeKey> keys() { return references.getAllKeys(); } @Override public String toString() { return toString(new StringBuilder()).toString(); } public StringBuilder toString( StringBuilder sb ) { Iterator<ChildReference> iter = references.iterator(); if (iter.hasNext()) { sb.append(iter.next()); while (iter.hasNext()) { sb.append(", "); sb.append(iter.next()); } } return sb; } } }
3e1ed6ac616440d77507776c68947bcb61527de8
3,841
java
Java
processor/src/main/java/com/linecorp/decaton/processor/tracing/TracingProvider.java
arhont375/decaton
4d48d4a314d9f603f8121c22570be7069e0b7c3c
[ "Apache-2.0" ]
245
2020-03-13T06:58:19.000Z
2022-03-25T07:40:29.000Z
processor/src/main/java/com/linecorp/decaton/processor/tracing/TracingProvider.java
arhont375/decaton
4d48d4a314d9f603f8121c22570be7069e0b7c3c
[ "Apache-2.0" ]
89
2020-03-13T06:40:46.000Z
2022-03-31T20:29:51.000Z
processor/src/main/java/com/linecorp/decaton/processor/tracing/TracingProvider.java
ryamagishi/decaton
9389900281cc7019d4a6659b9bb788fcd99fed6a
[ "Apache-2.0" ]
39
2020-03-13T07:26:16.000Z
2022-03-08T14:35:47.000Z
44.662791
110
0.712054
13,038
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.decaton.processor.tracing; import org.apache.kafka.clients.consumer.ConsumerRecord; import com.linecorp.decaton.client.KafkaProducerSupplier; import com.linecorp.decaton.processor.DecatonProcessor; import com.linecorp.decaton.processor.DeferredCompletion; import com.linecorp.decaton.processor.ProcessingContext; import com.linecorp.decaton.processor.runtime.RetryConfig; /** * Interface for distributed tracing implementations that track traces via Kafka {@link ConsumerRecord}s * (typically through Kafka headers) e.g. Zipkin, OpenTracing, Kamon. * Note that this will usually need to be paired with a suitable {@link KafkaProducerSupplier} on the producer * side to write those Kafka headers. * In particular, if you want retries to be shown as part of the same (distributed) trace, make sure to supply * such a {@link KafkaProducerSupplier} in your {@link RetryConfig}. */ public interface TracingProvider { interface TraceHandle { /** * Invoked when processing is considered complete (whether normally or exceptionally). * This will be invoked by the thread that calls {@link DeferredCompletion#complete()}, * or a decaton thread if processing was synchronous * (i.e. {@link ProcessingContext#deferCompletion()} was never called). */ void processingCompletion(); } /** * Handle for tracing the execution of a specific {@link DecatonProcessor} */ interface ProcessorTraceHandle extends TraceHandle { /** * Invoked by the thread that will perform processing immediately before processing * Implementations may wish to associate the passed trace with the current thread * (e.g. using a {@link ThreadLocal}) for use during {@link DecatonProcessor} execution */ void processingStart(); /** * Invoked by the thread that performed processing immediately after *synchronous* processing finishes * (whether normally or exceptionally). * Implementations that associated this trace with the current thread in {@link #processingStart} * should dissociate it here. * Note that processing associated with this trace/record may continue (on other threads) * for some time after this call in the case of an asynchronous processor. */ void processingReturn(); } interface RecordTraceHandle extends TraceHandle { /** * @return A handle for tracing the execution of the given processor. * The returned trace will likely capture some details of this processor * e.g. its {@link DecatonProcessor#name()}. */ ProcessorTraceHandle childFor(DecatonProcessor<?> processor); } /** * Invoked as soon as we poll the record from Kakfa * (generally not from the thread that will be responsible for processing this record) * * @return an implementation-specific value to use when tracing processing of the given record. * The returned {@link TraceHandle} must be thread-safe. */ RecordTraceHandle traceFor(ConsumerRecord<?, ?> record, String subscriptionId); }
3e1ed841cdefbcbe516d990e86ce8c95759a3d40
2,634
java
Java
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataNodeConnectionHandler.java
wilsonvolker/sofa-registry
db4fce5a0415ffc021312ef6736edfdc03184764
[ "Apache-2.0" ]
361
2019-05-14T09:07:59.000Z
2022-03-30T09:46:18.000Z
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataNodeConnectionHandler.java
wilsonvolker/sofa-registry
db4fce5a0415ffc021312ef6736edfdc03184764
[ "Apache-2.0" ]
175
2019-05-20T04:16:58.000Z
2022-03-31T13:36:52.000Z
server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataNodeConnectionHandler.java
wilsonvolker/sofa-registry
db4fce5a0415ffc021312ef6736edfdc03184764
[ "Apache-2.0" ]
156
2019-05-14T09:38:07.000Z
2022-03-31T07:38:48.000Z
38.735294
94
0.744115
13,039
/* * 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.alipay.sofa.registry.server.session.remoting.handler; import org.springframework.beans.factory.annotation.Autowired; import com.alipay.sofa.registry.common.model.Node.NodeType; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.remoting.RemotingException; import com.alipay.sofa.registry.server.session.registry.SessionRegistry; import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListenerManager; /** * * @author shangyu.wh * @version $Id: ClientConnectionHandler.java, v 0.1 2017-12-08 20:17 shangyu.wh Exp $ */ public class DataNodeConnectionHandler extends AbstractClientHandler { private static final Logger taskLogger = LoggerFactory.getLogger(SessionRegistry.class, "[Task]"); /** * trigger task com.alipay.sofa.registry.server.meta.listener process */ @Autowired private TaskListenerManager taskListenerManager; @Override public HandlerType getType() { return HandlerType.LISENTER; } @Override public void connected(Channel channel) throws RemotingException { super.connected(channel); fireRegisterProcessIdTask(channel); } @Override protected NodeType getConnectNodeType() { return NodeType.DATA; } private void fireRegisterProcessIdTask(Channel boltChannel) { TaskEvent taskEvent = new TaskEvent(boltChannel, TaskType.SESSION_REGISTER_DATA_TASK); taskLogger.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); taskListenerManager.sendTaskEvent(taskEvent); } }
3e1ed925ddd70f1a0ccef0a842c261f4574b9048
6,757
java
Java
plugins/com.google.cloud.tools.eclipse.swtbot/src/com/google/cloud/tools/eclipse/swtbot/SwtBotTestingUtilities.java
chanseokoh/google-cloud-eclipse
418b4bc88c446afe31eb87e6d54d475ebfc3a931
[ "Apache-2.0" ]
80
2016-10-09T10:28:00.000Z
2022-01-21T15:43:22.000Z
plugins/com.google.cloud.tools.eclipse.swtbot/src/com/google/cloud/tools/eclipse/swtbot/SwtBotTestingUtilities.java
chanseokoh/google-cloud-eclipse
418b4bc88c446afe31eb87e6d54d475ebfc3a931
[ "Apache-2.0" ]
2,802
2016-09-26T16:44:53.000Z
2022-03-16T03:50:13.000Z
plugins/com.google.cloud.tools.eclipse.swtbot/src/com/google/cloud/tools/eclipse/swtbot/SwtBotTestingUtilities.java
isabella232/google-cloud-eclipse
4d213f59421f7d28aab17e336a248713fc97f1fa
[ "Apache-2.0" ]
63
2016-10-09T17:59:29.000Z
2022-03-29T15:01:44.000Z
31.427907
100
0.669972
13,040
/* * Copyright 2016 Google 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.google.cloud.tools.eclipse.swtbot; import com.google.common.collect.Iterables; import java.util.function.Supplier; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.waits.DefaultCondition; import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotStyledText; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable; import org.hamcrest.Matcher; /** * Provides helper methods to aid in SWTBot testing. */ public class SwtBotTestingUtilities { /** * The delay to use between a simulated key/button press's down and up events. */ public static final int EVENT_DOWN_UP_DELAY_MS = 100; /** Click the button, wait for the window change. */ public static void clickButtonAndWaitForWindowChange(SWTBot bot, SWTBotButton button) { performAndWaitForWindowChange(bot, button::click); } /** Click the button, wait for the window close. */ public static void clickButtonAndWaitForWindowClose(SWTBot bot, SWTBotButton button) { performAndWaitForWindowClose(bot, button::click); } /** * Click on all table cells in column {@code col} with the contents {@code value}. Selection * should be the last cell clicked upon. */ public static void clickOnTableCellValue(SWTBotTable table, int col, String value) { String column = table.columns().get(col); for (int row = 0; row < table.rowCount(); row++) { String cellValue = table.cell(row, column); if (cellValue.equals(value)) { table.click(row, col); break; } } } /** * Return true if the operating system is Mac. */ public static boolean isMac() { String platform = SWT.getPlatform(); return ("carbon".equals(platform) || "cocoa".equals(platform)); } /** * Simple wrapper to block for actions that either open or close a window. */ public static void performAndWaitForWindowChange(SWTBot bot, Runnable runnable) { SWTBotShell shell = bot.activeShell(); runnable.run(); waitUntilShellIsNotActive(bot, shell); } /** * Simple wrapper to block for actions that close a window. */ public static void performAndWaitForWindowClose(SWTBot bot, Runnable runnable) { SWTBotShell shell = bot.activeShell(); runnable.run(); waitUntilShellIsClosed(bot, shell); } /** * Injects a key or character via down and up events. Only one of {@code keyCode} or * {@code character} must be provided. Use * * @param keyCode the keycode of the key (use {@code 0} if unspecified) * @param character the character to press (use {@code '\0'} if unspecified) */ public static void sendKeyDownAndUp(SWTBot bot, int keyCode, char character) { Event ev = new Event(); ev.keyCode = keyCode; ev.character = character; ev.type = SWT.KeyDown; bot.getDisplay().post(ev); bot.sleep(EVENT_DOWN_UP_DELAY_MS); ev.type = SWT.KeyUp; bot.getDisplay().post(ev); } /** * Blocks the caller until the given shell is no longer active. */ public static void waitUntilShellIsNotActive(SWTBot bot, SWTBotShell shell) { bot.waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Shell " + shell.getText() + " did not become inactive"; //$NON-NLS-1$ } @Override public boolean test() throws Exception { return !shell.isActive(); } }); } /** * Blocks the caller until the shell matching the text is open. */ public static void waitUntilShellIsOpen(SWTBot bot, String text) { bot.waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Cannot find a shell with text '" + text + "'"; } @Override public boolean test() throws Exception { return bot.shell(text).isOpen(); } }); } /** * Blocks the caller until the given shell is closed. */ public static void waitUntilShellIsClosed(SWTBot bot, SWTBotShell shell) { bot.waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Shell " + shell.getText() + " did not close"; //$NON-NLS-1$ } @Override public boolean test() throws Exception { return !shell.isOpen(); } }); } /** * Wait until the given text widget contains the provided string */ public static void waitUntilStyledTextContains(SWTBot bot, String text, SWTBotStyledText widget) { bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return widget.getText().contains(text); } @Override public String getFailureMessage() { return "Text not found!"; } }); } /** Wait until the view's content description matches. */ public static void waitUntilViewContentDescription( SWTBot bot, SWTBotView consoleView, Matcher<String> matcher) { bot.waitUntil( new DefaultCondition() { @Override public boolean test() throws Exception { return matcher.matches(consoleView.getViewReference().getContentDescription()); } @Override public String getFailureMessage() { return matcher.toString(); } }); } /** Wait until a menu contains a matching item. */ public static void waitUntilMenuHasItem( SWTBot bot, Supplier<SWTBotMenu> menuSupplier, Matcher<String> matcher) { bot.waitUntil( new DefaultCondition() { @Override public boolean test() throws Exception { return Iterables.any(menuSupplier.get().menuItems(), matcher::matches); } @Override public String getFailureMessage() { return "Never matched menu with " + matcher.toString(); } }); } }
3e1eda73ce399a075b79918d549449faec0b3a61
847
java
Java
app/src/main/java/com/jessyan/xs/topline/mvp/contract/UserContract.java
ResidualSuspense/TopLine
e490611d61452a66cf74cc5c3152a6861107412f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jessyan/xs/topline/mvp/contract/UserContract.java
ResidualSuspense/TopLine
e490611d61452a66cf74cc5c3152a6861107412f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jessyan/xs/topline/mvp/contract/UserContract.java
ResidualSuspense/TopLine
e490611d61452a66cf74cc5c3152a6861107412f
[ "Apache-2.0" ]
null
null
null
27.580645
75
0.730994
13,041
package com.jessyan.xs.topline.mvp.contract; import com.jess.arms.base.DefaultAdapter; import com.jess.arms.mvp.BaseView; import com.jess.arms.mvp.IModel; import com.jessyan.xs.topline.mvp.model.entity.User; import com.tbruyelle.rxpermissions.RxPermissions; import java.util.List; import rx.Observable; /** * Created by jess on 9/4/16 10:47 * Contact with nnheo@example.com */ public interface UserContract { //对于经常使用的关于UI的方法可以定义到BaseView中,如显示隐藏进度条,和显示文字消息 interface View extends BaseView { void setAdapter(DefaultAdapter adapter); void startLoadMore(); void endLoadMore(); //申请权限 RxPermissions getRxPermissions(); } //Model层定义接口,外部只需关心model返回的数据,无需关心内部细节,及是否使用缓存 interface Model extends IModel{ Observable<List<User>> getUsers(int lastIdQueried, boolean update); } }
3e1edce0c592653a166fda8eb330b16d61e43ff7
3,368
java
Java
trash/PlayerEntityMixin.java
AmibeSkyfy16/PlayTime
7718af1af49944d0f59d28f100f4fb509cb51f5c
[ "CC0-1.0" ]
null
null
null
trash/PlayerEntityMixin.java
AmibeSkyfy16/PlayTime
7718af1af49944d0f59d28f100f4fb509cb51f5c
[ "CC0-1.0" ]
null
null
null
trash/PlayerEntityMixin.java
AmibeSkyfy16/PlayTime
7718af1af49944d0f59d28f100f4fb509cb51f5c
[ "CC0-1.0" ]
null
null
null
32.384615
110
0.606591
13,042
package ch.skyfy.playtime.mixin; import ch.skyfy.playtime.PlayerManager; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.Packet; import net.minecraft.screen.PlayerScreenHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.math.Vec3d; import net.minecraft.util.profiling.jfr.event.PacketReceivedEvent; import org.spongepowered.asm.mixin.Final; 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.CallbackInfo; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; @Mixin(PlayerEntity.class) public class PlayerEntityMixin { private static final Long TIMEOUT = 2000L; Vec3d vec3d; Long lastTime = null; Long elapsed; private List<Vec3d> elapsedList = new ArrayList<>(); Timer timer = new Timer(true); boolean timerStarted = false; private void schedule(PlayerEntity player){ timerStarted = true; timer.schedule(new TimerTask() { @Override public void run() { if(lastTime == null){ lastTime = System.currentTimeMillis(); }else{ elapsed = System.currentTimeMillis() - lastTime; if(elapsed >= TIMEOUT){ if(elapsedList.stream().allMatch(vec3d1 -> vec3d1.getX() == 0 && vec3d1.getZ() == 0)){ PlayerManager.getInstance().getWalkingTime().createAndAddElapsedTime(player); System.out.println("Player is standing"); elapsedList.clear(); lastTime = null; } } } } }, 500, 500); } int count = 0; @Inject(method = "travel", at = @At("HEAD")) private void onPlayerTravel(Vec3d movementInput, CallbackInfo ci){ if(0 == 0)return; count++; var entity = ((PlayerEntity) (Object) this); if(!timerStarted)schedule(entity); elapsedList.add(movementInput); System.out.println("count : " + count); System.out.println("X: "+movementInput.getX()); System.out.println("Z:" + movementInput.getZ()); if(movementInput.getZ() > 0 || movementInput.getX() > 0){ if(entity.isSprinting()){ // PlayerManager.getInstance().getWalkingTime().playerStartWalking(entity); // System.out.println("player sprinting"); }else{ PlayerManager.getInstance().getWalkingTime().playerStartWalking(entity); // PlayerManager.getInstance().walking.pressed = true; // System.out.println("player walking"); } } if(movementInput.getZ() == 0 && movementInput.getX() == 0){ // PlayerManager.getInstance().getWalkingTime().playerStopWalking(entity); } // always 0 // System.out.println("GetY " + movementInput.getY()); // if(movementInput.getY() > 0){ // System.out.println("entity is falling "); // } } }
3e1edd740629b4b0ce13056143f75bb4b07fabcc
2,553
java
Java
src/main/java/com/cml/idex/packets/ReturnCurrenciesWithPairs.java
CodeMonkeyLab/java-api-idex
b7e70a40caea3f6e5b26954b71702562e2d18ed9
[ "MIT" ]
1
2020-04-09T18:17:36.000Z
2020-04-09T18:17:36.000Z
src/main/java/com/cml/idex/packets/ReturnCurrenciesWithPairs.java
CodeMonkeyLab/java-api-idex
b7e70a40caea3f6e5b26954b71702562e2d18ed9
[ "MIT" ]
4
2019-11-13T09:34:14.000Z
2021-01-20T23:43:08.000Z
src/main/java/com/cml/idex/packets/ReturnCurrenciesWithPairs.java
CodeMonkeyLab/java-api-idex
b7e70a40caea3f6e5b26954b71702562e2d18ed9
[ "MIT" ]
null
null
null
31.518519
116
0.663533
13,043
package com.cml.idex.packets; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.cml.idex.ErrorCode; import com.cml.idex.IDexException; import com.cml.idex.util.Utils; import com.cml.idex.value.Currency; import com.cml.idex.value.CurrencyPairs; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class ReturnCurrenciesWithPairs implements Req, Parser<CurrencyPairs> { private ReturnCurrenciesWithPairs() { } @Override public String getEndpoint() { return "returnCurrenciesWithPairs"; } @Override public String getPayload() { return ""; } public static ReturnCurrenciesWithPairs create() { return INSTANCE; } public static final ReturnCurrenciesWithPairs INSTANCE = new ReturnCurrenciesWithPairs(); @Override public CurrencyPairs parse(ObjectMapper mapper, String json) { return fromJson(mapper, json); } public static CurrencyPairs fromJson(final ObjectMapper mapper, final String body) { try { JsonNode root = mapper.readTree(body); Utils.checkError(root); Map<String, List<String>> pairs = new HashMap<>(); JsonNode node = root.get("pairs"); if (node != null) { Iterator<Entry<String, JsonNode>> pairItr = node.fields(); while (pairItr.hasNext()) { Entry<String, JsonNode> pairNode = pairItr.next(); List<String> tokens = new LinkedList<>(); pairNode.getValue().elements().forEachRemaining(tokenNode -> tokens.add(tokenNode.asText())); pairs.put(pairNode.getKey(), tokens); } } return new CurrencyPairs(pairs, parseCurrencies(root.get("tokens"))); } catch (Exception e1) { throw new IDexException(ErrorCode.RESPONSE_PARSE_FAILED, e1.getLocalizedMessage(), e1); } } public static Map<String, Currency> parseCurrencies(final JsonNode tokensNode) { if (tokensNode == null) return null; final Map<String, Currency> currencies = new HashMap<>(); Iterator<JsonNode> nodeItr = tokensNode.iterator(); while (nodeItr.hasNext()) { JsonNode node = nodeItr.next(); currencies.put(node.get("symbol").asText(), new Currency(node.get("decimals").asInt(), node.get("address").asText(), node.get("name").asText())); } return currencies; } }
3e1eddf2358713a4305551f86c1d4154f0c939f9
361
java
Java
src/main/java/com/crm/application/service/EventService.java
Wolfinstein/crm_backend
02ee2412ce2b61b20d65276f04d3b471c9d996c8
[ "MIT" ]
null
null
null
src/main/java/com/crm/application/service/EventService.java
Wolfinstein/crm_backend
02ee2412ce2b61b20d65276f04d3b471c9d996c8
[ "MIT" ]
null
null
null
src/main/java/com/crm/application/service/EventService.java
Wolfinstein/crm_backend
02ee2412ce2b61b20d65276f04d3b471c9d996c8
[ "MIT" ]
1
2018-08-30T07:17:30.000Z
2018-08-30T07:17:30.000Z
18.05
43
0.731302
13,044
package com.crm.application.service; import com.crm.application.model.Event; import java.util.List; import java.util.Optional; public interface EventService { List<Event> findAllEvent(); Optional<Event> getEventById(Long id); void saveEvent(Long id, Event event); void updateEvent(long id, Event event); void deleteEvent(Long id); }
3e1ede2409d01456f6025754cb27cb852fe59ca4
1,292
java
Java
sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java
franz1981/opentelemetry-java
4844b82a59c5172c6b1d7206a2b7a3a3ea5d748f
[ "Apache-2.0" ]
1
2021-07-05T13:32:13.000Z
2021-07-05T13:32:13.000Z
sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java
franz1981/opentelemetry-java
4844b82a59c5172c6b1d7206a2b7a3a3ea5d748f
[ "Apache-2.0" ]
7
2021-07-26T05:14:57.000Z
2022-03-15T05:13:13.000Z
sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java
franz1981/opentelemetry-java
4844b82a59c5172c6b1d7206a2b7a3a3ea5d748f
[ "Apache-2.0" ]
null
null
null
32.3
91
0.668731
13,045
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; class MetricExporterConfigurationTest { // Timeout difficult to test using real exports so just check implementation detail here. @Test void configureOtlpTimeout() { OtlpGrpcMetricExporter exporter = MetricExporterConfiguration.configureOtlpMetrics( ConfigProperties.createForTest( ImmutableMap.of( "otel.exporter.otlp.timeout", "10ms", "otel.imr.export.interval", "5s")), SdkMeterProvider.builder().build()); try { assertThat(exporter) .isInstanceOfSatisfying( OtlpGrpcMetricExporter.class, otlp -> assertThat(otlp) .extracting("timeoutNanos") .isEqualTo(TimeUnit.MILLISECONDS.toNanos(10L))); } finally { exporter.shutdown(); } } }
3e1ede2d57d0de23b61ee58e6125ee573d3447a4
3,246
java
Java
com/planet_ink/coffee_mud/Items/interfaces/Container.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
com/planet_ink/coffee_mud/Items/interfaces/Container.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
com/planet_ink/coffee_mud/Items/interfaces/Container.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
39.108434
75
0.747073
13,046
package com.planet_ink.coffee_mud.Items.interfaces; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public interface Container extends Item, CloseableLockable { public ReadOnlyList<Item> getDeepContents(); public ReadOnlyList<Item> getContents(); public int capacity(); public void setCapacity(int newValue); public boolean hasContent(); public boolean canContain(Environmental E); public boolean isInside(Item I); public long containTypes(); public void setContainTypes(long containTypes); public void emptyPlease(boolean flatten); public static final int CONTAIN_ANYTHING=0; public static final int CONTAIN_LIQUID=1; public static final int CONTAIN_COINS=2; public static final int CONTAIN_SWORDS=4; public static final int CONTAIN_DAGGERS=8; public static final int CONTAIN_OTHERWEAPONS=16; public static final int CONTAIN_ONEHANDWEAPONS=32; public static final int CONTAIN_BODIES=64; public static final int CONTAIN_READABLES=128; public static final int CONTAIN_SCROLLS=256; public static final int CONTAIN_CAGED=512; public static final int CONTAIN_KEYS=1024; public static final int CONTAIN_DRINKABLES=2048; public static final int CONTAIN_CLOTHES=4096; public static final int CONTAIN_SMOKEABLES=8192; public static final int CONTAIN_SSCOMPONENTS=16384; public static final int CONTAIN_FOOTWEAR=32768; public static final int CONTAIN_RAWMATERIALS=65536; public static final String[] CONTAIN_DESCS={"ANYTHING", "LIQUID", "COINS", "SWORDS", "DAGGERS", "OTHER WEAPONS", "ONE-HANDED WEAPONS", "BODIES", "READABLES", "SCROLLS", "CAGED ANIMALS", "KEYS", "DRINKABLES", "CLOTHES", "SMOKEABLES", "SS COMPONENTS", "FOOTWEAR", "RAWMATERIALS"}; }
3e1ede9cd4681e78307f9c0c032a530786cfae36
12,066
java
Java
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestTokenClientRMService.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
14,425
2015-01-01T15:34:43.000Z
2022-03-31T15:28:37.000Z
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestTokenClientRMService.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
3,805
2015-03-20T15:58:53.000Z
2022-03-31T23:58:37.000Z
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestTokenClientRMService.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
9,521
2015-01-01T19:12:52.000Z
2022-03-31T03:07:51.000Z
39.168831
93
0.686008
13,047
/** * 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.hadoop.yarn.server.resourcemanager; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.security.PrivilegedExceptionAction; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.SaslRpcServer.AuthMethod; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; import org.apache.hadoop.security.authentication.util.KerberosName; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.protocolrecords.CancelDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.RenewDelegationTokenRequest; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.recovery.NullRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class TestTokenClientRMService { private final static String kerberosRule = "RULE:[1:$1@$0](envkt@example.com)s/@.*//\nDEFAULT"; private static RMDelegationTokenSecretManager dtsm; static { KerberosName.setRules(kerberosRule); } private static final UserGroupInformation owner = UserGroupInformation .createRemoteUser("owner", AuthMethod.KERBEROS); private static final UserGroupInformation other = UserGroupInformation .createRemoteUser("other", AuthMethod.KERBEROS); private static final UserGroupInformation tester = UserGroupInformation .createRemoteUser("tester", AuthMethod.KERBEROS); private static final String testerPrincipal = "kenaa@example.com"; private static final String ownerPrincipal = "lyhxr@example.com"; private static final String otherPrincipal = "envkt@example.com"; private static final UserGroupInformation testerKerb = UserGroupInformation .createRemoteUser(testerPrincipal, AuthMethod.KERBEROS); private static final UserGroupInformation ownerKerb = UserGroupInformation .createRemoteUser(ownerPrincipal, AuthMethod.KERBEROS); private static final UserGroupInformation otherKerb = UserGroupInformation .createRemoteUser(otherPrincipal, AuthMethod.KERBEROS); @BeforeClass public static void setupSecretManager() throws IOException { ResourceManager rm = mock(ResourceManager.class); RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(new NullRMStateStore()); when(rm.getRMContext()).thenReturn(rmContext); when(rmContext.getResourceManager()).thenReturn(rm); dtsm = new RMDelegationTokenSecretManager(60000, 60000, 60000, 60000, rmContext); dtsm.startThreads(); Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "kerberos"); conf.set("hadoop.security.auth_to_local", kerberosRule); UserGroupInformation.setConfiguration(conf); UserGroupInformation.getLoginUser() .setAuthenticationMethod(AuthenticationMethod.KERBEROS); } @AfterClass public static void teardownSecretManager() { if (dtsm != null) { dtsm.stopThreads(); } } @Test public void testTokenCancellationByOwner() throws Exception { // two tests required - one with a kerberos name // and with a short name RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(rmService, testerKerb, other); return null; } }); owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(owner, other); return null; } }); } @Test public void testTokenRenewalWrongUser() throws Exception { try { owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenRenewal(owner, other); return null; } catch (YarnException ex) { Assert.assertTrue(ex.getMessage().contains( owner.getUserName() + " tries to renew a token")); Assert.assertTrue(ex.getMessage().contains( "with non-matching renewer " + other.getUserName())); throw ex; } } }); } catch (Exception e) { return; } Assert.fail("renew should have failed"); } @Test public void testTokenRenewalByLoginUser() throws Exception { UserGroupInformation.getLoginUser().doAs( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenRenewal(owner, owner); checkTokenRenewal(owner, other); return null; } }); } private void checkTokenRenewal(UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier(new Text(owner.getUserName()), new Text(renewer.getUserName()), null); Token<?> token = new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm); org.apache.hadoop.yarn.api.records.Token dToken = BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind() .toString(), token.getPassword(), token.getService().toString()); RenewDelegationTokenRequest request = Records.newRecord(RenewDelegationTokenRequest.class); request.setDelegationToken(dToken); RMContext rmContext = mock(RMContext.class); ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); rmService.renewDelegationToken(request); } @Test public void testTokenCancellationByRenewer() throws Exception { // two tests required - one with a kerberos name // and with a short name RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(rmService, owner, testerKerb); return null; } }); other.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(owner, other); return null; } }); } @Test public void testTokenCancellationByWrongUser() { // two sets to test - // 1. try to cancel tokens of short and kerberos users as a kerberos UGI // 2. try to cancel tokens of short and kerberos users as a simple auth UGI RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); UserGroupInformation[] kerbTestOwners = { owner, other, tester, ownerKerb, otherKerb }; UserGroupInformation[] kerbTestRenewers = { owner, other, ownerKerb, otherKerb }; for (final UserGroupInformation tokOwner : kerbTestOwners) { for (final UserGroupInformation tokRenewer : kerbTestRenewers) { try { testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenCancellation(rmService, tokOwner, tokRenewer); Assert.fail("We should not reach here; token owner = " + tokOwner.getUserName() + ", renewer = " + tokRenewer.getUserName()); return null; } catch (YarnException e) { Assert.assertTrue(e.getMessage().contains( testerKerb.getUserName() + " is not authorized to cancel the token")); return null; } } }); } catch (Exception e) { Assert.fail("Unexpected exception; " + e.getMessage()); } } } UserGroupInformation[] simpleTestOwners = { owner, other, ownerKerb, otherKerb, testerKerb }; UserGroupInformation[] simpleTestRenewers = { owner, other, ownerKerb, otherKerb }; for (final UserGroupInformation tokOwner : simpleTestOwners) { for (final UserGroupInformation tokRenewer : simpleTestRenewers) { try { tester.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenCancellation(tokOwner, tokRenewer); Assert.fail("We should not reach here; token owner = " + tokOwner.getUserName() + ", renewer = " + tokRenewer.getUserName()); return null; } catch (YarnException ex) { Assert.assertTrue(ex.getMessage().contains( tester.getUserName() + " is not authorized to cancel the token")); return null; } } }); } catch (Exception e) { Assert.fail("Unexpected exception; " + e.getMessage()); } } } } private void checkTokenCancellation(UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); checkTokenCancellation(rmService, owner, renewer); } private void checkTokenCancellation(ClientRMService rmService, UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier(new Text(owner.getUserName()), new Text(renewer.getUserName()), null); Token<?> token = new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm); org.apache.hadoop.yarn.api.records.Token dToken = BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind() .toString(), token.getPassword(), token.getService().toString()); CancelDelegationTokenRequest request = Records.newRecord(CancelDelegationTokenRequest.class); request.setDelegationToken(dToken); rmService.cancelDelegationToken(request); } @Test public void testTokenRenewalByOwner() throws Exception { owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenRenewal(owner, owner); return null; } }); } }
3e1ee002b12ffec2ab7c1020085efb5f4860385e
8,691
java
Java
src/java/com/rollsoftware/br/lfms/db/impl/entity/Cost.java
R0g3r10LL31t3/LFMS-ROLLSoftware
868f5df2d2e96a521423567d4d5a973f2fb90948
[ "Apache-2.0" ]
1
2021-05-27T20:51:42.000Z
2021-05-27T20:51:42.000Z
src/java/com/rollsoftware/br/lfms/db/impl/entity/Cost.java
R0g3r10LL31t3/LFMS-ROLLSoftware
868f5df2d2e96a521423567d4d5a973f2fb90948
[ "Apache-2.0" ]
null
null
null
src/java/com/rollsoftware/br/lfms/db/impl/entity/Cost.java
R0g3r10LL31t3/LFMS-ROLLSoftware
868f5df2d2e96a521423567d4d5a973f2fb90948
[ "Apache-2.0" ]
null
null
null
29.361486
85
0.632493
13,048
/* * Copyright 2016-2026 Rogério Lecarião Leite * * 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. * * CEO 2016: Rogério Lecarião Leite; ROLL Software */ package com.rollsoftware.br.lfms.db.impl.entity; import com.rollsoftware.br.common.db.entity.ObjectData; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.PrimaryKeyJoinColumns; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; /** * * @author Rogério * @date September, 2017 * * Logistics and Finances Management System */ @Entity @Table(name = "CST_COST", schema = "LFMS_DB", uniqueConstraints = { @UniqueConstraint(columnNames = {"CST_UUID_FK", "CST_TYPE"}) ,@UniqueConstraint(columnNames = {"CST_NAME"}) } ) @DiscriminatorValue("Cost") @PrimaryKeyJoinColumns({ @PrimaryKeyJoinColumn(name = "CST_UUID_FK", referencedColumnName = "OBJ_UUID_PK") ,@PrimaryKeyJoinColumn(name = "CST_TYPE", referencedColumnName = "OBJ_TYPE") }) @NamedQueries({ @NamedQuery(name = "Cost.findAll", query = "SELECT c FROM Cost c") , @NamedQuery(name = "Cost.findByName", query = "SELECT c FROM Cost c" + " WHERE c.name = :name") , @NamedQuery(name = "Cost.findByDescription", query = "SELECT c FROM Cost c" + " WHERE c.description = :description") , @NamedQuery(name = "Cost.findStockInfoOwner", query = "SELECT c FROM Cost c" + " WHERE c.stockInfoOwner = :stockInfoOwner") }) @XmlRootElement(name = "cost") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cost", propOrder = { "stockInfoOwner", "name", "description", "featureList", "stockTreeList", "stockInfoList" }) public class Cost extends ObjectData implements Serializable { private static final long serialVersionUID = 1L; // @Version // @Basic(optional = false) // @NotNull // @Column(name = "CST_VERSION", nullable = false) @Transient @XmlTransient private Integer cstVersion; @Basic(optional = false) @NotNull @Size(min = 1, max = 256) @Column(name = "CST_NAME", nullable = false, length = 256) protected String name; @Basic(optional = false) @NotNull @Size(min = 1, max = 256) @Column(name = "CST_DESCRIPTION", nullable = false, length = 256) protected String description; @OneToMany( mappedBy = "cost", fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) @OrderBy("dateCreated ASC") @XmlElement(name = "feature") @XmlIDREF protected List<CostFeature> featureList; @OneToMany( mappedBy = "cost", fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) @OrderBy("dateCreated ASC") @XmlElement(name = "stock") @XmlIDREF protected List<StockInfo> stockInfoList; @OneToMany( mappedBy = "cost", fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) @OrderBy("dateCreated ASC") @XmlElement(name = "stockTree") @XmlIDREF protected List<StockTree> stockTreeList; @ManyToOne( optional = true, fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) @JoinColumns({ @JoinColumn(name = "CST_STI_UUID_FK", referencedColumnName = "STI_UUID_FK") ,@JoinColumn(name = "CST_STI_TYPE", referencedColumnName = "STI_TYPE") }) @XmlElement(name = "stockOwner") @XmlIDREF protected StockInfo stockInfoOwner; public Cost() { this(""); } public Cost(String uuid) { this(0, "Cost", uuid, null, "", "", new ArrayList(), new ArrayList(), new ArrayList(), 0); } public Cost(Integer id, String type, String uuid, StockInfo stockInfoOwner, String name, String description, List<CostFeature> featureList, List<StockInfo> stockInfoList, List<StockTree> stockTreeList, Integer cstVersion) { super(id, type, uuid); this.name = name; this.description = description; this.featureList = featureList; this.stockInfoList = stockInfoList; this.stockTreeList = stockTreeList; this.stockInfoOwner = stockInfoOwner; this.cstVersion = cstVersion; init(); } private void init() { for (Feature feature : getCostFeatureList()) { feature.setCost(this); } for (StockTree stock : getStockTreeList()) { stock.setCost(this); } for (StockInfo stockInfo : getStockInfoList()) { stockInfo.setCost(this); } } public StockInfo getStockInfoOwner() { return stockInfoOwner; } public void setStockInfoOwner(StockInfo stockInfoOwner) { this.stockInfoOwner = stockInfoOwner; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<CostFeature> getCostFeatureList() { return featureList; } public void setCostFeatureList(List<CostFeature> featureList) { this.featureList = featureList; } public List<StockInfo> getStockInfoList() { return stockInfoList; } public void setStockInfoList(List<StockInfo> stockInfoList) { this.stockInfoList = stockInfoList; } public List<StockTree> getStockTreeList() { return stockTreeList; } public void setStockTreeList(List<StockTree> stockTreeList) { this.stockTreeList = stockTreeList; } @Override public int hashCode() { int _uuid = super.hashCode(); _uuid += Objects.hashCode(getName()); _uuid += Objects.hashCode(getDescription()); _uuid += Objects.hashCode(getCostFeatureList()); return _uuid; } @Override public boolean equals(Object object) { if (object == null) { return false; } if (!super.equals(object)) { return false; } if (!(object instanceof Cost)) { return false; } final Cost other = (Cost) object; if (!Objects.equals(this.getName(), other.getName())) { return false; } if (!Objects.equals(this.getDescription(), other.getDescription())) { return false; } if (!Objects.equals(this.getCostFeatureList(), other.getCostFeatureList())) { return false; } return true; } @Override public String toString() { return "Cost[\n\t" + "id=" + getId() + ", uuid=" + getUUID() + ", version=" + cstVersion + ",\n\tname=" + getName() + ",\n\tdescription=" + getDescription() + "\n]"; } }
3e1ee0f24398747888361d9454d53de1ab65c164
9,562
java
Java
src/main/java/cct/database/DatabaseManagerDialog.java
eroma2014/seagrid-rich-client
a432af6aa97d6c1d5855dffa4c85cb9c14718af9
[ "Apache-2.0" ]
1
2017-02-22T08:41:20.000Z
2017-02-22T08:41:20.000Z
src/main/java/cct/database/DatabaseManagerDialog.java
eroma2014/seagrid-rich-client
a432af6aa97d6c1d5855dffa4c85cb9c14718af9
[ "Apache-2.0" ]
39
2018-09-06T10:47:02.000Z
2018-12-11T14:16:35.000Z
src/main/java/cct/database/DatabaseManagerDialog.java
airavata-courses/airavata-nextcoud
b8d89c60363167b16b27dd42ff4f46beca815d66
[ "Apache-2.0" ]
8
2016-03-08T17:15:49.000Z
2019-07-28T11:35:39.000Z
36.496183
137
0.708534
13,049
/* * 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 cct.database; import cct.GlobalSettings; import java.awt.Frame; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; /** * * @author vvv900 */ public class DatabaseManagerDialog extends javax.swing.JDialog { private Set<String> databases; private DatabaseManager databaseManager; /** * Creates new form DatabaseManagerDialog */ public DatabaseManagerDialog(Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * 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(); databaseList = new javax.swing.JList(); jPanel2 = new javax.swing.JPanel(); addDBButton = new javax.swing.JButton(); removeSelectedButton = new javax.swing.JButton(); initButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setTitle("Databases"); setAlwaysOnTop(true); jPanel1.setLayout(new java.awt.BorderLayout()); databaseList.setBorder(javax.swing.BorderFactory.createTitledBorder("Available Databases")); databaseList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(databaseList); jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); addDBButton.setText("Add Database"); addDBButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addDBButtonActionPerformed(evt); } }); jPanel2.add(addDBButton); removeSelectedButton.setText("Remove Selected"); removeSelectedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeSelectedButtonActionPerformed(evt); } }); jPanel2.add(removeSelectedButton); initButton.setText("Initialize/Reset DB"); initButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { initButtonActionPerformed(evt); } }); jPanel2.add(initButton); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); jPanel2.add(cancelButton); getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); pack(); }// </editor-fold>//GEN-END:initComponents private Set<String> getDatabases() { return databases; } private void setDatabases(Set<String> databases) { this.databases = databases; DefaultListModel dlm = new DefaultListModel(); for (String str : databases) { dlm.addElement(str); } databaseList.setModel(dlm); } private void setDatabases(String[] dbEntries) { databases.clear(); DefaultListModel dlm = new DefaultListModel(); for (String str : dbEntries) { databases.add(str); dlm.addElement(str); } databaseList.setModel(dlm); } public DatabaseManager getDatabaseManager() { return databaseManager; } public void setDatabaseManager(DatabaseManager databaseManager) { this.databaseManager = databaseManager; } private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void removeSelectedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSelectedButtonActionPerformed int[] list = this.databaseList.getSelectedIndices(); // List list = this.databaseList.getSelectedValuesList(); //int[] list = databaseList.getSelectedIndices();databaseList.getModel(). if (list == null || list.length < 1) { JOptionPane.showMessageDialog(this, "Nothing to delete", "Nothing to delete", JOptionPane.WARNING_MESSAGE); return; } DefaultListModel dlm = (DefaultListModel) databaseList.getModel(); for (int i : list) { dlm.removeElementAt(i); } validate(); }//GEN-LAST:event_removeSelectedButtonActionPerformed private void addDBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDBButtonActionPerformed ConnectToDatabaseDialog connectToDatabaseDialog = new ConnectToDatabaseDialog(new Frame(), true); connectToDatabaseDialog.setLocationRelativeTo(this); connectToDatabaseDialog.setDatabaseManager(databaseManager); connectToDatabaseDialog.validate(); connectToDatabaseDialog.setAlwaysOnTop(true); connectToDatabaseDialog.setVisible(true); if (connectToDatabaseDialog.isDialogCancelled()) { return; } // --- connectToDatabaseDialog.dispose(); this.setDatabases(databaseManager.getDBEntriesAsSortedArray()); }//GEN-LAST:event_addDBButtonActionPerformed private void initButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_initButtonActionPerformed //List list = this.databaseList.getSelectedValuesList(); int[] list = this.databaseList.getSelectedIndices(); //int[] list = databaseList.getSelectedIndices();databaseList.getModel(). if (list == null || list.length < 1) { JOptionPane.showMessageDialog(this, "Select database first", "Select database first", JOptionPane.WARNING_MESSAGE); return; } for (int i : list) { try { databaseManager.resetDBEntry(databaseList.getModel().getElementAt(i).toString()); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error reseting/creating database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return; } } JOptionPane.showMessageDialog(this, "Initialization/reset of database(s) was successful", "Success", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_initButtonActionPerformed /** * @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) { Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { Logger.getLogger(DatabaseManagerDialog.class.getName()).log(Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { DatabaseManagerDialog dialog = new DatabaseManagerDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); Set<String> db = new HashSet<String>(); //db.add("mysql:localhost:chemistry"); //db.add("sqlite:chemistry.db"); dialog.setDatabases(db); DatabaseManager dbm = new DatabaseManager(); try { dbm.initiateFromProperties(GlobalSettings.getProperties()); } catch (Exception ex) { Logger.getLogger(DatabaseDriver.class.getName()).log(Level.SEVERE, null, ex); } dialog.setDatabaseManager(dbm); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addDBButton; private javax.swing.JButton cancelButton; private javax.swing.JList databaseList; private javax.swing.JButton initButton; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton removeSelectedButton; // End of variables declaration//GEN-END:variables }
3e1ee14425fb2102010c9280be16107e79a1c176
10,055
java
Java
cdm/src/main/java/ucar/nc2/time/CalendarDuration.java
joansmith2/thredds
ac321ce2a15f020f0cdef1ff9a2cf82261d8297c
[ "NetCDF" ]
1
2019-01-22T11:30:51.000Z
2019-01-22T11:30:51.000Z
cdm/src/main/java/ucar/nc2/time/CalendarDuration.java
joansmith/thredds
3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8
[ "NetCDF" ]
16
2016-04-11T06:42:41.000Z
2019-05-03T04:04:50.000Z
cdm/src/main/java/ucar/nc2/time/CalendarDuration.java
joansmith/thredds
3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8
[ "NetCDF" ]
null
null
null
30.56231
122
0.612034
13,050
package ucar.nc2.time; import net.jcip.annotations.Immutable; import org.joda.time.Period; /** * A replacement for ucar.nc2.units.TimeDuration. incomplete. * * * A Duration is a fixed number of seconds. * I think thats wrong: a CalendarDuration should be a integer and a CalendarPeriod. * Optionally, a CalendarPeriod could have an integer value. * * Implements the thredds "duration" XML element type: specifies a length of time. * This is really the same as a ucar.nc2.units.TimeUnit, but it allows xsd:duration syntax as well as udunits syntax. * It also keeps track if the text is empty. * <p/> * A duration can be one of the following: * <ol> * <li> a valid udunits string compatible with "secs" * <li> an xsd:duration type specified in the following form "PnYnMnDTnHnMnS" where: * <ul> * <li>P indicates the period (required) * <li>nY indicates the number of years * <li>nM indicates the number of months * <li>nD indicates the number of days * <li>T indicates the start of a time section (required if you are going to specify hours, minutes, or seconds) * <li>nH indicates the number of hours * <li>nM indicates the number of minutes * <li>nS indicates the number of seconds * </ul> * </ol> * * <p> * change to JSR-310 javax.time.Duration when ready * relation to javax.xml.datatype ? * * @author john caron * @see "http://www.unidata.ucar.edu/projects/THREDDS/tech/catalog/InvCatalogSpec.html#durationType" */ @Immutable public class CalendarDuration { /** * Convert a time udunit string * @param value number of units * @param udunit msec, sec, minute, hour, hr, day, week, month, year (plural form ok) * @return joda Period */ static org.joda.time.Period convertToPeriod(int value, String udunit) { if (udunit.endsWith("s")) udunit = udunit.substring(0, udunit.length()-1); switch (udunit) { case "msec": return Period.millis(value); case "sec": return Period.seconds(value); case "minute": return Period.minutes(value); case "hour": case "hr": return Period.hours(value); case "day": return Period.days(value); case "week": return Period.weeks(value); case "month": return Period.months(value); case "year": return Period.years(value); } throw new IllegalArgumentException("cant convert "+ udunit +" to Joda Period"); } ///////////////////////////////////////////////////////////////////// //private final String text; private final CalendarPeriod.Field timeUnit; //private final boolean isBlank; private final double value; //private org.joda.time.Period jperiod; public CalendarDuration(int value, CalendarPeriod.Field timeUnit) { this.value = value; this.timeUnit = timeUnit; } public CalendarPeriod.Field getTimeUnit() { return timeUnit; } public static CalendarDuration fromUnitString(String unitString) { return new CalendarDuration(1, CalendarPeriod.fromUnitString(unitString)); } /* * Construct from 1) udunit time udunit string, 2) xsd:duration syntax, 3) blank string. * * @param text parse this text. * @throws java.text.ParseException if invalid text. * public CalendarDuration(String text) throws java.text.ParseException { /* TimeUnit tunit = null; text = (text == null) ? "" : text.trim(); this.text = text; this.isBlank = (text == null) || text.length() == 0; // see if its blank if (isBlank) { try { tunit = new TimeUnit("1 sec"); } catch (Exception e) { // cant happen } } else { // see if its a udunits string try { tunit = new TimeUnit(text); if (debug) System.out.println(" set time udunit= " + timeUnit); } catch (Exception e) { // see if its a xsd:duration /* * A time span as defined in the W3C XML Schema 1.0 specification: * "PnYnMnDTnHnMnS, where nY represents the number of years, nM the number of months, nD the number of days, * 'T' is the date/time separator, nH the number of hours, nM the number of minutes and nS the number of seconds. * The number of seconds can include decimal digits to arbitrary precision." * try { javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance(); javax.xml.datatype.Duration d = factory.newDuration(text); long secs = d.getTimeInMillis(new Date()) / 1000; tunit = new TimeUnit(secs + " secs"); } catch (Exception e1) { throw new java.text.ParseException(e1.getMessage(), 0); } } } timeUnit = tunit; duration = tunit.toDurationStandard(); }*/ /** * Get the duration in natural units, ie units of getTimeUnit() * @return the duration in natural units */ public double getValue() { return value; } /** * Get the duration in seconds * @return the duration in seconds * public double getValueInMillisecs() { if (timeUnit == CalendarPeriod.Millisec) return value; else if (timeUnit == CalendarPeriod.Second) return 1000 * value; else if (timeUnit == CalendarPeriod.Minute) return 60 * 1000 * value; else if (timeUnit == CalendarPeriod.Hour) return 60 * 60 * 1000 * value; else if (timeUnit == CalendarPeriod.Day) return 24 * 60 * 60 * 1000 * value; else if (timeUnit == CalendarPeriod.Month) return 30.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value; else if (timeUnit == CalendarPeriod.Year) return 365.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value; else throw new IllegalStateException(); } public double getValueInSeconds() { if (timeUnit == CalendarPeriod.Millisec) return value/1000; else if (timeUnit == CalendarPeriod.Second) return value; else if (timeUnit == CalendarPeriod.Minute) return 60 * value; else if (timeUnit == CalendarPeriod.Hour) return 60 * 60 * value; else if (timeUnit == CalendarPeriod.Day) return 24 * 60 * 60 * value; else if (timeUnit == CalendarPeriod.Month) return 30.0 * 24.0 * 60.0 * 60.0 * value; else if (timeUnit == CalendarPeriod.Year) return 365.0 * 24.0 * 60.0 * 60.0 * value; else throw new IllegalStateException(); } public double getValueInHours() { if (timeUnit == CalendarPeriod.Millisec) return value/1000/60/60; else if (timeUnit == CalendarPeriod.Second) return value/60/60; else if (timeUnit == CalendarPeriod.Minute) return value/60; else if (timeUnit == CalendarPeriod.Hour) return value; else if (timeUnit == CalendarPeriod.Day) return 24 * value; else if (timeUnit == CalendarPeriod.Month) return 30.0 * 24.0 * value; else if (timeUnit == CalendarPeriod.Year) return 365.0 * 24.0 * value; else throw new IllegalStateException(); } public double getValueInDays() { if (timeUnit == CalendarPeriod.Millisec) return value/1000/60/60/24; else if (timeUnit == CalendarPeriod.Second) return value/60/60/24; else if (timeUnit == CalendarPeriod.Minute) return value/60/24; else if (timeUnit == CalendarPeriod.Hour) return value/24; else if (timeUnit == CalendarPeriod.Day) return value; else if (timeUnit == CalendarPeriod.Month) return 30.0 * value; else if (timeUnit == CalendarPeriod.Year) return 365.0 * value; else throw new IllegalStateException(); } */ /* * If this is a blank string * @return true if this is a blank string * public boolean isBlank() { return isBlank; } /* * Get the String text * @return the text * public String getText() { return text == null ? timeUnit.toString() : text; } */ /** * String representation * @return getText() */ public String toString() { return timeUnit.toString(); } /* * Override to be consistent with equals * public int hashCode2() { return isBlank() ? 0 : (int) getValueInSeconds(); } /* * TimeDurations with same value in seconds are equals * public boolean equals2(Object o) { if (this == o) return true; if (!(o instanceof CalendarDuration)) return false; CalendarDuration to = (CalendarDuration) o; return to.getValueInMillisecs() == getValueInMillisecs(); } */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CalendarDuration that = (CalendarDuration) o; if (Double.compare(that.value, value) != 0) return false; return timeUnit == that.timeUnit; } @Override public int hashCode() { int result; long temp; result = timeUnit != null ? timeUnit.hashCode() : 0; temp = value != +0.0d ? Double.doubleToLongBits(value) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } /////////////////////////// static private void test(String unit, String result) throws Exception { org.joda.time.Period jp = convertToPeriod(1, unit); assert jp != null; System.out.printf("%s == %s%n", unit, jp); assert jp.toString().equals(result) : jp.toString()+" != "+ result; } static public void main(String args[]) throws Exception { test("sec", "PT1S"); test("secs", "PT1S"); test("minute", "PT1M"); test("minutes", "PT1M"); test("hour", "PT1H"); test("hours", "PT1H"); test("hr", "PT1H"); test("day", "P1D"); test("days", "P1D"); test("week", "P7D"); test("weeks", "P7D"); test("month", "P1M"); test("months", "P1M"); test("year", "P1Y"); test("years", "P1Y"); } }
3e1ee14a8ddce63384c31b6594eb7daafecfef22
1,575
java
Java
chapter_11/shopCar/src/main/java/ru/job4j/component/ApplicationListener.java
andreiHi/hincuA
6d1321d508b87aa68241bccc7f286162b388f245
[ "Apache-2.0" ]
2
2017-10-17T11:13:25.000Z
2018-11-18T19:35:16.000Z
chapter_11/shopCar/src/main/java/ru/job4j/component/ApplicationListener.java
andreiHi/hincuA
6d1321d508b87aa68241bccc7f286162b388f245
[ "Apache-2.0" ]
7
2020-03-04T21:57:32.000Z
2022-03-28T19:19:59.000Z
chapter_11/shopCar/src/main/java/ru/job4j/component/ApplicationListener.java
andreiHi/hincuA
6d1321d508b87aa68241bccc7f286162b388f245
[ "Apache-2.0" ]
null
null
null
30.365385
86
0.677644
13,051
package ru.job4j.component; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.io.File; /** * @author Hincu Andrei (lyhxr@example.com)on 24.05.2018. * @version $Id$. * @since 0.1. */ public class ApplicationListener implements ServletContextListener { private static final Logger LOG = LogManager.getLogger(ApplicationListener.class); private static final String SAVE_DIRECTORY = "uploadDir"; @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); String fullSavePath = createUploadPath(context.getRealPath("")); LOG.info(String.format("Full save path was created : %s", fullSavePath)); context.setAttribute("fullSavePath", fullSavePath); LOG.info("Application started"); } @Override public void contextDestroyed(ServletContextEvent sce) { LOG.info("Application destroyed"); } private String createUploadPath(String appPath) { appPath = appPath.replace('\\', '/'); String fullSavePath; if (appPath.endsWith("/")) { fullSavePath = appPath + SAVE_DIRECTORY; } else { fullSavePath = appPath + "/" + SAVE_DIRECTORY; } File fileSaveDir = new File(fullSavePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } return fullSavePath; } }
3e1ee1b4368e01875fab7b17ea6d3d9c7751ca99
4,013
java
Java
src/main/java/com/arthur/webnovel/entity/Story.java
remagine/webNovel
25f175ccb45fb0bcd819c0e7cb79bb11725f5679
[ "MIT" ]
null
null
null
src/main/java/com/arthur/webnovel/entity/Story.java
remagine/webNovel
25f175ccb45fb0bcd819c0e7cb79bb11725f5679
[ "MIT" ]
null
null
null
src/main/java/com/arthur/webnovel/entity/Story.java
remagine/webNovel
25f175ccb45fb0bcd819c0e7cb79bb11725f5679
[ "MIT" ]
null
null
null
21.809783
93
0.657364
13,052
package com.arthur.webnovel.entity; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.OrderBy; import org.hibernate.annotations.Type; import org.hibernate.annotations.Where; import com.arthur.webnovel.code.State; @Entity @Table(name = "story") public class Story { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_story") @SequenceGenerator(name = "seq_story", sequenceName = "story_id_seq", allocationSize = 1) private Integer id; @Column(name = "title") private String title; @Column(name = "description") private String description; @Column(name = "foreword") private String foreword; @Column(name = "character") private String character; @Column(name = "tags") @Type(type = "com.iropke.common.hibernate.ArrayType") private String[] tags; @Column(name = "co_author") private String coAuthor; @Column(name = "cover_image") private String coverImage; @Column(name = "views", columnDefinition = "Integer default 0") private Integer views; @Enumerated(EnumType.STRING) @Column(name = "state") private State state; @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_at", insertable = false, updatable = false) private Date createAt; @ManyToOne @JoinColumn(name="member") private Member member; @OneToMany @Where(clause = "state not in ('deleted')") @OrderBy(clause = "id asc") @JoinColumn(name = "story") private List<Chapter> chapterList; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getForeword() { return foreword; } public void setForeword(String foreword) { this.foreword = foreword; } public String getCharacter() { return character; } public void setCharacter(String character) { this.character = character; } public String[] getTags() { return tags; } public void setTags(String[] tags) { this.tags = tags; } public String getCoAuthor() { return coAuthor; } public void setCoAuthor(String coAuthor) { this.coAuthor = coAuthor; } public String getCoverImage() { return coverImage; } public void setCoverImage(String coverImage) { this.coverImage = coverImage; } public Integer getViews() { return views; } public void setViews(Integer views) { this.views = views; } public State getState() { return state; } public void setState(State state) { this.state = state; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public List<Chapter> getChapterList() { return chapterList; } public void setChapterList(List<Chapter> chapterList) { this.chapterList = chapterList; } }