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
92415a8dab8cf36a87afdd35d256d0d9789971d8
307
java
Java
backend/src/main/java/com/herostore/products/handler/ProductOrdersPDFWriter.java
cesar-lp/hulk-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
null
null
null
backend/src/main/java/com/herostore/products/handler/ProductOrdersPDFWriter.java
cesar-lp/hulk-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
7
2020-04-26T19:59:44.000Z
2022-02-26T22:42:26.000Z
backend/src/main/java/com/herostore/products/handler/ProductOrdersPDFWriter.java
cesar-lp/hero-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
null
null
null
25.583333
68
0.833876
1,001,874
package com.herostore.products.handler; import com.herostore.products.dto.response.ProductOrderResponse; import com.herostore.products.io.PDFWriter; import java.util.List; public interface ProductOrdersPDFWriter extends PDFWriter { void setProductOrders(List<ProductOrderResponse> paymentOrders); }
92415ab03d37b0aaf32b44fe3b3a2901a0ab6f64
589
java
Java
cloudnet-wrapper-jvm/src/main/java/de/dytanic/cloudnet/wrapper/database/IDatabaseProvider.java
hammermaps/CloudNet-v3
7bb1beb1b06eb44216dbed3f7fc98ba1ad372737
[ "Apache-2.0" ]
2
2021-03-08T19:59:38.000Z
2021-04-24T11:41:11.000Z
cloudnet-wrapper-jvm/src/main/java/de/dytanic/cloudnet/wrapper/database/IDatabaseProvider.java
KxmischesDomi/CloudNet-v3
1b6bc79f839c1a30dac9a499f510cee204205279
[ "Apache-2.0" ]
4
2021-12-22T05:18:12.000Z
2022-03-07T05:22:37.000Z
cloudnet-wrapper-jvm/src/main/java/de/dytanic/cloudnet/wrapper/database/IDatabaseProvider.java
KxmischesDomi/CloudNet-v3
1b6bc79f839c1a30dac9a499f510cee204205279
[ "Apache-2.0" ]
null
null
null
20.310345
54
0.760611
1,001,875
package de.dytanic.cloudnet.wrapper.database; import de.dytanic.cloudnet.common.concurrent.ITask; import org.jetbrains.annotations.NotNull; import java.util.Collection; public interface IDatabaseProvider { IDatabase getDatabase(String name); boolean containsDatabase(String name); boolean deleteDatabase(String name); Collection<String> getDatabaseNames(); @NotNull ITask<Boolean> containsDatabaseAsync(String name); @NotNull ITask<Boolean> deleteDatabaseAsync(String name); @NotNull ITask<Collection<String>> getDatabaseNamesAsync(); }
92415ac10b43e0aff307434ca6f6b095d9e5a26f
1,046
java
Java
itcast/XC/xcEduService/xc-service-manage-cms/src/main/java/com/xuecheng/manage_cms/controller/CmsTemplateController.java
diqiuonline/Demo
cba12f44b57b47a4ea7f23ed3e28b21de5ef0d86
[ "MIT" ]
null
null
null
itcast/XC/xcEduService/xc-service-manage-cms/src/main/java/com/xuecheng/manage_cms/controller/CmsTemplateController.java
diqiuonline/Demo
cba12f44b57b47a4ea7f23ed3e28b21de5ef0d86
[ "MIT" ]
22
2020-04-14T15:52:45.000Z
2022-02-28T14:52:14.000Z
itcast/XC/xcEduService/xc-service-manage-cms/src/main/java/com/xuecheng/manage_cms/controller/CmsTemplateController.java
diqiuonline/Demo
cba12f44b57b47a4ea7f23ed3e28b21de5ef0d86
[ "MIT" ]
1
2020-08-31T06:51:57.000Z
2020-08-31T06:51:57.000Z
32.6875
72
0.787763
1,001,876
package com.xuecheng.manage_cms.controller; import com.xuecheng.api.cms.CmsTemplateControllerApi; import com.xuecheng.framework.model.response.QueryResponseResult; import com.xuecheng.manage_cms.service.PageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * User: 李锦卓 * Time: 2019/1/7 21:12 */ @RefreshScope @RestController @RequestMapping("/cms/template") public class CmsTemplateController implements CmsTemplateControllerApi { @Autowired private PageService pageService; @Value("${cms.ip}") private String ip; @GetMapping("/list") @Override public QueryResponseResult findAll() { System.out.println(ip); return pageService.findTemplateAll(); } }
92415bb56cfbbdf0056f247a6ccd2f9927c82ba4
946
java
Java
chapter_004/src/main/java/stream/task/PriorityQueue.java
ssabrii/job4j-1
4c356d5e0a9b942dad9882eb7a1bc03a57478e5e
[ "Apache-2.0" ]
2
2019-03-04T11:53:35.000Z
2019-03-04T11:53:37.000Z
chapter_004/src/main/java/stream/task/PriorityQueue.java
ssabrii/job4j-1
4c356d5e0a9b942dad9882eb7a1bc03a57478e5e
[ "Apache-2.0" ]
22
2020-07-08T16:34:22.000Z
2022-02-16T01:16:11.000Z
chapter_004/src/main/java/stream/task/PriorityQueue.java
maxvanny2010/job4j
bb158ad78ebef7fbaa0acaf3235ef80c0f5c9a2f
[ "Apache-2.0" ]
3
2019-02-10T22:05:58.000Z
2019-09-03T15:28:09.000Z
19.708333
66
0.54334
1,001,877
package stream.task; import java.util.LinkedList; /** * PriorityQueue. * * @author Maxim Vanny. * @version 4.0 * @since 0.1 */ public class PriorityQueue { /** * List tasks. */ private final LinkedList<Task> tasks = new LinkedList<>(); /** * Метод использует add(int index, E value). * * @param task задача */ public final void put(final Task task) { var index = (int) tasks.stream() .filter(t -> t.getPriority() < task.getPriority()) .count(); tasks.add(index, task); } /** * Method get first task from list. * * @return first task from list tasks. */ public final Task takeFirst() { return this.tasks.pollFirst(); } /** * Method get last task from list. * * @return last task from list. */ public final Task takeLast() { return this.tasks.pollLast(); } }
92415bf5b73187a220f235e1f7bdfd9a568ea38e
1,730
java
Java
app/src/main/java/com/wechat/files/cleaner/holder/WechatCleanResultGroupViewHolder.java
DavidInChina/DavidInChina-Cleaner
699af9a3a988da90e0737b26e82ce65449c106e5
[ "Apache-2.0" ]
7
2020-05-28T03:15:24.000Z
2021-12-02T10:32:26.000Z
app/src/main/java/com/wechat/files/cleaner/holder/WechatCleanResultGroupViewHolder.java
DavidInChina/DavidInChina-Cleaner
699af9a3a988da90e0737b26e82ce65449c106e5
[ "Apache-2.0" ]
1
2021-07-19T06:59:42.000Z
2021-07-19T06:59:42.000Z
app/src/main/java/com/wechat/files/cleaner/holder/WechatCleanResultGroupViewHolder.java
DavidInChina/DavidInChina-Cleaner
699af9a3a988da90e0737b26e82ce65449c106e5
[ "Apache-2.0" ]
1
2020-07-24T06:54:51.000Z
2020-07-24T06:54:51.000Z
27.03125
114
0.713295
1,001,878
package com.wechat.files.cleaner.holder; import android.support.v7.widget.AppCompatCheckBox; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.TextView; import com.thoughtbot.expandablerecyclerview.viewholders.GroupViewHolder; import com.wechat.files.cleaner.R; import butterknife.BindView; import butterknife.ButterKnife; public class WechatCleanResultGroupViewHolder extends GroupViewHolder { @BindView(R.id.arrow) public ImageView mArrow; @BindView(R.id.junk_type_name) public TextView mJunkTypeName; @BindView(R.id.junk_count) public TextView mJunkItemCount; @BindView(R.id.total_size) public TextView mTotalSize; @BindView(R.id.checkBox) public AppCompatCheckBox mCheckBox; public WechatCleanResultGroupViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void expand() { animateExpand(); } @Override public void collapse() { animateCollapse(); } private void animateExpand() { RotateAnimation rotate = new RotateAnimation(360, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotate.setDuration(300); rotate.setFillAfter(true); mArrow.startAnimation(rotate); } private void animateCollapse() { RotateAnimation rotate = new RotateAnimation(180, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotate.setDuration(300); rotate.setFillAfter(true); mArrow.startAnimation(rotate); } }
92415c61e01e7d565dcff9d5fb81a171fa5a52d9
249
java
Java
src/com/zzy/learn/swing/tabs/tinypng/view/ia/ViewIA.java
zhaoyangzhou/tinypng_client
6973e827f8b1cbbef2cdf0a4d811cdea3e875bed
[ "Apache-2.0" ]
null
null
null
src/com/zzy/learn/swing/tabs/tinypng/view/ia/ViewIA.java
zhaoyangzhou/tinypng_client
6973e827f8b1cbbef2cdf0a4d811cdea3e875bed
[ "Apache-2.0" ]
null
null
null
src/com/zzy/learn/swing/tabs/tinypng/view/ia/ViewIA.java
zhaoyangzhou/tinypng_client
6973e827f8b1cbbef2cdf0a4d811cdea3e875bed
[ "Apache-2.0" ]
null
null
null
20.75
58
0.7751
1,001,879
package com.zzy.learn.swing.tabs.tinypng.view.ia; import java.io.File; import java.util.Vector; import com.zzy.learn.swing.tabs.tinypng.model.ia.Callback; public interface ViewIA extends Callback { void doRequest(File file); void doCancel(); }
92415d37c3a8d6c475b4b3df97651ef3e98cb03d
11,817
java
Java
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/DetailedEnvironmentResponse.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
174
2017-07-14T03:20:42.000Z
2022-03-25T05:03:18.000Z
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/DetailedEnvironmentResponse.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
2,242
2017-07-12T05:52:01.000Z
2022-03-31T15:50:08.000Z
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/DetailedEnvironmentResponse.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
172
2017-07-12T08:53:48.000Z
2022-03-24T12:16:33.000Z
34.351744
106
0.6874
1,001,880
package com.sequenceiq.environment.api.v1.environment.model.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.sequenceiq.common.api.backup.response.BackupResponse; import com.sequenceiq.common.api.telemetry.response.TelemetryResponse; import com.sequenceiq.common.api.type.CcmV2TlsType; import com.sequenceiq.common.api.type.Tunnel; import com.sequenceiq.environment.api.doc.environment.EnvironmentModelDescription; import com.sequenceiq.environment.api.v1.credential.model.response.CredentialResponse; import com.sequenceiq.environment.api.v1.environment.model.base.CloudStorageValidation; import com.sequenceiq.environment.api.v1.environment.model.base.IdBrokerMappingSource; import com.sequenceiq.environment.api.v1.environment.model.request.aws.AwsEnvironmentParameters; import com.sequenceiq.environment.api.v1.environment.model.request.azure.AzureEnvironmentParameters; import com.sequenceiq.environment.api.v1.environment.model.request.gcp.GcpEnvironmentParameters; import com.sequenceiq.environment.api.v1.environment.model.request.yarn.YarnEnvironmentParameters; import com.sequenceiq.environment.api.v1.proxy.model.response.ProxyResponse; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @ApiModel(value = "DetailedEnvironmentV1Response") public class DetailedEnvironmentResponse extends EnvironmentBaseResponse { @ApiModelProperty(EnvironmentModelDescription.CREDENTIAL_RESPONSE) private CredentialResponse credential; @ApiModelProperty(EnvironmentModelDescription.PROXYCONFIG_RESPONSE) private ProxyResponse proxyConfig; public CredentialResponse getCredential() { return credential; } public void setCredential(CredentialResponse credential) { this.credential = credential; } public ProxyResponse getProxyConfig() { return proxyConfig; } public void setProxyConfig(ProxyResponse proxyConfig) { this.proxyConfig = proxyConfig; } public static Builder builder() { return new Builder(); } @Override public String toString() { return super.toString() + ", " + "DetailedEnvironmentResponse{" + "credential=" + credential + ", proxyConfig=" + proxyConfig + '}'; } public static final class Builder { private String crn; private String name; private String description; private String creator; private boolean createFreeIpa; private FreeIpaResponse freeIpa; private CompactRegionResponse regions; private String cloudPlatform; private CredentialResponse credential; private LocationResponse location; private EnvironmentNetworkResponse network; private TelemetryResponse telemetry; private BackupResponse backup; private EnvironmentStatus environmentStatus; private String statusReason; private Long created; private EnvironmentAuthenticationResponse authentication; private SecurityAccessResponse securityAccess; private Tunnel tunnel; private String adminGroupName; private IdBrokerMappingSource idBrokerMappingSource; private CloudStorageValidation cloudStorageValidation; private AwsEnvironmentParameters aws; private AzureEnvironmentParameters azure; private TagResponse tag; private String parentEnvironmentCrn; private String parentEnvironmentName; private String parentEnvironmentCloudPlatform; private ProxyResponse proxyConfig; private GcpEnvironmentParameters gcp; private YarnEnvironmentParameters yarn; private String environmentServiceVersion; private CcmV2TlsType ccmV2TlsType; private EnvironmentDeletionType deletionType; private Builder() { } public Builder withCrn(String crn) { this.crn = crn; return this; } public Builder withName(String name) { this.name = name; return this; } public Builder withDescription(String description) { this.description = description; return this; } public Builder withRegions(CompactRegionResponse regions) { this.regions = regions; return this; } public Builder withCreator(String creator) { this.creator = creator; return this; } public Builder withCloudPlatform(String cloudPlatform) { this.cloudPlatform = cloudPlatform; return this; } public Builder withCredential(CredentialResponse credential) { this.credential = credential; return this; } public Builder withLocation(LocationResponse location) { this.location = location; return this; } public Builder withNetwork(EnvironmentNetworkResponse network) { this.network = network; return this; } public Builder withTelemetry(TelemetryResponse telemetry) { this.telemetry = telemetry; return this; } public Builder withBackup(BackupResponse backup) { this.backup = backup; return this; } public Builder withEnvironmentStatus(EnvironmentStatus environmentStatus) { this.environmentStatus = environmentStatus; return this; } public Builder withCreateFreeIpa(boolean createFreeIpa) { this.createFreeIpa = createFreeIpa; return this; } public Builder withFreeIpa(FreeIpaResponse freeIpa) { this.freeIpa = freeIpa; return this; } public Builder withStatusReason(String statusReason) { this.statusReason = statusReason; return this; } public Builder withCreated(Long created) { this.created = created; return this; } public Builder withAuthentication(EnvironmentAuthenticationResponse authentication) { this.authentication = authentication; return this; } public Builder withSecurityAccess(SecurityAccessResponse securityAccess) { this.securityAccess = securityAccess; return this; } public Builder withTunnel(Tunnel tunnel) { this.tunnel = tunnel; return this; } public Builder withIdBrokerMappingSource(IdBrokerMappingSource idBrokerMappingSource) { this.idBrokerMappingSource = idBrokerMappingSource; return this; } public Builder withCloudStorageValidation(CloudStorageValidation cloudStorageValidation) { this.cloudStorageValidation = cloudStorageValidation; return this; } public Builder withAdminGroupName(String adminGroupName) { this.adminGroupName = adminGroupName; return this; } public Builder withAws(AwsEnvironmentParameters aws) { this.aws = aws; return this; } public Builder withAzure(AzureEnvironmentParameters azure) { this.azure = azure; return this; } public Builder withYarn(YarnEnvironmentParameters yarn) { this.yarn = yarn; return this; } public Builder withTag(TagResponse tag) { this.tag = tag; return this; } public Builder withParentEnvironmentCrn(String parentEnvironmentCrn) { this.parentEnvironmentCrn = parentEnvironmentCrn; return this; } public Builder withParentEnvironmentName(String parentEnvironmentName) { this.parentEnvironmentName = parentEnvironmentName; return this; } public Builder withParentEnvironmentCloudPlatform(String parentEnvironmentCloudPlatform) { this.parentEnvironmentCloudPlatform = parentEnvironmentCloudPlatform; return this; } public Builder withProxyConfig(ProxyResponse proxyConfig) { this.proxyConfig = proxyConfig; return this; } public Builder withGcp(GcpEnvironmentParameters gcp) { this.gcp = gcp; return this; } public Builder withEnvironmentServiceVersion(String environmentServiceVersion) { this.environmentServiceVersion = environmentServiceVersion; return this; } public Builder withCcmV2TlsType(CcmV2TlsType ccmV2TlsType) { this.ccmV2TlsType = ccmV2TlsType; return this; } public Builder withDeletionType(EnvironmentDeletionType deletionType) { this.deletionType = deletionType; return this; } public DetailedEnvironmentResponse build() { DetailedEnvironmentResponse detailedEnvironmentResponse = new DetailedEnvironmentResponse(); detailedEnvironmentResponse.setCrn(crn); detailedEnvironmentResponse.setName(name); detailedEnvironmentResponse.setCreator(creator); detailedEnvironmentResponse.setDescription(description); detailedEnvironmentResponse.setRegions(regions); detailedEnvironmentResponse.setCloudPlatform(cloudPlatform); detailedEnvironmentResponse.setCredential(credential); detailedEnvironmentResponse.setLocation(location); detailedEnvironmentResponse.setNetwork(network); detailedEnvironmentResponse.setCreateFreeIpa(createFreeIpa); detailedEnvironmentResponse.setFreeIpa(freeIpa); detailedEnvironmentResponse.setEnvironmentStatus(environmentStatus); detailedEnvironmentResponse.setStatusReason(statusReason); detailedEnvironmentResponse.setCreated(created); detailedEnvironmentResponse.setAuthentication(authentication); detailedEnvironmentResponse.setTelemetry(telemetry); detailedEnvironmentResponse.setBackup(backup); detailedEnvironmentResponse.setSecurityAccess(securityAccess); detailedEnvironmentResponse.setTunnel(tunnel); detailedEnvironmentResponse.setIdBrokerMappingSource(idBrokerMappingSource); detailedEnvironmentResponse.setCloudStorageValidation(cloudStorageValidation); detailedEnvironmentResponse.setAdminGroupName(adminGroupName); detailedEnvironmentResponse.setAws(aws); detailedEnvironmentResponse.setTags(tag); detailedEnvironmentResponse.setParentEnvironmentCrn(parentEnvironmentCrn); detailedEnvironmentResponse.setParentEnvironmentName(parentEnvironmentName); detailedEnvironmentResponse.setParentEnvironmentCloudPlatform(parentEnvironmentCloudPlatform); detailedEnvironmentResponse.setProxyConfig(proxyConfig); detailedEnvironmentResponse.setAzure(azure); detailedEnvironmentResponse.setGcp(gcp); detailedEnvironmentResponse.setYarn(yarn); detailedEnvironmentResponse.setEnvironmentServiceVersion(environmentServiceVersion); detailedEnvironmentResponse.setCcmV2TlsType(ccmV2TlsType); detailedEnvironmentResponse.setDeletionType(deletionType); return detailedEnvironmentResponse; } } }
92415d9ac1ffc210a4019bb898b38c04951f98f4
1,567
java
Java
src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/AbstractSuperClass.java
sjvs/Kundera
2d9644587a9ee0ab31fbba5a08c3481032d4db4e
[ "Apache-2.0" ]
377
2015-01-02T07:59:37.000Z
2018-01-27T12:13:16.000Z
src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/AbstractSuperClass.java
sjvs/Kundera
2d9644587a9ee0ab31fbba5a08c3481032d4db4e
[ "Apache-2.0" ]
332
2015-01-02T10:14:23.000Z
2018-01-29T14:22:24.000Z
src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/AbstractSuperClass.java
sjvs/Kundera
2d9644587a9ee0ab31fbba5a08c3481032d4db4e
[ "Apache-2.0" ]
135
2015-01-02T07:59:42.000Z
2018-01-25T19:22:13.000Z
26.116667
80
0.596682
1,001,881
/******************************************************************************* * * Copyright 2017 Impetus Infotech. * * * * 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.impetus.kundera.client.crud.entitylisteners; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; /** * The Class AbstractSuperClass. */ @MappedSuperclass @EntityListeners(Listener.class) public abstract class AbstractSuperClass { /** The extern id. */ private String externId; /** * Instantiates a new abstract super class. */ public AbstractSuperClass() { } /** * Gets the extern id. * * @return the extern id */ public String getExternId() { return this.externId; } /** * Sets the extern id. * * @param externId * the new extern id */ public void setExternId(String externId) { this.externId = externId; } }
92415f3de5353b4971df272ee5c0f86ac3b92286
201
java
Java
CoreFeatures/Base/IAction/src/main/java/info/smart_tools/smartactors/base/interfaces/iaction/IPoorAction.java
d-protsenko/smartactors-core
c548148636dd49510d8f6130157f2095d5ec671b
[ "Apache-2.0" ]
null
null
null
CoreFeatures/Base/IAction/src/main/java/info/smart_tools/smartactors/base/interfaces/iaction/IPoorAction.java
d-protsenko/smartactors-core
c548148636dd49510d8f6130157f2095d5ec671b
[ "Apache-2.0" ]
null
null
null
CoreFeatures/Base/IAction/src/main/java/info/smart_tools/smartactors/base/interfaces/iaction/IPoorAction.java
d-protsenko/smartactors-core
c548148636dd49510d8f6130157f2095d5ec671b
[ "Apache-2.0" ]
null
null
null
20.1
61
0.791045
1,001,882
package info.smart_tools.smartactors.base.interfaces.iaction; /** * Interface IPoorAction. * Action without incoming argument. */ @Deprecated public interface IPoorAction extends IActionNoArgs { }
92416012402ea44376b8d4021236d334422f9243
3,069
java
Java
src/main/java/org/apache/hadoop/yarn/server/nodemanager/GlusterContainerExecutor.java
shtripat/glusterfs-hadoop
955da2ae2f042f1f9e6ab44106d4e836445543b1
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/hadoop/yarn/server/nodemanager/GlusterContainerExecutor.java
shtripat/glusterfs-hadoop
955da2ae2f042f1f9e6ab44106d4e836445543b1
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/hadoop/yarn/server/nodemanager/GlusterContainerExecutor.java
shtripat/glusterfs-hadoop
955da2ae2f042f1f9e6ab44106d4e836445543b1
[ "Apache-2.0" ]
null
null
null
42.041096
108
0.79798
1,001,883
/** * 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.nodemanager; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.Shell.ExitCodeException; import org.apache.hadoop.util.Shell.ShellCommandExecutor; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.ExitCode; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.Signal; import org.apache.hadoop.yarn.server.nodemanager.LinuxContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerDiagnosticsUpdateEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer; import org.apache.hadoop.yarn.server.nodemanager.util.DefaultLCEResourcesHandler; import org.apache.hadoop.yarn.server.nodemanager.util.LCEResourcesHandler; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.log4j.spi.LoggerFactory; import org.slf4j.Logger; public class GlusterContainerExecutor extends LinuxContainerExecutor { static Logger log = org.slf4j.LoggerFactory.getLogger(GlusterContainerExecutor.class); /** * We override the YARN-1235 patch here. * @param user * @return */ @Override String getRunAsUser(String user) { log.info("Container EXEC overrid: returning user " + user); //return UserGroupInformation.isSecurityEnabled() ? user : nonsecureLocalUser; return user; } @Override public void deleteAsUser(String arg0,Path arg1,Path...arg2){ log.info("DELETE AS USER " + arg0 + " " + arg1 +" " + arg2); super.deleteAsUser(arg0, arg1, arg2); } }
924161f8f96851b16980b69bbd17e2231fd877d1
2,577
java
Java
src/main/java/pw/aru/libs/snowflake/local/LocalWorker.java
jibrilbot/snowflake-local
a406b4be0d873feb0fb090ace6d6825483de1abb
[ "Apache-2.0" ]
null
null
null
src/main/java/pw/aru/libs/snowflake/local/LocalWorker.java
jibrilbot/snowflake-local
a406b4be0d873feb0fb090ace6d6825483de1abb
[ "Apache-2.0" ]
null
null
null
src/main/java/pw/aru/libs/snowflake/local/LocalWorker.java
jibrilbot/snowflake-local
a406b4be0d873feb0fb090ace6d6825483de1abb
[ "Apache-2.0" ]
null
null
null
31.814815
169
0.656577
1,001,884
package pw.aru.libs.snowflake.local; import pw.aru.libs.snowflake.SnowflakeConfig; import pw.aru.libs.snowflake.entities.SnowflakeDatacenter; import pw.aru.libs.snowflake.entities.SnowflakeGenerator; import pw.aru.libs.snowflake.entities.SnowflakeWorker; import static java.lang.System.currentTimeMillis; class LocalWorker implements SnowflakeWorker { private final LocalDatacenter datacenter; private final LocalGenerator generator; private final long workerId; private long lastTimestamp = -1L; private long sequence = 0L; LocalWorker(LocalGenerator generator, LocalDatacenter datacenter, long workerId) { this.generator = generator; this.datacenter = datacenter; // sanity check for workerId long maxWorkerId = generator.config.maxWorkerId; if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException("Worker ID can't be greater than " + maxWorkerId + " or less than 0"); } this.workerId = workerId; } @Override public long generate() { SnowflakeConfig config = generator.getConfig(); long timestamp = currentTimeMillis(); if (timestamp < lastTimestamp) { throw new IllegalStateException(String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp )); } synchronized (this) { if (lastTimestamp == timestamp) { sequence = (sequence + 1) & config.sequenceMask; if (sequence == 0) timestamp = tilNextMillis(lastTimestamp); } else sequence = 0L; lastTimestamp = timestamp; return timestamp - config.epoch << config.timestampShift | datacenter.datacenterId << config.datacenterIdShift | workerId << config.workerIdShift | sequence; } } @Override public SnowflakeDatacenter getDatacenter() { return datacenter; } @Override public SnowflakeGenerator getGenerator() { return generator; } @Override public long getWorkerId() { return workerId; } @Override public String toString() { return "LocalWorker[config=" + generator.config + ", datacenterId=" + datacenter.datacenterId + ", workerId=" + workerId + "]"; } private long tilNextMillis(long lastTimestamp) { long timestamp = currentTimeMillis(); while (timestamp <= lastTimestamp) timestamp = currentTimeMillis(); return timestamp; } }
92416214a3271217c44c64afa0a36378f8ce3ee1
61
java
Java
src/main/java/org/caulfield/enigma/Enigma.java
megaman2/egnima
232b40ea03bbc8945438329a9d9d0b738f1a1bdd
[ "MIT" ]
null
null
null
src/main/java/org/caulfield/enigma/Enigma.java
megaman2/egnima
232b40ea03bbc8945438329a9d9d0b738f1a1bdd
[ "MIT" ]
null
null
null
src/main/java/org/caulfield/enigma/Enigma.java
megaman2/egnima
232b40ea03bbc8945438329a9d9d0b738f1a1bdd
[ "MIT" ]
null
null
null
10.166667
30
0.688525
1,001,885
package org.caulfield.enigma; public class Enigma { }
92416214ab13d2071b864c6dfff22a442f611900
319
java
Java
customer-entity-external/customer-entity-postgresql-db/src/main/java/com/jrmcdonald/customer/entity/db/repository/CustomerRepository.java
jrmcdonald/ms-customer-entity
18ad1b4e321e807c6c8d286fe0adbca80dad98d7
[ "MIT" ]
null
null
null
customer-entity-external/customer-entity-postgresql-db/src/main/java/com/jrmcdonald/customer/entity/db/repository/CustomerRepository.java
jrmcdonald/ms-customer-entity
18ad1b4e321e807c6c8d286fe0adbca80dad98d7
[ "MIT" ]
19
2020-05-25T19:56:39.000Z
2020-12-22T09:29:07.000Z
customer-entity-external/customer-entity-postgresql-db/src/main/java/com/jrmcdonald/customer/entity/db/repository/CustomerRepository.java
jrmcdonald/ms-customer-entity
18ad1b4e321e807c6c8d286fe0adbca80dad98d7
[ "MIT" ]
null
null
null
26.583333
77
0.84326
1,001,886
package com.jrmcdonald.customer.entity.db.repository; import com.jrmcdonald.customer.entity.db.model.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CustomerRepository extends JpaRepository<Customer, String> { }
924163124f6f3e8113474acac9262bb99860b916
3,277
java
Java
src/main/java/com/spotinst/sdkjava/model/ElastigroupCapacityConfiguration.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
2
2017-10-20T04:53:19.000Z
2020-09-14T11:04:21.000Z
src/main/java/com/spotinst/sdkjava/model/ElastigroupCapacityConfiguration.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
31
2018-10-09T18:32:48.000Z
2022-03-09T06:06:39.000Z
src/main/java/com/spotinst/sdkjava/model/ElastigroupCapacityConfiguration.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
5
2017-08-20T14:34:37.000Z
2021-06-04T09:42:25.000Z
21.993289
67
0.609399
1,001,887
package com.spotinst.sdkjava.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.HashSet; import java.util.Set; /** * Created by aharontwizer on 8/24/15. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class ElastigroupCapacityConfiguration { //region Members @JsonIgnore private Set<String> isSet; private Integer minimum; private Integer maximum; private Integer target; private String unit; //endregion //region Constructor private ElastigroupCapacityConfiguration() { isSet = new HashSet<>(); } //endregion //region Getter and Setter methods public Set<String> getIsSet() { return isSet; } public void setIsSet(Set<String> isSet) { this.isSet = isSet; } public Integer getMinimum() { return minimum; } public void setMinimum(Integer minimum) { isSet.add("minimum"); this.minimum = minimum; } public Integer getMaximum() { return maximum; } public void setMaximum(Integer maximum) { isSet.add("maximum"); this.maximum = maximum; } public Integer getTarget() { return target; } public void setTarget(Integer target) { isSet.add("target"); this.target = target; } public String getUnit() { return unit; } public void setUnit(String unit) { isSet.add("unit"); this.unit = unit; } //endregion //endregion //region Builder class public static class Builder { private ElastigroupCapacityConfiguration capacity; private Builder() { this.capacity = new ElastigroupCapacityConfiguration(); } public static Builder get() { Builder builder = new Builder(); return builder; } public Builder setMinimum(final Integer minimum) { capacity.setMinimum(minimum); return this; } public Builder setMaximum(final Integer maximum) { capacity.setMaximum(maximum); return this; } public Builder setTarget(final Integer target) { capacity.setTarget(target); return this; } public Builder setUnit(final String unit) { capacity.setUnit(unit); return this; } public ElastigroupCapacityConfiguration build() { // TODO : Validations return capacity; } } //endregion //region isSet methods // Is minimum Set boolean method @JsonIgnore public boolean isMinimumSet() { return isSet.contains("minimum"); } // Is maximum Set boolean method @JsonIgnore public boolean isMaximumSet() { return isSet.contains("maximum"); } // Is target Set boolean method @JsonIgnore public boolean isTargetSet() { return isSet.contains("target"); } @JsonIgnore public boolean isUnitSet() { return isSet.contains("unit"); } //endregion }
924163d3548fc63d353db2fa4d46239edd396ef7
302
java
Java
wegas-core/src/main/java/com/wegas/core/persistence/Orderable.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
wegas-core/src/main/java/com/wegas/core/persistence/Orderable.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
wegas-core/src/main/java/com/wegas/core/persistence/Orderable.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
15.1
78
0.63245
1,001,888
/** * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2020 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ package com.wegas.core.persistence; /** * @author Maxence */ public interface Orderable { /* * */ Integer getOrder(); }
9241644dcb9c2c7877761c19a5da7d9c93deeebc
7,607
java
Java
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReferenceValidation.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-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReferenceValidation.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-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReferenceValidation.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
33.959821
78
0.684107
1,001,889
/* * 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.hdfs.server.namenode; import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions; import org.apache.hadoop.hdfs.server.namenode.FsImageValidation.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.apache.hadoop.hdfs.server.namenode.FsImageValidation.Cli.*; /** For validating {@link INodeReference} subclasses. */ public class INodeReferenceValidation { public static final Logger LOG = LoggerFactory.getLogger( INodeReferenceValidation.class); private static final AtomicReference<INodeReferenceValidation> INSTANCE = new AtomicReference<>(); public static void start() { INSTANCE.compareAndSet(null, new INodeReferenceValidation()); println("%s started", INodeReferenceValidation.class.getSimpleName()); } public static void end(AtomicInteger errorCount) { final INodeReferenceValidation instance = INSTANCE.getAndSet(null); if (instance == null) { return; } final int initCount = errorCount.get(); instance.assertReferences(errorCount); println("%s ended successfully: %d error(s) found.", INodeReferenceValidation.class.getSimpleName(), errorCount.get() - initCount); } static <REF extends INodeReference> void add(REF ref, Class<REF> clazz) { final INodeReferenceValidation validation = INSTANCE.get(); if (validation != null) { final boolean added = validation.getReferences(clazz).add(ref); Preconditions.checkState(added); LOG.trace("add {}: {}", clazz, ref.toDetailString()); } } static <REF extends INodeReference> void remove(REF ref, Class<REF> clazz) { final INodeReferenceValidation validation = INSTANCE.get(); if (validation != null) { final boolean removed = validation.getReferences(clazz).remove(ref); Preconditions.checkState(removed); LOG.trace("remove {}: {}", clazz, ref.toDetailString()); } } static class ReferenceSet<REF extends INodeReference> { private final Class<REF> clazz; private final List<REF> references = new LinkedList<>(); private volatile List<Task<REF>> tasks; private volatile List<Future<Integer>> futures; private final AtomicInteger taskCompleted = new AtomicInteger(); ReferenceSet(Class<REF> clazz) { this.clazz = clazz; } boolean add(REF ref) { return references.add(ref); } boolean remove(REF ref) { for(final Iterator<REF> i = references.iterator(); i.hasNext();) { if (i.next() == ref) { i.remove(); return true; } } return false; } void submit(AtomicInteger errorCount, ExecutorService service) throws InterruptedException { final int size = references.size(); tasks = createTasks(references, errorCount); println("Submitting %d tasks for validating %s %s(s)", tasks.size(), Util.toCommaSeparatedNumber(size), clazz.getSimpleName()); futures = service.invokeAll(tasks); } void waitForFutures() throws Exception { for(Future<Integer> f : futures) { f.get(); taskCompleted.incrementAndGet(); } } double getTaskCompletedPercent() { final List<Task<REF>> t = tasks; return t == null? 0 : t.isEmpty()? 100 : taskCompleted.get()*100.0/tasks.size(); } @Override public String toString() { return String.format("%s %.1f%%", clazz.getSimpleName(), getTaskCompletedPercent()); } } private final ReferenceSet<INodeReference.WithCount> withCounts = new ReferenceSet<>(INodeReference.WithCount.class); private final ReferenceSet<INodeReference.WithName> withNames = new ReferenceSet<>(INodeReference.WithName.class); private final ReferenceSet<INodeReference.DstReference> dstReferences = new ReferenceSet<>(INodeReference.DstReference.class); <REF extends INodeReference> ReferenceSet<REF> getReferences( Class<REF> clazz) { if (clazz == INodeReference.WithCount.class) { return (ReferenceSet<REF>) withCounts; } else if (clazz == INodeReference.WithName.class) { return (ReferenceSet<REF>) withNames; } else if (clazz == INodeReference.DstReference.class) { return (ReferenceSet<REF>) dstReferences; } throw new IllegalArgumentException("References not found for " + clazz); } private void assertReferences(AtomicInteger errorCount) { final int p = Runtime.getRuntime().availableProcessors(); LOG.info("Available Processors: {}", p); final ExecutorService service = Executors.newFixedThreadPool(p); final TimerTask checkProgress = new TimerTask() { @Override public void run() { LOG.info("ASSERT_REFERENCES Progress: {}, {}, {}", dstReferences, withCounts, withNames); } }; final Timer t = new Timer(); t.scheduleAtFixedRate(checkProgress, 0, 1_000); try { dstReferences.submit(errorCount, service); withCounts.submit(errorCount, service); withNames.submit(errorCount, service); dstReferences.waitForFutures(); withCounts.waitForFutures(); withNames.waitForFutures(); } catch (Throwable e) { printError("Failed to assertReferences", e); } finally { service.shutdown(); t.cancel(); } } static <REF extends INodeReference> List<Task<REF>> createTasks( List<REF> references, AtomicInteger errorCount) { final List<Task<REF>> tasks = new LinkedList<>(); for (final Iterator<REF> i = references.iterator(); i.hasNext();) { tasks.add(new Task<>(i, errorCount)); } return tasks; } static class Task<REF extends INodeReference> implements Callable<Integer> { static final int BATCH_SIZE = 100_000; private final List<REF> references = new LinkedList<>(); private final AtomicInteger errorCount; Task(Iterator<REF> i, AtomicInteger errorCount) { for(int n = 0; i.hasNext() && n < BATCH_SIZE; n++) { references.add(i.next()); i.remove(); } this.errorCount = errorCount; } @Override public Integer call() throws Exception { for (final REF ref : references) { try { ref.assertReferences(); } catch (Throwable t) { printError(errorCount, "%s", t); } } return references.size(); } } }
9241649143cc8a239b8c9dc8ced97b6900498a2e
4,730
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotutil/VuMark.java
theintersect/intersect2018
8e1885b20be0c9bf84fb353b54122b80416edf27
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotutil/VuMark.java
theintersect/intersect2018
8e1885b20be0c9bf84fb353b54122b80416edf27
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotutil/VuMark.java
theintersect/intersect2018
8e1885b20be0c9bf84fb353b54122b80416edf27
[ "MIT" ]
null
null
null
49.784314
422
0.780228
1,001,890
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) 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 FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. 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.firstinspires.ftc.teamcode.robotutil; import com.qualcomm.robotcore.eventloop.opmode.*; import org.firstinspires.ftc.robotcontroller.external.samples.ConceptVuforiaNavigation; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix; import org.firstinspires.ftc.robotcore.external.matrices.VectorF; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark; import org.firstinspires.ftc.robotcore.external.navigation.VuMarkInstanceId; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables; public class VuMark { public VuforiaTrackables relicTrackables; public VuforiaLocalizer vuforia; public VuforiaTrackable relicTemplate; public RelicRecoveryVuMark vuMark; public LinearOpMode opMode; VuforiaLocalizer.Parameters parameters; public VuMark(LinearOpMode opMode) { this.opMode = opMode; int cameraMonitorViewId = opMode.hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", opMode.hardwareMap.appContext.getPackageName()); parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId); parameters.vuforiaLicenseKey = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK; this.vuforia = ClassFactory.createVuforiaLocalizer(parameters); relicTrackables = this.vuforia.loadTrackablesFromAsset("RelicVuMark"); relicTemplate = relicTrackables.get(0); relicTemplate.setName("relicVuMarkTemplate"); vuMark = RelicRecoveryVuMark.from(relicTemplate); relicTrackables.activate(); } public RelicRecoveryVuMark detectColumn(int timeoutS) { long endtime = System.currentTimeMillis() + (timeoutS * 1000); while (opMode.opModeIsActive() && System.currentTimeMillis()<endtime && vuMark == RelicRecoveryVuMark.UNKNOWN) { vuMark = RelicRecoveryVuMark.from(relicTemplate); opMode.telemetry.addLine("Detecting VuMark....."); opMode.telemetry.addLine(vuMark.toString()); opMode.telemetry.update(); } if (vuMark != RelicRecoveryVuMark.UNKNOWN) { opMode.telemetry.addData("Detected ", vuMark); }else{ opMode.telemetry.addLine("Detection timed out"); } opMode.telemetry.addLine(vuMark.toString()); opMode.telemetry.update(); return vuMark; } }
924164b9b5f47a9b31214c1031fde5dc279f7294
3,806
java
Java
utils_android/src/main/java/com/georgebindragon/base/system/software/BroadcastReceiverUtil.java
GeorgeBin/BaseUtils
8f995736b5f9d88136027864d5533f454bfbe535
[ "MIT" ]
null
null
null
utils_android/src/main/java/com/georgebindragon/base/system/software/BroadcastReceiverUtil.java
GeorgeBin/BaseUtils
8f995736b5f9d88136027864d5533f454bfbe535
[ "MIT" ]
null
null
null
utils_android/src/main/java/com/georgebindragon/base/system/software/BroadcastReceiverUtil.java
GeorgeBin/BaseUtils
8f995736b5f9d88136027864d5533f454bfbe535
[ "MIT" ]
null
null
null
30.448
153
0.733841
1,001,891
package com.georgebindragon.base.system.software; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import com.georgebindragon.base.function.log.LogProxy; import com.georgebindragon.base.utils.EmptyUtil; import com.georgebindragon.base.utils.StringUtil; import java.util.Set; /** * 创建人:George * 类名称:BroadcastReceiverUtil * 类概述: * 详细描述: * * 1. 完整解析Broadcast的Intent的内容 * * 修改人: * 修改时间: * 修改备注: */ public class BroadcastReceiverUtil { private static final String TAG = "BroadcastReceiverUtil-->"; public static void getBroadcastIntentDetail(Intent intent) { getBroadcastIntentDetail(TAG, intent); } public static void getBroadcastIntentDetail(String tag, Intent intent) { boolean logEnable = LogProxy.isLogEnable(); System.out.println("getBroadcastIntentDetail-->log是否可见: " + (logEnable ? "可见, 进行打印" : "不可见, 不调用分析打印")); if (!logEnable) return; if (EmptyUtil.isEmpty(tag)) tag = TAG; try { if (EmptyUtil.isEmpty(intent)) return; String action = intent.getAction(); LogProxy.d(tag, "getBroadcastIntentDetail-->action=" + StringUtil.getPrintString(action)); if (null == action) return; Bundle extras = intent.getExtras(); if (null == extras) return; Set<String> keySet = extras.keySet(); //获取所有的Key if (null == keySet) return; for (String key : keySet)//bundle.get(key);来获取对应的value { Object value = extras.get(key); String keyInfo = "key" + (EmptyUtil.isEmpty(key) ? "" : "(" + key.getClass().getSimpleName() + ")") + "=" + StringUtil.getPrintString(key); String valueInfo = "value" + (EmptyUtil.isEmpty(value) ? "" : "(" + value.getClass().getSimpleName() + ")") + "=" + StringUtil.getPrintString(value); LogProxy.d(tag, "getBroadcastIntentDetail-->extras:Bundle:" + keyInfo + "\t\t" + valueInfo); } } catch (Exception e) { e.printStackTrace(); LogProxy.e(tag, "getBroadcastIntentDetail", e); } } public static void registerBroadcastByActionStrings(Context context, String[] actionStrings, BroadcastReceiver receiver) { registerBroadcastByActionStrings(context, actionStrings, 0, receiver); } public static void registerBroadcastByActionStrings(Context context, String[] actionStrings, int priority, BroadcastReceiver receiver) { if (EmptyUtil.notEmpty(context, actionStrings, receiver)) { IntentFilter intentFilter = new IntentFilter(); for (String action : actionStrings) { if (EmptyUtil.notEmpty(action)) intentFilter.addAction(action); } intentFilter.setPriority(priority);//设置 广播接受者 优先级 context.getApplicationContext().registerReceiver(receiver, intentFilter); LogProxy.i(TAG, "registerBroadcastByActionString-->注册广播"); } } public static void registerBroadcastByActionString(Context context, String actionString, BroadcastReceiver receiver) { registerBroadcastByActionString(context, actionString, 0, receiver); } public static void registerBroadcastByActionString(Context context, String actionString, int priority, BroadcastReceiver receiver) { if (EmptyUtil.notEmpty(context, actionString, receiver)) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(actionString); intentFilter.setPriority(priority);//设置 广播接受者 优先级 context.getApplicationContext().registerReceiver(receiver, intentFilter); LogProxy.i(TAG, "registerBroadcastByActionString-->注册广播"); } } public static void unregisterBroadcastReceiver(Context context, BroadcastReceiver receiver) { if (EmptyUtil.notEmpty(context, receiver)) { try { context.getApplicationContext().unregisterReceiver(receiver); } catch (Exception e) { LogProxy.e(TAG, "unregisterBroadcastReceiver", e); } } } }
924165063a2f3c6489c7742b3c79832f0e6f87b6
872
java
Java
src/main/java/self/liang/netty/example/com/shengsiyuan/netty/secondexample/MyClient.java
chenliangold4j/MyJavaDictionary
9769ee92e1abb54576910b68c68068469ef16b87
[ "Apache-2.0" ]
null
null
null
src/main/java/self/liang/netty/example/com/shengsiyuan/netty/secondexample/MyClient.java
chenliangold4j/MyJavaDictionary
9769ee92e1abb54576910b68c68068469ef16b87
[ "Apache-2.0" ]
1
2022-02-16T05:41:56.000Z
2022-02-16T05:41:56.000Z
src/main/java/self/liang/netty/example/com/shengsiyuan/netty/secondexample/MyClient.java
chenliangold4j/MyJavaDictionary
9769ee92e1abb54576910b68c68068469ef16b87
[ "Apache-2.0" ]
1
2020-11-24T00:37:09.000Z
2020-11-24T00:37:09.000Z
32.296296
86
0.694954
1,001,892
package self.liang.netty.example.com.shengsiyuan.netty.secondexample; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient { public static void main(String[] args) throws Exception{ EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). handler(new MyClientInitializer()); ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); channelFuture.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } }
9241680bba3fdd693dc56d64281307d169e918bb
1,347
java
Java
DFS/Detonate Maximum Bombs.java
KevzPeter/Le-epic-programming
d26de54ca870088f5d24067ee9049cb9d4de34e5
[ "MIT" ]
null
null
null
DFS/Detonate Maximum Bombs.java
KevzPeter/Le-epic-programming
d26de54ca870088f5d24067ee9049cb9d4de34e5
[ "MIT" ]
1
2021-12-10T14:30:01.000Z
2021-12-10T14:30:01.000Z
DFS/Detonate Maximum Bombs.java
KevzPeter/Le-epic-programming
d26de54ca870088f5d24067ee9049cb9d4de34e5
[ "MIT" ]
null
null
null
32.853659
99
0.475872
1,001,893
class Solution { public int maximumDetonation(int[][] bombs) { List<Integer>[] adj = new List[bombs.length]; for (int i = 0; i < bombs.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < bombs.length - 1; i++)// generate every pair for (int j = i + 1; j < bombs.length; j++) { long dist = dist(bombs[i], bombs[j]);// distance between the bombs if (dist <= 1l * bombs[i][2] * bombs[i][2]) adj[i].add(j);// make a edge from i to j if (dist <= 1l * bombs[j][2] * bombs[j][2]) adj[j].add(i);// make a edge from j to i } int res = 0; for (int i = 0; i < bombs.length; i++) // count the exploded bombs for every bomb explosion res = Math.max(res, dfs(adj, i, new boolean[bombs.length])); return res; } private int dfs(List<Integer>[] adj, int src, boolean[] vis) {// traverse graph if (vis[src]) return 0; int res = 1; vis[src] = true; for (int next : adj[src]) res += dfs(adj, next, vis); return res; } private long dist(int[] p1, int[] p2) {// distance formula return 1l * (p1[0] - p2[0]) * (p1[0] - p2[0]) + 1l * (p1[1] - p2[1]) * (p1[1] - p2[1]); } }
9241682036aa403d36a6ee5fa11ddd4c4d16922f
56,143
java
Java
hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
2
2019-04-24T15:30:34.000Z
2019-04-24T15:30:34.000Z
hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
null
null
null
hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
1
2018-08-29T08:04:48.000Z
2018-08-29T08:04:48.000Z
41.218796
100
0.739971
1,001,894
/** * 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.hbase; import static org.apache.hadoop.hbase.io.hfile.BlockType.MAGIC_LENGTH; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; import org.apache.commons.lang3.ArrayUtils; import org.apache.hadoop.hbase.util.Bytes; import org.apache.yetus.audience.InterfaceAudience; /** * HConstants holds a bunch of HBase-related constants */ @InterfaceAudience.Public public final class HConstants { // NOTICE!!!! Please do not add a constants here, unless they are referenced by a lot of classes. //Bytes.UTF8_ENCODING should be updated if this changed /** When we encode strings, we always specify UTF8 encoding */ public static final String UTF8_ENCODING = "UTF-8"; //Bytes.UTF8_CHARSET should be updated if this changed /** When we encode strings, we always specify UTF8 encoding */ public static final Charset UTF8_CHARSET = Charset.forName(UTF8_ENCODING); /** * Default block size for an HFile. */ public final static int DEFAULT_BLOCKSIZE = 64 * 1024; /** Used as a magic return value while optimized index key feature enabled(HBASE-7845) */ public final static int INDEX_KEY_MAGIC = -2; /* * Name of directory that holds recovered edits written by the wal log * splitting code, one per region */ public static final String RECOVERED_EDITS_DIR = "recovered.edits"; /** * The first four bytes of Hadoop RPC connections */ public static final byte[] RPC_HEADER = new byte[] { 'H', 'B', 'a', 's' }; public static final byte RPC_CURRENT_VERSION = 0; // HFileBlock constants. TODO!!!! THESE DEFINES BELONG IN HFILEBLOCK, NOT UP HERE. // Needed down in hbase-common though by encoders but these encoders should not be dealing // in the internals of hfileblocks. Fix encapsulation. /** The size data structures with minor version is 0 */ public static final int HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM = MAGIC_LENGTH + 2 * Bytes.SIZEOF_INT + Bytes.SIZEOF_LONG; /** The size of a version 2 HFile block header, minor version 1. * There is a 1 byte checksum type, followed by a 4 byte bytesPerChecksum * followed by another 4 byte value to store sizeofDataOnDisk. */ public static final int HFILEBLOCK_HEADER_SIZE = HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM + Bytes.SIZEOF_BYTE + 2 * Bytes.SIZEOF_INT; /** Just an array of bytes of the right size. */ public static final byte[] HFILEBLOCK_DUMMY_HEADER = new byte[HFILEBLOCK_HEADER_SIZE]; //End HFileBlockConstants. /** * Status codes used for return values of bulk operations. */ @InterfaceAudience.Private public enum OperationStatusCode { NOT_RUN, SUCCESS, BAD_FAMILY, STORE_TOO_BUSY, SANITY_CHECK_FAILURE, FAILURE } /** long constant for zero */ public static final Long ZERO_L = Long.valueOf(0L); public static final String NINES = "99999999999999"; public static final String ZEROES = "00000000000000"; // For migration /** name of version file */ public static final String VERSION_FILE_NAME = "hbase.version"; /** * Current version of file system. * Version 4 supports only one kind of bloom filter. * Version 5 changes versions in catalog table regions. * Version 6 enables blockcaching on catalog tables. * Version 7 introduces hfile -- hbase 0.19 to 0.20.. * Version 8 introduces namespace */ // public static final String FILE_SYSTEM_VERSION = "6"; public static final String FILE_SYSTEM_VERSION = "8"; // Configuration parameters //TODO: Is having HBase homed on port 60k OK? /** Cluster is in distributed mode or not */ public static final String CLUSTER_DISTRIBUTED = "hbase.cluster.distributed"; /** Config for pluggable load balancers */ public static final String HBASE_MASTER_LOADBALANCER_CLASS = "hbase.master.loadbalancer.class"; /** Config for balancing the cluster by table */ public static final String HBASE_MASTER_LOADBALANCE_BYTABLE = "hbase.master.loadbalance.bytable"; /** Config for the max percent of regions in transition */ public static final String HBASE_MASTER_BALANCER_MAX_RIT_PERCENT = "hbase.master.balancer.maxRitPercent"; /** Default value for the max percent of regions in transition */ public static final double DEFAULT_HBASE_MASTER_BALANCER_MAX_RIT_PERCENT = 1.0; /** Config for the max balancing time */ public static final String HBASE_BALANCER_MAX_BALANCING = "hbase.balancer.max.balancing"; /** Config for the balancer period */ public static final String HBASE_BALANCER_PERIOD = "hbase.balancer.period"; /** Default value for the balancer period */ public static final int DEFAULT_HBASE_BALANCER_PERIOD = 300000; /** The name of the ensemble table */ public static final TableName ENSEMBLE_TABLE_NAME = TableName.valueOf("hbase:ensemble"); /** Config for pluggable region normalizer */ public static final String HBASE_MASTER_NORMALIZER_CLASS = "hbase.master.normalizer.class"; /** Cluster is standalone or pseudo-distributed */ public static final boolean CLUSTER_IS_LOCAL = false; /** Default value for cluster distributed mode */ public static final boolean DEFAULT_CLUSTER_DISTRIBUTED = CLUSTER_IS_LOCAL; /** default host address */ public static final String DEFAULT_HOST = "0.0.0.0"; /** Parameter name for port master listens on. */ public static final String MASTER_PORT = "hbase.master.port"; /** default port that the master listens on */ public static final int DEFAULT_MASTER_PORT = 16000; /** default port for master web api */ public static final int DEFAULT_MASTER_INFOPORT = 16010; /** Configuration key for master web API port */ public static final String MASTER_INFO_PORT = "hbase.master.info.port"; /** Parameter name for the master type being backup (waits for primary to go inactive). */ public static final String MASTER_TYPE_BACKUP = "hbase.master.backup"; /** * by default every master is a possible primary master unless the conf explicitly overrides it */ public static final boolean DEFAULT_MASTER_TYPE_BACKUP = false; /** Name of ZooKeeper quorum configuration parameter. */ public static final String ZOOKEEPER_QUORUM = "hbase.zookeeper.quorum"; /** Name of ZooKeeper quorum configuration parameter for client to locate meta. */ public static final String CLIENT_ZOOKEEPER_QUORUM = "hbase.client.zookeeper.quorum"; /** Client port of ZooKeeper for client to locate meta */ public static final String CLIENT_ZOOKEEPER_CLIENT_PORT = "hbase.client.zookeeper.property.clientPort"; /** Indicate whether the client ZK are observer nodes of the server ZK */ public static final String CLIENT_ZOOKEEPER_OBSERVER_MODE = "hbase.client.zookeeper.observer.mode"; /** Assuming client zk not in observer mode and master need to synchronize information */ public static final boolean DEFAULT_CLIENT_ZOOKEEPER_OBSERVER_MODE = false; /** Common prefix of ZooKeeper configuration properties */ public static final String ZK_CFG_PROPERTY_PREFIX = "hbase.zookeeper.property."; public static final int ZK_CFG_PROPERTY_PREFIX_LEN = ZK_CFG_PROPERTY_PREFIX.length(); /** * The ZK client port key in the ZK properties map. The name reflects the * fact that this is not an HBase configuration key. */ public static final String CLIENT_PORT_STR = "clientPort"; /** Parameter name for the client port that the zookeeper listens on */ public static final String ZOOKEEPER_CLIENT_PORT = ZK_CFG_PROPERTY_PREFIX + CLIENT_PORT_STR; /** Default client port that the zookeeper listens on */ public static final int DEFAULT_ZOOKEEPER_CLIENT_PORT = 2181; /** Parameter name for the root dir in ZK for this cluster */ public static final String ZOOKEEPER_ZNODE_PARENT = "zookeeper.znode.parent"; public static final String DEFAULT_ZOOKEEPER_ZNODE_PARENT = "/hbase"; /** * Parameter name for the limit on concurrent client-side zookeeper * connections */ public static final String ZOOKEEPER_MAX_CLIENT_CNXNS = ZK_CFG_PROPERTY_PREFIX + "maxClientCnxns"; /** Parameter name for the ZK data directory */ public static final String ZOOKEEPER_DATA_DIR = ZK_CFG_PROPERTY_PREFIX + "dataDir"; /** Parameter name for the ZK tick time */ public static final String ZOOKEEPER_TICK_TIME = ZK_CFG_PROPERTY_PREFIX + "tickTime"; /** Default limit on concurrent client-side zookeeper connections */ public static final int DEFAULT_ZOOKEEPER_MAX_CLIENT_CNXNS = 300; /** Configuration key for ZooKeeper session timeout */ public static final String ZK_SESSION_TIMEOUT = "zookeeper.session.timeout"; /** Default value for ZooKeeper session timeout */ public static final int DEFAULT_ZK_SESSION_TIMEOUT = 90 * 1000; /** Parameter name for port region server listens on. */ public static final String REGIONSERVER_PORT = "hbase.regionserver.port"; /** Default port region server listens on. */ public static final int DEFAULT_REGIONSERVER_PORT = 16020; /** default port for region server web api */ public static final int DEFAULT_REGIONSERVER_INFOPORT = 16030; /** A configuration key for regionserver info port */ public static final String REGIONSERVER_INFO_PORT = "hbase.regionserver.info.port"; /** A flag that enables automatic selection of regionserver info port */ public static final String REGIONSERVER_INFO_PORT_AUTO = REGIONSERVER_INFO_PORT + ".auto"; /** Parameter name for what region server implementation to use. */ public static final String REGION_SERVER_IMPL= "hbase.regionserver.impl"; /** Parameter name for what master implementation to use. */ public static final String MASTER_IMPL= "hbase.master.impl"; /** Parameter name for how often threads should wake up */ public static final String THREAD_WAKE_FREQUENCY = "hbase.server.thread.wakefrequency"; /** Default value for thread wake frequency */ public static final int DEFAULT_THREAD_WAKE_FREQUENCY = 10 * 1000; /** Parameter name for how often we should try to write a version file, before failing */ public static final String VERSION_FILE_WRITE_ATTEMPTS = "hbase.server.versionfile.writeattempts"; /** Parameter name for how often we should try to write a version file, before failing */ public static final int DEFAULT_VERSION_FILE_WRITE_ATTEMPTS = 3; /** Parameter name and default value for how often a region should perform a major compaction */ public static final String MAJOR_COMPACTION_PERIOD = "hbase.hregion.majorcompaction"; public static final long DEFAULT_MAJOR_COMPACTION_PERIOD = 1000 * 60 * 60 * 24 * 7; // 7 days /** * Parameter name and default value for major compaction jitter. * Used as a multiplier applied to {@link HConstants#MAJOR_COMPACTION_PERIOD} * to cause compaction to occur a given amount of time either side of * {@link HConstants#MAJOR_COMPACTION_PERIOD}. * Default to 0.5 so jitter has us fall evenly either side of when the compaction should run. */ public static final String MAJOR_COMPACTION_JITTER = "hbase.hregion.majorcompaction.jitter"; public static final float DEFAULT_MAJOR_COMPACTION_JITTER = 0.50F; /** Parameter name for the maximum batch of KVs to be used in flushes and compactions */ public static final String COMPACTION_KV_MAX = "hbase.hstore.compaction.kv.max"; public static final int COMPACTION_KV_MAX_DEFAULT = 10; /** Parameter name for HBase instance root directory */ public static final String HBASE_DIR = "hbase.rootdir"; /** Parameter name for HBase client IPC pool type */ public static final String HBASE_CLIENT_IPC_POOL_TYPE = "hbase.client.ipc.pool.type"; /** Parameter name for HBase client IPC pool size */ public static final String HBASE_CLIENT_IPC_POOL_SIZE = "hbase.client.ipc.pool.size"; /** Parameter name for HBase client operation timeout. */ public static final String HBASE_CLIENT_OPERATION_TIMEOUT = "hbase.client.operation.timeout"; /** Parameter name for HBase client operation timeout. */ public static final String HBASE_CLIENT_META_OPERATION_TIMEOUT = "hbase.client.meta.operation.timeout"; /** Default HBase client operation timeout, which is tantamount to a blocking call */ public static final int DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT = 1200000; /** Parameter name for HBase client meta replica scan call timeout. */ public static final String HBASE_CLIENT_META_REPLICA_SCAN_TIMEOUT = "hbase.client.meta.replica.scan.timeout"; /** Default HBase client meta replica scan call timeout, 1 second */ public static final int HBASE_CLIENT_META_REPLICA_SCAN_TIMEOUT_DEFAULT = 1000000; /** Used to construct the name of the log directory for a region server */ public static final String HREGION_LOGDIR_NAME = "WALs"; /** Used to construct the name of the splitlog directory for a region server */ public static final String SPLIT_LOGDIR_NAME = "splitWAL"; /** Like the previous, but for old logs that are about to be deleted */ public static final String HREGION_OLDLOGDIR_NAME = "oldWALs"; /** Staging dir used by bulk load */ public static final String BULKLOAD_STAGING_DIR_NAME = "staging"; public static final String CORRUPT_DIR_NAME = "corrupt"; /** Used by HBCK to sideline backup data */ public static final String HBCK_SIDELINEDIR_NAME = ".hbck"; /** Any artifacts left from migration can be moved here */ public static final String MIGRATION_NAME = ".migration"; /** Used to construct the name of the compaction directory during compaction */ public static final String HREGION_COMPACTIONDIR_NAME = "compaction.dir"; /** Conf key for the max file size after which we split the region */ public static final String HREGION_MAX_FILESIZE = "hbase.hregion.max.filesize"; /** Default maximum file size */ public static final long DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024 * 1024L; /** * Max size of single row for Get's or Scan's without in-row scanning flag set. */ public static final String TABLE_MAX_ROWSIZE_KEY = "hbase.table.max.rowsize"; /** * Default max row size (1 Gb). */ public static final long TABLE_MAX_ROWSIZE_DEFAULT = 1024 * 1024 * 1024L; /** * The max number of threads used for opening and closing stores or store * files in parallel */ public static final String HSTORE_OPEN_AND_CLOSE_THREADS_MAX = "hbase.hstore.open.and.close.threads.max"; /** * The default number for the max number of threads used for opening and * closing stores or store files in parallel */ public static final int DEFAULT_HSTORE_OPEN_AND_CLOSE_THREADS_MAX = 1; /** * Block updates if memstore has hbase.hregion.memstore.block.multiplier * times hbase.hregion.memstore.flush.size bytes. Useful preventing * runaway memstore during spikes in update traffic. */ public static final String HREGION_MEMSTORE_BLOCK_MULTIPLIER = "hbase.hregion.memstore.block.multiplier"; /** * Default value for hbase.hregion.memstore.block.multiplier */ public static final int DEFAULT_HREGION_MEMSTORE_BLOCK_MULTIPLIER = 4; /** Conf key for the memstore size at which we flush the memstore */ public static final String HREGION_MEMSTORE_FLUSH_SIZE = "hbase.hregion.memstore.flush.size"; public static final String HREGION_EDITS_REPLAY_SKIP_ERRORS = "hbase.hregion.edits.replay.skip.errors"; public static final boolean DEFAULT_HREGION_EDITS_REPLAY_SKIP_ERRORS = false; /** Maximum value length, enforced on KeyValue construction */ public static final int MAXIMUM_VALUE_LENGTH = Integer.MAX_VALUE - 1; /** name of the file for unique cluster ID */ public static final String CLUSTER_ID_FILE_NAME = "hbase.id"; /** Default value for cluster ID */ public static final String CLUSTER_ID_DEFAULT = "default-cluster"; /** Parameter name for # days to keep MVCC values during a major compaction */ public static final String KEEP_SEQID_PERIOD = "hbase.hstore.compaction.keep.seqId.period"; /** At least to keep MVCC values in hfiles for 5 days */ public static final int MIN_KEEP_SEQID_PERIOD = 5; // Always store the location of the root table's HRegion. // This HRegion is never split. // region name = table + startkey + regionid. This is the row key. // each row in the root and meta tables describes exactly 1 region // Do we ever need to know all the information that we are storing? // Note that the name of the root table starts with "-" and the name of the // meta table starts with "." Why? it's a trick. It turns out that when we // store region names in memory, we use a SortedMap. Since "-" sorts before // "." (and since no other table name can start with either of these // characters, the root region will always be the first entry in such a Map, // followed by all the meta regions (which will be ordered by their starting // row key as well), followed by all user tables. So when the Master is // choosing regions to assign, it will always choose the root region first, // followed by the meta regions, followed by user regions. Since the root // and meta regions always need to be on-line, this ensures that they will // be the first to be reassigned if the server(s) they are being served by // should go down. public static final String BASE_NAMESPACE_DIR = "data"; /** delimiter used between portions of a region name */ public static final int META_ROW_DELIMITER = ','; /** The catalog family as a string*/ public static final String CATALOG_FAMILY_STR = "info"; /** The catalog family */ public static final byte [] CATALOG_FAMILY = Bytes.toBytes(CATALOG_FAMILY_STR); /** The RegionInfo qualifier as a string */ public static final String REGIONINFO_QUALIFIER_STR = "regioninfo"; /** The regioninfo column qualifier */ public static final byte [] REGIONINFO_QUALIFIER = Bytes.toBytes(REGIONINFO_QUALIFIER_STR); /** The server column qualifier */ public static final String SERVER_QUALIFIER_STR = "server"; /** The server column qualifier */ public static final byte [] SERVER_QUALIFIER = Bytes.toBytes(SERVER_QUALIFIER_STR); /** The startcode column qualifier */ public static final String STARTCODE_QUALIFIER_STR = "serverstartcode"; /** The startcode column qualifier */ public static final byte [] STARTCODE_QUALIFIER = Bytes.toBytes(STARTCODE_QUALIFIER_STR); /** The open seqnum column qualifier */ public static final String SEQNUM_QUALIFIER_STR = "seqnumDuringOpen"; /** The open seqnum column qualifier */ public static final byte [] SEQNUM_QUALIFIER = Bytes.toBytes(SEQNUM_QUALIFIER_STR); /** The state column qualifier */ public static final String STATE_QUALIFIER_STR = "state"; public static final byte [] STATE_QUALIFIER = Bytes.toBytes(STATE_QUALIFIER_STR); /** * The serverName column qualifier. Its the server where the region is * transitioning on, while column server is the server where the region is * opened on. They are the same when the region is in state OPEN. */ public static final String SERVERNAME_QUALIFIER_STR = "sn"; public static final byte [] SERVERNAME_QUALIFIER = Bytes.toBytes(SERVERNAME_QUALIFIER_STR); /** The lower-half split region column qualifier */ public static final byte [] SPLITA_QUALIFIER = Bytes.toBytes("splitA"); /** The upper-half split region column qualifier */ public static final byte [] SPLITB_QUALIFIER = Bytes.toBytes("splitB"); /** The lower-half merge region column qualifier */ public static final byte[] MERGEA_QUALIFIER = Bytes.toBytes("mergeA"); /** The upper-half merge region column qualifier */ public static final byte[] MERGEB_QUALIFIER = Bytes.toBytes("mergeB"); /** The catalog family as a string*/ public static final String TABLE_FAMILY_STR = "table"; /** The catalog family */ public static final byte [] TABLE_FAMILY = Bytes.toBytes(TABLE_FAMILY_STR); /** The serialized table state qualifier */ public static final byte[] TABLE_STATE_QUALIFIER = Bytes.toBytes("state"); /** The replication barrier family as a string*/ public static final String REPLICATION_BARRIER_FAMILY_STR = "rep_barrier"; /** The replication barrier family */ public static final byte[] REPLICATION_BARRIER_FAMILY = Bytes.toBytes(REPLICATION_BARRIER_FAMILY_STR); /** * The meta table version column qualifier. * We keep current version of the meta table in this column in <code>-ROOT-</code> * table: i.e. in the 'info:v' column. */ public static final byte [] META_VERSION_QUALIFIER = Bytes.toBytes("v"); /** * The current version of the meta table. * - pre-hbase 0.92. There is no META_VERSION column in the root table * in this case. The meta has HTableDescriptor serialized into the HRegionInfo; * - version 0 is 0.92 and 0.94. Meta data has serialized HRegionInfo's using * Writable serialization, and HRegionInfo's does not contain HTableDescriptors. * - version 1 for 0.96+ keeps HRegionInfo data structures, but changes the * byte[] serialization from Writables to Protobuf. * See HRegionInfo.VERSION */ public static final short META_VERSION = 1; // Other constants /** * An empty instance. */ public static final byte [] EMPTY_BYTE_ARRAY = new byte [0]; public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(EMPTY_BYTE_ARRAY); /** * Used by scanners, etc when they want to start at the beginning of a region */ public static final byte [] EMPTY_START_ROW = EMPTY_BYTE_ARRAY; /** * Last row in a table. */ public static final byte [] EMPTY_END_ROW = EMPTY_START_ROW; /** * Used by scanners and others when they're trying to detect the end of a * table */ public static final byte [] LAST_ROW = EMPTY_BYTE_ARRAY; /** * Max length a row can have because of the limitation in TFile. */ public static final int MAX_ROW_LENGTH = Short.MAX_VALUE; /** * Timestamp to use when we want to refer to the latest cell. * * On client side, this is the timestamp set by default when no timestamp is specified, * to refer to the latest. * On server side, this acts as a notation. * (1) For a cell of Put, which has this notation, * its timestamp will be replaced with server's current time. * (2) For a cell of Delete, which has this notation, * A. If the cell is of {@link KeyValue.Type#Delete}, HBase issues a Get operation firstly. * a. When the count of cell it gets is less than the count of cell to delete, * the timestamp of Delete cell will be replaced with server's current time. * b. When the count of cell it gets is equal to the count of cell to delete, * the timestamp of Delete cell will be replaced with the latest timestamp of cell it * gets. * (c. It is invalid and an exception will be thrown, * if the count of cell it gets is greater than the count of cell to delete, * as the max version of Get is set to the count of cell to delete.) * B. If the cell is of other Delete types, like {@link KeyValue.Type#DeleteFamilyVersion}, * {@link KeyValue.Type#DeleteColumn}, or {@link KeyValue.Type#DeleteFamily}, * the timestamp of Delete cell will be replaced with server's current time. * * So that is why it is named as "latest" but assigned as the max value of Long. */ public static final long LATEST_TIMESTAMP = Long.MAX_VALUE; /** * Timestamp to use when we want to refer to the oldest cell. * Special! Used in fake Cells only. Should never be the timestamp on an actual Cell returned to * a client. * @deprecated Should not be public since hbase-1.3.0. For internal use only. Move internal to * Scanners flagged as special timestamp value never to be returned as timestamp on a Cell. */ @Deprecated public static final long OLDEST_TIMESTAMP = Long.MIN_VALUE; /** * LATEST_TIMESTAMP in bytes form */ public static final byte [] LATEST_TIMESTAMP_BYTES = { // big-endian (byte) (LATEST_TIMESTAMP >>> 56), (byte) (LATEST_TIMESTAMP >>> 48), (byte) (LATEST_TIMESTAMP >>> 40), (byte) (LATEST_TIMESTAMP >>> 32), (byte) (LATEST_TIMESTAMP >>> 24), (byte) (LATEST_TIMESTAMP >>> 16), (byte) (LATEST_TIMESTAMP >>> 8), (byte) LATEST_TIMESTAMP, }; /** * Define for 'return-all-versions'. */ public static final int ALL_VERSIONS = Integer.MAX_VALUE; /** * Unlimited time-to-live. */ // public static final int FOREVER = -1; public static final int FOREVER = Integer.MAX_VALUE; /** * Seconds in a day, hour and minute */ public static final int DAY_IN_SECONDS = 24 * 60 * 60; public static final int HOUR_IN_SECONDS = 60 * 60; public static final int MINUTE_IN_SECONDS = 60; //TODO: although the following are referenced widely to format strings for // the shell. They really aren't a part of the public API. It would be // nice if we could put them somewhere where they did not need to be // public. They could have package visibility public static final String NAME = "NAME"; public static final String VERSIONS = "VERSIONS"; public static final String IN_MEMORY = "IN_MEMORY"; public static final String METADATA = "METADATA"; public static final String CONFIGURATION = "CONFIGURATION"; /** * Retrying we multiply hbase.client.pause setting by what we have in this array until we * run out of array items. Retries beyond this use the last number in the array. So, for * example, if hbase.client.pause is 1 second, and maximum retries count * hbase.client.retries.number is 10, we will retry at the following intervals: * 1, 2, 3, 5, 10, 20, 40, 100, 100, 100. * With 100ms, a back-off of 200 means 20s */ public static final int [] RETRY_BACKOFF = {1, 2, 3, 5, 10, 20, 40, 100, 100, 100, 100, 200, 200}; public static final String REGION_IMPL = "hbase.hregion.impl"; /** * Scope tag for locally scoped data. * This data will not be replicated. */ public static final int REPLICATION_SCOPE_LOCAL = 0; /** * Scope tag for globally scoped data. * This data will be replicated to all peers. */ public static final int REPLICATION_SCOPE_GLOBAL = 1; /** * Default cluster ID, cannot be used to identify a cluster so a key with * this value means it wasn't meant for replication. */ public static final UUID DEFAULT_CLUSTER_ID = new UUID(0L,0L); /** * Parameter name for maximum number of bytes returned when calling a scanner's next method. * Controlled by the client. */ public static final String HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY = "hbase.client.scanner.max.result.size"; /** * Parameter name for maximum number of bytes returned when calling a scanner's next method. * Controlled by the server. */ public static final String HBASE_SERVER_SCANNER_MAX_RESULT_SIZE_KEY = "hbase.server.scanner.max.result.size"; /** * Maximum number of bytes returned when calling a scanner's next method. * Note that when a single row is larger than this limit the row is still * returned completely. * * The default value is 2MB. */ public static final long DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE = 2 * 1024 * 1024; /** * Maximum number of bytes returned when calling a scanner's next method. * Note that when a single row is larger than this limit the row is still * returned completely. * Safety setting to protect the region server. * * The default value is 100MB. (a client would rarely request larger chunks on purpose) */ public static final long DEFAULT_HBASE_SERVER_SCANNER_MAX_RESULT_SIZE = 100 * 1024 * 1024; /** * Parameter name for client pause value, used mostly as value to wait * before running a retry of a failed get, region lookup, etc. */ public static final String HBASE_CLIENT_PAUSE = "hbase.client.pause"; /** * Default value of {@link #HBASE_CLIENT_PAUSE}. */ public static final long DEFAULT_HBASE_CLIENT_PAUSE = 100; /** * Parameter name for client pause value for special case such as call queue too big, etc. */ public static final String HBASE_CLIENT_PAUSE_FOR_CQTBE = "hbase.client.pause.cqtbe"; /** * The maximum number of concurrent connections the client will maintain. */ public static final String HBASE_CLIENT_MAX_TOTAL_TASKS = "hbase.client.max.total.tasks"; /** * Default value of {@link #HBASE_CLIENT_MAX_TOTAL_TASKS}. */ public static final int DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS = 100; /** * The maximum number of concurrent connections the client will maintain to a single * RegionServer. */ public static final String HBASE_CLIENT_MAX_PERSERVER_TASKS = "hbase.client.max.perserver.tasks"; /** * Default value of {@link #HBASE_CLIENT_MAX_PERSERVER_TASKS}. */ public static final int DEFAULT_HBASE_CLIENT_MAX_PERSERVER_TASKS = 2; /** * The maximum number of concurrent connections the client will maintain to a single * Region. */ public static final String HBASE_CLIENT_MAX_PERREGION_TASKS = "hbase.client.max.perregion.tasks"; /** * Default value of {@link #HBASE_CLIENT_MAX_PERREGION_TASKS}. */ public static final int DEFAULT_HBASE_CLIENT_MAX_PERREGION_TASKS = 1; /** * The maximum number of concurrent pending RPC requests for one server in process level. */ public static final String HBASE_CLIENT_PERSERVER_REQUESTS_THRESHOLD = "hbase.client.perserver.requests.threshold"; /** * Default value of {@link #HBASE_CLIENT_PERSERVER_REQUESTS_THRESHOLD}. */ public static final int DEFAULT_HBASE_CLIENT_PERSERVER_REQUESTS_THRESHOLD = Integer.MAX_VALUE; /** * Parameter name for server pause value, used mostly as value to wait before * running a retry of a failed operation. */ public static final String HBASE_SERVER_PAUSE = "hbase.server.pause"; /** * Default value of {@link #HBASE_SERVER_PAUSE}. */ public static final int DEFAULT_HBASE_SERVER_PAUSE = 1000; /** * Parameter name for maximum retries, used as maximum for all retryable * operations such as fetching of the root region from root region server, * getting a cell's value, starting a row update, etc. */ public static final String HBASE_CLIENT_RETRIES_NUMBER = "hbase.client.retries.number"; /** * Default value of {@link #HBASE_CLIENT_RETRIES_NUMBER}. */ public static final int DEFAULT_HBASE_CLIENT_RETRIES_NUMBER = 15; public static final String HBASE_CLIENT_SERVERSIDE_RETRIES_MULTIPLIER = "hbase.client.serverside.retries.multiplier"; public static final int DEFAULT_HBASE_CLIENT_SERVERSIDE_RETRIES_MULTIPLIER = 3; /** * Parameter name to set the default scanner caching for all clients. */ public static final String HBASE_CLIENT_SCANNER_CACHING = "hbase.client.scanner.caching"; /** * Default value for {@link #HBASE_CLIENT_SCANNER_CACHING} */ public static final int DEFAULT_HBASE_CLIENT_SCANNER_CACHING = Integer.MAX_VALUE; /** * Parameter name for number of rows that will be fetched when calling next on * a scanner if it is not served from memory. Higher caching values will * enable faster scanners but will eat up more memory and some calls of next * may take longer and longer times when the cache is empty. */ public static final String HBASE_META_SCANNER_CACHING = "hbase.meta.scanner.caching"; /** * Default value of {@link #HBASE_META_SCANNER_CACHING}. */ public static final int DEFAULT_HBASE_META_SCANNER_CACHING = 100; /** * Parameter name for number of versions, kept by meta table. */ public static final String HBASE_META_VERSIONS = "hbase.meta.versions"; /** * Default value of {@link #HBASE_META_VERSIONS}. */ public static final int DEFAULT_HBASE_META_VERSIONS = 3; /** * Parameter name for number of versions, kept by meta table. */ public static final String HBASE_META_BLOCK_SIZE = "hbase.meta.blocksize"; /** * Default value of {@link #HBASE_META_BLOCK_SIZE}. */ public static final int DEFAULT_HBASE_META_BLOCK_SIZE = 8 * 1024; /** * Parameter name for unique identifier for this {@link org.apache.hadoop.conf.Configuration} * instance. If there are two or more {@link org.apache.hadoop.conf.Configuration} instances that, * for all intents and purposes, are the same except for their instance ids, then they will not be * able to share the same org.apache.hadoop.hbase.client.HConnection instance. On the other hand, * even if the instance ids are the same, it could result in non-shared * org.apache.hadoop.hbase.client.HConnection instances if some of the other connection parameters * differ. */ public static final String HBASE_CLIENT_INSTANCE_ID = "hbase.client.instance.id"; /** * The client scanner timeout period in milliseconds. */ public static final String HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = "hbase.client.scanner.timeout.period"; /** * Use {@link #HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD} instead. * @deprecated This config option is deprecated. Will be removed at later releases after 0.96. */ @Deprecated public static final String HBASE_REGIONSERVER_LEASE_PERIOD_KEY = "hbase.regionserver.lease.period"; /** * Default value of {@link #HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD}. */ public static final int DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = 60000; /** * timeout for each RPC */ public static final String HBASE_RPC_TIMEOUT_KEY = "hbase.rpc.timeout"; /** * timeout for each read RPC */ public static final String HBASE_RPC_READ_TIMEOUT_KEY = "hbase.rpc.read.timeout"; /** * timeout for each write RPC */ public static final String HBASE_RPC_WRITE_TIMEOUT_KEY = "hbase.rpc.write.timeout"; /** * Default value of {@link #HBASE_RPC_TIMEOUT_KEY} */ public static final int DEFAULT_HBASE_RPC_TIMEOUT = 60000; /** * timeout for short operation RPC */ public static final String HBASE_RPC_SHORTOPERATION_TIMEOUT_KEY = "hbase.rpc.shortoperation.timeout"; /** * Default value of {@link #HBASE_RPC_SHORTOPERATION_TIMEOUT_KEY} */ public static final int DEFAULT_HBASE_RPC_SHORTOPERATION_TIMEOUT = 10000; /** * Value indicating the server name was saved with no sequence number. */ public static final long NO_SEQNUM = -1; /* * cluster replication constants. */ public static final String REPLICATION_SOURCE_SERVICE_CLASSNAME = "hbase.replication.source.service"; public static final String REPLICATION_SINK_SERVICE_CLASSNAME = "hbase.replication.sink.service"; public static final String REPLICATION_SERVICE_CLASSNAME_DEFAULT = "org.apache.hadoop.hbase.replication.regionserver.Replication"; public static final String REPLICATION_BULKLOAD_ENABLE_KEY = "hbase.replication.bulkload.enabled"; public static final boolean REPLICATION_BULKLOAD_ENABLE_DEFAULT = false; /** Replication cluster id of source cluster which uniquely identifies itself with peer cluster */ public static final String REPLICATION_CLUSTER_ID = "hbase.replication.cluster.id"; /** * Max total size of buffered entries in all replication peers. It will prevent server getting * OOM if there are many peers. Default value is 256MB which is four times to default * replication.source.size.capacity. */ public static final String REPLICATION_SOURCE_TOTAL_BUFFER_KEY = "replication.total.buffer.quota"; public static final int REPLICATION_SOURCE_TOTAL_BUFFER_DFAULT = 256 * 1024 * 1024; /** * Directory where the source cluster file system client configuration are placed which is used by * sink cluster to copy HFiles from source cluster file system */ public static final String REPLICATION_CONF_DIR = "hbase.replication.conf.dir"; /** Maximum time to retry for a failed bulk load request */ public static final String BULKLOAD_MAX_RETRIES_NUMBER = "hbase.bulkload.retries.number"; public static final String KEY_FOR_HOSTNAME_SEEN_BY_MASTER = "hbase.regionserver.hostname.seen.by.master"; public static final String HBASE_MASTER_LOGCLEANER_PLUGINS = "hbase.master.logcleaner.plugins"; public static final String HBASE_REGION_SPLIT_POLICY_KEY = "hbase.regionserver.region.split.policy"; /** Whether nonces are enabled; default is true. */ public static final String HBASE_RS_NONCES_ENABLED = "hbase.regionserver.nonces.enabled"; /** * Configuration key for the size of the block cache */ public static final String HFILE_BLOCK_CACHE_SIZE_KEY = "hfile.block.cache.size"; public static final float HFILE_BLOCK_CACHE_SIZE_DEFAULT = 0.4f; /* * Minimum percentage of free heap necessary for a successful cluster startup. */ public static final float HBASE_CLUSTER_MINIMUM_MEMORY_THRESHOLD = 0.2f; /** * @deprecated It is used internally. As of release 2.0.0, this will be removed in HBase 3.0.0. */ @Deprecated public static final Pattern CP_HTD_ATTR_KEY_PATTERN = Pattern.compile("^coprocessor\\$([0-9]+)$", Pattern.CASE_INSENSITIVE); /** * <pre> * Pattern that matches a coprocessor specification. Form is: * {@code <coprocessor jar file location> '|' <class name> ['|' <priority> ['|' <arguments>]]} * where arguments are {@code <KEY> '=' <VALUE> [,...]} * For example: {@code hdfs:///foo.jar|com.foo.FooRegionObserver|1001|arg1=1,arg2=2} * </pre> * @deprecated It is used internally. As of release 2.0.0, this will be removed in HBase 3.0.0. */ @Deprecated public static final Pattern CP_HTD_ATTR_VALUE_PATTERN = Pattern.compile("(^[^\\|]*)\\|([^\\|]+)\\|[\\s]*([\\d]*)[\\s]*(\\|.*)?$"); /** * @deprecated It is used internally. As of release 2.0.0, this will be removed in HBase 3.0.0. */ @Deprecated public static final String CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN = "[^=,]+"; /** * @deprecated It is used internally. As of release 2.0.0, this will be removed in HBase 3.0.0. */ @Deprecated public static final String CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN = "[^,]+"; /** * @deprecated It is used internally. As of release 2.0.0, this will be removed in HBase 3.0.0. */ @Deprecated public static final Pattern CP_HTD_ATTR_VALUE_PARAM_PATTERN = Pattern.compile( "(" + CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN + ")=(" + CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN + "),?"); public static final String CP_HTD_ATTR_INCLUSION_KEY = "hbase.coprocessor.classloader.included.classes"; /** The delay when re-trying a socket operation in a loop (HBASE-4712) */ public static final int SOCKET_RETRY_WAIT_MS = 200; /** Host name of the local machine */ public static final String LOCALHOST = "localhost"; /** * If this parameter is set to true, then hbase will read * data and then verify checksums. Checksum verification * inside hdfs will be switched off. However, if the hbase-checksum * verification fails, then it will switch back to using * hdfs checksums for verifiying data that is being read from storage. * * If this parameter is set to false, then hbase will not * verify any checksums, instead it will depend on checksum verification * being done in the hdfs client. */ public static final String HBASE_CHECKSUM_VERIFICATION = "hbase.regionserver.checksum.verify"; public static final String LOCALHOST_IP = "127.0.0.1"; public static final String REGION_SERVER_HANDLER_COUNT = "hbase.regionserver.handler.count"; public static final int DEFAULT_REGION_SERVER_HANDLER_COUNT = 30; /* * REGION_SERVER_HANDLER_ABORT_ON_ERROR_PERCENT: * -1 => Disable aborting * 0 => Abort if even a single handler has died * 0.x => Abort only when this percent of handlers have died * 1 => Abort only all of the handers have died */ public static final String REGION_SERVER_HANDLER_ABORT_ON_ERROR_PERCENT = "hbase.regionserver.handler.abort.on.error.percent"; public static final double DEFAULT_REGION_SERVER_HANDLER_ABORT_ON_ERROR_PERCENT = 0.5; //High priority handlers to deal with admin requests and system table operation requests public static final String REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT = "hbase.regionserver.metahandler.count"; public static final int DEFAULT_REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT = 20; public static final String REGION_SERVER_REPLICATION_HANDLER_COUNT = "hbase.regionserver.replication.handler.count"; public static final int DEFAULT_REGION_SERVER_REPLICATION_HANDLER_COUNT = 3; /** Conf key for enabling meta replication */ public static final String USE_META_REPLICAS = "hbase.meta.replicas.use"; public static final boolean DEFAULT_USE_META_REPLICAS = false; public static final String META_REPLICAS_NUM = "hbase.meta.replica.count"; public static final int DEFAULT_META_REPLICA_NUM = 1; /** * The name of the configuration parameter that specifies * the number of bytes in a newly created checksum chunk. */ public static final String BYTES_PER_CHECKSUM = "hbase.hstore.bytes.per.checksum"; /** * The name of the configuration parameter that specifies * the name of an algorithm that is used to compute checksums * for newly created blocks. */ public static final String CHECKSUM_TYPE_NAME = "hbase.hstore.checksum.algorithm"; /** Enable file permission modification from standard hbase */ public static final String ENABLE_DATA_FILE_UMASK = "hbase.data.umask.enable"; /** File permission umask to use when creating hbase data files */ public static final String DATA_FILE_UMASK_KEY = "hbase.data.umask"; /** Configuration name of WAL Compression */ public static final String ENABLE_WAL_COMPRESSION = "hbase.regionserver.wal.enablecompression"; /** Configuration name of WAL storage policy * Valid values are: HOT, COLD, WARM, ALL_SSD, ONE_SSD, LAZY_PERSIST * See http://hadoop.apache.org/docs/r2.7.3/hadoop-project-dist/hadoop-hdfs/ArchivalStorage.html*/ public static final String WAL_STORAGE_POLICY = "hbase.wal.storage.policy"; public static final String DEFAULT_WAL_STORAGE_POLICY = "HOT"; /** Region in Transition metrics threshold time */ public static final String METRICS_RIT_STUCK_WARNING_THRESHOLD = "hbase.metrics.rit.stuck.warning.threshold"; public static final String LOAD_BALANCER_SLOP_KEY = "hbase.regions.slop"; /** delimiter used between portions of a region name */ public static final int DELIMITER = ','; /** * QOS attributes: these attributes are used to demarcate RPC call processing * by different set of handlers. For example, HIGH_QOS tagged methods are * handled by high priority handlers. */ // normal_QOS < replication_QOS < replay_QOS < QOS_threshold < admin_QOS < high_QOS public static final int PRIORITY_UNSET = -1; public static final int NORMAL_QOS = 0; public static final int REPLICATION_QOS = 5; public static final int REPLAY_QOS = 6; public static final int QOS_THRESHOLD = 10; public static final int ADMIN_QOS = 100; public static final int HIGH_QOS = 200; public static final int SYSTEMTABLE_QOS = HIGH_QOS; /** Directory under /hbase where archived hfiles are stored */ public static final String HFILE_ARCHIVE_DIRECTORY = "archive"; /** * Name of the directory to store all snapshots. See SnapshotDescriptionUtils for * remaining snapshot constants; this is here to keep HConstants dependencies at a minimum and * uni-directional. */ public static final String SNAPSHOT_DIR_NAME = ".hbase-snapshot"; /* Name of old snapshot directory. See HBASE-8352 for details on why it needs to be renamed */ public static final String OLD_SNAPSHOT_DIR_NAME = ".snapshot"; /** Temporary directory used for table creation and deletion */ public static final String HBASE_TEMP_DIRECTORY = ".tmp"; /** * The period (in milliseconds) between computing region server point in time metrics */ public static final String REGIONSERVER_METRICS_PERIOD = "hbase.regionserver.metrics.period"; public static final long DEFAULT_REGIONSERVER_METRICS_PERIOD = 5000; /** Directories that are not HBase table directories */ public static final List<String> HBASE_NON_TABLE_DIRS = Collections.unmodifiableList(Arrays.asList(new String[] { HBCK_SIDELINEDIR_NAME, HBASE_TEMP_DIRECTORY, MIGRATION_NAME })); /** Directories that are not HBase user table directories */ public static final List<String> HBASE_NON_USER_TABLE_DIRS = Collections.unmodifiableList(Arrays.asList((String[])ArrayUtils.addAll( new String[] { TableName.META_TABLE_NAME.getNameAsString() }, HBASE_NON_TABLE_DIRS.toArray()))); /** Health script related settings. */ public static final String HEALTH_SCRIPT_LOC = "hbase.node.health.script.location"; public static final String HEALTH_SCRIPT_TIMEOUT = "hbase.node.health.script.timeout"; public static final String HEALTH_CHORE_WAKE_FREQ = "hbase.node.health.script.frequency"; public static final long DEFAULT_HEALTH_SCRIPT_TIMEOUT = 60000; /** * The maximum number of health check failures a server can encounter consecutively. */ public static final String HEALTH_FAILURE_THRESHOLD = "hbase.node.health.failure.threshold"; public static final int DEFAULT_HEALTH_FAILURE_THRESHOLD = 3; /** * Setting to activate, or not, the publication of the status by the master. Default * notification is by a multicast message. */ public static final String STATUS_PUBLISHED = "hbase.status.published"; public static final boolean STATUS_PUBLISHED_DEFAULT = false; /** * IP to use for the multicast status messages between the master and the clients. * The default address is chosen as one among others within the ones suitable for multicast * messages. */ public static final String STATUS_MULTICAST_ADDRESS = "hbase.status.multicast.address.ip"; public static final String DEFAULT_STATUS_MULTICAST_ADDRESS = "172.16.31.10"; /** * The address to use for binding the local socket for receiving multicast. Defaults to * 0.0.0.0. * @see <a href="https://issues.apache.org/jira/browse/HBASE-9961">HBASE-9961</a> */ public static final String STATUS_MULTICAST_BIND_ADDRESS = "hbase.status.multicast.bind.address.ip"; public static final String DEFAULT_STATUS_MULTICAST_BIND_ADDRESS = "0.0.0.0"; /** * The port to use for the multicast messages. */ public static final String STATUS_MULTICAST_PORT = "hbase.status.multicast.address.port"; public static final int DEFAULT_STATUS_MULTICAST_PORT = 16100; /** * The network interface name to use for the multicast messages. */ public static final String STATUS_MULTICAST_NI_NAME = "hbase.status.multicast.ni.name"; /** * The address to use for binding the local socket for sending multicast. Defaults to 0.0.0.0. */ public static final String STATUS_MULTICAST_PUBLISHER_BIND_ADDRESS = "hbase.status.multicast.publisher.bind.address.ip"; public static final String DEFAULT_STATUS_MULTICAST_PUBLISHER_BIND_ADDRESS = "0.0.0.0"; public static final long NO_NONCE = 0; /** Default cipher for encryption */ public static final String CIPHER_AES = "AES"; /** Configuration key for the crypto algorithm provider, a class name */ public static final String CRYPTO_CIPHERPROVIDER_CONF_KEY = "hbase.crypto.cipherprovider"; /** Configuration key for the crypto key provider, a class name */ public static final String CRYPTO_KEYPROVIDER_CONF_KEY = "hbase.crypto.keyprovider"; /** Configuration key for the crypto key provider parameters */ public static final String CRYPTO_KEYPROVIDER_PARAMETERS_KEY = "hbase.crypto.keyprovider.parameters"; /** Configuration key for the name of the master key for the cluster, a string */ public static final String CRYPTO_MASTERKEY_NAME_CONF_KEY = "hbase.crypto.master.key.name"; /** Configuration key for the name of the alternate master key for the cluster, a string */ public static final String CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY = "hbase.crypto.master.alternate.key.name"; /** Configuration key for the algorithm to use when encrypting the WAL, a string */ public static final String CRYPTO_WAL_ALGORITHM_CONF_KEY = "hbase.crypto.wal.algorithm"; /** Configuration key for the name of the master WAL encryption key for the cluster, a string */ public static final String CRYPTO_WAL_KEY_NAME_CONF_KEY = "hbase.crypto.wal.key.name"; /** Configuration key for the algorithm used for creating jks key, a string */ public static final String CRYPTO_KEY_ALGORITHM_CONF_KEY = "hbase.crypto.key.algorithm"; /** Configuration key for the name of the alternate cipher algorithm for the cluster, a string */ public static final String CRYPTO_ALTERNATE_KEY_ALGORITHM_CONF_KEY = "hbase.crypto.alternate.key.algorithm"; /** Configuration key for enabling WAL encryption, a boolean */ public static final String ENABLE_WAL_ENCRYPTION = "hbase.regionserver.wal.encryption"; /** Configuration key for setting RPC codec class name */ public static final String RPC_CODEC_CONF_KEY = "hbase.client.rpc.codec"; /** Configuration key for setting replication codec class name */ public static final String REPLICATION_CODEC_CONF_KEY = "hbase.replication.rpc.codec"; /** Maximum number of threads used by the replication source for shipping edits to the sinks */ public static final String REPLICATION_SOURCE_MAXTHREADS_KEY = "hbase.replication.source.maxthreads"; /** Drop edits for tables that been deleted from the replication source and target */ public static final String REPLICATION_DROP_ON_DELETED_TABLE_KEY = "hbase.replication.drop.on.deleted.table"; /** Maximum number of threads used by the replication source for shipping edits to the sinks */ public static final int REPLICATION_SOURCE_MAXTHREADS_DEFAULT = 10; /** Configuration key for SplitLog manager timeout */ public static final String HBASE_SPLITLOG_MANAGER_TIMEOUT = "hbase.splitlog.manager.timeout"; /** * Configuration keys for Bucket cache */ // TODO moving these bucket cache implementation specific configs to this level is violation of // encapsulation. But as these has to be referred from hbase-common and bucket cache // sits in hbase-server, there were no other go! Can we move the cache implementation to // hbase-common? /** * Current ioengine options in include: heap, offheap and file:PATH (where PATH is the path * to the file that will host the file-based cache. See BucketCache#getIOEngineFromName() for * list of supported ioengine options. * <p>Set this option and a non-zero {@link #BUCKET_CACHE_SIZE_KEY} to enable bucket cache. */ public static final String BUCKET_CACHE_IOENGINE_KEY = "hbase.bucketcache.ioengine"; /** * When using bucket cache, this is a float that EITHER represents a percentage of total heap * memory size to give to the cache (if &lt; 1.0) OR, it is the capacity in * megabytes of the cache. */ public static final String BUCKET_CACHE_SIZE_KEY = "hbase.bucketcache.size"; /** * HConstants for fast fail on the client side follow */ /** * Config for enabling/disabling the fast fail mode. */ public static final String HBASE_CLIENT_FAST_FAIL_MODE_ENABLED = "hbase.client.fast.fail.mode.enabled"; public static final boolean HBASE_CLIENT_ENABLE_FAST_FAIL_MODE_DEFAULT = false; public static final String HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS = "hbase.client.fastfail.threshold"; public static final long HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS_DEFAULT = 60000; public static final String HBASE_CLIENT_FAST_FAIL_CLEANUP_MS_DURATION_MS = "hbase.client.fast.fail.cleanup.duration"; public static final long HBASE_CLIENT_FAST_FAIL_CLEANUP_DURATION_MS_DEFAULT = 600000; public static final String HBASE_CLIENT_FAST_FAIL_INTERCEPTOR_IMPL = "hbase.client.fast.fail.interceptor.impl"; /** Config key for if the server should send backpressure and if the client should listen to * that backpressure from the server */ public static final String ENABLE_CLIENT_BACKPRESSURE = "hbase.client.backpressure.enabled"; public static final boolean DEFAULT_ENABLE_CLIENT_BACKPRESSURE = false; public static final String HEAP_OCCUPANCY_LOW_WATERMARK_KEY = "hbase.heap.occupancy.low_water_mark"; public static final float DEFAULT_HEAP_OCCUPANCY_LOW_WATERMARK = 0.95f; public static final String HEAP_OCCUPANCY_HIGH_WATERMARK_KEY = "hbase.heap.occupancy.high_water_mark"; public static final float DEFAULT_HEAP_OCCUPANCY_HIGH_WATERMARK = 0.98f; /** * The max number of threads used for splitting storefiles in parallel during * the region split process. */ public static final String REGION_SPLIT_THREADS_MAX = "hbase.regionserver.region.split.threads.max"; /** Canary config keys */ public static final String HBASE_CANARY_WRITE_DATA_TTL_KEY = "hbase.canary.write.data.ttl"; public static final String HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY = "hbase.canary.write.perserver.regions.lowerLimit"; public static final String HBASE_CANARY_WRITE_PERSERVER_REGIONS_UPPERLIMIT_KEY = "hbase.canary.write.perserver.regions.upperLimit"; public static final String HBASE_CANARY_WRITE_VALUE_SIZE_KEY = "hbase.canary.write.value.size"; public static final String HBASE_CANARY_WRITE_TABLE_CHECK_PERIOD_KEY = "hbase.canary.write.table.check.period"; public static final String HBASE_CANARY_READ_RAW_SCAN_KEY = "hbase.canary.read.raw.enabled"; /** * Configuration keys for programmatic JAAS configuration for secured ZK interaction */ public static final String ZK_CLIENT_KEYTAB_FILE = "hbase.zookeeper.client.keytab.file"; public static final String ZK_CLIENT_KERBEROS_PRINCIPAL = "hbase.zookeeper.client.kerberos.principal"; public static final String ZK_SERVER_KEYTAB_FILE = "hbase.zookeeper.server.keytab.file"; public static final String ZK_SERVER_KERBEROS_PRINCIPAL = "hbase.zookeeper.server.kerberos.principal"; /** Config key for hbase temporary directory in hdfs */ public static final String TEMPORARY_FS_DIRECTORY_KEY = "hbase.fs.tmp.dir"; public static final String DEFAULT_TEMPORARY_HDFS_DIRECTORY = "/user/" + System.getProperty("user.name") + "/hbase-staging"; public static final String SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT = "hbase.snapshot.restore.take.failsafe.snapshot"; public static final boolean DEFAULT_SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT = true; public static final String SNAPSHOT_RESTORE_FAILSAFE_NAME = "hbase.snapshot.restore.failsafe.name"; public static final String DEFAULT_SNAPSHOT_RESTORE_FAILSAFE_NAME = "hbase-failsafe-{snapshot.name}-{restore.timestamp}"; public static final String NOT_IMPLEMENTED = "Not implemented"; private HConstants() { // Can't be instantiated with this ctor. } }
9241683a6b24cbabec1a4465b131e3e5204bb9c2
1,473
java
Java
core/src/test/java/info/xiantang/jerrymouse/core/pipeline/ContentInBoundPipelineTest.java
xiantang/JerryMouse
0ae3331bc8415f8e6cd9a667450a9e2d99d0dfea
[ "MIT" ]
32
2019-06-06T03:17:11.000Z
2022-01-27T18:22:55.000Z
core/src/test/java/info/xiantang/jerrymouse/core/pipeline/ContentInBoundPipelineTest.java
xiantang/JerryMouse
0ae3331bc8415f8e6cd9a667450a9e2d99d0dfea
[ "MIT" ]
6
2019-04-25T04:05:44.000Z
2020-05-10T06:39:42.000Z
core/src/test/java/info/xiantang/jerrymouse/core/pipeline/ContentInBoundPipelineTest.java
xiantang/JerryMouse
0ae3331bc8415f8e6cd9a667450a9e2d99d0dfea
[ "MIT" ]
6
2019-06-16T16:22:51.000Z
2021-03-04T09:04:01.000Z
38.763158
91
0.75017
1,001,895
package info.xiantang.jerrymouse.core.pipeline; import info.xiantang.jerrymouse.core.handler.ServletContext; import info.xiantang.jerrymouse.core.server.Context; import info.xiantang.jerrymouse.core.server.HttpServer; import info.xiantang.jerrymouse.core.utils.NetUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.junit.jupiter.api.Assertions; import java.util.List; public class ContentInBoundPipelineTest { @Test public void testContextInBoundPipeline() throws Exception { int availablePort = NetUtils.getAvailablePort(); HttpServer httpSever = new HttpServer("/tmp/static"); List<Context> contexts = httpSever.getContexts(); Context context = contexts.get(0); context.setPort(availablePort); context.init(); context.start(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/index.html"); CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); int length = EntityUtils.toByteArray(entity).length; Assertions.assertEquals( 994,length); } }
92416883cc4a79203015ce10449d9b25896d26f5
316
java
Java
libs/reactive-session-security/src/main/java/no/nav/testnav/libs/reactivesessionsecurity/resolver/logut/OcidLogoutUriResolver.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
3
2020-06-30T18:14:44.000Z
2022-03-07T10:10:48.000Z
libs/reactive-session-security/src/main/java/no/nav/testnav/libs/reactivesessionsecurity/resolver/logut/OcidLogoutUriResolver.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
1,546
2020-05-25T14:39:45.000Z
2022-03-31T13:41:00.000Z
libs/reactive-session-security/src/main/java/no/nav/testnav/libs/reactivesessionsecurity/resolver/logut/OcidLogoutUriResolver.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
1
2021-11-03T16:02:17.000Z
2021-11-03T16:02:17.000Z
26.333333
74
0.829114
1,001,896
package no.nav.testnav.libs.reactivesessionsecurity.resolver.logut; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import reactor.core.publisher.Mono; import java.net.URI; @FunctionalInterface public interface OcidLogoutUriResolver { Mono<URI> generateUrl(DefaultOidcUser user); }
92416bf593c5a17809cbf31308ffe16ad0f9d641
67,284
java
Java
src/FALCONSEED/plot/src/ssac/util/swing/plot/CustomPlot.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
src/FALCONSEED/plot/src/ssac/util/swing/plot/CustomPlot.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
src/FALCONSEED/plot/src/ssac/util/swing/plot/CustomPlot.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
32.3948
138
0.605389
1,001,897
/* * 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. * * Copyright 2007-2013 SSAC(Systems of Social Accounting Consortium) * <author> Yasunari Ishizuka (PieCake,Inc.) * <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY) * <author> Yuji Onuki (Statistics Bureau) * <author> Shungo Sakaki (Tokyo University of Technology) * <author> Akira Sasaki (HOSEI UNIVERSITY) * <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY) * <author> Hideaki Yagi (MRI) */ /* * @(#)CustomPlot.java 2.1.0 2013/07/16 * - created by Y.Ishizuka(PieCake.inc,) */ package ssac.util.swing.plot; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.Serializable; import java.math.BigInteger; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.TreeMap; import ptolemy.plot.EPSGraphics; import ptolemy.plot.PlotPoint; import ptolemy.util.RunnableExceptionCatcher; /** * <code>ptolemy.plot.Plot</code> のカスタマイズ。 * * @version 2.1.0 2013/07/16 * @since 2.1.0 */ public class CustomPlot extends CustomPlotBox { //------------------------------------------------------------ // Constants //------------------------------------------------------------ private static final long serialVersionUID = 4961107640649855692L; //------------------------------------------------------------ // Fields //------------------------------------------------------------ protected PlotModel _plotModel; /** 誤差範囲の端点に描画する線分の長さ(Pixel) **/ private int _errorBarLegLength = PlotConstants.DEFAULT_ERRORBAR_LEG_LENGTH; //------------------------------------------------------------ // Original protected fields of ptolemy.plot.Plot //------------------------------------------------------------ /** The current dataset. */ protected int _currentdataset = -1; /** An indicator of the marks style. See _parseLine method for * interpretation. */ protected volatile int _marks; //------------------------------------------------------------ // Original private fields of ptolemy.plot.Plot //------------------------------------------------------------ // /** The initial default width. // */ // private static final float _DEFAULT_WIDTH = 2f; // // // Half of the length of the error bar horizontal leg length; // private static final int _ERRORBAR_LEG_LENGTH = 5; // // /** @serial Is this the first datapoint in a set? */ // private boolean _firstInSet = true; /** The width of the current stroke. Only effective if the * Graphics is a Graphics2D. * */ private float _width = PlotConstants.DEFAULT_WIDTH; /** @serial Give the radius of a point for efficiency. */ private int _radius = PlotConstants.DEFAULT_MARK_RADIUS; /** @serial Give the diameter of a point for efficiency. */ private int _diameter = PlotConstants.DEFAULT_MARK_DIAMETER; /** True when disconnections should be marked.*/ private boolean _markDisconnections = false; /** @serial True if this is a bar plot. */ private boolean _bars = false; /** @serial Offset per dataset in x axis units. */ private volatile double _barOffset = 0.05; /** @serial Width of a bar in x axis units. */ private volatile double _barWidth = 0.5; /** @serial True if the points are connected. */ private boolean _connected = true; /** @serial Format information on a per data set basis. */ private ArrayList<Format> _formats = new ArrayList<Format>(); /** Cached copy of graphics, needed to reset when we are exporting * to EPS. */ private Graphics _graphics = null; /** @serial True if this is an impulse plot. */ private boolean _impulses = false; /** Initial value for elements in _prevx and _prevy that indicate * we have not yet seen data. */ private static final Long _INITIAL_PREVIOUS_VALUE = Long.MIN_VALUE; // We keep track of the last dot that has been add to be able to // remove the dot again in case an extra point was added afterwards. private HashMap<Integer, PlotPoint> _lastPointWithExtraDot = new HashMap<Integer, PlotPoint>(); // A stroke of width 1. private static final BasicStroke _LINE_STROKE1 = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND); // A stroke of width 2. private static final BasicStroke _LINE_STROKE2 = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND); /** True if different line styles should be used. */ private boolean _lineStyles = false; /** True if different line styles should be used. */ private static String[] _LINE_STYLES_ARRAY = { "solid", "dotted", "dashed", "dotdashed", "dotdotdashed" }; /** @serial The highest data set used. */ private int _maxDataset = -1; // Maximum number of different marks // NOTE: There are 11 colors in the base class. Combined with 10 // marks, that makes 110 unique signal identities. private static final int _MAX_MARKS = 10; // True when a bin has been changed and it need to be repainted // by the next scheduled repaint. private boolean _needBinRedraw = false; // True when a the plot need to be refilled // by the next scheduled repaint. private boolean _needPlotRefill = false; /** @serial Number of points to persist for. */ private int _pointsPersistence = 0; /** @serial Information about the previously plotted point. */ private ArrayList<Long> _prevxpos = new ArrayList<Long>(); /** @serial Information about the previously plotted point. */ private ArrayList<Long> _prevypos = new ArrayList<Long>(); /** @serial Information about the previously erased point. */ private ArrayList<Long> _prevErasedxpos = new ArrayList<Long>(); /** @serial Information about the previously erased point. */ private ArrayList<Long> _prevErasedypos = new ArrayList<Long>(); /** @serial Persistence in units of the horizontal axis. */ private double _xPersistence = 0.0; /** @serial Flag indicating validity of _xBottom, _xTop, * _yBottom, and _yTop. */ private boolean _xyInvalid = true; //------------------------------------------------------------ // Constructions //------------------------------------------------------------ public CustomPlot() { this((PlotModel)null); } public CustomPlot(PlotModel model) { super(); setPlotModel(model); } //------------------------------------------------------------ // Public interfaces //------------------------------------------------------------ public PlotModel getPlotModel() { return _plotModel; } public void setPlotModel(PlotModel newModel) { if (newModel == null) { _plotModel = createDefaultPlotModel(); } else { _plotModel = newModel; } _plotModel.setSettingsModifiedFlag(true); _plotModel.resetDataConstraints(); clear(true); } @Override public synchronized void paintComponent(Graphics graphics) { // update chart informations // call superclass super.paintComponent(graphics); } //------------------------------------------------------------ // Internal methods //------------------------------------------------------------ protected PlotModel createDefaultPlotModel() { return new PlotModel(EmptyDataTable.instance); } //------------------------------------------------------------ // Local value accessor for Plot interfaces //------------------------------------------------------------ @Override protected void setupProgressMaxValue() { // 最大ステップ更新 super.setupProgressMaxValue(); BigInteger maxStep = BigInteger.ZERO; DrawProgressTask task = _drawingTask; if (task != null) { maxStep = task.getMaxStep(); } // データ系列から未更新のフィールドを収集 long numRecords = _plotModel.getDataTable().getDataRecordCount(); int numSeries = _plotModel.getSeriesCount(); PlotDataField field; TreeMap<Integer, PlotDataField> tmap = new TreeMap<Integer, PlotDataField>(); for (int i = 0; i < numSeries; ++i) { PlotDataSeries series = _plotModel.getSeries(i); // X-Field field = series.getXField(); if (field != null && !field.isDecimalRangeUpdated()) { tmap.put(field.getFieldIndex(), field); } // Y-Field field = series.getYField(); if (field != null && !field.isDecimalRangeUpdated()) { tmap.put(field.getFieldIndex(), field); } } if (!tmap.isEmpty()) { maxStep = maxStep.add(BigInteger.valueOf(numRecords)); } // 描画時のデータ走査回数を計算(maxStep += (dataRecordCount * seriesCount)) maxStep = maxStep.add(BigInteger.valueOf(numRecords).multiply(BigInteger.valueOf(numSeries))); if (task != null) { task.setMaxStep(maxStep); } if (terminateByCanceled()) { return; // canceled } // データ系列の数値範囲更新 if (!tmap.isEmpty()) { _plotModel.clearDataConstraints(); PlotDataField[] refreshFields = tmap.values().toArray(new PlotDataField[tmap.size()]); for (long rindex = 0L; rindex < numRecords; ++rindex) { for (PlotDataField f : refreshFields) { f.refreshDecimalRange(rindex); } incrementProgressStep(); if (terminateByCanceled()) { return; // canceled } } //--- 更新完了フラグ設定 for (PlotDataField f : refreshFields) { f.decimalRangeUpdateFinished(); } } // 全体の統計情報を更新する _plotModel.updateEntireConstraints(); // チャート描画設定を更新 updateChartSettings(); } protected void updateChartSettings() { if (_plotImage != null && !_plotModel.isModifiedSettings()) { // 変更なし return; } // 状態取得 int numSeries = _plotModel.getSeriesCount(); PlotStyles curStyles = _plotModel.getStyles(); // グラフ設定のクリア clear(true); //--- clear local status _maxDataset = numSeries; _formats.clear(); _prevxpos.clear(); _prevypos.clear(); _prevErasedxpos.clear(); _prevErasedypos.clear(); _lastPointWithExtraDot.clear(); // タイトル、ラベル setTitle(_plotModel.getTitle()); setXLabel(_plotModel.getXLabel()); setYLabel(_plotModel.getYLabel()); setXTickField(_plotModel.getXTicksField()); setYTickField(_plotModel.getYTicksField()); // update internal status _currentdataset = -1; _marks = curStyles.getMarkStyle().id(); _width = curStyles.getStrokeWidth(); _radius = curStyles.getRadius(); _diameter = curStyles.getDiameter(); _markDisconnections = curStyles.isDrawMarkDisconnection(); _bars = curStyles.isDrawBars(); _barOffset = curStyles.getBarOffset(); _barWidth = curStyles.getBarWidth(); _connected = curStyles.isLineConnected(); _impulses = curStyles.isDrawImpulses(); _lineStyles = curStyles.isLineDifferenceEachSeries(); // データ系列 for (int dataset = 0; dataset < numSeries; ++dataset) { PlotDataSeries series = _plotModel.getSeries(dataset); // Legend addLegend(dataset, series.getAvailableLegend()); // format for data series _formats.add(new Format()); // initialize temporary values _prevxpos.add(_INITIAL_PREVIOUS_VALUE); _prevypos.add(_INITIAL_PREVIOUS_VALUE); _prevErasedxpos.add(_INITIAL_PREVIOUS_VALUE); _prevErasedypos.add(_INITIAL_PREVIOUS_VALUE); _lastPointWithExtraDot.put(dataset, null); } // reset modified flags _plotModel.setSettingsModifiedFlag(false); curStyles.setModifiedFlag(false); // refresh constraints double dXMin = _plotModel.convertXDecimalToDouble(_plotModel.getXEntireMinimumDecimalValue()); double dXMax = _plotModel.convertXDecimalToDouble(_plotModel.getXEntireMaximumDecimalValue()); double dYMin = _plotModel.convertYDecimalToDouble(_plotModel.getYEntireMinimumDecimalValue()); double dYMax = _plotModel.convertYDecimalToDouble(_plotModel.getYEntireMaximumDecimalValue()); refreshLocalConstraints(dXMin, dYMin, 0, 0, false); // no error bar refreshLocalConstraints(dXMax, dYMax, 0, 0, false); // no error bar if (!Double.isNaN(dXMin) && !Double.isNaN(dXMax)) { setXRange(dXMin, dXMax); } if (!Double.isNaN(dYMin) && !Double.isNaN(dYMax)) { setYRange(dYMin, dYMax); } } // Return true if the specified dataset is connected by default. private boolean _isConnected(int dataset) { // no check index Format fmt = _formats.get(dataset); if (fmt.connectedUseDefault) { return _connected; } else { return fmt.connected; } } protected double logXValue(double x) { if (_xlog) { if (x <= 0.0) { System.err.println("Can't plot non-positive X values " + "when the logarithmic X axis value is specified: " + x); return Double.NaN; } //x = Math.log(x) * _LOG10SCALE; x = Math.log10(x); } return x; } protected double wrapXValue(double x) { if (_wrap) { double width = _wrapHigh - _wrapLow; if (x < _wrapLow) { x += (width * Math.floor(1.0 + ((_wrapLow - x) / width))); } else if (x > _wrapHigh) { x -= (width * Math.floor(1.0 + ((x - _wrapHigh) / width))); // NOTE: Could quantization errors be a problem here? if (Math.abs(x - _wrapLow) < 0.00001) { x = _wrapHigh; } } } return x; } protected double logYValue(double y) { if (_ylog) { if (y <= 0.0) { System.err.println("Can't plot non-positive Y values " + "when the logarithmic Y axis value is specified: " + y); return Double.NaN; } y = Math.log(y) * _LOG10SCALE; } return y; } protected double logYLowErrorBar(double yLowEB) { if (_ylog) { if (yLowEB <= 0.0) { System.err .println("Can't plot non-positive Y(Low error bar) values " + "when the logarithmic Y axis value is specified: " + yLowEB); return Double.NaN; } //yLowEB = Math.log(yLowEB) * _LOG10SCALE; yLowEB = Math.log10(yLowEB); } return yLowEB; } protected double logYHighErrorBar(double yHighEB) { if (_ylog) { if (yHighEB <= 0.0) { System.err .println("Can't plot non-positive Y(High error bar) values " + "when the logarithmic Y axis value is specified: " + yHighEB); return Double.NaN; } //yHighEB = Math.log(yHighEB) * _LOG10SCALE; yHighEB = Math.log10(yHighEB); } return yHighEB; } protected void refreshLocalConstraints(double x, double y, double yLowEB, double yHighEB, boolean errorBar) { if (!Double.isNaN(x)) { x = logXValue(x); if (!Double.isNaN(x)) { x = wrapXValue(x); if (x < _xBottom) { if (_automaticRescale() && _xTop != -Double.MAX_VALUE && _xBottom != Double.MAX_VALUE) { // needPlotRefill = true; _xBottom = x - (_xTop - _xBottom); } else { _xBottom = x; } } if (x > _xTop) { if (_automaticRescale() && _xTop != -Double.MAX_VALUE && _xBottom != Double.MAX_VALUE) { // needPlotRefill = true; _xTop = x + _xTop - _xBottom; } else { _xTop = x; } } } } if (!Double.isNaN(y)) { y = logYValue(y); if (!Double.isNaN(y)) { if (y < _yBottom) { if (_automaticRescale() && _yTop != -Double.MAX_VALUE && _yBottom != Double.MAX_VALUE) { // needPlotRefill = true; _yBottom = y - (_yTop - _yBottom); } else { _yBottom = y; } } if (y > _yTop) { if (_automaticRescale() && _yTop != -Double.MAX_VALUE && _yBottom != Double.MAX_VALUE) { // needPlotRefill = true; _yTop = y + _yTop - _yBottom; } else { _yTop = y; } } if (errorBar) { if (!Double.isNaN(yLowEB)) { yLowEB = logYLowErrorBar(yLowEB); if (!Double.isNaN(yLowEB)) { if (yLowEB < _yBottom) { _yBottom = yLowEB; } if (yLowEB > _yTop) { _yTop = yLowEB; } } } if (!Double.isNaN(yHighEB)) { yHighEB = logYHighErrorBar(yHighEB); if (!Double.isNaN(yHighEB)) { if (yHighEB < _yBottom) { _yBottom = yHighEB; } if (yHighEB > _yTop) { _yTop = yHighEB; } } } } } } } private PlotPoint createPlotPoint(int dataset, double x, double y, double yLowEB, double yHighEB, boolean connected, boolean errorBar) { double originalx = x; if (!Double.isNaN(x)) { x = logXValue(x); if (!Double.isNaN(x)) { originalx = x; x = wrapXValue(x); } } if (!Double.isNaN(y)) { y = logYValue(y); if (!Double.isNaN(y)) { if (errorBar && !Double.isNaN(yLowEB) && !Double.isNaN(yHighEB)) { yLowEB = logYLowErrorBar(yLowEB); yHighEB = logYHighErrorBar(yHighEB); if (Double.isNaN(yLowEB) || Double.isNaN(yHighEB)) { errorBar = false; } } else { errorBar = false; } } else { errorBar = false; } } PlotPoint pt = new PlotPoint(); pt.originalx = originalx; pt.x = x; pt.y = y; pt.connected = connected && _isConnected(dataset); if (errorBar) { pt.yLowEB = yLowEB; pt.yHighEB = yHighEB; pt.errorBar = true; } // if (_wrap) { // // Do not connect points if wrapping... // PlotPoint old = points.get(size - 1); // // if (old.x > x) { // pt.connected = false; // } // } return pt; } protected Bin appendPointToBin(int dataset, Bin curBin, PlotPoint point, long dataRecordIndex) { long xpos = _ulx + (long) ((point.x - _xMin) * _xscale); long ypos = _lry - (long) ((point.y - _yMin) * _yscale); int nbrOfBins = 0; // データセット内の Bin の数 Bin newBin = null; if (curBin != null && curBin.xpos == xpos) { // same x position curBin.addPoint(point, dataRecordIndex, ypos); } else { // create new bin newBin = new Bin(xpos, dataset); newBin.addPoint(point, dataRecordIndex, ypos); } return newBin; } //------------------------------------------------------------ // Override methods of ptolemy.plot.PlotBox //------------------------------------------------------------ @Override protected synchronized void _drawPlot(Graphics graphics, boolean clearfirst, Rectangle drawRectangle) { // BRDebug System.err.println("_drawPlot(begin)"); if (_graphics == null) { _graphics = graphics; } else if (graphics != _graphics) { _graphics = graphics; } // We must call PlotBox._drawPlot() before calling _drawPlotPoint // so that _xscale and _yscale are set. super._drawPlot(graphics, clearfirst, drawRectangle); // Divide the points into different Bins. This should be done each time // _xscale and _yscale are set //_dividePointsIntoBins(); boolean connectInvalidValue = _plotModel.getStyles().isInvalidValueConnection(); PlotPoint point = null; Bin prevBin=null, nextBin=null, curBin=null; long numRecords = _plotModel.getDataTable().getDataRecordCount(); int numSeries = _plotModel.getSeriesCount(); for (int dataset = numSeries - 1; dataset >= 0; dataset--) { PlotDataSeries series = _plotModel.getSeries(dataset); boolean connected = false; for (long rindex = 0L; rindex < numRecords; ++rindex) { // 描画点の取得 double dx = _plotModel.convertXDecimalToDouble(series.getXDecimalValue(rindex)); double dy = _plotModel.convertYDecimalToDouble(series.getYDecimalValue(rindex)); incrementProgressStep(); if (Double.isNaN(dx) || Double.isInfinite(dx) || Double.isNaN(dy) || Double.isInfinite(dy)) { if (!connectInvalidValue) { connected = false; // 無効値で線を分断 } continue; // 無効値の含まれる系列はスキップ } point = createPlotPoint(dataset, dx, dy, 0, 0, connected, false); nextBin = appendPointToBin(dataset, curBin, point, rindex); if (nextBin != null) { if (curBin != null) { _drawBin(graphics, dataset, prevBin, curBin); } if (prevBin != null) { prevBin.clearAllPoints(); } prevBin = curBin; curBin = nextBin; nextBin = null; } connected = _connected; } if (curBin != null) { _drawBin(graphics, dataset, prevBin, curBin); if (_markDisconnections && _marks == 0) { Bin bin = curBin; boolean connectedFlag = _connected; PlotPoint lastPoint = point; if (connectedFlag && lastPoint.connected) { // In case the point is not connected there is already a dot. _setColorForDrawing(graphics, dataset, false); long xpos = bin.xpos; long ypos = _lry - (long) ((lastPoint.y - _yMin) * _yscale); // BRDebug System.out.println("_drawPlot"); _drawPoint(graphics, dataset, xpos, ypos, true, 2 /*dots*/); _resetColorForDrawing(graphics, false); // We keep track of the last dot that has been add to be able to // remove the dot again in case an extra point was added afterwards. _lastPointWithExtraDot.put(dataset, lastPoint); } } if (prevBin != null) prevBin.clearAllPoints(); curBin.clearAllPoints(); } prevBin = null; curBin = null; nextBin = null; } } private void _drawBin(Graphics graphics, int dataset, Bin prevBin, Bin curBin) { _setColorForDrawing(graphics, dataset, false); if (_lineStyles) { int lineStyle = dataset % _LINE_STYLES_ARRAY.length; _setLineStyle(_LINE_STYLES_ARRAY[lineStyle], dataset); } //ArrayList<Bin> bins = _bins.get(dataset); //Bin bin = bins.get(binIndex); long xpos = curBin.xpos; if (!curBin.needReplot()) { return; } boolean connectedFlag = _connected; PlotPointNode firstNode = curBin.getFirstPoint(); PlotPointNode lastNode = curBin.getLastPoint(); // long startPosition = curBin.nextPointToPlot(); // long endPosition = curBin.afterLastPointIndex(); //ArrayList<PlotPoint> points = _points.get(dataset); // Check to see whether the dataset has a marks directive int marks = _marks; // Draw decorations that may be specified on a per-dataset basis Format fmt = _formats.get(dataset); if (!fmt.marksUseDefault) { marks = fmt.marks; } // if (_markDisconnections && marks == 0 && endPosition > startPosition && startPosition > 0) { if (_markDisconnections && marks == 0 && prevBin != null && !prevBin.isPointsEmpty()) { // PlotPoint previousPoint = points.get(startPosition - 1); PlotPointNode previousPoint = prevBin.getLastPoint(); // if (!(connectedFlag && points.get(startPosition).connected)) { if (!(connectedFlag && firstNode.point.connected)) { // if (connectedFlag && previousPoint.connected) { if (connectedFlag && previousPoint.point.connected) { // if (_lastPointWithExtraDot.get(dataset) != previousPoint) { if (_lastPointWithExtraDot.get(dataset) != previousPoint.point) { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // BRDebug System.out.println("Plotting point:" + prevxpos + ", " + prevypos + ", position :" + (startPosition-1) + ", previous"); _drawPoint(graphics, dataset, prevxpos, prevypos, true, 2 /*dots*/); } else { // BRDebug System.out.println("Skipping point"); // We already painted this dot in the _drawplot code. No need // to draw the same point again here. // Now reset the flag: _lastPointWithExtraDot.put(dataset, null); } } } else { // if (_lastPointWithExtraDot.get(dataset) == previousPoint) { if (_lastPointWithExtraDot.get(dataset) == previousPoint.point) { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // BRDebug System.err.println("Erasing point:" + prevxpos + ", " + prevypos + ", position :" + (startPosition-1) + ", previous"); // We keep track of the last dot that has been add to be able to // remove the dot again in case an extra point was added afterwards. // The erasing happens by drawing the point again with the same color (EXOR) _setColorForDrawing(graphics, dataset, true); _drawPoint(graphics, dataset, prevxpos, prevypos, true, 2 /*dots*/); _resetColorForDrawing(graphics, true); _setColorForDrawing(graphics, dataset, false); } } } // if (connectedFlag && bin.needConnectionWithPreviousBin()) { if (connectedFlag && curBin.needConnectionWithPreviousBin() && prevBin != null && !prevBin.isPointsEmpty()) { // Bin previousBin = bins.get(binIndex - 1); // _drawLine(graphics, dataset, xpos, bin.firstYPos(), // previousBin.xpos, previousBin.lastYPos(), true, // _DEFAULT_WIDTH); _drawLine(graphics, dataset, xpos, curBin.firstYPos(), prevBin.xpos, prevBin.lastYPos(), true, PlotConstants.DEFAULT_WIDTH); } // if (connectedFlag && bin.isConnected() && bin.rangeChanged() && bin.minYPos() != bin.maxYPos()) { // _drawLine(graphics, dataset, xpos, bin.minYPos(), xpos, bin // .maxYPos(), true, _DEFAULT_WIDTH); // } if (connectedFlag && curBin.isConnected() && curBin.rangeChanged() && curBin.minYPos() != curBin.maxYPos()) { _drawLine(graphics, dataset, xpos, curBin.minYPos(), xpos, curBin.maxYPos(), true, PlotConstants.DEFAULT_WIDTH); } if ((fmt.impulsesUseDefault && _impulses) || (!fmt.impulsesUseDefault && fmt.impulses)) { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // for (int i = startPosition; i < endPosition; ++i) { // PlotPoint point = points.get(i); // long ypos = _lry - (long) ((point.y - _yMin) * _yscale); // if (prevypos != ypos || prevxpos != xpos) { // _drawImpulse(graphics, xpos, ypos, true); // prevypos = ypos; // prevxpos = xpos; // } // } for (PlotPointNode node = firstNode; node != null; node = node.next()) { long ypos = node.ypos; if (prevypos != ypos || prevxpos != xpos) { _drawImpulse(graphics, xpos, ypos, true); prevypos = ypos; prevxpos = xpos; } } } { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // for (int i = startPosition; i < endPosition; ++i) { // PlotPoint point = points.get(i); // // // I a point is not connected, we mark it with a dot. // if (_marks != 0 // || (_markDisconnections && !(connectedFlag && point.connected))) { // long ypos = _lry - (long) ((point.y - _yMin) * _yscale); // if (prevypos != ypos || prevxpos != xpos) { // int updatedMarks = marks; // if (!(connectedFlag && point.connected) && marks == 0) { // updatedMarks = 2; // marking style: dots // } // // BRDebug System.out.println("Plotting point:" + xpos + ", " + ypos + ", position :" + (i) + ", current"); // _drawPoint(graphics, dataset, xpos, ypos, true, // updatedMarks); // prevypos = ypos; // prevxpos = xpos; // } // } // // } for (PlotPointNode node = firstNode; node != null; node = node.next()) { // I a point is not connected, we mark it with a dot. if (_marks != 0 || (_markDisconnections && !(connectedFlag && node.point.connected))) { long ypos = node.ypos; if (prevypos != ypos || prevxpos != xpos) { int updatedMarks = marks; if (!(connectedFlag && node.point.connected) && marks == 0) { updatedMarks = 2; // marking style: dots } // BRDebug System.out.println("Plotting point:" + xpos + ", " + ypos + ", position :" + (i) + ", current"); _drawPoint(graphics, dataset, xpos, ypos, true, updatedMarks); prevypos = ypos; prevxpos = xpos; } } } } if (_bars) { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // for (int i = startPosition; i < endPosition; ++i) { // PlotPoint point = points.get(i); // long ypos = _lry - (long) ((point.y - _yMin) * _yscale); // if (prevypos != ypos || prevxpos != xpos) { // _drawBar(graphics, dataset, xpos, ypos, true); // prevypos = ypos; // prevxpos = xpos; // } // } for (PlotPointNode node = firstNode; node != null; node = node.next()) { long ypos = node.ypos; if (prevypos != ypos || prevxpos != xpos) { _drawBar(graphics, dataset, xpos, ypos, true); prevypos = ypos; prevxpos = xpos; } } } // if (bin.errorBar()) { if (curBin.errorBar()) { long prevypos = _prevypos.get(dataset); long prevxpos = _prevxpos.get(dataset); // for (int i = startPosition; i < endPosition; ++i) { // PlotPoint point = points.get(i); // if (point.errorBar) { // long ypos = _lry - (long) ((point.y - _yMin) * _yscale); // if (prevypos != ypos || prevxpos != xpos) { // _drawErrorBar( // graphics, // dataset, // xpos, // _lry // - (long) ((point.yLowEB - _yMin) * _yscale), // _lry // - (long) ((point.yHighEB - _yMin) * _yscale), // true); // prevypos = ypos; // prevxpos = xpos; // // } // } // } for (PlotPointNode node = firstNode; node != null; node = node.next()) { if (node.point.errorBar) { long ypos = node.ypos; if (prevypos != ypos || prevxpos != xpos) { _drawErrorBar( graphics, dataset, xpos, _lry - (long) ((node.point.yLowEB - _yMin) * _yscale), _lry - (long) ((node.point.yHighEB - _yMin) * _yscale), true); prevypos = ypos; prevxpos = xpos; } } } } _prevxpos.set(dataset, xpos); // _prevypos.set(dataset, bin.lastYPos()); _prevypos.set(dataset, curBin.lastYPos()); curBin.resetDisplayStateAfterPlot(); _resetColorForDrawing(graphics, false); } //------------------------------------------------------------ // Internal methods of ptolemy.plot.Plot //------------------------------------------------------------ protected void _setLineStyle(String styleString, int dataset) { float[] dashvalues; Format format = _formats.get(dataset); if (styleString.equalsIgnoreCase("solid")) { format.lineStroke = new BasicStroke(_width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0); ///_graphics.setStroke(stroke); } else if (styleString.equalsIgnoreCase("dotted")) { dashvalues = new float[2]; dashvalues[0] = (float) 2.0; dashvalues[1] = (float) 2.0; format.lineStroke = new BasicStroke(_width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashvalues, 0); } else if (styleString.equalsIgnoreCase("dashed")) { dashvalues = new float[2]; dashvalues[0] = (float) 8.0; dashvalues[1] = (float) 4.0; format.lineStroke = new BasicStroke(_width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 0, dashvalues, 0); } else if (styleString.equalsIgnoreCase("dotdashed")) { dashvalues = new float[4]; dashvalues[0] = (float) 2.0; dashvalues[1] = (float) 2.0; dashvalues[2] = (float) 8.0; dashvalues[3] = (float) 2.0; format.lineStroke = new BasicStroke(_width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashvalues, 0); } else if (styleString.equalsIgnoreCase("dotdotdashed")) { dashvalues = new float[6]; dashvalues[0] = (float) 2.0; dashvalues[1] = (float) 2.0; dashvalues[2] = (float) 2.0; dashvalues[3] = (float) 2.0; dashvalues[4] = (float) 8.0; dashvalues[5] = (float) 2.0; format.lineStroke = new BasicStroke(_width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashvalues, 0); } else { StringBuffer results = new StringBuffer(); for (String style : java.util.Arrays.asList(_LINE_STYLES_ARRAY)) { if (results.length() > 0) { results.append(", "); } results.append("\"" + style + "\""); } throw new IllegalArgumentException("Line style \"" + styleString + "\" is not found, style must be one of " + results); } format.lineStyle = styleString; format.lineStyleUseDefault = false; } // Only pure java's graphics methods /** If the graphics argument is an instance of Graphics2D, then set * the current stroke to the specified width. Otherwise, do nothing. * @param graphics The graphics object. * @param width The width. */ protected void _setWidth(Graphics graphics, float width) { _width = width; // For historical reasons, the API here only assumes Graphics // objects, not Graphics2D. if (graphics instanceof Graphics2D) { // We cache the two most common cases. if (width == 1f) { ((Graphics2D) graphics).setStroke(_LINE_STROKE1); } else if (width == 2f) { ((Graphics2D) graphics).setStroke(_LINE_STROKE2); } else { ((Graphics2D) graphics).setStroke(new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); } } } /** Reset the color for drawing. This typically needs to happen after having drawn * a bin or erasing one. * @param graphics The graphics context. * @param forceExorWithBackground Restore the paint made back from exor mode */ private void _resetColorForDrawing(Graphics graphics, boolean forceExorWithBackground) { // Restore the color, in case the box gets redrawn. graphics.setColor(_foreground); if ((_pointsPersistence > 0) || (_xPersistence > 0.0) || forceExorWithBackground) { // Restore paint mode in case axes get redrawn. graphics.setPaintMode(); } } /** Set the color for drawing. This typically needs to happen before drawing * a bin or erasing one. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param forceExorWithBackground Force to go into exor mode. */ private void _setColorForDrawing(Graphics graphics, int dataset, boolean forceExorWithBackground) { if ((_pointsPersistence > 0) || (_xPersistence > 0.0) || forceExorWithBackground) { // To allow erasing to work by just redrawing the points. if (_background == null) { // java.awt.Component.setBackground(color) says that // if the color "parameter is null then this component // will inherit the background color of its parent." graphics.setXORMode(getBackground()); } else { graphics.setXORMode(_background); } } // Set the color if (_usecolor) { int color = dataset % _colors.length; graphics.setColor(_colors[color]); } else { graphics.setColor(_foreground); } } // Only pure java's graphics methods /** Draw bar from the specified point to the y axis. * If the specified point is below the y axis or outside the * x range, do nothing. If the <i>clip</i> argument is true, * then do not draw above the y range. * Note that paintComponent() should be called before * calling this method so that _xscale and _yscale are properly set. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param xpos The x position. * @param ypos The y position. * @param clip If true, then do not draw outside the range. */ protected void _drawBar(Graphics graphics, int dataset, long xpos, long ypos, boolean clip) { if (clip) { if (ypos < _uly) { ypos = _uly; } if (ypos > _lry) { ypos = _lry; } } if ((ypos <= _lry) && (xpos <= _lrx) && (xpos >= _ulx)) { // left x position of bar. int barlx = (int) (xpos - ((_barWidth * _xscale) / 2) + (dataset * _barOffset * _xscale)); // right x position of bar int barrx = (int) (barlx + (_barWidth * _xscale)); if (barlx < _ulx) { barlx = _ulx; } if (barrx > _lrx) { barrx = _lrx; } // Make sure that a bar is always at least one pixel wide. if (barlx >= barrx) { barrx = barlx + 1; } // The y position of the zero line. long zeroypos = _lry - (long) ((0 - _yMin) * _yscale); if (_lry < zeroypos) { zeroypos = _lry; } if (_uly > zeroypos) { zeroypos = _uly; } if ((_yMin >= 0) || (ypos <= zeroypos)) { graphics.fillRect(barlx, (int) ypos, barrx - barlx, (int) (zeroypos - ypos)); } else { graphics.fillRect(barlx, (int) zeroypos, barrx - barlx, (int) (ypos - zeroypos)); } } } /** Draw an error bar for the specified yLowEB and yHighEB values. * If the specified point is below the y axis or outside the * x range, do nothing. If the <i>clip</i> argument is true, * then do not draw above the y range. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param xpos The x position. * @param yLowEBPos The lower y position of the error bar. * @param yHighEBPos The upper y position of the error bar. * @param clip If true, then do not draw above the range. */ protected void _drawErrorBar(Graphics graphics, int dataset, long xpos, long yLowEBPos, long yHighEBPos, boolean clip) { // _drawLine(graphics, dataset, xpos - _ERRORBAR_LEG_LENGTH, yHighEBPos, xpos + _ERRORBAR_LEG_LENGTH, yHighEBPos, clip); _drawLine(graphics, dataset, xpos - _errorBarLegLength, yHighEBPos, xpos + _errorBarLegLength, yHighEBPos, clip); _drawLine(graphics, dataset, xpos, yLowEBPos, xpos, yHighEBPos, clip); // _drawLine(graphics, dataset, xpos - _ERRORBAR_LEG_LENGTH, yLowEBPos, xpos + _ERRORBAR_LEG_LENGTH, yLowEBPos, clip); _drawLine(graphics, dataset, xpos - _errorBarLegLength, yLowEBPos, xpos + _errorBarLegLength, yLowEBPos, clip); } // Only pure java's graphics methods, (Actually, call _setWidth() private method) /** Draw a line from the specified point to the y axis. * If the specified point is below the y axis or outside the * x range, do nothing. If the <i>clip</i> argument is true, * then do not draw above the y range. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param xpos The x position. * @param ypos The y position. * @param clip If true, then do not draw outside the range. */ protected void _drawImpulse(Graphics graphics, long xpos, long ypos, boolean clip) { if (clip) { if (ypos < _uly) { ypos = _uly; } if (ypos > _lry) { ypos = _lry; } } if ((ypos <= _lry) && (xpos <= _lrx) && (xpos >= _ulx)) { // The y position of the zero line. double zeroypos = _lry - (long) ((0 - _yMin) * _yscale); if (_lry < zeroypos) { zeroypos = _lry; } if (_uly > zeroypos) { zeroypos = _uly; } _setWidth(graphics, 1f); graphics.drawLine((int) xpos, (int) ypos, (int) xpos, (int) zeroypos); } } // Only pure java's graphics methods /** Draw a line from the specified starting point to the specified * ending point. The current color is used. If the <i>clip</i> argument * is true, then draw only that portion of the line that lies within the * plotting rectangle. This method draws a line one pixel wide. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param startx The starting x position. * @param starty The starting y position. * @param endx The ending x position. * @param endy The ending y position. * @param clip If true, then do not draw outside the range. */ protected void _drawLine(Graphics graphics, int dataset, long startx, long starty, long endx, long endy, boolean clip) { _drawLine(graphics, dataset, startx, starty, endx, endy, clip, 1f); } // Only pure java's graphics methods /** Draw a line from the specified starting point to the specified * ending point. The current color is used. If the <i>clip</i> argument * is true, then draw only that portion of the line that lies within the * plotting rectangle. The width argument is ignored if the graphics * argument is not an instance of Graphics2D. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param startx The starting x position. * @param starty The starting y position. * @param endx The ending x position. * @param endy The ending y position. * @param clip If true, then do not draw outside the range. * @param width The thickness of the line. */ protected void _drawLine(Graphics graphics, int dataset, long startx, long starty, long endx, long endy, boolean clip, float width) { _setWidth(graphics, width); Format format = _formats.get(dataset); Stroke previousStroke = null; if (!format.lineStyleUseDefault && graphics instanceof Graphics2D) { previousStroke = ((Graphics2D) graphics).getStroke(); // Draw a dashed or dotted line ((Graphics2D) graphics).setStroke(format.lineStroke); } if (clip) { // Rule out impossible cases. if (!(((endx <= _ulx) && (startx <= _ulx)) || ((endx >= _lrx) && (startx >= _lrx)) || ((endy <= _uly) && (starty <= _uly)) || ((endy >= _lry) && (starty >= _lry)))) { // If the end point is out of x range, adjust // end point to boundary. // The integer arithmetic has to be done with longs so as // to not loose precision on extremely close zooms. if (startx != endx) { if (endx < _ulx) { endy = (int) (endy + (((starty - endy) * (_ulx - endx)) / (startx - endx))); endx = _ulx; } else if (endx > _lrx) { endy = (int) (endy + (((starty - endy) * (_lrx - endx)) / (startx - endx))); endx = _lrx; } } // If end point is out of y range, adjust to boundary. // Note that y increases downward if (starty != endy) { if (endy < _uly) { endx = (int) (endx + (((startx - endx) * (_uly - endy)) / (starty - endy))); endy = _uly; } else if (endy > _lry) { endx = (int) (endx + (((startx - endx) * (_lry - endy)) / (starty - endy))); endy = _lry; } } // Adjust current point to lie on the boundary. if (startx != endx) { if (startx < _ulx) { starty = (int) (starty + (((endy - starty) * (_ulx - startx)) / (endx - startx))); startx = _ulx; } else if (startx > _lrx) { starty = (int) (starty + (((endy - starty) * (_lrx - startx)) / (endx - startx))); startx = _lrx; } } if (starty != endy) { if (starty < _uly) { startx = (int) (startx + (((endx - startx) * (_uly - starty)) / (endy - starty))); starty = _uly; } else if (starty > _lry) { startx = (int) (startx + (((endx - startx) * (_lry - starty)) / (endy - starty))); starty = _lry; } } } // Are the new points in range? if ((endx >= _ulx) && (endx <= _lrx) && (endy >= _uly) && (endy <= _lry) && (startx >= _ulx) && (startx <= _lrx) && (starty >= _uly) && (starty <= _lry)) { graphics.drawLine((int) startx, (int) starty, (int) endx, (int) endy); } } else { // draw unconditionally. graphics.drawLine((int) startx, (int) starty, (int) endx, (int) endy); } if (previousStroke != null) { ((Graphics2D) graphics).setStroke(previousStroke); } } /** Put a mark corresponding to the specified dataset at the * specified x and y position. The mark is drawn in the current * color. What kind of mark is drawn depends on the _marks * variable and the dataset argument. If the fourth argument is * true, then check the range and plot only points that * are in range. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param xpos The x position. * @param ypos The y position. * @param clip If true, then do not draw outside the range. */ protected void _drawPoint(Graphics graphics, int dataset, long xpos, long ypos, boolean clip) { // Check to see whether the dataset has a marks directive Format fmt = _formats.get(dataset); int marks = _marks; if (!fmt.marksUseDefault) { marks = fmt.marks; } _drawPoint(graphics, dataset, xpos, ypos, clip, marks); } /** Put a mark corresponding to the specified dataset at the * specified x and y position. The mark is drawn in the current * color. What kind of mark is drawn depends on the marks * argument and the dataset argument. If the fourth argument is * true, then check the range and plot only points that * are in range. * This method should be called only from the event dispatch thread. * It is not synchronized, so its caller should be. * @param graphics The graphics context. * @param dataset The index of the dataset. * @param xpos The x position. * @param ypos The y position. * @param clip If true, then do not draw outside the range. * @param marks The marks that have to be used for plotting the point. */ private void _drawPoint(Graphics graphics, int dataset, long xpos, long ypos, boolean clip, final int marks) { // BRDebug System.out.println("_drawPoint, " + xpos + ", " + ypos); // If the point is not out of range, draw it. boolean pointinside = (ypos <= _lry) && (ypos >= _uly) && (xpos <= _lrx) && (xpos >= _ulx); if (!clip || pointinside) { int xposi = (int) xpos; int yposi = (int) ypos; // If the point is out of range, and being drawn, then it is // probably a legend point. When printing in black and white, // we want to use a line rather than a point for the legend. // (So that line patterns are visible). The only exception is // when the marks style uses distinct marks, or if there is // no line being drawn. // NOTE: It is unfortunate to have to test the class of graphics, // but there is no easy way around this that I can think of. if (!pointinside && (marks != 3) && _isConnected(dataset) && ((graphics instanceof EPSGraphics) || !_usecolor)) { // Use our line styles. _drawLine(graphics, dataset, xposi - 6, yposi, xposi + 6, yposi, false, _width); } else { // Color display. Use normal legend. switch (marks) { case 0: // If no mark style is given, draw a filled rectangle. // This is used, for example, to draw the legend. graphics.fillRect(xposi - 6, yposi - 6, 6, 6); break; case 1: // points -- use 3-pixel ovals. graphics.fillOval(xposi - 1, yposi - 1, 3, 3); break; case 2: // dots graphics.fillOval(xposi - _radius, yposi - _radius, _diameter, _diameter); break; case 3: // various int[] xpoints; // various int[] ypoints; // Points are only distinguished up to _MAX_MARKS data sets. int mark = dataset % _MAX_MARKS; switch (mark) { case 0: // filled circle graphics.fillOval(xposi - _radius, yposi - _radius, _diameter, _diameter); break; case 1: // cross graphics.drawLine(xposi - _radius, yposi - _radius, xposi + _radius, yposi + _radius); graphics.drawLine(xposi + _radius, yposi - _radius, xposi - _radius, yposi + _radius); break; case 2: // square graphics.drawRect(xposi - _radius, yposi - _radius, _diameter, _diameter); break; case 3: // filled triangle xpoints = new int[4]; ypoints = new int[4]; xpoints[0] = xposi; ypoints[0] = yposi - _radius; xpoints[1] = xposi + _radius; ypoints[1] = yposi + _radius; xpoints[2] = xposi - _radius; ypoints[2] = yposi + _radius; xpoints[3] = xposi; ypoints[3] = yposi - _radius; graphics.fillPolygon(xpoints, ypoints, 4); break; case 4: // diamond xpoints = new int[5]; ypoints = new int[5]; xpoints[0] = xposi; ypoints[0] = yposi - _radius; xpoints[1] = xposi + _radius; ypoints[1] = yposi; xpoints[2] = xposi; ypoints[2] = yposi + _radius; xpoints[3] = xposi - _radius; ypoints[3] = yposi; xpoints[4] = xposi; ypoints[4] = yposi - _radius; graphics.drawPolygon(xpoints, ypoints, 5); break; case 5: // circle graphics.drawOval(xposi - _radius, yposi - _radius, _diameter, _diameter); break; case 6: // plus sign graphics.drawLine(xposi, yposi - _radius, xposi, yposi + _radius); graphics.drawLine(xposi - _radius, yposi, xposi + _radius, yposi); break; case 7: // filled square graphics.fillRect(xposi - _radius, yposi - _radius, _diameter, _diameter); break; case 8: // triangle xpoints = new int[4]; ypoints = new int[4]; xpoints[0] = xposi; ypoints[0] = yposi - _radius; xpoints[1] = xposi + _radius; ypoints[1] = yposi + _radius; xpoints[2] = xposi - _radius; ypoints[2] = yposi + _radius; xpoints[3] = xposi; ypoints[3] = yposi - _radius; graphics.drawPolygon(xpoints, ypoints, 4); break; case 9: // filled diamond xpoints = new int[5]; ypoints = new int[5]; xpoints[0] = xposi; ypoints[0] = yposi - _radius; xpoints[1] = xposi + _radius; ypoints[1] = yposi; xpoints[2] = xposi; ypoints[2] = yposi + _radius; xpoints[3] = xposi - _radius; ypoints[3] = yposi; xpoints[4] = xposi; ypoints[4] = yposi - _radius; graphics.fillPolygon(xpoints, ypoints, 5); break; } break; case 4: // bigdots //graphics.setColor(_marksColor); if (graphics instanceof Graphics2D) { Object obj = ((Graphics2D) graphics) .getRenderingHint(RenderingHints.KEY_ANTIALIASING); ((Graphics2D) graphics).setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.fillOval(xposi - 4, yposi - 4, 8, 8); ((Graphics2D) graphics).setRenderingHint( RenderingHints.KEY_ANTIALIASING, obj); } else { graphics.fillOval(xposi - 4, yposi - 4, 8, 8); } break; case 5: // If the mark style is pixels, draw a filled rectangle. graphics.fillRect(xposi, yposi, 1, 1); break; default: // none } } } } //------------------------------------------------------------ // Original ptolemy.plot.Plot class, Override ptolemy.plot.PlotBox interfaces //------------------------------------------------------------ @Override public synchronized void zoom(double lowx, double lowy, double highx, double highy) { // super.zoom(lowx, lowy, highx, highy); //--- Zoom 機能は使用しない } @Override void _zoom(int x, int y) { // super._zoom(x, y); //--- Zoom 機能は使用しない } @Override void _zoomBox(int x, int y) { //super._zoomBox(x, y); //--- Zoom 機能は使用しない } @Override void _zoomStart(int x, int y) { //super._zoomStart(x, y); //--- Zoom 機能は使用しない } @Override public synchronized void fillPlot() { throw new UnsupportedOperationException("PlotPane#fillPlot() is not supported!"); } @Deprecated @Override public void parseFile(String filespec, URL documentBase) { throw new UnsupportedOperationException("PlotPane#parseFile(String, URL) is not supported!"); } @Override public synchronized void read(InputStream inputStream) throws IOException { throw new UnsupportedOperationException("PlotPane#read(InputStream) is not supported!"); } @Override public synchronized void samplePlot() { // This needs to be done in the event thread. Runnable sample = new RunnableExceptionCatcher(new Runnable() { public void run() { synchronized (CustomPlot.this) { PlotModel model; DefaultDataTable table = new DefaultDataTable(); table.setHeaderValue(0, 0, "xdata", true); table.setHeaderValue(0, 1, "datetime", true); table.setHeaderValue(0, 2, "data2", true); table.setHeaderValue(0, 3, "data3", true); table.setHeaderValue(0, 4, "data4", true); table.setHeaderValue(0, 5, "data5", true); table.setHeaderValue(1, 2, "A", true); table.setHeaderValue(1, 3, "B", true); table.setHeaderValue(1, 4, "C", true); table.setHeaderValue(1, 5, "D", true); table.setHeaderValue(1, 6, "E", true); Calendar cal = Calendar.getInstance(); PlotDateTimeFormats formats = new PlotDateTimeFormats(); for (int i = 0; i <= 100; i++) { double xvalue = i; cal.add(Calendar.DAY_OF_MONTH, 10); table.setValue(i, 0, xvalue, true); table.setValue(i, 1, formats.format(cal), true); table.setValue(i, 2, (5 * Math.cos((Math.PI * i) / 20)), true); table.setValue(i, 3, (4.5 * Math.cos((Math.PI * i) / 25)), true); table.setValue(i, 4, (4 * Math.cos((Math.PI * i) / 30)), true); table.setValue(i, 5, (3.5 * Math.cos((Math.PI * i) / 35)), true); table.setValue(i, 6, (3 * Math.cos((Math.PI * i) / 40)), true); table.setValue(i, 7, (2.5 * Math.cos((Math.PI * i) / 45)), true); table.setValue(i, 8, (2 * Math.cos((Math.PI * i) / 50)), true); table.setValue(i, 9, (1.5 * Math.cos((Math.PI * i) / 55)), true); table.setValue(i, 10, (1 * Math.cos((Math.PI * i) / 60)), true); table.setValue(i, 11, (0.5 * Math.cos((Math.PI * i) / 65)), true); } model = new PlotModel(table); model.setTitle("Sample plot"); model.setXLabel("time"); model.setYLabel("value"); model.getStyles().setMarkStyle(PlotMarkStyles.NONE); model.getStyles().setDrawImpulses(true); model.getStyles().setLineStyle(PlotLineStyles.SOLID); PlotDataField xfield = new PlotDateTimeField(table, 1, formats); for (int i = 2; i < table.getFieldCount(); i++) { PlotDataField yfield = new PlotDecimalField(table, i); PlotDataSeries series = new PlotDataSeries(xfield, yfield); model.addSeries(series); } model.setXTicksField(xfield); //model.setYTicksField(yfield); setPlotModel(model); updateChartSettings(); } // synchronized repaint(); } // run method }); // Runnable class deferIfNecessary(sample); } /** Write plot data information to the specified output stream in PlotML. * @param output A buffered print writer. */ @Override public synchronized void writeData(PrintWriter output) { throw new UnsupportedOperationException("PlotPane#writeData(PrintWriter) is not supported!"); } @Override public synchronized void writeFormat(PrintWriter output) { throw new UnsupportedOperationException("PlotPane#writeFormat(PrintWriter) is not supported!"); } @Override protected boolean _parseLine(String line) { throw new UnsupportedOperationException("PlotPane#_parseLine(String) is not supported!"); } @Override protected void _resetScheduledTasks() { throw new UnsupportedOperationException("PlotPane#_resetScheduledTasks() is not supported!"); } @Override protected void _scheduledRedraw() { throw new UnsupportedOperationException("PlotPane#_scheduledRedraw() is not supported!"); } @Deprecated @Override protected void _writeOldSyntax(PrintWriter output) { super._writeOldSyntax(output); throw new UnsupportedOperationException("PlotPane#writeOldSyntax(PrintWriter) is not supported!"); } //------------------------------------------------------------ // Inner classes //------------------------------------------------------------ private class Bin { public Bin(long xPos, int dataset) { _dataset = dataset; xpos = xPos; } public void addPoint(PlotPoint point, long pointIndex, long ypos) { long absolutePointIndex = pointIndex; //The absolute point index is a index in the list of // all points that once existed in the plot if (_maxYPos < ypos) { _maxYPos = ypos; _rangeChanged = true; } if (_minYPos > ypos) { _minYPos = ypos; _rangeChanged = true; } if (_firstPointIndex == -1) { _needConnectionWithPreviousBin = point.connected; _firstYPos = ypos; _firstPointIndex = absolutePointIndex; _nextPointToPlot = _firstPointIndex; } else { _isConnected |= point.connected; // if one point is connected within the bin, all points will be (it is difficult to do this otherwise) assert _afterLastPointIndex == absolutePointIndex; //Bin intervals should be contiguous intervals } _afterLastPointIndex = absolutePointIndex + 1; _lastYPos = ypos; _errorBar |= point.errorBar; PlotPointNode node = new PlotPointNode(pointIndex, xpos, ypos, point); if (_lastPoint == null) { _firstPoint = node; _lastPoint = node; } else { node.prev = _lastPoint; _lastPoint.next = node; _lastPoint = node; } ++_numPoints; } /** * Return the position after the last point of the range of points within the bin * This index is the index within the current points of the plot. */ public long afterLastPointIndex() { assert _firstPointIndex != -1; return _afterLastPointIndex; } /** * Return true in case there is one point that needs an error bar, otherwise false */ public boolean errorBar() { return _errorBar; } /** * Return the position of the first point of the range of points within the bin * This index is the index within the current points of the plot. */ public long firstPointIndex() { assert _firstPointIndex != -1; return _firstPointIndex; } /** * Return the y position of the first added point in the bin. */ // Precondition: only valid in case there is at least one point public long firstYPos() { assert _firstPointIndex != -1; return _firstYPos; } /** * Return the minimum y position of the bin. * Precondition: only valid in case there is at least one point */ public long minYPos() { assert _firstPointIndex != -1; return _minYPos; } /** * Return the y position of the last added point in the bin. * Precondition: only valid in case there is at least one point */ public long lastYPos() { assert _firstPointIndex != -1; return _lastYPos; } /** * Return the maximum y position of the bin. * Precondition: only valid in case there is at least one point */ public long maxYPos() { assert _firstPointIndex != -1; return _maxYPos; } /** * Return whether a line should be drawn with the previous bin. * After you have reset the display state, the boolean return false */ public boolean needConnectionWithPreviousBin() { return _needConnectionWithPreviousBin; } /** * Return true a line has been drawn to the previous bin. */ public boolean isConnectedWithPreviousBin() { return _isConnectedWithPreviousBin; } public boolean isConnected() { return _isConnected; } /** * Return true when the bin should be plotted (again) */ public boolean needReplot() { return _needConnectionWithPreviousBin || _rangeChanged || _nextPointToPlot != _afterLastPointIndex; } /** * Return the position of the next point of the bin that should be plotted * This index is the index within the current points of the plot. */ public long nextPointToPlot() { return _nextPointToPlot; } /** * Return true when the rangeChanged */ public boolean rangeChanged() { return _rangeChanged; } /** * Reset the plot state for this bin when you have * plotted this bin/ */ public void resetDisplayStateAfterPlot() { if (_needConnectionWithPreviousBin) { _isConnectedWithPreviousBin = true; _needConnectionWithPreviousBin = false; } _rangeChanged = false; _nextPointToPlot = _afterLastPointIndex; } // /** // * Disconnect this bin with the previous bin. // */ // public void setNotConnectedWithPreviousBin() { // _needConnectionWithPreviousBin = false; // _isConnectedWithPreviousBin = false; // _points.get(_dataset).get( // _firstPointIndex - _pointInBinOffset.get(_dataset)).connected = false; // } public final long xpos; private long _afterLastPointIndex = 0; private int _dataset = 0; // _errorBar is true in case there is one point that needs an error bar, otherwise false private boolean _errorBar = false; private long _firstPointIndex = -1; private long _firstYPos = java.lang.Long.MIN_VALUE; private boolean _isConnected = false; private boolean _isConnectedWithPreviousBin = false; private long _lastYPos = java.lang.Long.MIN_VALUE; private long _maxYPos = java.lang.Long.MIN_VALUE; private long _minYPos = java.lang.Long.MAX_VALUE; // Indicate whether a line has to be added with previous bin or not // Once the line has been drawn, the boolean should be switched to false private boolean _needConnectionWithPreviousBin = false; private boolean _rangeChanged = false; private long _nextPointToPlot = 0; private long _numPoints = 0L; private PlotPointNode _firstPoint = null; private PlotPointNode _lastPoint = null; public boolean isPointsEmpty() { return (_numPoints == 0L); } public long getNumPoints() { return _numPoints; } public PlotPointNode getFirstPoint() { return _firstPoint; } public PlotPointNode getLastPoint() { return _lastPoint; } public void clearAllPoints() { PlotPointNode nextNode = _firstPoint; _firstPoint = null; _lastPoint = null; _numPoints = 0; for (; nextNode != null; ) { PlotPointNode curNode = nextNode; nextNode = curNode.next; curNode.next = null; curNode.prev = null; } } } private static class PlotPointNode { public final long recordIndex; public final long xpos; public final long ypos; public final PlotPoint point; protected PlotPointNode prev; protected PlotPointNode next; public PlotPointNode(long inRecordIndex, long x, long y, PlotPoint inPoint) { recordIndex = inRecordIndex; xpos = x; ypos = y; point = inPoint; } public boolean isFirst() { return (prev==null); } public boolean isLast() { return (next==null); } public boolean hasPrev() { return (prev != null); } public boolean hasNext() { return (next != null); } public PlotPointNode next() { return next; } public PlotPointNode prev() { return prev; } } private static class Format implements Serializable { // FindBugs suggests making this class static so as to decrease // the size of instances and avoid dangling references. // Indicate whether the current dataset is connected. public boolean connected; // Indicate whether the above variable should be ignored. public boolean connectedUseDefault = true; // Indicate whether a stem plot should be drawn for this data set. // This is ignored unless the following variable is set to false. public boolean impulses; // Indicate whether the above variable should be ignored. public boolean impulsesUseDefault = true; // The stroke used for lines // This is ignored unless strokeUseDefault is true public BasicStroke lineStroke; // The name of the stroke, see Plot.setLineStyle() // This is ignored unless strokeUseDefault is true public String lineStyle; // Indicate whether lineStroke should be used public boolean lineStyleUseDefault = true; // Indicate what type of mark to use. // This is ignored unless the following variable is set to false. public int marks; // Indicate whether the above variable should be ignored. public boolean marksUseDefault = true; } }
92416cea5536907ed45e0fd937fd6090a49fd686
1,648
java
Java
log4j-catalog/log4j-catalog-jpa/src/main/java/org/apache/logging/log4j/catalog/jpa/service/AttributeService.java
tomscommerce/logging-log4j-audit
29ce1439a367507ab7998e30b76a86d3437eb911
[ "Apache-2.0" ]
22
2018-04-04T01:47:00.000Z
2022-02-22T19:37:17.000Z
log4j-catalog/log4j-catalog-jpa/src/main/java/org/apache/logging/log4j/catalog/jpa/service/AttributeService.java
tomscommerce/logging-log4j-audit
29ce1439a367507ab7998e30b76a86d3437eb911
[ "Apache-2.0" ]
10
2018-09-04T15:00:16.000Z
2020-02-11T18:13:55.000Z
log4j-catalog/log4j-catalog-jpa/src/main/java/org/apache/logging/log4j/catalog/jpa/service/AttributeService.java
tomscommerce/logging-log4j-audit
29ce1439a367507ab7998e30b76a86d3437eb911
[ "Apache-2.0" ]
10
2017-10-20T21:38:47.000Z
2021-11-10T19:53:06.000Z
43.368421
109
0.758495
1,001,898
/* * 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.logging.log4j.catalog.jpa.service; import java.util.List; import java.util.Optional; import org.apache.logging.log4j.catalog.jpa.model.AttributeModel; /** * */ public interface AttributeService { List<AttributeModel> getAttributes(int startPage, int itemsPerPage, String sortColumn, String direction); List<AttributeModel> getAttributes(String catalogId, int startPage, int itemsPerPage, String sortColumn, String direction); List<AttributeModel> getAttributes(); List<AttributeModel> getAttributes(String catalogId); Optional<AttributeModel> getAttribute(Long attributeId); Optional<AttributeModel> getAttribute(String catalogId, String attributeName); AttributeModel saveAttribute(AttributeModel attribute); void deleteAttribute(Long attributeId); }
92416e08b19d18a17079fda4dc75b1d232b3b619
703
java
Java
src/main/java/com/crap/sms/service/UserManagementService.java
Riesenmumpitz/crap-sms
790c8fc6e7d91a0ed9f0ede44ad39dda4f488065
[ "MIT" ]
null
null
null
src/main/java/com/crap/sms/service/UserManagementService.java
Riesenmumpitz/crap-sms
790c8fc6e7d91a0ed9f0ede44ad39dda4f488065
[ "MIT" ]
null
null
null
src/main/java/com/crap/sms/service/UserManagementService.java
Riesenmumpitz/crap-sms
790c8fc6e7d91a0ed9f0ede44ad39dda4f488065
[ "MIT" ]
null
null
null
24.241379
80
0.642959
1,001,899
package com.crap.sms.service; import com.crap.sms.domain.model.User; import com.crap.sms.domain.repository.UserRepository; /** * Created by Martin Geßenich on 09.03.2017. */ public class UserManagementService { private static UserRepository userRepository = UserRepository.getInstance(); public static User createUser(String name, int password) { if (name == null || name.length() == 0) { return null; } User user = new User(name, password); if (userRepository.save(user)) { return user; } return null; } public static User findUser(String name) { return userRepository.getByUsername(name); } }
92416e87657b12cece56317af016251bacd129af
821
java
Java
src/main/java/io/proleap/vb6/asg/metamodel/statement/ifstmt/impl/ElseIfBlockImpl.java
joangilabert/vb6grammar
11d5b3df32ae754c62fad619e03d25eaa57d5324
[ "BSD-3-Clause" ]
47
2018-04-30T04:16:02.000Z
2022-03-24T03:31:00.000Z
src/main/java/io/proleap/vb6/asg/metamodel/statement/ifstmt/impl/ElseIfBlockImpl.java
joangilabert/vb6grammar
11d5b3df32ae754c62fad619e03d25eaa57d5324
[ "BSD-3-Clause" ]
3
2018-06-11T18:17:49.000Z
2022-02-08T11:57:39.000Z
src/main/java/io/proleap/vb6/asg/metamodel/statement/ifstmt/impl/ElseIfBlockImpl.java
joangilabert/vb6grammar
11d5b3df32ae754c62fad619e03d25eaa57d5324
[ "BSD-3-Clause" ]
18
2018-03-31T09:37:56.000Z
2022-03-18T07:56:44.000Z
34.625
102
0.773767
1,001,900
/* * Copyright (C) 2017, Ulrich Wolffgang <[email protected]> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.vb6.asg.metamodel.statement.ifstmt.impl; import io.proleap.vb6.VisualBasic6Parser.IfElseIfBlockStmtContext; import io.proleap.vb6.asg.metamodel.Module; import io.proleap.vb6.asg.metamodel.Scope; import io.proleap.vb6.asg.metamodel.impl.ScopedElementImpl; import io.proleap.vb6.asg.metamodel.statement.ifstmt.ElseIfBlock; public class ElseIfBlockImpl extends ScopedElementImpl implements ElseIfBlock { public ElseIfBlockImpl(final Module module, final Scope scope, final IfElseIfBlockStmtContext ctx) { super(module.getProgram(), module, scope, ctx); } }
92416fdc1e3dc8609c51f0dc8c3358059f974530
3,052
java
Java
com.ngc.seaside.gradle.plugins.ci/src/main/java/com/ngc/seaside/gradle/tasks/dependencies/RemoveSnapshotsAction.java
NorthropGrumman/seaside-gradle-plugins
34999237b4048678dc42bb5e08c4bdacabd4a8b5
[ "MIT" ]
null
null
null
com.ngc.seaside.gradle.plugins.ci/src/main/java/com/ngc/seaside/gradle/tasks/dependencies/RemoveSnapshotsAction.java
NorthropGrumman/seaside-gradle-plugins
34999237b4048678dc42bb5e08c4bdacabd4a8b5
[ "MIT" ]
1
2021-12-11T02:36:02.000Z
2021-12-11T02:36:02.000Z
com.ngc.seaside.gradle.plugins.ci/src/main/java/com/ngc/seaside/gradle/tasks/dependencies/RemoveSnapshotsAction.java
NorthropGrumman/seaside-gradle-plugins
34999237b4048678dc42bb5e08c4bdacabd4a8b5
[ "MIT" ]
1
2021-02-12T18:47:08.000Z
2021-02-12T18:47:08.000Z
42.388889
115
0.692661
1,001,901
/** * UNCLASSIFIED * * Copyright 2020 Northrop Grumman Systems Corporation * * 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.ngc.seaside.gradle.tasks.dependencies; import com.google.common.base.Preconditions; import com.ngc.seaside.gradle.tasks.DefaultTaskAction; import org.apache.commons.io.FileUtils; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyResult; import java.io.File; import java.io.IOException; import java.util.Collection; public class RemoveSnapshotsAction extends DefaultTaskAction<PopulateMaven2Repository> { private Collection<DependencyResult> dependencyResults; public RemoveSnapshotsAction setDependencyResults( Collection<DependencyResult> dependencyResults) { this.dependencyResults = Preconditions.checkNotNull(dependencyResults, "dependencyResults may not be null!"); return this; } @Override protected void doExecute() { if (task.isRemoveSnapshots()) { Preconditions.checkState(dependencyResults != null, "dependencyResults must be set!"); for (DependencyResult dependencyResult : dependencyResults) { for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) { if (artifactResult.getArtifact().isSnapshot()) { File parentDir = artifactResult.getArtifact().getFile().getParentFile(); if (parentDir.isDirectory()) { logger.info("Removing {} from local maven repository to avoid polluting the repository.", parentDir); // Delete the entire directory contents of the dependency. try { FileUtils.deleteDirectory(parentDir); } catch (IOException e) { logger.error("Unexpected exception while deleting {}.", parentDir, e); } } } } } } } }
9241712fb2222507fd23b55de15c943fd2245a6b
5,061
java
Java
src/com/jwetherell/algorithms/data_structures/test/IntervalTreeTests.java
Souidan/java-algorithms-implementation
cdab8fc0bec8fa14aacb2f416a984497edd82cde
[ "Apache-2.0" ]
2
2018-09-15T00:38:52.000Z
2018-09-20T09:40:36.000Z
src/com/jwetherell/algorithms/data_structures/test/IntervalTreeTests.java
Souidan/java-algorithms-implementation
cdab8fc0bec8fa14aacb2f416a984497edd82cde
[ "Apache-2.0" ]
null
null
null
src/com/jwetherell/algorithms/data_structures/test/IntervalTreeTests.java
Souidan/java-algorithms-implementation
cdab8fc0bec8fa14aacb2f416a984497edd82cde
[ "Apache-2.0" ]
1
2017-01-19T12:26:10.000Z
2017-01-19T12:26:10.000Z
56.233333
186
0.651255
1,001,902
package com.jwetherell.algorithms.data_structures.test; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import com.jwetherell.algorithms.data_structures.IntervalTree; @SuppressWarnings("static-method") public class IntervalTreeTests { private static boolean collectionsEqual(Collection<?> c1, Collection<?> c2) { if (c1.size()!=c2.size()) return false; return c1.containsAll(c2) && c2.containsAll(c1); } @Test public void testIntervalTree() { { // Interval tree final String RED = "RED"; final String ORANGE = "ORANGE"; final String GREEN = "GREEN"; final String DARK_GREEN = "DARK_GREEN"; final String BLUE = "BLUE"; final String PURPLE = "PURPLE"; final String BLACK = "BLACK"; java.util.List<IntervalTree.IntervalData<String>> intervals = new ArrayList<IntervalTree.IntervalData<String>>(); intervals.add((new IntervalTree.IntervalData<String>(2, 6, RED))); intervals.add((new IntervalTree.IntervalData<String>(3, 5, ORANGE))); intervals.add((new IntervalTree.IntervalData<String>(4, 11, GREEN))); intervals.add((new IntervalTree.IntervalData<String>(5, 10, DARK_GREEN))); intervals.add((new IntervalTree.IntervalData<String>(8, 12, BLUE))); intervals.add((new IntervalTree.IntervalData<String>(9, 14, PURPLE))); intervals.add((new IntervalTree.IntervalData<String>(13, 15, BLACK))); IntervalTree<String> tree = new IntervalTree<String>(intervals); IntervalTree.IntervalData<String> query = tree.query(2); assertTrue("Interval Tree query error. query=2 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(RED))); query = tree.query(4); // Stabbing query assertTrue("Interval Tree query error. query=4 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(RED, ORANGE, GREEN))); query = tree.query(9); // Stabbing query assertTrue("Interval Tree query error. query=9 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(GREEN, DARK_GREEN, BLUE, PURPLE))); query = tree.query(1, 16); // Range query assertTrue("Interval Tree query error. query=1->16 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(RED, ORANGE, GREEN, DARK_GREEN, BLUE, PURPLE, BLACK))); query = tree.query(7, 14); // Range query assertTrue("Interval Tree query error. query=7->14 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(GREEN, DARK_GREEN, BLUE, PURPLE, BLACK))); query = tree.query(14, 15); // Range query assertTrue("Interval Tree query error. query=14->15 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(PURPLE, BLACK))); } { // Lifespan Interval tree final String stravinsky = "Stravinsky"; final String schoenberg = "Schoenberg"; final String grieg = "Grieg"; final String schubert = "Schubert"; final String mozart = "Mozart"; final String schuetz = "Schuetz"; java.util.List<IntervalTree.IntervalData<String>> intervals = new ArrayList<IntervalTree.IntervalData<String>>(); intervals.add((new IntervalTree.IntervalData<String>(1888, 1971, stravinsky))); intervals.add((new IntervalTree.IntervalData<String>(1874, 1951, schoenberg))); intervals.add((new IntervalTree.IntervalData<String>(1843, 1907, grieg))); intervals.add((new IntervalTree.IntervalData<String>(1779, 1828, schubert))); intervals.add((new IntervalTree.IntervalData<String>(1756, 1791, mozart))); intervals.add((new IntervalTree.IntervalData<String>(1585, 1672, schuetz))); IntervalTree<String> tree = new IntervalTree<String>(intervals); IntervalTree.IntervalData<String> query = tree.query(1890); // Stabbing query assertTrue("Interval Tree query error. query=1890 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(stravinsky, schoenberg, grieg))); query = tree.query(1909); // Stabbing query assertTrue("Interval Tree query error. query=1909 returned=" + query , collectionsEqual(query.getData(), Arrays.asList(stravinsky, schoenberg))); query = tree.query(1792, 1903); // Range query assertTrue("Interval Tree query error. query=1792->1903 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(stravinsky, schoenberg, grieg, schubert))); query = tree.query(1776, 1799); // Range query assertTrue("Interval Tree query error. query=1776->1799 returned=" + query, collectionsEqual(query.getData(), Arrays.asList(schubert, mozart))); } } }
924172419ce7076392236bd02aab0a4a7e98b750
1,840
java
Java
baleen-core/src/main/java/uk/gov/dstl/baleen/core/logging/MinMaxFilter.java
uk-gov-mirror/NationalCrimeAgency.baleen
4620f1ee685602d8542ec66a8e4f58c7548a2da8
[ "Apache-2.0" ]
166
2015-09-15T12:53:37.000Z
2021-08-23T17:45:06.000Z
baleen-core/src/main/java/uk/gov/dstl/baleen/core/logging/MinMaxFilter.java
NationalCrimeAgency/baleen
4620f1ee685602d8542ec66a8e4f58c7548a2da8
[ "Apache-2.0" ]
61
2015-10-20T08:25:07.000Z
2019-10-24T14:28:54.000Z
baleen-core/src/main/java/uk/gov/dstl/baleen/core/logging/MinMaxFilter.java
NationalCrimeAgency/baleen
4620f1ee685602d8542ec66a8e4f58c7548a2da8
[ "Apache-2.0" ]
57
2015-10-01T09:29:12.000Z
2021-04-10T22:02:00.000Z
26.666667
99
0.680978
1,001,903
// Dstl (c) Crown Copyright 2017 package uk.gov.dstl.baleen.core.logging; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; /** * A log event filter which includes only logs within a certain level window (defined by a minimum * and maximum level). */ public class MinMaxFilter extends Filter<ILoggingEvent> { private final Level min; private final Level max; /** * Create a new instance of MinMaxFilter * * @param min The lowest level to log (inclusive), defaults to INFO if not provided * @param max The highest level to log (inclusive), defaults to the highest level, ERROR, if not * provided */ public MinMaxFilter(Level min, Level max) { this.min = min == null ? Level.INFO : min; this.max = max == null ? Level.ERROR : max; } /** * Get the minimum level of the current filter. * * @return The minimum level */ public Level getMin() { return min; } /** * Get the maximum level of the current filter. * * @return The maximum level */ public Level getMax() { return max; } /** * Decide whether a given logging event should be accepted or not by this filter (i.e. whether it * falls within the specified levels). * * @param event The logging event being examined * @return Whether the event should be accepted or not */ @Override public FilterReply decide(ILoggingEvent event) { Level level = event.getLevel(); if (level == null) { // We specifically avoid logging here to avoid any circular issues. return FilterReply.DENY; } boolean allow = level.isGreaterOrEqual(min) && max.isGreaterOrEqual(level); return allow ? FilterReply.NEUTRAL : FilterReply.DENY; } }
924172e3cf86fc8af7ae2c7689337ce6663a4abd
1,419
java
Java
src/main/java/com/gitlab/martinpiz097/htmlbuilder/html/types/HTMLContentElement.java
martinpiz097/htmlbuilder
e45417613fb3942b25eae58ed5865180491f2762
[ "Apache-2.0" ]
null
null
null
src/main/java/com/gitlab/martinpiz097/htmlbuilder/html/types/HTMLContentElement.java
martinpiz097/htmlbuilder
e45417613fb3942b25eae58ed5865180491f2762
[ "Apache-2.0" ]
null
null
null
src/main/java/com/gitlab/martinpiz097/htmlbuilder/html/types/HTMLContentElement.java
martinpiz097/htmlbuilder
e45417613fb3942b25eae58ed5865180491f2762
[ "Apache-2.0" ]
null
null
null
26.277778
80
0.601832
1,001,904
package com.gitlab.martinpiz097.htmlbuilder.html.types; import com.gitlab.martinpiz097.htmlbuilder.html.interfaces.HtmlDrawable; import java.util.ArrayList; public class HTMLContentElement extends HTMLElement { protected String content; public HTMLContentElement(String name) { this(name, null, null); } public HTMLContentElement(String name, HTMLElement parent, String content) { super(name, parent); this.content = content; } public HTMLContentElement(String name, String content) { this(name, null, content); } public boolean hasContent() { return content != null; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String draw() { StringBuilder sbHtml = new StringBuilder(); sbHtml.append('<').append(name); appendAttributes(sbHtml); sbHtml.append(">"); if (content != null) sbHtml.append('\n').append(content).append('\n'); else if (listChilds.size() > 0) { sbHtml.append('\n'); for (int i = 0; i < listChilds.size(); i++) sbHtml.append(listChilds.get(i).draw()); sbHtml.append('\n'); } sbHtml.append("</").append(name).append(">\n"); return sbHtml.toString(); } }
924174e9029c3f7f4fe218371dc42eff48c34c18
1,619
java
Java
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/types/LogicalOperatorType.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/types/LogicalOperatorType.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/types/LogicalOperatorType.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
29.436364
86
0.630636
1,001,905
/* * 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.camel.language.simple.types; /** * Types of logical operators supported */ public enum LogicalOperatorType { AND, OR; public static LogicalOperatorType asOperator(String text) { switch (text) { case "&&": return AND; case "||": return OR; default: throw new IllegalArgumentException("Operator not supported: " + text); } } public String getOperatorText(LogicalOperatorType operator) { switch (operator) { case AND: return "&&"; case OR: return "||"; default: return ""; } } @Override public String toString() { return getOperatorText(this); } }
92417527d7f907a1bd693de96d5073c221ec054a
2,019
java
Java
src/main/java/com/qa/rest/TeacherController.java
RQAJohnson/todoLIST
156285dc1374ff66c72e2a46dc22d4cdf11e634c
[ "MIT" ]
null
null
null
src/main/java/com/qa/rest/TeacherController.java
RQAJohnson/todoLIST
156285dc1374ff66c72e2a46dc22d4cdf11e634c
[ "MIT" ]
null
null
null
src/main/java/com/qa/rest/TeacherController.java
RQAJohnson/todoLIST
156285dc1374ff66c72e2a46dc22d4cdf11e634c
[ "MIT" ]
null
null
null
30.134328
107
0.78207
1,001,906
package com.qa.rest; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.qa.persistance.domain.TeacherDomain; import com.qa.persistance.dto.TeacherDTO; import com.qa.service.TeacherService; @RestController @RequestMapping("/teacher") public class TeacherController { private TeacherService service; public TeacherController(TeacherService service) { super(); this.service = service; } // POST or CREATE @PostMapping("/create") public ResponseEntity<TeacherDTO> create(@RequestBody TeacherDomain teacher) { return new ResponseEntity<TeacherDTO>(this.service.create(teacher), HttpStatus.CREATED); } // READ @GetMapping("/readAll") public ResponseEntity<List<TeacherDTO>> readAll() { return ResponseEntity.ok(this.service.readAll()); } // READ BY ID @GetMapping("/read/{id}") public ResponseEntity<TeacherDTO> readTeacher(@PathVariable("id") Long id) { return ResponseEntity.ok(this.service.readOne(id)); } // UPDATE @PutMapping("update/{id}") public ResponseEntity<TeacherDTO> update(@PathVariable("id") Long id, @RequestBody TeacherDomain teacher){ return new ResponseEntity<TeacherDTO>(this.service.update(id, teacher), HttpStatus.ACCEPTED); } // DELETE @DeleteMapping("/delete/{id}") public ResponseEntity<Object> delete(@PathVariable("id") Long id) { return this.service.delete(id) ? new ResponseEntity<>(HttpStatus.NO_CONTENT) : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
92417613ee637546ffed2c86a8f31a70e34aba89
831
java
Java
src/main/java/org/battlecode/bc18/api/MyKnight.java
TheButlah/Battlecode-2018
1d512d74b875f98ee2329ea90b299dade06408d3
[ "MIT" ]
null
null
null
src/main/java/org/battlecode/bc18/api/MyKnight.java
TheButlah/Battlecode-2018
1d512d74b875f98ee2329ea90b299dade06408d3
[ "MIT" ]
null
null
null
src/main/java/org/battlecode/bc18/api/MyKnight.java
TheButlah/Battlecode-2018
1d512d74b875f98ee2329ea90b299dade06408d3
[ "MIT" ]
null
null
null
23.083333
65
0.647413
1,001,907
package org.battlecode.bc18.api; import bc.Unit; import bc.UnitType; public interface MyKnight extends MyRobot, MyAttacker{ UnitType TYPE = UnitType.Knight; @Override default UnitType getType() { return TYPE; } /** * Whether the javelin is ready to use. * NOTE: Checks both heat and unlock status. */ boolean isJavelinReady(); /** Whether the target is within javelin range */ boolean isWithinJavelinRange(Unit target); /** * Whether we can javelin the target. * Checks heat, distance, and unlock status. */ boolean canJavelin(Unit target); /** * Javelins the target, dealing the knight's standard damage. * NOTE: Does not check to see if we can first. * @param target The target unit. */ void javelin(Unit target); }
924177330abc53ab2b74b7fdd31512d07bb228a6
1,349
java
Java
camel3-cdi/cdi-rabbit-consumer/src/main/java/edu/emmerson/camel3/cdi/rmq/controlbus/MngtDescribeRouteBuilder.java
Emmerson-Miranda/camel
c6d3e6e18c8bf2b2e695041586b17e8aa218f742
[ "Apache-2.0" ]
3
2020-06-03T10:33:57.000Z
2021-09-21T11:10:21.000Z
camel3-cdi/cdi-rabbit-consumer/src/main/java/edu/emmerson/camel3/cdi/rmq/controlbus/MngtDescribeRouteBuilder.java
Emmerson-Miranda/camel
c6d3e6e18c8bf2b2e695041586b17e8aa218f742
[ "Apache-2.0" ]
null
null
null
camel3-cdi/cdi-rabbit-consumer/src/main/java/edu/emmerson/camel3/cdi/rmq/controlbus/MngtDescribeRouteBuilder.java
Emmerson-Miranda/camel
c6d3e6e18c8bf2b2e695041586b17e8aa218f742
[ "Apache-2.0" ]
6
2019-05-13T12:48:46.000Z
2021-12-27T20:09:16.000Z
25.942308
78
0.674574
1,001,908
package edu.emmerson.camel3.cdi.rmq.controlbus; import java.time.Instant; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import org.apache.camel.CamelContext; import org.apache.camel.Route; import org.apache.camel.builder.RouteBuilder; public class MngtDescribeRouteBuilder extends RouteBuilder { @Override public void configure() throws Exception { from(MngtConstants.MNGT_DESCRIBE_DIRECT_ENDPOINT) .routeId(MngtConstants.MNGT_DESCRIBE_DIRECT_ROUTE_ID) .process().message(m -> { LinkedHashMap<String, String> routes = new LinkedHashMap<String, String>(); LinkedHashMap<String, Object> body = new LinkedHashMap<String, Object>(); body.put("date", Instant.now().toString()); body.put("routes", routes); final CamelContext ctx = m.getExchange().getContext(); Comparator<Route> compareById = new Comparator<Route>() { @Override public int compare(Route o1, Route o2) { return o1.getId().compareTo(o2.getId()); } }; List<Route> ordered = ctx.getRoutes(); Collections.sort(ordered, compareById); ordered.forEach(r -> { routes.put(r.getId(), r.getEndpoint().getClass().getSimpleName()); }); m.setBody(body); }) ; } }
924178ca486e6172ac591a3f4eec3146ae6ba8d0
2,955
java
Java
app/src/main/java/com/youngmanster/collection/activity/MainActivity.java
kimonic/Collection-Android-master
c0b3ff0edabb80fdd162e33ba860e75704a1a1eb
[ "MIT" ]
null
null
null
app/src/main/java/com/youngmanster/collection/activity/MainActivity.java
kimonic/Collection-Android-master
c0b3ff0edabb80fdd162e33ba860e75704a1a1eb
[ "MIT" ]
null
null
null
app/src/main/java/com/youngmanster/collection/activity/MainActivity.java
kimonic/Collection-Android-master
c0b3ff0edabb80fdd162e33ba860e75704a1a1eb
[ "MIT" ]
null
null
null
25.695652
103
0.767513
1,001,909
package com.youngmanster.collection.activity; import android.content.Intent; import android.support.v7.widget.GridLayoutManager; import android.view.LayoutInflater; import android.view.View; import com.youngmanster.collection.R; import com.youngmanster.collection.activity.base.BaseUiActivity; import com.youngmanster.collection.activity.baseadapter.BaseAdapterActivity; import com.youngmanster.collection.activity.recyclerview.RecyclerViewActivity; import com.youngmanster.collection.adapter.MainViewAdapter; import com.youngmanster.collection.base.BaseActivity; import com.youngmanster.collection.mvp.ui.MVPActivity; import com.youngmanster.collectionlibrary.refreshrecyclerview.base.adapter.BaseRecyclerViewAdapter; import com.youngmanster.collectionlibrary.refreshrecyclerview.pulltorefresh.PullToRefreshRecyclerView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * Created by yangyan * on 2018/3/8. */ public class MainActivity extends BaseActivity implements BaseRecyclerViewAdapter.OnItemClickListener { @BindView(R.id.recycler_rv) PullToRefreshRecyclerView mRecyclerView; private MainViewAdapter mainViewAdapter; private List<String> listData = new ArrayList<>(); private Intent intent; @Override public int getLayoutId() { return R.layout.activity_main; } @Override public void init() { setTitleContent(getString(R.string.activity_main_title)); GridLayoutManager layoutManager = new GridLayoutManager(this, 2); mRecyclerView.setLayoutManager(layoutManager); View header = LayoutInflater.from(this).inflate(R.layout.layout_main_header, null); mRecyclerView.addHeaderView(header); } @Override public void requestData() { listData.add("RecyclerView"); listData.add("BaseAdapter"); listData.add("MVP+RxJava+Retrofit"); listData.add("Base"); refreshUI(); } public void refreshUI() { mainViewAdapter = new MainViewAdapter(this, listData, mRecyclerView); mRecyclerView.setAdapter(mainViewAdapter); mainViewAdapter.setOnItemClickListener(this); } private long currentTime; @Override public void onBackPressed() { if (System.currentTimeMillis() > currentTime) { showToast("再按一次即可退出"); } else { super.onBackPressed(); } currentTime = System.currentTimeMillis() + 2000; } @Override public void onDestroy() { super.onDestroy(); if (mRecyclerView != null) { mRecyclerView.destroy(); mRecyclerView = null; } } @Override public void onItemClick(View view, int position) { switch (position) { case 0: intent = new Intent(this, RecyclerViewActivity.class); startActivity(intent); break; case 1: intent = new Intent(this, BaseAdapterActivity.class); startActivity(intent); break; case 2: intent = new Intent(this, MVPActivity.class); startActivity(intent); break; case 3: intent = new Intent(this, BaseUiActivity.class); startActivity(intent); break; } } }
92417a28513a9fc9b98dc0d75d26bb0a970aa064
20,819
java
Java
src/main/java/ai/snips/snipsdemo/MainActivity.java
melanievogel/bike-voice-assistant
db02a6ee7320768c6e15aa31ab2e3f0f2cca992c
[ "Apache-2.0" ]
1
2019-01-30T18:40:53.000Z
2019-01-30T18:40:53.000Z
src/main/java/ai/snips/snipsdemo/MainActivity.java
melanievogel/bike-voice-assistant
db02a6ee7320768c6e15aa31ab2e3f0f2cca992c
[ "Apache-2.0" ]
null
null
null
src/main/java/ai/snips/snipsdemo/MainActivity.java
melanievogel/bike-voice-assistant
db02a6ee7320768c6e15aa31ab2e3f0f2cca992c
[ "Apache-2.0" ]
null
null
null
38.986891
157
0.541765
1,001,910
package ai.snips.snipsdemo; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.AudioFormat; import android.media.AudioRecord; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.speech.tts.TextToSpeech; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import ai.snips.hermes.InjectionOperation; import ai.snips.hermes.InjectionRequestMessage; import ai.snips.hermes.IntentMessage; import ai.snips.hermes.SessionEndedMessage; import ai.snips.hermes.SessionQueuedMessage; import ai.snips.hermes.SessionStartedMessage; import ai.snips.platform.SnipsPlatformClient; import ai.snips.platform.SnipsPlatformClient.SnipsPlatformError; import kotlin.Unit; import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function1; import utils.ActionsUtil; import static ai.snips.hermes.InjectionKind.Add; import static android.location.Location.distanceBetween; import static android.media.MediaRecorder.AudioSource.MIC; import static android.speech.tts.TextToSpeech.QUEUE_FLUSH; import static java.util.Collections.singletonList; public class MainActivity extends AppCompatActivity { private static final int AUDIO_ECHO_REQUEST = 0; private static final String TAG = "MainActivity"; private static final int FREQUENCY = 16_000; private static final int CHANNEL = AudioFormat.CHANNEL_IN_MONO; private static final int ENCODING = AudioFormat.ENCODING_PCM_16BIT; Location oLocation; private SnipsPlatformClient client; private AudioRecord recorder; private TextToSpeech mTTS; private volatile boolean continueStreaming = true; private LocationManager m; private LocationListener l; private String p; private TextView speed; /* private void timer(){ new Timer().schedule(new TimerTask() { public void run () { speak(); } }, 20000, 20000); } */ /* private void speak(){ mTTS.speak("Hallo Johannes hier kommt eine Gefahrenmeldung", TextToSpeech.QUEUE_FLUSH, null,null); } */ @SuppressLint("MissingPermission") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); speed = findViewById(R.id.speed); ensurePermissions(); if (!new File(getApplicationContext().getFilesDir() + "/zones.bike").exists()) { write(getApplicationContext().getFilesDir() + "/zones.bike", null); } m = (LocationManager) getSystemService(LOCATION_SERVICE); doIt(); m.requestLocationUpdates(p, 250, (float) 5, l); mTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = mTTS.setLanguage(Locale.ENGLISH); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language not supported"); } else { Log.e("TTS", "working"); } } else { Log.e("TTS", "Initialization failed"); } } }); findViewById(R.id.start).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (ensurePermissions()) { final Button button = findViewById(R.id.start); button.setEnabled(false); button.setText(R.string.loading); final View scrollView = findViewById(R.id.scrollView); scrollView.setVisibility(View.GONE); final View loadingPanel = findViewById(R.id.loadingPanel); loadingPanel.setVisibility(View.INVISIBLE); startMegazordService(); //timer(); } } }); } @Override protected void onDestroy() { if (client != null) { client.disconnect(); } super.onDestroy(); } private boolean ensurePermissions() { int status = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO); if (status != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE }, AUDIO_ECHO_REQUEST); return false; } return true; } private void startMegazordService() { if (client == null) { // a dir where the assistant models was unziped. It should contain the folders // custom_asr, custom_dialogue, custom_hotword and nlu_engine File assistantDir = new File(Environment.getExternalStorageDirectory() .toString(), "snips_android_assistant_j"); client = new SnipsPlatformClient.Builder(assistantDir) .enableDialogue(true) // defaults to true .enableHotword(true) // defaults to true .enableSnipsWatchHtml(true) // defaults to false .enableLogs(true) // defaults to false .withHotwordSensitivity(0.5f) // defaults to 0.5 .enableStreaming(true) // defaults to false .enableInjection(true) // defaults to false .build(); client.setOnPlatformReady(new Function0<Unit>() { @Override public Unit invoke() { runOnUiThread(new Runnable() { @Override public void run() { findViewById(R.id.loadingPanel).setVisibility(View.GONE); findViewById(R.id.scrollView).setVisibility(View.VISIBLE); final Button button = findViewById(R.id.start); button.setEnabled(true); //Before string: Start a dialogue session - means that no hotword is needed to trigger the listening button.setText(R.string.startVoice); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // programmatically start a dialogue session client.startSession(null, new ArrayList<String>(), false, null); } }); button.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { // inject new values in the "house_room" entity HashMap<String, List<String>> values = new HashMap<>(); values.put("house_room", Arrays.asList("bunker", "batcave")); InjectionOperation op = new InjectionOperation(Add, values); client.requestInjection(new InjectionRequestMessage( singletonList(op), Collections.<String, List<String>>emptyMap(), null, null)); return true; } }); } }); return null; } }); client.setOnPlatformError(new Function1<SnipsPlatformError, Unit>() { @Override public Unit invoke(SnipsPlatformError snipsPlatformError) { findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE); findViewById(R.id.scrollView).setVisibility(View.GONE); final Button button = findViewById(R.id.start); button.setEnabled(false); return null; } }); client.setOnHotwordDetectedListener(new Function0<Unit>() { @Override public Unit invoke() { Log.d(TAG, "an hotword was detected !"); // Do your magic here :D return null; } }); client.setOnIntentDetectedListener(new Function1<IntentMessage, Unit>() { @Override public Unit invoke(IntentMessage intentMessage) { String answer; Log.d(TAG, "received an intent: " + intentMessage); // Do your magic here :D // For now, lets just use a random sentence to tell the user we understood but // don't know what to do /* List<String> answers = Arrays.asList( "This is only a demo app. I understood you but I don't know how to do that", "Can you teach me how to do that?", "Oops! This action has not be coded yet!", "Yes Master! ... hum, ..., er, ... imagine this as been done", "Let's pretend I've done it! OK?"); */ switch (intentMessage.getIntent().getIntentName()) { case "melanievogel:AskForMountain": answer = CheckForDz(); break; default: answer = "I don't know how to do that"; } //int index = Math.abs(ThreadLocalRandom.current().nextInt()) % answers.size(); client.endSession(intentMessage.getSessionId(), answer); return null; } }); client.setOnListeningStateChangedListener(new Function1<Boolean, Unit>() { @Override public Unit invoke(Boolean isListening) { Log.d(TAG, "asr listening state: " + isListening); // Do you magic here :D return null; } }); client.setOnSessionStartedListener(new Function1<SessionStartedMessage, Unit>() { @Override public Unit invoke(SessionStartedMessage sessionStartedMessage) { Log.d(TAG, "dialogue session started: " + sessionStartedMessage); return null; } }); client.setOnSessionQueuedListener(new Function1<SessionQueuedMessage, Unit>() { @Override public Unit invoke(SessionQueuedMessage sessionQueuedMessage) { Log.d(TAG, "dialogue session queued: " + sessionQueuedMessage); return null; } }); client.setOnSessionEndedListener(new Function1<SessionEndedMessage, Unit>() { @Override public Unit invoke(SessionEndedMessage sessionEndedMessage) { Log.d(TAG, "dialogue session ended: " + sessionEndedMessage); return null; } }); // This api is really for debugging purposes and you should not have features depending // on its output. If you need us to expose more APIs please do ask ! client.setOnSnipsWatchListener(new Function1<String, Unit>() { public Unit invoke(final String s) { runOnUiThread(new Runnable() { public void run() { // We enabled html logs in the builder, hence the fromHtml. If you only // log to the console, or don't want colors to be displayed, do not // enable the option ((EditText) findViewById(R.id.text)).append(Html.fromHtml(s + "<br />")); findViewById(R.id.scrollView).post(new Runnable() { @Override public void run() { ((ScrollView) findViewById(R.id.scrollView)).fullScroll(View.FOCUS_DOWN); } }); } }); return null; } }); // We enabled steaming in the builder, so we need to provide the platform an audio // stream. If you don't want to manage the audio stream do no enable the option, and the // snips platform will grab the mic by itself startStreaming(); client.connect(this.getApplicationContext()); } } private void startStreaming() { continueStreaming = true; new Thread() { public void run() { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO); runStreaming(); } }.start(); } private void runStreaming() { Log.d(TAG, "starting audio streaming"); final int minBufferSizeInBytes = AudioRecord.getMinBufferSize(FREQUENCY, CHANNEL, ENCODING); Log.d(TAG, "minBufferSizeInBytes: " + minBufferSizeInBytes); recorder = new AudioRecord(MIC, FREQUENCY, CHANNEL, ENCODING, minBufferSizeInBytes); recorder.startRecording(); while (continueStreaming) { short[] buffer = new short[minBufferSizeInBytes / 2]; recorder.read(buffer, 0, buffer.length); if (client != null) { client.sendAudioBuffer(buffer); } } recorder.stop(); Log.d(TAG, "audio streaming stopped"); } @SuppressLint("MissingPermission") @Override protected void onResume() { super.onResume(); if (client != null) { startStreaming(); client.resume(); } m.requestLocationUpdates(p, 0, (float) 0, l); } @Override protected void onPause() { continueStreaming = false; if (client != null) { client.pause(); } super.onPause(); m.removeUpdates(l); } public void write(String file, ArrayList<DangerZoneObject> myArrayList) { FileOutputStream out; if (myArrayList == null) { } if (new File(file).exists()) { myArrayList.addAll(read(file)); } try { out = new FileOutputStream(file); for (int i = myArrayList.size() - 1; i > -1; i--) { String content = "name\n" + myArrayList.get(i).getName() + "\n" + myArrayList.get(i).getLati() + "\n" + myArrayList.get(i).getLongi() + "\n"; out.write(content.getBytes()); } out.close(); } catch (Exception e) { //fehlende Permission oder sd an pc gemountet e.printStackTrace(); } } public ArrayList<DangerZoneObject> read(String file) { ArrayList<DangerZoneObject> result = new ArrayList<>(); try { BufferedReader buf = new BufferedReader(new FileReader(file)); String line; while ((line = buf.readLine()) != null) { if (line.equals("name")) { DangerZoneObject object = new DangerZoneObject("", 0.0, 0.0, ""); object.setName(buf.readLine()); object.setLati(Double.parseDouble(buf.readLine())); object.setLongi(Double.parseDouble(buf.readLine())); result.add(object); } } buf.close(); } catch (IOException e) { e.printStackTrace(); } return result; } @SuppressLint("MissingPermission") private void doIt() { // LocationManager-Instanz ermitteln m = getSystemService(LocationManager.class); if (m == null) { finish(); } // Provider mit genauer Auflösung // und mittlerem Energieverbrauch p = ActionsUtil.getCriteria(m); // LocationListener-Objekt erzeugen l = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { Runnable runnable = new myThread(); Thread thread = new Thread(runnable); thread.start(); if (oLocation != null) { long time = location.getTime() - oLocation.getTime(); speed.setText(location.distanceTo(oLocation) * 1000 * 60 * 60 / time +"\n"+location.getLatitude()+"\n"+location.getLongitude()); if (time==0){ speed.setText("time 0"); } } oLocation = new Location(location); } }; } /* public double greatCircleInKilometers(double lat1, double long1, double lat2, double long2) { double phi1 = lat1 * PI_RAD; double phi2 = lat2 * PI_RAD; double lam1 = long1 * PI_RAD; double lam2 = long2 * PI_RAD; return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1)); }*/ public String CheckForDz() { String answer = "There is a "; Log.d(TAG, "entered"); ArrayList<DangerZoneObject> arrayList = new ArrayList<>(); if (arrayList.size() == 0) { arrayList.addAll(read(getApplicationContext().getFilesDir() + "/zones.bike")); Log.d(TAG, String.valueOf(arrayList.size())); } for (DangerZoneObject dz : arrayList) { float[] results = new float[1]; // double distance = Location.distanceBetween(oLocation.getLatitude(), oLocation.getLongitude(), dz.getLati(), dz.getLongi(), results[]); distanceBetween(oLocation.getLatitude(), oLocation.getLongitude(), dz.getLati(), dz.getLongi(), results); double distance = results [0]; Log.d(TAG, String.valueOf(distance)); if (100.00 > distance) { if (!answer.equals("There is a ")) { answer = answer + " and a "; } answer = answer + dz.getName() + " in " + (int) distance + " metres"; } } if (answer.equals("There is a ")) { answer = "No there isn't"; } else { answer = answer + " coming"; } return answer; } public class myThread implements Runnable { @Override public void run() { String warning; warning = CheckForDz(); //failure if (!warning.equals("No there isn't") && mTTS.isSpeaking() == false) { mTTS.speak(warning, QUEUE_FLUSH, null, null); } } } }
92417a4064b8d00450d800584af37de925e4e0d4
223
java
Java
src/main/java/demo/dp/b/proxy/Graphic.java
myid999/dpdemo
d52f10009041a92bc2a119a762f8d974561933be
[ "MIT" ]
null
null
null
src/main/java/demo/dp/b/proxy/Graphic.java
myid999/dpdemo
d52f10009041a92bc2a119a762f8d974561933be
[ "MIT" ]
null
null
null
src/main/java/demo/dp/b/proxy/Graphic.java
myid999/dpdemo
d52f10009041a92bc2a119a762f8d974561933be
[ "MIT" ]
null
null
null
22.3
68
0.672646
1,001,911
package demo.dp.b.proxy; /** * A graphic interface that proxy and real object should implement * so a proxy can proxy several real object */ public interface Graphic { public abstract void Draw(); }
92417ac5e4058475bc775dbfe7742acc9c6c543d
3,357
java
Java
wechat/src/main/java/com/yonyou/up/webservice/client/LoadChildDataEx.java
jacktuan2000/springstudy
6ea0c597ae05101349ed9c97a270e90264dd13e2
[ "Apache-2.0" ]
null
null
null
wechat/src/main/java/com/yonyou/up/webservice/client/LoadChildDataEx.java
jacktuan2000/springstudy
6ea0c597ae05101349ed9c97a270e90264dd13e2
[ "Apache-2.0" ]
null
null
null
wechat/src/main/java/com/yonyou/up/webservice/client/LoadChildDataEx.java
jacktuan2000/springstudy
6ea0c597ae05101349ed9c97a270e90264dd13e2
[ "Apache-2.0" ]
null
null
null
22.682432
112
0.501043
1,001,912
package com.yonyou.up.webservice.client; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>anonymous complex type�� Java �ࡣ * * <p>����ģʽƬ��ָ�����ڴ����е�Ԥ�����ݡ� * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="BCName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="OID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="recordXml" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="SubBC_SQLCondi" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "bcName", "oid", "recordXml", "subBCSQLCondi" }) @XmlRootElement(name = "loadChildDataEx") public class LoadChildDataEx { @XmlElement(name = "BCName") protected String bcName; @XmlElement(name = "OID") protected String oid; protected String recordXml; @XmlElement(name = "SubBC_SQLCondi") protected String subBCSQLCondi; /** * ��ȡbcName���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getBCName() { return bcName; } /** * ����bcName���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setBCName(String value) { this.bcName = value; } /** * ��ȡoid���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getOID() { return oid; } /** * ����oid���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setOID(String value) { this.oid = value; } /** * ��ȡrecordXml���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getRecordXml() { return recordXml; } /** * ����recordXml���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setRecordXml(String value) { this.recordXml = value; } /** * ��ȡsubBCSQLCondi���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getSubBCSQLCondi() { return subBCSQLCondi; } /** * ����subBCSQLCondi���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setSubBCSQLCondi(String value) { this.subBCSQLCondi = value; } }
92417c5686cc35f90602e5e41ebf8822455ff458
1,069
java
Java
src/main/java/org/mistah/steemgoalsetter/security/CustomUserDetails.java
mistah-org/steemtracker
09cb5fd1c3673dd481d04ae779b0c986e966dcf1
[ "MIT" ]
null
null
null
src/main/java/org/mistah/steemgoalsetter/security/CustomUserDetails.java
mistah-org/steemtracker
09cb5fd1c3673dd481d04ae779b0c986e966dcf1
[ "MIT" ]
null
null
null
src/main/java/org/mistah/steemgoalsetter/security/CustomUserDetails.java
mistah-org/steemtracker
09cb5fd1c3673dd481d04ae779b0c986e966dcf1
[ "MIT" ]
null
null
null
35.633333
200
0.761459
1,001,913
package org.mistah.steemgoalsetter.security; import java.util.Collection; import org.mistah.steemgoalsetter.model.admin.SystemUser; import org.springframework.security.core.GrantedAuthority; public class CustomUserDetails extends org.springframework.security.core.userdetails.User { /** auto-generated serialVersionUID */ private static final long serialVersionUID = -4533278283358246109L; private SystemUser user; public CustomUserDetails(SystemUser user, Collection<? extends GrantedAuthority> authorities) { super(user.getUsername(), user.getPassword(), authorities); this.user = user; } public CustomUserDetails(SystemUser user, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); this.user = user; } public SystemUser getUser() { return user; } }
92417d910d44e053f37cf1d04e3feadaddb8033b
328
java
Java
src/main/java/com/simbest/boot/sys/service/ISysHealthService.java
zhanshigong889/simbest-boot-cores
7a70a42021648e7e9ac20480d59839b92a972074
[ "MIT" ]
null
null
null
src/main/java/com/simbest/boot/sys/service/ISysHealthService.java
zhanshigong889/simbest-boot-cores
7a70a42021648e7e9ac20480d59839b92a972074
[ "MIT" ]
null
null
null
src/main/java/com/simbest/boot/sys/service/ISysHealthService.java
zhanshigong889/simbest-boot-cores
7a70a42021648e7e9ac20480d59839b92a972074
[ "MIT" ]
null
null
null
14.909091
44
0.685976
1,001,914
/* * 版权所有 © 北京晟壁科技有限公司 2008-2027。保留一切权利! */ package com.simbest.boot.sys.service; import com.simbest.boot.sys.model.SysHealth; /** * 用途:系统健康检查服务层 * 作者: lishuyi * 时间: 2019/12/6 9:51 */ public interface ISysHealthService { SysHealth databaseCheck(); SysHealth redisCheck(); SysHealth fileSystemCheck(); }
92417debfabcbbd08ee7c8c9ea546126902739f4
405
java
Java
src/main/java/com/github/chrisruffalo/pincushion/util/PathUtil.java
chrisruffalo/pincushion
189b0941dea2d8d3b74bc02bb571e4ce8ab4bff3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/chrisruffalo/pincushion/util/PathUtil.java
chrisruffalo/pincushion
189b0941dea2d8d3b74bc02bb571e4ce8ab4bff3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/chrisruffalo/pincushion/util/PathUtil.java
chrisruffalo/pincushion
189b0941dea2d8d3b74bc02bb571e4ce8ab4bff3
[ "Apache-2.0" ]
null
null
null
16.875
48
0.679012
1,001,915
package com.github.chrisruffalo.pincushion.util; import java.io.File; import java.io.IOException; public class PathUtil { /** * Returns a sanitized path for the given file * * @param file * @return */ public static String sanitize(File file) { try { final String path = file.getCanonicalPath(); return path; } catch (IOException e) { return file.getAbsolutePath(); } } }
92417e01585ef9eb3f797969a0562e3ecda325da
15,208
java
Java
src/main/java/de/acosix/alfresco/audit/repo/job/ConsolidateActiveUsersAuditJob.java
Acosix/alfresco-audit
1f038a85557d7cfdc87f617e07c1a1f05ebc0a8d
[ "Apache-2.0" ]
11
2017-08-25T14:09:47.000Z
2022-01-17T00:17:13.000Z
src/main/java/de/acosix/alfresco/audit/repo/job/ConsolidateActiveUsersAuditJob.java
Acosix/alfresco-audit
1f038a85557d7cfdc87f617e07c1a1f05ebc0a8d
[ "Apache-2.0" ]
5
2019-02-08T21:55:40.000Z
2021-10-20T00:14:48.000Z
src/main/java/de/acosix/alfresco/audit/repo/job/ConsolidateActiveUsersAuditJob.java
Acosix/alfresco-audit
1f038a85557d7cfdc87f617e07c1a1f05ebc0a8d
[ "Apache-2.0" ]
8
2017-08-25T14:09:59.000Z
2021-04-09T15:44:51.000Z
44.467836
140
0.645252
1,001,916
/* * Copyright 2017 - 2020 Acosix GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.acosix.alfresco.audit.repo.job; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicBoolean; import org.alfresco.model.ContentModel; import org.alfresco.repo.audit.AuditComponent; import org.alfresco.repo.audit.model.AuditApplication; import org.alfresco.repo.batch.BatchProcessor; import org.alfresco.repo.batch.BatchProcessor.BatchProcessWorkerAdaptor; import org.alfresco.repo.lock.LockAcquisitionException; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.transaction.RetryingTransactionHelper; import org.alfresco.service.cmr.audit.AuditQueryParameters; import org.alfresco.service.cmr.audit.AuditService; import org.alfresco.service.cmr.audit.AuditService.AuditQueryCallback; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.security.PersonService; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.alfresco.service.transaction.TransactionService; import org.alfresco.util.EqualsHelper; import org.alfresco.util.ISO8601DateFormat; import org.alfresco.util.Pair; import org.apache.commons.logging.LogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.acosix.alfresco.audit.repo.AuditModuleConstants; import de.acosix.alfresco.utility.repo.batch.PersonBatchWorkProvider; import de.acosix.alfresco.utility.repo.job.GenericJob; import de.acosix.alfresco.utility.repo.job.JobUtilities; /** * This job is responsible for regularly consolidating the data from the audit application {@code acosix-audit-activeUserLogin} to keep a * record of dates when users have connected to the Alfresco Repository, e.g. can be considered {@code activeUsers}. The size of the time * frame in which data will be consolidated to a single audit entry can be configured between one hour and a day, with values in between the * limits required to be proper divisors of 24 (hours). * * @author Axel Faust, <a href="http://acosix.de">Acosix GmbH</a> */ public class ConsolidateActiveUsersAuditJob implements GenericJob { private static final Logger LOGGER = LoggerFactory.getLogger(ConsolidateActiveUsersAuditJob.class); private static final QName LOCK_QNAME = QName.createQName(AuditModuleConstants.SERVICE_NAMESPACE, ConsolidateActiveUsersAuditJob.class.getSimpleName()); /** * * {@inheritDoc} */ @Override public void execute(final Object context) { try { LOGGER.debug("Running consolidation on active users audit data"); AuthenticationUtil.runAsSystem(() -> { JobUtilities.runWithJobLock(context, LOCK_QNAME, (lockReleaseCheck) -> { final TransactionService transactionService = JobUtilities.getJobDataValue(context, "transactionService", TransactionService.class); final RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper(); retryingTransactionHelper.doInTransaction(() -> { this.consolidateActiveUsersAudit(context, retryingTransactionHelper); return null; }); }); return null; }); } catch (final RuntimeException e) { if (!(e instanceof LockAcquisitionException)) { LOGGER.warn("Consolidation of active users audit data failed", e); } } catch (final Exception e) { LOGGER.error("Consolidation of active users audit data failed", e); } } protected void consolidateActiveUsersAudit(final Object context, final RetryingTransactionHelper retryingTransactionHelper) { final AuditService auditService = JobUtilities.getJobDataValue(context, "auditService", AuditService.class); final AuditComponent auditComponent = JobUtilities.getJobDataValue(context, "auditComponent", AuditComponent.class); final NamespaceService namespaceService = JobUtilities.getJobDataValue(context, "namespaceService", NamespaceService.class); final NodeService nodeService = JobUtilities.getJobDataValue(context, "nodeService", NodeService.class); final PersonService personService = JobUtilities.getJobDataValue(context, "personService", PersonService.class); final SearchService searchService = JobUtilities.getJobDataValue(context, "searchService", SearchService.class); final String workerThreadsParam = JobUtilities.getJobDataValue(context, "workerThreads", String.class, true); final String batchSizeParam = JobUtilities.getJobDataValue(context, "batchSize", String.class, true); final String timeframeHoursParam = JobUtilities.getJobDataValue(context, "timeframeHours", String.class, true); final int workerThreads = workerThreadsParam != null ? Math.min(1, Integer.parseInt(workerThreadsParam, 10)) : 4; final int batchSize = batchSizeParam != null ? Math.min(1, Integer.parseInt(batchSizeParam, 10)) : 10; final int timeframeHours = timeframeHoursParam != null ? Integer.parseInt(timeframeHoursParam, 10) : 1; if (timeframeHours <= 0) { throw new IllegalArgumentException("timeframeHours must be a positive integer"); } if (timeframeHours > 24) { throw new IllegalArgumentException("timeframeHours cannot be greater than a day of 24 hours"); } if (24 % timeframeHours != 0) { throw new IllegalArgumentException("Number of hours in a day must be divisible by timeframeHours"); } final BatchProcessor<NodeRef> processor = new BatchProcessor<>(ConsolidateActiveUsersAuditJob.class.getName(), retryingTransactionHelper, new PersonBatchWorkProvider(namespaceService, nodeService, personService, searchService), workerThreads, batchSize, null, LogFactory.getLog(ConsolidateActiveUsersAuditJob.class.getName() + ".batchProcessor"), Math.max(25, workerThreads * batchSize * 2)); final PersonConsolidationAuditWorker worker = new PersonConsolidationAuditWorker(nodeService, auditService, auditComponent, timeframeHours); processor.process(worker, true); } protected static class PersonConsolidationAuditWorker extends BatchProcessWorkerAdaptor<NodeRef> { private final NodeService nodeService; private final AuditService auditService; private final AuditComponent auditComponent; private final int timeframeHours; protected PersonConsolidationAuditWorker(final NodeService nodeService, final AuditService auditService, final AuditComponent auditComponent, final int timeframeHours) { this.nodeService = nodeService; this.auditService = auditService; this.auditComponent = auditComponent; this.timeframeHours = timeframeHours; } /** * * {@inheritDoc} */ @Override public void process(final NodeRef personRef) throws Throwable { AuthenticationUtil.setRunAsUserSystem(); final Map<QName, Serializable> personProperties = this.nodeService.getProperties(personRef); final String userName = DefaultTypeConverter.INSTANCE.convert(String.class, personProperties.get(ContentModel.PROP_USERNAME)); LOGGER.debug("Processing user {} (node {})", userName, personRef); final Set<Pair<String, String>> timeframes = new HashSet<>(); final List<Long> auditEntryIds = new ArrayList<>(); this.queryUserLogins(userName, timeframes, auditEntryIds); LOGGER.debug("Clearing active user login entries {}", auditEntryIds); this.auditService.clearAudit(auditEntryIds); LOGGER.debug("Recording active user time frames {}", timeframes); this.recordTimeframes(userName, timeframes); } protected void recordTimeframes(final String userName, final Set<Pair<String, String>> timeframes) { for (final Pair<String, String> timeframe : timeframes) { final String timeframeStart = timeframe.getFirst(); final String timeframeEnd = timeframe.getSecond(); final boolean exists = this.checkEntryExists(userName, timeframeStart, timeframeEnd); if (!exists) { // recording should be done using the proper user name AuthenticationUtil.clearCurrentSecurityContext(); AuthenticationUtil.setRunAsUser(userName); final String rootPath = AuditApplication.buildPath(AuditModuleConstants.AUDIT_PRODUCER_ROOT_PATH, ConsolidateActiveUsersAuditJob.class.getSimpleName()); final Map<String, Serializable> auditMap = new HashMap<>(); auditMap.put("userName", userName); auditMap.put("timeframeStart", timeframeStart); auditMap.put("timeframeEnd", timeframeEnd); LOGGER.debug("Recording 'new' active user time frame {} to {}", timeframeStart, timeframeEnd); this.auditComponent.recordAuditValuesWithUserFilter(rootPath, auditMap, false); // reset for next iteration AuthenticationUtil.clearCurrentSecurityContext(); AuthenticationUtil.setRunAsUserSystem(); } } } private boolean checkEntryExists(final String userName, final String timeframeStart, final String timeframeEnd) { final AuditQueryParameters aqp = new AuditQueryParameters(); aqp.setApplicationName(AuditModuleConstants.AUDIT_ACTIVE_USERS_APP_NAME); aqp.setForward(true); aqp.setUser(userName); aqp.addSearchKey(AuditModuleConstants.AUDIT_ACTIVE_USERS_TIMEFRAME_START_KEY, timeframeStart); final AtomicBoolean exists = new AtomicBoolean(); this.auditService.auditQuery(new AuditQueryCallback() { /** * * {@inheritDoc} */ @Override public boolean valuesRequired() { return true; } /** * * {@inheritDoc} */ @Override public boolean handleAuditEntry(final Long entryId, final String applicationName, final String user, final long time, final Map<String, Serializable> values) { final Serializable timeframeEndCandidate = values.get(AuditModuleConstants.AUDIT_ACTIVE_USERS_TIMEFRAME_END_KEY); if (EqualsHelper.nullSafeEquals(timeframeEndCandidate, timeframeEnd)) { exists.set(true); } return !exists.get(); } /** * * {@inheritDoc} */ @Override public boolean handleAuditEntryError(final Long entryId, final String errorMsg, final Throwable error) { return true; } }, aqp, 7); // there are only 7 possible divisors of 24 return exists.get(); } protected void queryUserLogins(final String userName, final Set<Pair<String, String>> timeframes, final List<Long> auditEntryIds) { final AuditQueryParameters aqp = new AuditQueryParameters(); aqp.setApplicationName(AuditModuleConstants.AUDIT_ACTIVE_USER_LOGIN_APP_NAME); aqp.setForward(true); aqp.addSearchKey(AuditModuleConstants.AUDIT_ACTIVE_USER_LOGIN_USER_KEY, userName); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); this.auditService.auditQuery(new AuditQueryCallback() { /** * * {@inheritDoc} */ @Override public boolean valuesRequired() { return false; } /** * * {@inheritDoc} */ @Override public boolean handleAuditEntry(final Long entryId, final String applicationName, final String user, final long time, final Map<String, Serializable> values) { cal.setTimeInMillis(time); final int hourOfDay = cal.get(Calendar.HOUR_OF_DAY); final int startHour = hourOfDay - (hourOfDay % PersonConsolidationAuditWorker.this.timeframeHours); cal.set(Calendar.HOUR_OF_DAY, startHour); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); final String timeframeStart = ISO8601DateFormat.format(cal.getTime()); cal.add(Calendar.HOUR_OF_DAY, PersonConsolidationAuditWorker.this.timeframeHours); final String timeframeEnd = ISO8601DateFormat.format(cal.getTime()); timeframes.add(new Pair<>(timeframeStart, timeframeEnd)); auditEntryIds.add(entryId); return true; } /** * * {@inheritDoc} */ @Override public boolean handleAuditEntryError(final Long entryId, final String errorMsg, final Throwable error) { return true; } }, aqp, Integer.MAX_VALUE); } } }
92417eacbf7eae6bf3a30f1bacb38319609da8c1
868
java
Java
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/hash/DefaultHashable.java
ckooma001c/Comcast-traffic_control
62286f875703b4de1b3a094b6b80c97afbf13d70
[ "Apache-2.0" ]
1
2017-02-14T21:09:10.000Z
2017-02-14T21:09:10.000Z
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/hash/DefaultHashable.java
ckooma001c/Comcast-traffic_control
62286f875703b4de1b3a094b6b80c97afbf13d70
[ "Apache-2.0" ]
1
2016-08-05T16:30:48.000Z
2016-08-05T16:30:48.000Z
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/hash/DefaultHashable.java
ckooma001c/Comcast-traffic_control
62286f875703b4de1b3a094b6b80c97afbf13d70
[ "Apache-2.0" ]
null
null
null
25.529412
82
0.737327
1,001,917
package com.comcast.cdn.traffic_control.traffic_router.core.hash; import java.util.Arrays; import java.util.List; import java.util.TreeSet; public class DefaultHashable implements Hashable { private Double[] hashes; @Override public double getClosestHash(final double hash) { return hashes[NumberSearcher.findClosest(hashes, hash)]; } @Override public DefaultHashable generateHashes(final String hashId, final int hashCount) { final TreeSet<Double> hashSet = new TreeSet<Double>(); final MD5HashFunction hashFunction = new MD5HashFunction(); for (int i = 0; i < hashCount; i++) { hashSet.add(hashFunction.hash(hashId + "--" + i)); } hashes = new Double[hashSet.size()]; System.arraycopy(hashSet.toArray(),0,hashes,0,hashSet.size()); return this; } @Override public List<Double> getHashValues() { return Arrays.asList(hashes); } }
92417fdf926b02fe414fe631ba64bac0b073a790
1,851
java
Java
src/main/java/org/lanternpowered/server/data/persistence/DataContainerInput.java
shisheng-1/Lantern
ed947a3c58574f513e940800b0094652766a092b
[ "MIT" ]
73
2015-09-08T05:55:55.000Z
2019-01-25T22:42:04.000Z
src/main/java/org/lanternpowered/server/data/persistence/DataContainerInput.java
shisheng-1/Lantern
ed947a3c58574f513e940800b0094652766a092b
[ "MIT" ]
41
2016-02-10T18:19:55.000Z
2018-11-25T01:36:58.000Z
src/main/java/org/lanternpowered/server/data/persistence/DataContainerInput.java
shisheng-1/Lantern
ed947a3c58574f513e940800b0094652766a092b
[ "MIT" ]
11
2016-01-25T22:37:52.000Z
2018-01-24T18:04:26.000Z
39.382979
80
0.753106
1,001,918
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.lanternpowered.server.data.persistence; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.persistence.InvalidDataFormatException; import java.io.IOException; /** * A input that can be used to read data views. */ public interface DataContainerInput { /** * Reads a {@link DataContainer} from the input. * * @return the data view * @throws IOException when a i/o error occurred */ DataContainer read() throws InvalidDataFormatException, IOException; }
92418021febd08634cdddf31c9a263b434dff498
1,151
java
Java
src/arrays/MaxConsecutiveOnesII.java
g1patil/data-structures-and-algorithms
5b3e6512f7de895154241cf048382efbf3883523
[ "Apache-2.0" ]
2
2022-01-31T21:12:40.000Z
2022-03-10T23:17:07.000Z
src/arrays/MaxConsecutiveOnesII.java
g1patil/data-structures-and-algorithms
5b3e6512f7de895154241cf048382efbf3883523
[ "Apache-2.0" ]
null
null
null
src/arrays/MaxConsecutiveOnesII.java
g1patil/data-structures-and-algorithms
5b3e6512f7de895154241cf048382efbf3883523
[ "Apache-2.0" ]
null
null
null
22.134615
55
0.46742
1,001,919
package arrays; import annotation.Platform; import annotation.Quality; import annotation.Site; import annotation.Stage; import org.junit.jupiter.api.Test; /** * @author g1patil * 487. Max Consecutive Ones II */ @Quality(Stage.TESTED) @Platform(Site.LEETCODE) public class MaxConsecutiveOnesII { public int findMaxConsecutiveOnes(int[] nums) { int max = 0 , slow = 0 , fast = 0 ; int zeroCount = 1 ; while ( fast < nums.length){ if (nums[fast] == 1){ max = Math.max( max , fast - slow + 1); fast++; continue; } if (nums[fast] == 0 && zeroCount > 0){ zeroCount--; max = Math.max( max , fast - slow + 1); fast++; } else { while (zeroCount <= 0){ if (nums[slow] == 0) zeroCount++; slow++; } } } return max; } @Test public void test_(){ System.out.println( findMaxConsecutiveOnes(new int[]{0}) ); } }
924180e738e006bfaaf001ffc635bad8562fecaa
2,210
java
Java
agp-7.1.0-alpha01/tools/base/sdk-common/src/main/java/com/android/ide/common/process/ProcessResultImpl.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
1
2020-10-04T19:30:22.000Z
2020-10-04T19:30:22.000Z
agp-7.1.0-alpha01/tools/base/sdk-common/src/main/java/com/android/ide/common/process/ProcessResultImpl.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/sdk-common/src/main/java/com/android/ide/common/process/ProcessResultImpl.java
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
2
2020-10-04T19:30:24.000Z
2020-11-04T05:58:17.000Z
28.333333
79
0.657014
1,001,920
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.common.process; import com.android.annotations.NonNull; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import java.util.List; /** * Internal implementation of ProcessResult used by DefaultProcessExecutor. */ class ProcessResultImpl implements ProcessResult { @NonNull private final ImmutableList<String> mCommand; private final int mExitValue; private final Throwable mFailure; ProcessResultImpl(List<String> command, int exitValue) { this(command, exitValue, null); } ProcessResultImpl(List<String> command, Throwable failure) { this(command, -1, failure); } ProcessResultImpl(List<String> command, int exitValue, Throwable failure) { mCommand = ImmutableList.copyOf(command); mExitValue = exitValue; mFailure = failure; } @NonNull @Override public ProcessResult assertNormalExitValue() throws ProcessException { if (mExitValue != 0) { throw new ProcessException( String.format( "Return code %d for process '%s'", mExitValue, Joiner.on(" ").join(mCommand))); } return this; } @Override public int getExitValue() { return mExitValue; } @NonNull @Override public ProcessResult rethrowFailure() throws ProcessException { if (mFailure != null) { throw new ProcessException("", mFailure); } return this; } }
9241812036be7d39b028924139654b15297b8a59
4,752
java
Java
work/jetty/nifi-web-ui-1.3.0.war/webapp/WEB-INF/classes/org/apache/jsp/WEB_002dINF/partials/users/user_002ddelete_002ddialog_jsp.java
pramod08/NIFI1.4.0-sercure-1
011fe50c034e90a8dbd0dac4a429fe61b8ed9bce
[ "Apache-2.0" ]
null
null
null
work/jetty/nifi-web-ui-1.3.0.war/webapp/WEB-INF/classes/org/apache/jsp/WEB_002dINF/partials/users/user_002ddelete_002ddialog_jsp.java
pramod08/NIFI1.4.0-sercure-1
011fe50c034e90a8dbd0dac4a429fe61b8ed9bce
[ "Apache-2.0" ]
null
null
null
work/jetty/nifi-web-ui-1.3.0.war/webapp/WEB-INF/classes/org/apache/jsp/WEB_002dINF/partials/users/user_002ddelete_002ddialog_jsp.java
pramod08/NIFI1.4.0-sercure-1
011fe50c034e90a8dbd0dac4a429fe61b8ed9bce
[ "Apache-2.0" ]
null
null
null
37.417323
300
0.700758
1,001,921
/* * Generated by the Jasper component of Apache Tomcat * Version: JspC/ApacheTomcat8 * Generated at: 2017-06-05 16:22:00 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.partials.users; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class user_002ddelete_002ddialog_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, false, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); out = pageContext.getOut(); _jspx_out = out; out.write("\n\n<div id=\"user-delete-dialog\" class=\"hidden\">\n <div class=\"dialog-content\">\n <input type=\"hidden\" id=\"user-id-delete-dialog\"/>\n Are you sure you want to delete the account for '<span id=\"user-identity-delete-dialog\"></span>'?\n </div>\n</div>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
9241819d9c1548a3717711eb3ed6200748fdcd60
35,715
java
Java
src/main/java/com/ben9583/chess_ai/components/Board.java
ben9583/chess-ai
12a7b805eacc5d44b4dd8b0074a1f882b4f4169a
[ "MIT" ]
1
2022-03-05T23:59:42.000Z
2022-03-05T23:59:42.000Z
src/main/java/com/ben9583/chess_ai/components/Board.java
ben9583/chess-ai
12a7b805eacc5d44b4dd8b0074a1f882b4f4169a
[ "MIT" ]
null
null
null
src/main/java/com/ben9583/chess_ai/components/Board.java
ben9583/chess-ai
12a7b805eacc5d44b4dd8b0074a1f882b4f4169a
[ "MIT" ]
null
null
null
39.949664
268
0.600896
1,001,922
package com.ben9583.chess_ai.components; import com.ben9583.chess_ai.components.pieces.*; import com.ben9583.chess_ai.utils.Vector2; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class Board { /* 2D array representing all the pieces belonging to this board at (x, y). */ private final Piece[][] board; /* Lookup table to make finding pieces easier. */ @NotNull private final Map<Piece, Vector2> pieces; /* Whose turn it is in the game. */ @NotNull private Player whoseTurn; /* Whether castling is possible for each player and each side. */ private boolean castleWhiteKing; private boolean castleWhiteQueen; private boolean castleBlackKing; private boolean castleBlackQueen; /* The Vector2 corresponding to the pawn awaiting a decision on promotion. Null if no piece to promote. */ @Nullable private Vector2 awaitPromotion = null; /* The Vector2 corresponding to the position at which en passant can take place, following FEN notation. */ @Nullable private Vector2 enPassantPosition = null; /* Number of half-moves since a capture or pawn move. Draw at 50. */ private int halfMoveClock = 0; /* Number of full-moves occurred since this game started. */ private int fullMoveNumber = 1; /* Number of times a given position has been reached. Two positions are equal by rules of threefold repetition. */ private final Map<String, Integer> reachedPositions = new HashMap<>(); /* Record of all moves made, in standard algebraic notation. */ private final List<String> notationMoves = new ArrayList<>(); /* Whether the game is over because of checkmate or stalemate. */ private boolean gameOver = false; /* Message for why the game ended. */ private String gameOverReason = null; /* Whether the next move should increment the turn. Used for validating checks. */ private boolean disableMovementThisTurn = false; /* The piece the user clicked. See also: Board2D */ private Vector2 clicked = null; /* External function to be run when a turn has ended. */ private Runnable onNextTurn; /** * Creates a standard chess board. */ public Board() { this.board = new Piece[][]{ { new Rook(Player.WHITE, this), new Knight(Player.WHITE, this), new Bishop(Player.WHITE, this), new Queen(Player.WHITE, this), new King(Player.WHITE, this), new Bishop(Player.WHITE, this), new Knight(Player.WHITE, this), new Rook(Player.WHITE, this) }, { new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this), new Pawn(Player.WHITE, this) }, { null, null, null, null, null, null, null, null }, { null, null, null, null, null, null, null, null }, { null, null, null, null, null, null, null, null }, { null, null, null, null, null, null, null, null }, { new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this), new Pawn(Player.BLACK, this) }, { new Rook(Player.BLACK, this), new Knight(Player.BLACK, this), new Bishop(Player.BLACK, this), new Queen(Player.BLACK, this), new King(Player.BLACK, this), new Bishop(Player.BLACK, this), new Knight(Player.BLACK, this), new Rook(Player.BLACK, this) } }; this.pieces = new HashMap<>(); for(int i = 0; i < this.board.length; i++) { for(int j = 0; j < this.board[i].length; j++) { if(this.board[i][j] != null) { this.pieces.put(this.board[i][j], new Vector2(j, i)); } } } this.whoseTurn = Player.WHITE; this.castleWhiteKing = true; this.castleWhiteQueen = true; this.castleBlackKing = true; this.castleBlackQueen = true; } /** * Returns a string hash of this board. * Two hashes are equal if they would cause a threefold repetition. * @return A hash of this board */ @NotNull private String getBoardHash() { /* From Wikipedia: Two positions are by definition "the same" if the same types of pieces occupy the same squares, the same player has the move, the remaining castling rights are the same and the possibility to capture en passant is the same. */ String[] components = this.toFEN().split(" "); StringBuilder hash = new StringBuilder(); for(int i = 0; i < 4; i++) { hash.append(components[i]); } return hash.toString(); } /** * Converts a Vector2 representing some location on the board * to the standard chess notation of a square. For example, * (4, 3) -> "e4". * @param position Position on the board * @return Chess notation representation of position */ @NotNull public String vector2ToSquare(@NotNull Vector2 position) { if(!this.boardExistsAt(position)) throw new IllegalArgumentException("Position " + position + " does not exist on this board."); return Character.toString(position.getX() + 'a') + (position.getY() + 1); } /** * Converts this board to Forsyth-Edwards Notation (FEN). * @return String representing this board in FEN */ public String toFEN() { StringBuilder out = new StringBuilder(); int noneCounter = 0; for(int i = this.board.length - 1; i >= 0; i--) { for(int j = 0; j < this.board[i].length; j++) { Piece p = this.getPieceAtPosition(new Vector2(j, i)); if(p == null) { noneCounter++; } else { if(noneCounter != 0) { out.append(noneCounter); noneCounter = 0; } if(p.getPlayer().equals(Player.WHITE)) { out.append(p.getFENSymbol()); } else { out.append(Character.toLowerCase(p.getFENSymbol())); } } } if(noneCounter != 0) { out.append(noneCounter); noneCounter = 0; } out.append('/'); } out.deleteCharAt(out.length() - 1); // get rid of the last '/' out.append(' '); if(this.whoseTurn.equals(Player.WHITE)) { out.append('w'); } else { out.append('b'); } out.append(' '); boolean neitherSideCanCastle = true; if(this.castleWhiteKing) { neitherSideCanCastle = false; out.append('K'); } if(this.castleWhiteQueen) { neitherSideCanCastle = false; out.append('Q'); } if (this.castleBlackKing) { neitherSideCanCastle = false; out.append('k'); } if (this.castleBlackQueen) { neitherSideCanCastle = false; out.append('q'); } if(neitherSideCanCastle) { out.append('-'); } out.append(' '); if(this.enPassantPosition != null) { out.append(this.vector2ToSquare(this.enPassantPosition)); } else { out.append('-'); } out.append(' '); out.append(this.halfMoveClock); out.append(' '); out.append(this.fullMoveNumber); return out.toString(); } /** * Returns the PGN of this game currently. * @return PGN String of this game */ public String getPGN() { return String.join(" ", this.notationMoves); } /** * Returns an array of all the pieces on this board, where the 3rd dimension * corresponds whether a specific kind of piece is present. * This is in order of Pawn, Knight, Bishop, Rook, Queen, King. * For example, a knight on (x, y) would have an entry [0.0, 1.0, 0.0, 0.0, 0.0, 0.0] * at [y][x] on the array. * @return 3D array of floats corresponding to the pieces on this board */ public float[][][] get3DBoard() { float[][][] out = new float[this.board.length][this.board[0].length][]; for(int y = 0; y < this.board.length; y++) { for(int x = 0; x < this.board[y].length; x++) { if(this.board[y][x] instanceof Pawn && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Knight && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Bishop && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Rook && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Queen && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof King && this.board[y][x].getPlayer().equals(Player.WHITE)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Pawn && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Knight && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Bishop && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Rook && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}; else if(this.board[y][x] instanceof Queen && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; else if(this.board[y][x] instanceof King && this.board[y][x].getPlayer().equals(Player.BLACK)) out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; else out[y][x] = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; } } return out; } /** * Returns the full set of pieces belonging to player, in no particular order. * @param player Player on this board * @return Pieces belonging to player */ @NotNull public Piece[] getPlayerPieces(@NotNull Player player) { List<Piece> pieces = new ArrayList<>(); for(int i = 0; i < this.board.length; i++) { for(int j = 0; j < this.board[i].length; j++) { Piece p = this.getPieceAtPosition(new Vector2(j, i)); if(p != null && p.getPlayer().equals(player)) pieces.add(p); } } return pieces.toArray(Piece[]::new); } /** * Returns whether there is a square at location on this board. * @param location A potential square this board exists at * @return Whether location is a square on this board */ public boolean boardExistsAt(@NotNull Vector2 location) { return location.getY() >= 0 && location.getX() >= 0 && location.getY() < this.board.length && location.getX() < this.board[location.getY()].length; } /** * Returns the piece at location or null if none there. * @param location A square on the board * @return The piece at location or null if none there */ @Nullable public Piece getPieceAtPosition(Vector2 location) { return this.board[location.getY()][location.getX()]; } /** * Sets the position of piece to location on this board and returns the piece displaced by this action. * @param piece A piece belonging to this board * @param location The square to move this piece to * @return The piece replaced from this position. Position is null, but still belongs to this board */ @Nullable private Piece setPosition(@NotNull Piece piece, @NotNull Vector2 location) { Vector2 start = this.getPosition(piece); Piece pieceAtLocation = this.getPieceAtPosition(location); assert piece != pieceAtLocation; this.board[location.getY()][location.getX()] = piece; this.board[start.getY()][start.getX()] = null; this.pieces.put(piece, location); this.pieces.remove(pieceAtLocation); return pieceAtLocation; } /** * Gets the location of piece on this board. * Throws an exception if the piece is not on this board. * @param piece A piece on this board * @return the position of piece */ @NotNull public Vector2 getPosition(@NotNull Piece piece) { Vector2 location = this.pieces.getOrDefault(piece, null); if(location == null) throw new IllegalArgumentException("Piece " + piece + " was not found on the board."); return location; } /** * Function that changes whose turn it is. * Also checks for game-ending conditions like checkmate or stalemate. */ private void nextTurn() { if(this.whoseTurn.equals(Player.WHITE)) { this.whoseTurn = Player.BLACK; } else { this.whoseTurn = Player.WHITE; this.fullMoveNumber++; } if(this.isCheckmate(this.whoseTurn)) { //System.out.println("Checkmate! " + (this.whoseTurn.equals(Player.WHITE) ? "Black" : "White") + " wins."); this.gameOver = true; this.gameOverReason = "Checkmate! " + (this.whoseTurn.equals(Player.WHITE) ? "Black" : "White") + " wins."; return; } if(this.halfMoveClock == 50) { //System.out.println("Draw by 50-move rule."); this.gameOver = true; this.gameOverReason = "Draw by 50-move rule."; return; } if(this.onNextTurn != null) this.onNextTurn.run(); } /** * Moves piece to end and increments the turn if necessary. * Also checks for threefold repetition draws. * @param piece Piece to move * @param end Position to move piece to */ public void movePiece(@NotNull Piece piece, @NotNull Vector2 end) { boolean recordThisMove = false; boolean pieceCaptured = false; Vector2 oldPosition = this.getPosition(piece); if(!piece.getPlayer().equals(this.whoseTurn)) throw new IllegalArgumentException("It's Player " + this.whoseTurn + "'s turn, but a piece that tried to move belongs to player " + piece.getPlayer() + "."); if(!this.disableMovementThisTurn) { recordThisMove = true; Piece removedPiece = this.setPosition(piece, end); if(removedPiece != null) { pieceCaptured = true; this.resetHalfMoveClock(); if(removedPiece instanceof Rook) { if(removedPiece.getPlayer().equals(Player.WHITE) ? end.getY() == 0 : end.getY() == 7) { if(end.getX() == 0 && removedPiece.getPlayer().equals(Player.WHITE)) this.disableCastleWhiteKing(); if(end.getX() == 7 && removedPiece.getPlayer().equals(Player.WHITE)) this.disableCastleWhiteQueen(); if(end.getX() == 0 && removedPiece.getPlayer().equals(Player.BLACK)) this.disableCastleBlackKing(); if(end.getX() == 7 && removedPiece.getPlayer().equals(Player.BLACK)) this.disableCastleBlackQueen(); } } } } else { this.disableMovementThisTurn = false; } if(!(piece instanceof Pawn)) this.halfMoveClock++; if(this.awaitPromotion == null) { this.nextTurn(); String boardHash = this.getBoardHash(); int reachedTimes = this.reachedPositions.getOrDefault(boardHash, 0) + 1; this.reachedPositions.put(boardHash, reachedTimes); if(reachedTimes == 3) { //System.out.println("Draw by threefold repetition."); this.gameOver = true; this.gameOverReason = "Draw by threefold repetition."; } if(recordThisMove) { StringBuilder notationMove = new StringBuilder(); if(this.whoseTurn.equals(Player.BLACK)) notationMove.append(this.fullMoveNumber).append("."); if (!(piece instanceof Pawn)) { notationMove.append(piece.getFENSymbol()); notationMove.append(this.vector2ToSquare(oldPosition)); } else { if(pieceCaptured) notationMove.append(this.vector2ToSquare(oldPosition).charAt(0)); } if (pieceCaptured) notationMove.append('x'); notationMove.append(this.vector2ToSquare(end)); if(this.isInCheck(this.whoseTurn)) { if(this.gameOverReason != null && this.gameOverReason.startsWith("Checkmate")) { notationMove.append('#'); } else { notationMove.append('+'); } } this.notationMoves.add(notationMove.toString()); if(this.gameOver) { if(this.gameOverReason.startsWith("Checkmate")) { if(this.whoseTurn.equals(Player.WHITE)) { this.notationMoves.add("1-0"); } else { this.notationMoves.add("0-1"); } } else { this.notationMoves.add("1/2-1/2"); } } } else if(piece instanceof King && oldPosition.equals(end)) { StringBuilder notationMove = new StringBuilder(); if(this.whoseTurn.equals(Player.BLACK)) notationMove.append(this.fullMoveNumber).append("."); if(end.getX() == 2) notationMove.append("O-O-O"); else if(end.getX() == 5) notationMove.append("O-O"); if(this.isInCheck(this.whoseTurn)) { if(this.gameOverReason != null && this.gameOverReason.startsWith("Checkmate")) { notationMove.append('#'); } else { notationMove.append('+'); } } this.notationMoves.add(notationMove.toString()); if(this.gameOver) { if(this.gameOverReason.startsWith("Checkmate")) { if(this.whoseTurn.equals(Player.WHITE)) { this.notationMoves.add("1-0"); } else { this.notationMoves.add("0-1"); } } else { this.notationMoves.add("1/2-1/2"); } } } } } /** * Removes the piece at position. * Position will be null, but board will still be this. * @param position Square to remove the piece from * @return The piece at position that was just removed */ @NotNull public Piece removePiece(@NotNull Vector2 position) { Piece target = this.getPieceAtPosition(position); if(target == null) throw new IllegalArgumentException("Tried to remove piece at " + position + ", but nothing was there."); this.pieces.remove(target); this.board[position.getY()][position.getX()] = null; return target; } public void placePiece(@NotNull Piece piece, Vector2 position) { if(this.getPieceAtPosition(position) != null) throw new IllegalArgumentException("Tried to insert " + piece + " at " + position + ", but " + this.getPieceAtPosition(position) + " was already there."); this.board[position.getY()][position.getX()] = piece; this.pieces.put(piece, position); } /** * Removes target from its square. * Position will be null, but board will still be this. * @param target Piece to remove from its position * @return The location this piece was previously at */ @NotNull public Vector2 removePiece(Piece target) { Vector2 position = this.getPosition(target); this.pieces.remove(target); this.board[position.getY()][position.getX()] = null; return position; } /** * Returns whether target is currently in check. * @param target Player to be checked for check * @return Whether target is in check */ public boolean isInCheck(Player target) { Player attacker; if(target.equals(Player.WHITE)) attacker = Player.BLACK; else attacker = Player.WHITE; for(Piece p : this.pieces.keySet().toArray(new Piece[0])) { if(p.getPlayer().equals(attacker)) { Vector2[] attackingSquares = p.getMovableSquares(false); for(Vector2 square : attackingSquares) { Piece attackedPiece = this.getPieceAtPosition(square); if(attackedPiece instanceof King && attackedPiece.getPlayer().equals(target)) { return true; } } } } return false; } /** * Returns whether moving movingPiece to end puts the respective player in check. * @param movingPiece Piece to move * @param end Square to move movingPiece to * @return Whether the player that owns movingPiece is in check after moving it to end */ public boolean doesThisMovePutMeInCheck(Piece movingPiece, Vector2 end) { Vector2 start = this.getPosition(movingPiece); assert this.getPieceAtPosition(end) == null || !this.getPieceAtPosition(end).getPlayer().equals(movingPiece.getPlayer()); Piece attackedPiece = this.setPosition(movingPiece, end); boolean inCheck = this.isInCheck(this.whoseTurn); Piece thereBetterBeNothingHere = this.setPosition(movingPiece, start); assert thereBetterBeNothingHere == null; if(attackedPiece != null) this.placePiece(attackedPiece, end); return inCheck; } /** * Runs func after moving movingPiece to end, then reverts to the previous position. * @param movingPiece Piece to move * @param end Square to move movingPiece to * @param func Runnable to run on the board after moving */ public void runOnMove(Piece movingPiece, Vector2 end, Runnable func) { Vector2 start = this.getPosition(movingPiece); assert this.getPieceAtPosition(end) == null || !this.getPieceAtPosition(end).getPlayer().equals(movingPiece.getPlayer()); Piece attackedPiece = this.setPosition(movingPiece, end); func.run(); Piece thereBetterBeNothingHere = this.setPosition(movingPiece, start); assert thereBetterBeNothingHere == null; if(attackedPiece != null) this.placePiece(attackedPiece, end); } /** * Returns whether player is checkmated. * @param player Player to check if checkmated * @return Whether player is checkmated */ public boolean isCheckmate(Player player) { for(Piece p : this.pieces.keySet().toArray(new Piece[0])) { if(p.getPlayer().equals(player)) { Vector2[] movableSquares = p.getMovableSquares(true); if(movableSquares.length > 0) return false; } } return true; } /** * Returns whose turn it is. * @return The player whose turn it is */ @NotNull public Player getWhoseTurn() { return this.whoseTurn; } /** * Returns whether the White player can castle king-side. * @return Whether the White player can castle king-side */ public boolean canCastleWhiteKing() { return this.castleWhiteKing; } /** * Returns whether the White player can castle queen-side. * @return Whether the White player can castle queen-side */ public boolean canCastleWhiteQueen() { return this.castleWhiteQueen; } /** * Returns whether the Black player can castle king-side. * @return Whether the Black player can castle king-side */ public boolean canCastleBlackKing() { return this.castleBlackKing; } /** * Returns whether the Black player can castle queen-side. * @return Whether the Black player can castle queen-side */ public boolean canCastleBlackQueen() { return this.castleBlackQueen; } /** * Prevents the White player from castling king-side if possible. */ public void disableCastleWhiteKing() { this.castleWhiteKing = false; } /** * Prevents the White player from castling queen-side if possible. */ public void disableCastleWhiteQueen() { this.castleWhiteQueen = false; } /** * Prevents the Black player from castling king-side if possible. */ public void disableCastleBlackKing() { this.castleBlackKing = false; } /** * Prevents the Black player from castling queen-side if possible. */ public void disableCastleBlackQueen() { this.castleBlackQueen = false; } /** * Allows the White player to castle king-side if possible. Exists to allow undoing castling. */ public void enableCastleWhiteKing() { this.castleWhiteKing = true; } /** * Allows the White player to castle queen-side if possible. Exists to allow undoing castling. */ public void enableCastleWhiteQueen() { this.castleWhiteQueen = true; } /** * Allows the Black player to castle king-side if possible. Exists to allow undoing castling. */ public void enableCastleBlackKing() { this.castleBlackKing = true; } /** * Allows the Black player to castle queen-side if possible. Exists to allow undoing castling. */ public void enableCastleBlackQueen() { this.castleBlackQueen = true; } /** * Castles the White Player king-side by moving the king and rook. * @param king The king to castle */ public void castleWhiteKing(King king) { this.castle(king, king.getPosition().add(new Vector2(2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(3, 0)))), king.getPosition().add(Vector2.EAST)); this.castleWhiteKing = false; } /** * Castles the White Player queen-side by moving the king and rook. * @param king The king to castle */ public void castleWhiteQueen(King king) { this.castle(king, king.getPosition().add(new Vector2(-2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(-4, 0)))), king.getPosition().add(Vector2.WEST)); this.castleWhiteQueen = false; } /** * Castles the Black Player king-side by moving the king and rook. * @param king The king to castle */ public void castleBlackKing(King king) { this.castle(king, king.getPosition().add(new Vector2(2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(3, 0)))), king.getPosition().add(Vector2.EAST)); this.castleBlackKing = false; } /** * Castles the Black Player queen-side by moving the king and rook. * @param king The king to castle */ public void castleBlackQueen(King king) { this.castle(king, king.getPosition().add(new Vector2(-2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(-4, 0)))), king.getPosition().add(Vector2.WEST)); this.castleBlackQueen = false; } /** * Un-castles the White Player king-side by moving the king and rook. Exists to allow undoing castling. * @param king The king to un-castle */ public void uncastleWhiteKing(King king) { this.castle(king, king.getPosition().add(new Vector2(-2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(-2, 0)))), king.getPosition().add(Vector2.EAST)); this.castleWhiteKing = true; } /** * Un-castles the White Player queen-side by moving the king and rook. Exists to allow undoing castling. * @param king The king to un-castle */ public void uncastleWhiteQueen(King king) { this.castle(king, king.getPosition().add(new Vector2(2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(Vector2.EAST))), king.getPosition().add(new Vector2(-2, 0))); this.castleWhiteQueen = true; } /** * Un-castles the Black Player king-side by moving the king and rook. Exists to allow undoing castling. * @param king The king to un-castle */ public void uncastleBlackKing(King king) { this.castle(king, king.getPosition().add(new Vector2(-2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(new Vector2(-2, 0)))), king.getPosition().add(Vector2.EAST)); this.castleBlackKing = true; } /** * Un-castles the Black Player queen-side by moving the king and rook. Exists to allow undoing castling. * @param king The king to un-castle */ public void uncastleBlackQueen(King king) { this.castle(king, king.getPosition().add(new Vector2(2, 0)), Objects.requireNonNull(this.getPieceAtPosition(king.getPosition().add(Vector2.EAST))), king.getPosition().add(new Vector2(-2, 0))); this.castleBlackQueen = true; } /** * Castles by moving king to kingToWhere and rook to rookToWhere. * This is also used for un-castling. * @param king King to move * @param kingToWhere Location to move the king * @param rook Rook to move * @param rookToWhere Location to move the rook */ private void castle(Piece king, Vector2 kingToWhere, Piece rook, Vector2 rookToWhere) { assert king instanceof King; assert rook instanceof Rook; this.removePiece(king); this.removePiece(rook); this.placePiece(king, kingToWhere); this.placePiece(rook, rookToWhere); this.disableMovementThisTurn = true; } /** * Marks the game as 'awaiting promotion' by disabling movement * until the player whose turn it is promotes. * * See also: promote * @param square Square of the promoting pawn */ public void awaitPromotion(Vector2 square) { this.awaitPromotion = square; } /** * Returns whether the game is currently awaiting * the user to decide what piece to promote to. * @return Whether the game is awaiting promotion */ public boolean awaitingPromotion() { return this.awaitPromotion != null; } /** * Promotes the pawn at promotion square to piece, * a String that corresponds to the name of a piece that * will be created to replace the pawn. * @param piece Name of piece to promote to */ public void promote(String piece) { if(this.awaitPromotion == null) throw new IllegalStateException("Tried to promote to a " + piece + ", but there's nothing to promote."); this.removePiece(this.getPieceAtPosition(this.awaitPromotion)); Piece p; switch(piece) { case "Knight" -> p = new Knight(this.whoseTurn, this); case "Bishop" -> p = new Bishop(this.whoseTurn, this); case "Rook" -> p = new Rook(this.whoseTurn, this); case "Queen" -> p = new Queen(this.whoseTurn, this); default -> throw new IllegalArgumentException("There's no piece called '" + piece + "'."); } this.notationMoves.add(this.vector2ToSquare(this.awaitPromotion) + "=" + piece.substring(0, 1)); this.placePiece(p, this.awaitPromotion); this.awaitPromotion = null; this.nextTurn(); } /** * Returns the square corresponding to FEN en passant. * Is null if no pawn was moved two squares the previous turn. * @return The position where an opponent pawn can attack as en passant */ @Nullable public Vector2 getEnPassantPosition() { return this.enPassantPosition; } /** * Sets the FEN position where en passant can take place. * If a pawn have moved two squares, it should be the square it skipped. * This should be null in any other case. * @param position FEN position where en passant can take place */ public void setEnPassantPosition(@Nullable Vector2 position) { this.enPassantPosition = position; } /** * Resets the half move clock counter. * Runs when a pawn is moved or a piece is captured. * When it reaches 50 half-moves, the game is drawn. */ public void resetHalfMoveClock() { this.halfMoveClock = 0; } /** * Returns whether the game has been stopped because * either checkmate or stalemate has been reached. * @return Whether the game is over */ public boolean isGameOver() { return this.gameOver; } /** * Gets the square clicked in a graphical interface * using this board. * @return Square the user clicked */ public Vector2 getClicked() { return this.clicked; } /** * Gets the reason the game is over. * Throws an exception if the game is not over. * @return The reason the game is over */ @NotNull public String getGameOverReason() { if(this.gameOverReason == null) throw new IllegalStateException("Cannot get the reason the game is over because the game is not over."); return this.gameOverReason; } /** * Sets the square clicked in a graphical interface. * This should when the user clicks a square * @param square Square the user clicked */ public void setClicked(Vector2 square) { this.clicked = square; } /** * Sets the callback function to be fired when a move is made. * @param onNextTurn Runnable that is run when a move is made */ public void bindNextTurnEvent(Runnable onNextTurn) { this.onNextTurn = onNextTurn; } /** * Submits a resignation by player. Game ends. * @param player Player who is resigning */ public void resign(@NotNull Player player) { this.gameOver = true; this.gameOverReason = (player.equals(Player.WHITE) ? "White" : "Black") + " resigns."; } }
924182fb79a18ebae95c36a1b37d438776834af3
1,658
java
Java
corpus/class/eclipse.pde.ui/1064.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
15
2018-07-10T09:38:31.000Z
2021-11-29T08:28:07.000Z
corpus/class/eclipse.pde.ui/1064.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
3
2018-11-16T02:58:59.000Z
2021-01-20T16:03:51.000Z
corpus/class/eclipse.pde.ui/1064.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
6
2018-06-27T20:19:00.000Z
2022-02-19T02:29:53.000Z
30.145455
87
0.630881
1,001,923
/******************************************************************************* * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.pde.internal.ui.editor.plugin; import org.eclipse.core.runtime.*; import org.eclipse.pde.internal.core.text.bundle.PackageObject; import org.eclipse.pde.internal.ui.IPDEUIConstants; import org.eclipse.pde.internal.ui.search.SearchResult; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; public class BlankQuery implements ISearchQuery { private PackageObject fObject; BlankQuery(PackageObject object) { fObject = object; } @Override public IStatus run(IProgressMonitor monitor) throws OperationCanceledException { monitor.done(); //$NON-NLS-1$ return new Status(IStatus.OK, IPDEUIConstants.PLUGIN_ID, IStatus.OK, "", null); } @Override public String getLabel() { return '\'' + fObject.getName() + '\''; } @Override public boolean canRerun() { return true; } @Override public boolean canRunInBackground() { return true; } @Override public ISearchResult getSearchResult() { return new SearchResult(this); } }
924183fce18b03addd38894eb917e195129ef1b6
9,032
java
Java
src/test/java/com/s2soft/tinygb/cpu/TestInstructionLength.java
SPixs/TinyGB
eeef3584ded3a31d458ab4c9a8356da5fb15ae62
[ "Apache-2.0" ]
null
null
null
src/test/java/com/s2soft/tinygb/cpu/TestInstructionLength.java
SPixs/TinyGB
eeef3584ded3a31d458ab4c9a8356da5fb15ae62
[ "Apache-2.0" ]
null
null
null
src/test/java/com/s2soft/tinygb/cpu/TestInstructionLength.java
SPixs/TinyGB
eeef3584ded3a31d458ab4c9a8356da5fb15ae62
[ "Apache-2.0" ]
null
null
null
37.016393
164
0.552259
1,001,924
package com.s2soft.tinygb.cpu; import com.s2soft.tinygb.GameBoy; import com.s2soft.tinygb.IConfiguration; import com.s2soft.tinygb.audio.IAudioDevice; import com.s2soft.tinygb.audio.NullAudioDevice; import com.s2soft.tinygb.control.IJoypad; import com.s2soft.tinygb.control.IJoypadButtonListener; import com.s2soft.tinygb.display.IDisplay; import com.s2soft.tinygb.display.NullDisplay; import junit.framework.TestCase; public class TestInstructionLength extends TestCase { // Instruction lengths of opcodes. // 0 for instructions not timed. private byte[][] length = new byte[][] { { 1,3,1,1,1,1,2,1,3,1,1,1,1,1,2,1 }, // 0 { 0,3,1,1,1,1,2,1,2,1,1,1,1,1,2,1 }, // 1 { 2,3,1,1,1,1,2,1,2,1,1,1,1,1,2,1 }, // 2 { 2,3,1,1,1,1,2,1,2,1,1,1,1,1,2,1 }, // 3 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 4 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 5 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 6 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 7 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 8 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // 9 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // A { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // B { 1,1,3,3,3,1,2,1,1,1,3,0,3,3,2,1 }, // C { 1,1,3,0,3,1,2,1,1,1,3,0,3,0,2,1 }, // D { 2,1,1,0,0,1,2,1,2,1,3,0,0,0,2,1 }, // E { 2,1,1,1,0,1,2,1,2,1,3,1,0,0,2,1 } // F }; private byte[][] cyclesNoBranchTaken = new byte[][] { { 1,3,2,2,1,1,2,1,5,2,2,2,1,1,2,1 }, // 0 { 0,3,2,2,1,1,2,1,3,2,2,2,1,1,2,1 }, // 1 { 2,3,2,2,1,1,2,1,2,2,2,2,1,1,2,1 }, // 2 { 2,3,2,2,3,3,3,1,2,2,2,2,1,1,2,1 }, // 3 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 4 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 5 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 6 { 2,2,2,2,2,2,0,2,1,1,1,1,1,1,2,1 }, // 7 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 8 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 9 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // A { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // B { 2,3,3,4,3,4,2,4,2,4,3,0,3,6,2,4 }, // C { 2,3,3,0,3,4,2,4,2,4,3,0,3,0,2,4 }, // D { 3,3,2,0,0,4,2,4,4,1,4,0,0,0,2,4 }, // E { 3,3,2,1,0,4,2,4,3,2,4,1,0,0,2,4 } // F }; private byte[][] cyclesBranchTaken = new byte[][] { { 1,3,2,2,1,1,2,1,5,2,2,2,1,1,2,1 }, // 0 { 0,3,2,2,1,1,2,1,3,2,2,2,1,1,2,1 }, // 1 { 3,3,2,2,1,1,2,1,3,2,2,2,1,1,2,1 }, // 2 { 3,3,2,2,3,3,3,1,3,2,2,2,1,1,2,1 }, // 3 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 4 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 5 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 6 { 2,2,2,2,2,2,0,2,1,1,1,1,1,1,2,1 }, // 7 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 8 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // 9 { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // A { 1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1 }, // B { 5,3,4,4,6,4,2,4,5,4,4,0,6,6,2,4 }, // C { 5,3,4,0,6,4,2,4,5,4,4,0,6,0,2,4 }, // D { 3,3,2,0,0,4,2,4,4,1,4,0,0,0,2,4 }, // E { 3,3,2,1,0,4,2,4,3,2,4,1,0,0,2,4 } // F }; private byte[][] cyclesExtraOpcode = new byte[][] { { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 0 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 1 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 2 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 3 { 2,2,2,2,2,2,3,2,2,2,2,2,2,2,3,2 }, // 4 { 2,2,2,2,2,2,3,2,2,2,2,2,2,2,3,2 }, // 5 { 2,2,2,2,2,2,3,2,2,2,2,2,2,2,3,2 }, // 6 { 2,2,2,2,2,2,3,2,2,2,2,2,2,2,3,2 }, // 7 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 8 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // 9 { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // A { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // B { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // C { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // D { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // E { 2,2,2,2,2,2,4,2,2,2,2,2,2,2,4,2 }, // F }; public void testLength() { GameBoy gameboy = new GameBoy(getNullConfiguration(), getNullDisplay(), getNullAudioDevice(), getNullJoypad()); GBCpu cpu = new GBCpu(gameboy); for (int i=0;i<0x100;i++) { byte opcode = (byte)(i & 0xFF); Instruction intruction = cpu.getIntruction(opcode); byte expectedLength = length[(opcode & 0xF0) >> 4][(opcode & 0x0F)]; assertTrue("Instruction not implemented for opcode " + Instruction.toHexByte(opcode), expectedLength == 0 || intruction != null); assertTrue("Invalid opcode " + Instruction.toHexByte(opcode) + " must have a length of 0", (expectedLength == 0 && intruction == null) || (expectedLength > 0)); if (intruction != null) { assertEquals("Invalid length for opcode " + Instruction.toHexByte(opcode) + ", instruction " + intruction.getClass().getName(), expectedLength, intruction.getLengthInBytes(opcode)); } } } public void testCyclesNoBranchTaken() { testCycles(false); } public void testCyclesBranchTaken() { testCycles(true); } public void testCycles(boolean takeBranch) { GameBoy gameboy = new GameBoy(getNullConfiguration(), getNullDisplay(), getNullAudioDevice(), getNullJoypad()); GBCpu cpu = new GBCpu(gameboy); for (int i=0;i<0x100;i++) { byte opcode = (byte)(i & 0xFF); byte[][] cyclesArray = takeBranch ? cyclesBranchTaken : cyclesNoBranchTaken; int expectedCycles = 4 * cyclesArray[(opcode & 0xF0) >> 4][(opcode & 0x0F)]; Instruction intruction = cpu.getIntruction(opcode); if (intruction != null && expectedCycles != 0) { cpu.reset(); cpu.setSp(0xFFFE); // status flag = 00 if lower nible of opcode >= 8 (reverse if take branch) // status flag = F0 if upper nible of opcode < 8 (reverse if take branch) cpu.setF((byte) ((((opcode & 0x08) != 0) ^ takeBranch) ? 0x00 : 0xF0)); cpu.getMemory().setByte(0xC000, opcode); cpu.setPC(0xC000); assertEquals("CPU start cycle must be 0", 0, cpu.getCyclesCount()); cpu.step(); assertEquals("Incorrect cycles count for opcode " + Instruction.toHexByte(opcode) + ", instruction " + intruction.getClass().getName(), expectedCycles, cpu.getCyclesCount()); } } } public void testLengthCB() { GameBoy gameboy = new GameBoy(getNullConfiguration(), getNullDisplay(), getNullAudioDevice(), getNullJoypad()); GBCpu cpu = new GBCpu(gameboy); for (int i=0;i<0x100;i++) { byte opcode = (byte)(i & 0xFF); Instruction intruction = cpu.getExtraIntruction(opcode); byte expectedLength = 1; assertTrue("Extra instruction (prefix CB) not implemented for opcode " + Instruction.toHexByte(opcode), expectedLength == 0 || intruction != null); if (intruction != null) { assertEquals("Invalid length for extra intruction opcode " + Instruction.toHexByte(opcode) + ", instruction " + intruction.getClass().getName(), expectedLength, intruction.getLengthInBytes(opcode)); } } } public void testCyclesCB() { GameBoy gameboy = new GameBoy(getNullConfiguration(), getNullDisplay(), getNullAudioDevice(), getNullJoypad()); GBCpu cpu = new GBCpu(gameboy); for (int i=0;i<0x100;i++) { byte opcode = (byte)(i & 0xFF); int expectedCycles = 4 * cyclesExtraOpcode[(opcode & 0xF0) >> 4][(opcode & 0x0F)]; Instruction intruction = cpu.getExtraIntruction(opcode); if (intruction != null && expectedCycles != 0) { // Test with flags clear cpu.reset(); cpu.setSp(0xFFFE); cpu.setF((byte) 0x00); cpu.getMemory().setByte(0xC000, (byte)0xCB); cpu.getMemory().setByte(0xC001, opcode); cpu.setPC(0xC000); assertEquals("CPU start cycle must be 0", 0, cpu.getCyclesCount()); cpu.step(); assertEquals("Incorrect cycles count for extra opcode " + Instruction.toHexByte(opcode) + " with flags clears, instruction " + intruction.getClass().getName(), expectedCycles, cpu.getCyclesCount()); // Test with flags set cpu.reset(); cpu.setSp(0xFFFE); cpu.setF((byte) 0xF0); cpu.getMemory().setByte(0xC000, (byte)0xCB); cpu.getMemory().setByte(0xC001, opcode); cpu.setPC(0xC000); assertEquals("CPU start cycle must be 0", 0, cpu.getCyclesCount()); cpu.step(); assertEquals("Incorrect cycles count for extra opcode " + Instruction.toHexByte(opcode) + " with flags clears, instruction " + intruction.getClass().getName(), expectedCycles, cpu.getCyclesCount()); } } } private IJoypad getNullJoypad() { return new IJoypad() { @Override public void addButtonListener(IJoypadButtonListener listener) { } }; } private IAudioDevice getNullAudioDevice() { return new NullAudioDevice(); } private IDisplay getNullDisplay() { return new NullDisplay(); } private IConfiguration getNullConfiguration() { return new IConfiguration() { @Override public boolean useBootRom() { return false; } }; } }
9241847156b6565dc2f00e9b30c977ceb99a08fa
2,328
java
Java
trains/src/main/java/com/tw/work/model/Route.java
0532/home-work
fc9235e13e1720f0eb2fcda91f1ad4e3cd817d93
[ "MIT" ]
null
null
null
trains/src/main/java/com/tw/work/model/Route.java
0532/home-work
fc9235e13e1720f0eb2fcda91f1ad4e3cd817d93
[ "MIT" ]
null
null
null
trains/src/main/java/com/tw/work/model/Route.java
0532/home-work
fc9235e13e1720f0eb2fcda91f1ad4e3cd817d93
[ "MIT" ]
null
null
null
18.926829
82
0.57732
1,001,925
package com.tw.work.model; import java.math.BigDecimal; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class Route { private static final AtomicInteger counter = new AtomicInteger(0); private static final int MAX_CYCLE_REF = 3; private int id = 0; public Route(){ id = counter.getAndIncrement(); } public int getId() { return id; } /** * 开始城镇 */ private Town startNode; /** * 结束城镇 */ private Edge finalNode; /** * 途经站点 */ private List<Edge> routeNode = new LinkedList<Edge>(); private Map<Edge,Integer> routeSet = new HashMap<Edge, Integer>(); /** * 路径是否有效 */ private boolean valid = true; public Map<Edge,Integer> getRouteSet() { return routeSet; } public void setRouteSet(Map<Edge,Integer> routeSet) { this.routeSet = routeSet; } /** * 增加途经的站点 * @param edge */ public void addRouteNode(Edge edge){ routeNode.add(edge); if (routeSet.containsKey(edge)){ routeSet.put(edge,routeSet.get(edge).intValue()+1); }else { routeSet.put(edge,1); } } public boolean constainsEdge(Edge edge){ return !routeSet.containsKey(edge)?false:routeSet.get(edge)>MAX_CYCLE_REF; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } public List<Edge> getRouteNode() { return routeNode; } /** * 计算总的距离 * @return 距离数 */ public BigDecimal sumDistance(){ BigDecimal sum = new BigDecimal("0"); for (Edge edge :routeNode){ sum = sum.add(edge.getDistance()); } return sum; } /** * 计算途经站点数 * @return */ public int sumStopping(){ return routeNode.size(); } public Town getStartNode() { return startNode; } public void setStartNode(Town startNode) { this.startNode = startNode; } public Edge getFinalNode() { return finalNode; } public void setFinalNode(Edge finalNode) { this.finalNode = finalNode; } }
924184f6dcd84848fadb8abacb78805cf372c5ed
431
java
Java
grainmall-ware/src/main/java/com/w1nd/grainmall/ware/feign/OrderFeignService.java
2w1nd/grainmall
a1146737f7e22fa46954f98c324b7cc6b31a465f
[ "Apache-2.0" ]
7
2022-03-06T03:30:00.000Z
2022-03-14T14:29:30.000Z
grainmall-ware/src/main/java/com/w1nd/grainmall/ware/feign/OrderFeignService.java
2w1nd/grainmall
a1146737f7e22fa46954f98c324b7cc6b31a465f
[ "Apache-2.0" ]
null
null
null
grainmall-ware/src/main/java/com/w1nd/grainmall/ware/feign/OrderFeignService.java
2w1nd/grainmall
a1146737f7e22fa46954f98c324b7cc6b31a465f
[ "Apache-2.0" ]
null
null
null
35.916667
62
0.805104
1,001,926
package com.w1nd.grainmall.ware.feign; import com.w1nd.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("grainmall-order") public interface OrderFeignService { @GetMapping("/order/order/status/{orderSn}") R getOrderStatus(@PathVariable("orderSn") String orderSn); }
9241854b00098163ded2502c9ddea5f7c3a28c36
9,317
java
Java
app/src/main/java/com/battlelancer/seriesguide/ui/stats/StatsLiveData.java
FabrizioKruisland/SeriesGuideHVA
ba7b52731193717a6d861819e8c77a5c78fda0f6
[ "Unlicense" ]
1
2020-10-30T13:44:59.000Z
2020-10-30T13:44:59.000Z
app/src/main/java/com/battlelancer/seriesguide/ui/stats/StatsLiveData.java
FabrizioKruisland/SeriesGuideHVA
ba7b52731193717a6d861819e8c77a5c78fda0f6
[ "Unlicense" ]
null
null
null
app/src/main/java/com/battlelancer/seriesguide/ui/stats/StatsLiveData.java
FabrizioKruisland/SeriesGuideHVA
ba7b52731193717a6d861819e8c77a5c78fda0f6
[ "Unlicense" ]
null
null
null
37.720648
100
0.582162
1,001,927
package com.battlelancer.seriesguide.ui.stats; import android.annotation.SuppressLint; import android.arch.lifecycle.LiveData; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.format.DateUtils; import android.util.SparseIntArray; import com.battlelancer.seriesguide.provider.SeriesGuideContract; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows; import com.battlelancer.seriesguide.settings.DisplaySettings; import com.battlelancer.seriesguide.util.DBUtils; import com.battlelancer.seriesguide.ui.shows.ShowTools; public class StatsLiveData extends LiveData<StatsLiveData.StatsUpdateEvent> { private final Context context; private AsyncTask<Void, StatsUpdateEvent, StatsUpdateEvent> task; StatsLiveData(Context context) { this.context = context; } void loadStats() { if (task == null || task.getStatus() == AsyncTask.Status.FINISHED) { task = new StatsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @SuppressLint("StaticFieldLeak") public class StatsTask extends AsyncTask<Void, StatsUpdateEvent, StatsUpdateEvent> { private static final long PREVIEW_UPDATE_INTERVAL_MS = DateUtils.SECOND_IN_MILLIS; @Nullable @Override protected StatsUpdateEvent doInBackground(Void... params) { Stats stats = new Stats(); ContentResolver resolver = context.getContentResolver(); // movies if (!processMovies(resolver, stats)) { return buildFailure(stats); // failed to process movies } if (isCancelled()) { return buildFailure(stats); } // shows SparseIntArray showRuntimes = processShows(resolver, stats); if (showRuntimes == null) { return buildFailure(stats); // failed to process shows } if (isCancelled()) { return buildFailure(stats); } // episodes boolean includeSpecials = !DisplaySettings.isHidingSpecials(context); if (!processEpisodes(resolver, stats, includeSpecials)) { return buildFailure(stats); // failed to process episodes } if (isCancelled()) { return buildFailure(stats); } // report intermediate results before longest op publishProgress(buildUpdate(stats)); // calculate runtime of watched episodes per show long totalRuntimeMin = 0; long previewTime = System.currentTimeMillis() + PREVIEW_UPDATE_INTERVAL_MS; for (int i = 0, size = showRuntimes.size(); i < size; i++) { int showTvdbId = showRuntimes.keyAt(i); long runtimeOfShowMin = showRuntimes.valueAt(i); int watchedEpisodesOfShowCount = DBUtils.getCountOf(resolver, Episodes.buildEpisodesOfShowUri(showTvdbId), Episodes.SELECTION_WATCHED + (includeSpecials ? "" : " AND " + Episodes.SELECTION_NO_SPECIALS), null, -1); if (watchedEpisodesOfShowCount == -1) { // episode query failed, return what we have so far stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS; return buildFailure(stats); } // make sure we calculate with long here (first arg is long) to avoid overflows long runtimeOfEpisodesMin = runtimeOfShowMin * watchedEpisodesOfShowCount; totalRuntimeMin += runtimeOfEpisodesMin; // post regular update of minimum long currentTime = System.currentTimeMillis(); if (currentTime > previewTime) { previewTime = currentTime + PREVIEW_UPDATE_INTERVAL_MS; stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS; publishProgress(buildUpdate(stats)); } } stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS; // return final values return new StatsUpdateEvent(stats, true, true); } private StatsUpdateEvent buildFailure(Stats stats) { return new StatsUpdateEvent(stats, false, false); } private StatsUpdateEvent buildUpdate(Stats stats) { return new StatsUpdateEvent(stats, false, true); } @Override protected void onProgressUpdate(StatsUpdateEvent... values) { setValue(values[0]); } @Override protected void onPostExecute(StatsUpdateEvent event) { setValue(event); } private boolean processMovies(ContentResolver resolver, Stats stats) { // movies (count, in watchlist, runtime of watchlist) final Cursor movies = resolver.query(SeriesGuideContract.Movies.CONTENT_URI, new String[]{SeriesGuideContract.Movies._ID, SeriesGuideContract.Movies.IN_WATCHLIST, SeriesGuideContract.Movies.RUNTIME_MIN}, null, null, null ); if (movies == null) { return false; } stats.movies = movies.getCount(); int inWatchlist = 0; long watchlistRuntime = 0; while (movies.moveToNext()) { if (movies.getInt(1) == 1) { inWatchlist++; watchlistRuntime += movies.getInt(2) * DateUtils.MINUTE_IN_MILLIS; } } movies.close(); stats.moviesWatchlist = inWatchlist; stats.moviesWatchlistRuntime = watchlistRuntime; return true; } @Nullable public SparseIntArray processShows(ContentResolver resolver, Stats stats) { Cursor shows = resolver.query(Shows.CONTENT_URI, new String[]{ Shows._ID, // 0 Shows.STATUS, Shows.NEXTEPISODE, Shows.RUNTIME // 3 }, null, null, null ); if (shows == null) { return null; } int continuing = 0; int withnext = 0; // count all shows int showsCount = shows.getCount(); SparseIntArray showRuntimes = new SparseIntArray(showsCount); while (shows.moveToNext()) { // count continuing shows if (shows.getInt(1) == ShowTools.Status.CONTINUING) { continuing++; } // count shows with next episodes if (shows.getInt(2) != ShowTools.Status.ENDED) { withnext++; } // map show to its runtime showRuntimes.put(shows.getInt(0), shows.getInt(3)); } shows.close(); stats.shows = showsCount; stats.showsContinuing = continuing; stats.showsWithNextEpisodes = withnext; return showRuntimes; } private boolean processEpisodes(ContentResolver resolver, Stats stats, boolean includeSpecials) { // all episodes int allEpisodesCount = DBUtils.getCountOf(resolver, Episodes.CONTENT_URI, includeSpecials ? null : Episodes.SELECTION_NO_SPECIALS, null, -1); if (allEpisodesCount == -1) { return false; } stats.episodes = allEpisodesCount; // watched episodes int watchedEpisodesCount = DBUtils.getCountOf(resolver, Episodes.CONTENT_URI, Episodes.SELECTION_WATCHED + (includeSpecials ? "" : " AND " + Episodes.SELECTION_NO_SPECIALS), null, -1); if (watchedEpisodesCount == -1) { return false; } stats.episodesWatched = watchedEpisodesCount; return true; } } static class StatsUpdateEvent { @NonNull final Stats stats; final boolean finalValues; final boolean successful; StatsUpdateEvent(@NonNull Stats stats, boolean finalValues, boolean successful) { this.stats = stats; this.finalValues = finalValues; this.successful = successful; } } // class is package-private so direct member access is fine public static class Stats { int shows; int showsContinuing; int showsWithNextEpisodes; int episodes; public int episodesWatched; long episodesWatchedRuntime; int movies; int moviesWatchlist; long moviesWatchlistRuntime; } }
924186cbc9eb01a8b95093af10e9f318c857c73d
1,497
java
Java
com.ibm.xsp.webdav/src/biz/taoconsulting/dominodav/resource/DAVResourceADS.java
OpenNTF/WebDAVForDomino
99dff7586c52c122815f02551f9b268c77ab0368
[ "Apache-2.0" ]
1
2016-08-14T13:18:37.000Z
2016-08-14T13:18:37.000Z
com.ibm.xsp.webdav/src/biz/taoconsulting/dominodav/resource/DAVResourceADS.java
OpenNTF/WebDAVForDomino
99dff7586c52c122815f02551f9b268c77ab0368
[ "Apache-2.0" ]
null
null
null
com.ibm.xsp.webdav/src/biz/taoconsulting/dominodav/resource/DAVResourceADS.java
OpenNTF/WebDAVForDomino
99dff7586c52c122815f02551f9b268c77ab0368
[ "Apache-2.0" ]
null
null
null
19.192308
78
0.656647
1,001,928
/** * */ package biz.taoconsulting.dominodav.resource; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; /** * @author eugen.cretu * */ public class DAVResourceADS extends DAVAbstractResource { // implement Abstract Data Stream for a file resource // used in a NTFS -compatible file system /* * (non-Javadoc) * * @see * biz.taoconsulting.dominodav.interfaces.IDAVResource#patchLastModified * (java.util.Date) */ public void patchLastModified(Date dt) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * biz.taoconsulting.dominodav.interfaces.IDAVResource#patchCreationDate * (java.util.Date) */ public void patchCreationDate(Date dt) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see biz.taoconsulting.dominodav.resource.DAVAbstractResource#delete() */ @Override public boolean delete() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see * biz.taoconsulting.dominodav.resource.DAVAbstractResource#getOutputStream * () */ @Override public OutputStream getOutputStream() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see biz.taoconsulting.dominodav.resource.DAVAbstractResource#getStream() */ @Override public InputStream getStream() { // TODO Auto-generated method stub return null; } }
924186e1454bdc9c432ed52f6ae72b7f128c3adb
234
java
Java
drivers/mongock-driver-mongodb/mongodb-springdata-v3-driver/src/test/java/io/mongock/driver/mongodb/springdata/v3/repository/SpringData3LockRepositoryITest.java
philippeu/mongock
429d38709959813ad18fed8bfe2d375b0a8f3bee
[ "Apache-2.0" ]
279
2018-04-22T21:33:19.000Z
2021-09-14T13:55:54.000Z
drivers/mongock-driver-mongodb/mongodb-springdata-v3-driver/src/test/java/io/mongock/driver/mongodb/springdata/v3/repository/SpringData3LockRepositoryITest.java
philippeu/mongock
429d38709959813ad18fed8bfe2d375b0a8f3bee
[ "Apache-2.0" ]
183
2018-04-23T20:54:35.000Z
2021-09-21T21:05:41.000Z
drivers/mongock-driver-mongodb/mongodb-springdata-v3-driver/src/test/java/io/mongock/driver/mongodb/springdata/v3/repository/SpringData3LockRepositoryITest.java
philippeu/mongock
429d38709959813ad18fed8bfe2d375b0a8f3bee
[ "Apache-2.0" ]
52
2018-04-24T13:08:10.000Z
2021-08-28T10:58:34.000Z
23.4
83
0.858974
1,001,929
package io.mongock.driver.mongodb.springdata.v3.repository; import io.mongock.driver.mongodb.sync.v4.repository.MongoSync4LockRepositoryITest; public class SpringData3LockRepositoryITest extends MongoSync4LockRepositoryITest { }
92418958360c8fa4f31b977fa6d58997462922fd
7,892
java
Java
src/main/java/com/amazon/opendistroforelasticsearch/security/configuration/MaskedField.java
vengadanathan-s/opendistro-security
b46aa794d4d6bcff1b9f65ba7080547c00c4d9ac
[ "Apache-2.0" ]
479
2019-03-11T16:20:19.000Z
2022-01-30T22:21:25.000Z
src/main/java/com/amazon/opendistroforelasticsearch/security/configuration/MaskedField.java
vengadanathan-s/opendistro-security
b46aa794d4d6bcff1b9f65ba7080547c00c4d9ac
[ "Apache-2.0" ]
952
2019-03-11T18:45:03.000Z
2021-04-29T05:12:15.000Z
src/main/java/com/amazon/opendistroforelasticsearch/security/configuration/MaskedField.java
vengadanathan-s/opendistro-security
b46aa794d4d6bcff1b9f65ba7080547c00c4d9ac
[ "Apache-2.0" ]
225
2019-03-11T19:29:41.000Z
2022-03-16T18:44:16.000Z
31.822581
120
0.572605
1,001,930
/* * Copyright 2019 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://www.apache.org/licenses/LICENSE-2.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.amazon.opendistroforelasticsearch.security.configuration; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.apache.lucene.util.BytesRef; import org.bouncycastle.crypto.digests.Blake2bDigest; import org.bouncycastle.util.encoders.Hex; import com.google.common.base.Splitter; public class MaskedField { private final String name; private String algo = null; private List<RegexReplacement> regexReplacements; private final byte[] defaultSalt; public MaskedField(final String value, final Salt salt) { this.defaultSalt = salt.getSalt16(); final List<String> tokens = Splitter.on("::").splitToList(Objects.requireNonNull(value)); final int tokenCount = tokens.size(); if (tokenCount == 1) { name = tokens.get(0); } else if (tokenCount == 2) { name = tokens.get(0); algo = tokens.get(1); } else if (tokenCount >= 3 && tokenCount%2==1) { name = tokens.get(0); regexReplacements = new ArrayList<>((tokenCount-1)/2); for(int i=1; i<tokenCount-1; i=i+2) { regexReplacements.add(new RegexReplacement(tokens.get(i), tokens.get(i+1))); } } else { throw new IllegalArgumentException("Expected 1 or 2 or >=3 (but then odd count) tokens, got " + tokenCount); } } public final void isValid() throws Exception { mask(new byte[] {1,2,3,4,5}); } public byte[] mask(byte[] value) { if (isDefault()) { return blake2bHash(value); } else { return customHash(value); } } public String mask(String value) { if (isDefault()) { return blake2bHash(value); } else { return customHash(value); } } public BytesRef mask(BytesRef value) { if(value == null) { return null; } if (isDefault()) { return blake2bHash(value); } else { return customHash(value); } } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((algo == null) ? 0 : algo.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((regexReplacements == null) ? 0 : regexReplacements.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MaskedField other = (MaskedField) obj; if (algo == null) { if (other.algo != null) return false; } else if (!algo.equals(other.algo)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (regexReplacements == null) { if (other.regexReplacements != null) return false; } else if (!regexReplacements.equals(other.regexReplacements)) return false; return true; } @Override public String toString() { return "MaskedField [name=" + name + ", algo=" + algo + ", regexReplacements=" + regexReplacements + ", defaultSalt=" + Arrays.toString(defaultSalt) + ", isDefault()=" + isDefault() + "]"; } private boolean isDefault() { return regexReplacements == null && algo == null; } private byte[] customHash(byte[] in) { if (algo != null) { try { MessageDigest digest = MessageDigest.getInstance(algo); return Hex.encode(digest.digest(in)); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } } else if (regexReplacements != null) { String cur = new String(in, StandardCharsets.UTF_8); for(RegexReplacement rr: regexReplacements) { cur = cur.replaceAll(rr.getRegex(), rr.getReplacement()); } return cur.getBytes(StandardCharsets.UTF_8); } else { throw new IllegalArgumentException(); } } private BytesRef customHash(BytesRef in) { final BytesRef copy = BytesRef.deepCopyOf(in); return new BytesRef(customHash(copy.bytes)); } private String customHash(String in) { return new String(customHash(in.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); } private byte[] blake2bHash(byte[] in) { final Blake2bDigest hash = new Blake2bDigest(null, 32, null, defaultSalt); hash.update(in, 0, in.length); final byte[] out = new byte[hash.getDigestSize()]; hash.doFinal(out, 0); return Hex.encode(out); } private BytesRef blake2bHash(BytesRef in) { final BytesRef copy = BytesRef.deepCopyOf(in); return new BytesRef(blake2bHash(copy.bytes)); } private String blake2bHash(String in) { return new String(blake2bHash(in.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); } private static class RegexReplacement { private final String regex; private final String replacement; public RegexReplacement(String regex, String replacement) { super(); this.regex = regex.substring(1).substring(0, regex.length()-2); this.replacement = replacement; } public String getRegex() { return regex; } public String getReplacement() { return replacement; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((regex == null) ? 0 : regex.hashCode()); result = prime * result + ((replacement == null) ? 0 : replacement.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RegexReplacement other = (RegexReplacement) obj; if (regex == null) { if (other.regex != null) return false; } else if (!regex.equals(other.regex)) return false; if (replacement == null) { if (other.replacement != null) return false; } else if (!replacement.equals(other.replacement)) return false; return true; } @Override public String toString() { return "RegexReplacement [regex=" + regex + ", replacement=" + replacement + "]"; } } }
924189a1ef81e0c74d6d7d2ee38b7c44027168a9
5,959
java
Java
app/src/main/java/permission/auron/com/samplepermissionhelper/fragment/FragmentSinglePermission.java
RurioLuca/MarshmallowPermissionManager
320d8032cd46dc59c647209ed3f182d8d70701b9
[ "MIT" ]
62
2016-03-03T11:15:34.000Z
2016-09-02T20:26:46.000Z
app/src/main/java/permission/auron/com/samplepermissionhelper/fragment/FragmentSinglePermission.java
RurioLuca/PermissionManager
320d8032cd46dc59c647209ed3f182d8d70701b9
[ "MIT" ]
5
2017-05-11T13:51:39.000Z
2020-09-28T02:21:46.000Z
app/src/main/java/permission/auron/com/samplepermissionhelper/fragment/FragmentSinglePermission.java
RurioLuca/MarshmallowPermissionManager
320d8032cd46dc59c647209ed3f182d8d70701b9
[ "MIT" ]
16
2016-03-04T01:10:39.000Z
2016-08-30T12:21:04.000Z
35.89759
149
0.652962
1,001,931
/* * The MIT License (MIT) * * Copyright (c) 2016 Rurio Luca * * 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 permission.auron.com.samplepermissionhelper.fragment; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.appcompat.app.AlertDialog; import com.google.android.material.floatingactionbutton.FloatingActionButton; import permission.auron.com.permissionhelper.FragmentManagePermission; import permission.auron.com.permissionhelper.PermissionResult; import permission.auron.com.permissionhelper.utils.PermissionUtils; import permission.auron.com.samplemarshmallowpermissionhelper.R; import static android.app.Activity.RESULT_OK; public class FragmentSinglePermission extends FragmentManagePermission { private static final int REQUEST_IMAGE_CAPTURE = 2; public static String TAG = FragmentSinglePermission.class.getSimpleName(); private ImageView imageView; private FloatingActionButton floatingActionButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_single_permission, container, false); imageView = view.findViewById(R.id.image); floatingActionButton = view.findViewById(R.id.fab); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //single permission askCompactPermission(PermissionUtils.Manifest_CAMERA, new PermissionResult() { @Override public void permissionGranted() { //permission granted //replace with your action Log.d(TAG, "permissionGranted"); dispatchTakePictureIntent(); } @Override public void permissionDenied() { //permission denied //replace with your action Log.d(TAG, "permissionDenied"); } @Override public void permissionForeverDenied() { //permission denied //replace with your action Log.d(TAG, "permissionForeverDenied"); showDialog(); } }); } }); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); } } private void sampleAskMultiplePermission() { askCompactPermissions(new String[]{PermissionUtils.Manifest_READ_CONTACTS, PermissionUtils.Manifest_WRITE_CONTACTS}, new PermissionResult() { @Override public void permissionGranted() { //permission granted //replace with your action } @Override public void permissionDenied() { Log.d(FragmentSinglePermission.class.getSimpleName(), "denied"); //permission denied //replace with your action } @Override public void permissionForeverDenied() { } }); } private void showDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle); builder.setTitle(R.string.attention); builder.setMessage(R.string.messageperm); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { openSettingsApp(getActivity()); } }); builder.setNegativeButton("Cancel", null); builder.show(); } }
92418c05f770742904c3ad22d76fa41c274d5a72
5,158
java
Java
MaceSwinger/src/com/maceswinger/utils/Easing.java
Puddleduck/Mace-Swinger
e19189f96805b965dd882823f2f80361c52aa715
[ "MIT", "Unlicense" ]
null
null
null
MaceSwinger/src/com/maceswinger/utils/Easing.java
Puddleduck/Mace-Swinger
e19189f96805b965dd882823f2f80361c52aa715
[ "MIT", "Unlicense" ]
null
null
null
MaceSwinger/src/com/maceswinger/utils/Easing.java
Puddleduck/Mace-Swinger
e19189f96805b965dd882823f2f80361c52aa715
[ "MIT", "Unlicense" ]
null
null
null
28.497238
78
0.46045
1,001,932
package com.maceswinger.utils; public class Easing { public static float bounceIn(float t, float b, float c, float d) { return c - bounceOut(d - t, 0, c, d) + b; } public static float bounceOut(float t, float b, float c, float d) { if ((t /= d) < (1 / 2.75f)) { return c * (7.5625f * t * t) + b; } else if (t < (2 / 2.75f)) { return c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b; } else { return c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b; } } public static float bounceInOut(float t, float b, float c, float d) { if (t < d / 2) return bounceIn(t * 2, 0, c, d) * .5f + b; else return bounceOut(t * 2 - d, 0, c, d) * .5f + c * .5f + b; } public static float elasticIn(float t, float b, float c, float d) { if (t == 0) return b; if ((t /= d) == 1) return b + c; float p = d * .3f; float a = c; float s = p / 4; return -(a * (float) Math.pow(2, 10 * (t -= 1)) * (float) Math.sin((t * d - s) * (2 * (float) Math.PI) / p)) + b; } public static float elasticIn(float t, float b, float c, float d, float a, float p) { float s; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * (float) Math.PI) * (float) Math.asin(c / a); } return -(a * (float) Math.pow(2, 10 * (t -= 1)) * (float) Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; } public static float elasticOut(float t, float b, float c, float d) { if (t == 0) return b; if ((t /= d) == 1) return b + c; float p = d * .3f; float a = c; float s = p / 4; return (a * (float) Math.pow(2, -10 * t) * (float) Math.sin((t * d - s) * (2 * (float) Math.PI) / p) + c + b); } public static float elasticOut(float t, float b, float c, float d, float a, float p) { float s; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * (float) Math.PI) * (float) Math.asin(c / a); } return (a * (float) Math.pow(2, -10 * t) * (float) Math.sin((t * d - s) * (2 * (float) Math.PI) / p) + c + b); } public static float elasticInOut(float t, float b, float c, float d) { if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; float p = d * (.3f * 1.5f); float a = c; float s = p / 4; if (t < 1) return -.5f * (a * (float) Math.pow(2, 10 * (t -= 1)) * (float) Math .sin((t * d - s) * (2 * (float) Math.PI) / p)) + b; return a * (float) Math.pow(2, -10 * (t -= 1)) * (float) Math.sin((t * d - s) * (2 * (float) Math.PI) / p) * .5f + c + b; } public static float elasticInOut(float t, float b, float c, float d, float a, float p) { float s; if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * (float) Math.PI) * (float) Math.asin(c / a); } if (t < 1) return -.5f * (a * (float) Math.pow(2, 10 * (t -= 1)) * (float) Math .sin((t * d - s) * (2 * (float) Math.PI) / p)) + b; return a * (float) Math.pow(2, -10 * (t -= 1)) * (float) Math.sin((t * d - s) * (2 * (float) Math.PI) / p) * .5f + c + b; } public static float backIn(float t, float b, float c, float d) { float s = 1.70158f; return c * (t /= d) * t * ((s + 1) * t - s) + b; } public static float backIn(float t, float b, float c, float d, float s) { return c * (t /= d) * t * ((s + 1) * t - s) + b; } public static float backOut(float t, float b, float c, float d) { float s = 1.70158f; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } public static float backOut(float t, float b, float c, float d, float s) { return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } public static float backInOut(float t, float b, float c, float d) { float s = 1.70158f; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; } public static float backInOut(float t, float b, float c, float d, float s) { if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; } public static float expoIn(float t, float b, float c, float d) { return (t == 0) ? b : c * (float) Math.pow(2, 10 * (t / d - 1)) + b; } public static float expoOut(float t, float b, float c, float d) { return (t == d) ? b + c : c * (-(float) Math.pow(2, -10 * t / d) + 1) + b; } public static float expoInOut(float t, float b, float c, float d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * (float) Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-(float) Math.pow(2, -10 * --t) + 2) + b; } }
92418c6dbbae95eb04a509c79a3b325022368aaf
1,210
java
Java
python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
33.611111
134
0.738017
1,001,933
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.jetbrains.python.psi; import com.intellij.openapi.util.NlsSafe; import org.jetbrains.annotations.Nullable; /** * Base class for elements that have a qualified name (classes and functions). * * @author yole */ public interface PyQualifiedNameOwner extends PyElement { /** * Returns the qualified name of the element. * * @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or * is contained inside an element that doesn't have a qualified name. */ @Nullable @NlsSafe String getQualifiedName(); }
92418c81e9d61a12fd5c2af0f5838993194785f5
1,054
java
Java
sniffy-compatibility-tests/sniffy-compatibility-tests-io/src/test/java/io/sniffy/SniffySocketCompatibilityTest.java
Fuud/sniffy
d2864b78ceb378a91c00b1d129d3f5d205db270e
[ "MIT" ]
130
2016-03-11T17:44:11.000Z
2022-02-20T11:52:43.000Z
sniffy-compatibility-tests/sniffy-compatibility-tests-io/src/test/java/io/sniffy/SniffySocketCompatibilityTest.java
Fuud/sniffy
d2864b78ceb378a91c00b1d129d3f5d205db270e
[ "MIT" ]
407
2015-11-29T19:00:08.000Z
2022-03-08T21:20:08.000Z
sniffy-compatibility-tests/sniffy-compatibility-tests-io/src/test/java/io/sniffy/SniffySocketCompatibilityTest.java
Fuud/sniffy
d2864b78ceb378a91c00b1d129d3f5d205db270e
[ "MIT" ]
19
2015-12-16T20:51:36.000Z
2021-02-12T12:04:52.000Z
28.486486
87
0.680266
1,001,934
package io.sniffy; import io.sniffy.registry.ConnectionsRegistry; import io.sniffy.socket.SnifferSocketImplFactory; import org.junit.Test; import java.net.ConnectException; import java.net.URL; import java.net.URLConnection; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class SniffySocketCompatibilityTest { @Test public void testBlockHttpUrlConnection() throws Exception { try { SnifferSocketImplFactory.install(); ConnectionsRegistry.INSTANCE.setSocketAddressStatus("google.com", 443, -1); URL url = new URL("https://google.com"); URLConnection urlConnection = url.openConnection(); urlConnection.getInputStream().read(); fail("Should have been blocked by Sniffy"); } catch (ConnectException e) { assertTrue(e.getMessage().contains("refused by Sniffy")); } finally { ConnectionsRegistry.INSTANCE.clear(); SnifferSocketImplFactory.uninstall(); } } }
92418cb03e578cd4c210843d34d4d6fd4ab4c222
4,059
java
Java
ICareMyself/src/com/ftfl/icaremyself/database/VaccinationDataSource.java
FTFL02-ANDROID/Ankhi
23c859e8948e80103042421c85783bf4a38991e4
[ "Apache-2.0" ]
null
null
null
ICareMyself/src/com/ftfl/icaremyself/database/VaccinationDataSource.java
FTFL02-ANDROID/Ankhi
23c859e8948e80103042421c85783bf4a38991e4
[ "Apache-2.0" ]
null
null
null
ICareMyself/src/com/ftfl/icaremyself/database/VaccinationDataSource.java
FTFL02-ANDROID/Ankhi
23c859e8948e80103042421c85783bf4a38991e4
[ "Apache-2.0" ]
null
null
null
26.529412
73
0.730229
1,001,935
package com.ftfl.icaremyself.database; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import com.ftfl.icaremyself.util.VaccineProfile; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class VaccinationDataSource { // Database fields private SQLiteDatabase vacDataBase; SQLiteHelper vacDBhelper; List<VaccineProfile> vacList = new ArrayList<VaccineProfile>(); public String mCurrentDate = ""; public VaccinationDataSource(Context context) { vacDBhelper = new SQLiteHelper(context); } // open a method for writable database public void open() throws SQLException { vacDataBase = vacDBhelper.getWritableDatabase(); } // close database connection public void close() { vacDBhelper.close(); } // taking current date from system // @SuppressLint("SimpleDateFormat") public void currentDate() { DateFormat dateFormat = new SimpleDateFormat("dd/M/yyyy", Locale.getDefault()); Date date = new Date(); mCurrentDate = dateFormat.format(date); } // insert data into the database. public long insert(VaccineProfile eChart) { this.open(); ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMNL_NAME_VC_FIELD, eChart.getName()); values.put(SQLiteHelper.COLUMNL_REASON_FIELD, eChart.getReason()); values.put(SQLiteHelper.COLUMNL_DATE_VC_FIELD, eChart.getDate()); values.put(SQLiteHelper.COLUMNL_TIME_VC_FIELD, eChart.getTime()); long inserted = vacDataBase.insert(SQLiteHelper.TABLE_NAME_VACCINE, null, values); vacDataBase.close(); return inserted; } public Cursor getData(int id) { this.open(); Cursor cursor = vacDataBase.rawQuery("select * from vaccine where _id=" + id + "", null); return cursor; } // update database by Id public long updateData(Integer id, VaccineProfile eChart) { this.open(); ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMNL_NAME_VC_FIELD, eChart.getName()); values.put(SQLiteHelper.COLUMNL_REASON_FIELD, eChart.getReason()); values.put(SQLiteHelper.COLUMNL_DATE_VC_FIELD, eChart.getDate()); values.put(SQLiteHelper.COLUMNL_TIME_VC_FIELD, eChart.getTime()); long updated = 0; try { updated = vacDataBase.update(SQLiteHelper.TABLE_NAME_VACCINE, values, SQLiteHelper.COLUMNL_ID_VC_FIELD + "=" + id, null); } catch (Exception ex) { Log.e("ERROR", "data insertion problem"); } vacDataBase.close(); return updated; } // delete data form database. public Integer deleteData(Integer id) { this.open(); return vacDataBase.delete(SQLiteHelper.TABLE_NAME_VACCINE, SQLiteHelper.COLUMNL_ID_VC_FIELD + " = ? ", new String[] { Integer.toString(id) }); } /* * using cursor for display All data from database. */ public ArrayList<VaccineProfile> getAllData() { this.open(); ArrayList<VaccineProfile> allData = new ArrayList<VaccineProfile>(); Cursor cursor = vacDataBase.query(SQLiteHelper.TABLE_NAME_VACCINE, null, null, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor .getColumnIndex(SQLiteHelper.COLUMNL_ID_VC_FIELD)); String name = cursor .getString(cursor .getColumnIndex(SQLiteHelper.COLUMNL_NAME_VC_FIELD)); String reason = cursor.getString(cursor .getColumnIndex(SQLiteHelper.COLUMNL_REASON_FIELD)); String date = cursor .getString(cursor .getColumnIndex(SQLiteHelper.COLUMNL_DATE_VC_FIELD)); String time = cursor .getString(cursor .getColumnIndex(SQLiteHelper.COLUMNL_TIME_VC_FIELD)); VaccineProfile fItem = new VaccineProfile(id, name, reason, date, time); allData.add(fItem); } while (cursor.moveToNext()); } cursor.close(); } this.close(); return allData; } }
92418d12886f6dd6aaa2592bcb3d87dd5ba26f49
6,835
java
Java
fuusio.api/src/main/java/org/fuusio/api/rest/RestRequest.java
Fuusio/fuusio-app
6abdac44105b872a360dee55df6ccc0f34b050b3
[ "Apache-2.0" ]
null
null
null
fuusio.api/src/main/java/org/fuusio/api/rest/RestRequest.java
Fuusio/fuusio-app
6abdac44105b872a360dee55df6ccc0f34b050b3
[ "Apache-2.0" ]
null
null
null
fuusio.api/src/main/java/org/fuusio/api/rest/RestRequest.java
Fuusio/fuusio-app
6abdac44105b872a360dee55df6ccc0f34b050b3
[ "Apache-2.0" ]
null
null
null
28.961864
129
0.631309
1,001,936
package org.fuusio.api.rest; import org.fuusio.api.util.KeyValue; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; public abstract class RestRequest<T_Response, T_PeerRequest> { protected static final String DEFAULT_PARAMS_ENCODING = "UTF-8"; protected static final String PATH_SEPARATOR = "/"; protected final HttpHeaders mHeaders; protected final HttpParams mParams; protected final HttpParams mPathParams; protected Object mBody; protected HttpMethod mMethod; protected T_PeerRequest mPeerRequest; protected String mRelativeUrl; protected RequestListener<T_Response> mRequestListener; protected RestRequest(final String relativeUrl, final RequestListener<T_Response> requestListener) { this(HttpMethod.GET, relativeUrl, requestListener); } protected RestRequest(final HttpMethod method, final String relativeUrl, final RequestListener<T_Response> requestListener) { mMethod = method; mRelativeUrl = relativeUrl; mRequestListener = requestListener; mHeaders = new HttpHeaders(); mPathParams = new HttpParams(getParamsEncoding()); mParams = new HttpParams(getParamsEncoding()); } protected abstract String getBaseUrl(); protected String getParamsEncoding() { return DEFAULT_PARAMS_ENCODING; } public String getRelativeUrl() { return mRelativeUrl; } public T_PeerRequest getPeerRequest() { return mPeerRequest; } public int getMethodCode() { return mMethod.getMethodCode(); } /** * Construct the request url. * * @return The constructed url as a {@link String}. */ protected String constructUrl() { final String baseUrl = getBaseUrl(); final StringBuilder builder = new StringBuilder(baseUrl); final String relativeUrl = getRelativeUrl(); if (!baseUrl.endsWith(PATH_SEPARATOR)) { if (!relativeUrl.startsWith(PATH_SEPARATOR)) { builder.append(PATH_SEPARATOR); } builder.append(relativeUrl); } else { if (relativeUrl.startsWith(PATH_SEPARATOR)) { builder.append(relativeUrl.substring(1)); } else { builder.append(relativeUrl); } } if (hasQueryParams()) { builder.append('?'); getParams().encodeParameters(builder); } // Process path parameters String url = builder.toString(); if (mPathParams != null) { try { final List<KeyValue<String, String>> keyValues = mPathParams.getKeyValues(); for (final KeyValue<String, String> keyValue : keyValues) { final String key = "{" + keyValue.getKey() + "}"; final String value = URLEncoder.encode(keyValue.getValue(), HttpParams.DEFAULT_ENCODING); url = url.replace(key, value); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode path parameter.", e); } } return url; } public final void constructRequest() { mPeerRequest = createRequest(); initializeRequest(mPeerRequest); } protected abstract T_PeerRequest createRequest(); protected abstract void initializeRequest(T_PeerRequest request); public boolean hasQueryParams() { return (mParams != null && mParams.getSize() > 0); } /** * Set the body of the request. The given object is assumed to be a POJO that can be converted * by GSON to JSON. * * @param body A POJO as an {@link Object}. */ public void setBody(final Object body) { mBody = body; } /** * Add the specified query parameter with the given value. * * @param key The name of the parameter to be added as a {@link String}. * @param value The value of the parameter. */ public RestRequest addParam(final String key, final String value) { mParams.add(key, value); return this; } public RestRequest addParam(final String key, final boolean value) { mParams.add(key, Boolean.toString(value)); return this; } public RestRequest addParam(final String key, final float value) { mParams.add(key, Float.toString(value)); return this; } public RestRequest addParam(final String key, final int value) { mParams.add(key, Integer.toString(value)); return this; } public RestRequest addParam(final String key, final long value) { mParams.add(key, Long.toString(value)); return this; } /** * Add the specified path parameter with the given value. * * @param key The name of the parameter to be added as a {@link String}. * @param value The value of the parameter. */ public RestRequest addPathParam(final String key, final String value) { mPathParams.add(key, value); return this; } public RestRequest addPathParam(final String key, final boolean value) { mPathParams.add(key, Boolean.toString(value)); return this; } public RestRequest addPathParam(final String key, final float value) { mPathParams.add(key, Float.toString(value)); return this; } public RestRequest addPathParam(final String key, final int value) { mPathParams.add(key, Integer.toString(value)); return this; } public RestRequest addPathParam(final String key, final long value) { mPathParams.add(key, Long.toString(value)); return this; } public RestRequest addHeader(final String field, final String value) { mHeaders.add(field, value); return this; } public final HttpHeaders getHeaders() { return mHeaders; } public final HttpParams getParams() { return mParams; } public void setParams(final HttpParams params) { mParams.clear(); mParams.addAll(params); } public final HttpParams getPathParams() { return mPathParams; } public void setPathParams(final HttpParams params) { mPathParams.clear(); mPathParams.addAll(params); } public final RequestListener<T_Response> getRequestListener() { return mRequestListener; } public boolean isDelete() { return (mMethod == HttpMethod.DELETE); } public boolean isGet() { return (mMethod == HttpMethod.GET); } public boolean isPost() { return (mMethod == HttpMethod.POST); } public boolean isPut() { return (mMethod == HttpMethod.PUT); } }
92418d1ff0e5061030891541db81d4a9c717e3d8
196
java
Java
javaee/daw-purchases-client/src/main/java/com/mgl/demo/popularpurchases/dawps/client/model/wrapper/support/NothingWrappedException.java
MiguelGL/popular-purchases-demo
f8c45ea8a4a807eca1b58da88b6843f9c5d83bf7
[ "Apache-2.0" ]
3
2016-07-25T08:30:36.000Z
2017-05-31T13:49:10.000Z
javaee/daw-purchases-client/src/main/java/com/mgl/demo/popularpurchases/dawps/client/model/wrapper/support/NothingWrappedException.java
MiguelGL/popular-purchases-demo
f8c45ea8a4a807eca1b58da88b6843f9c5d83bf7
[ "Apache-2.0" ]
null
null
null
javaee/daw-purchases-client/src/main/java/com/mgl/demo/popularpurchases/dawps/client/model/wrapper/support/NothingWrappedException.java
MiguelGL/popular-purchases-demo
f8c45ea8a4a807eca1b58da88b6843f9c5d83bf7
[ "Apache-2.0" ]
null
null
null
24.5
73
0.816327
1,001,937
package com.mgl.demo.popularpurchases.dawps.client.model.wrapper.support; public class NothingWrappedException extends RuntimeException { private static final long serialVersionUID = 1L; }
92418d2175550a69ee809980eb3bb3f4a52160e9
3,085
java
Java
web-common/src/main/java/pl/edu/icm/unity/webui/authn/credreset/sms/SMSResetStep1Captcha.java
unity-idm/test-import
246b06505afe193167daf894dabff8cc7ffd6787
[ "BSD-3-Clause" ]
20
2017-10-15T19:29:10.000Z
2021-12-13T20:22:48.000Z
web-common/src/main/java/pl/edu/icm/unity/webui/authn/credreset/sms/SMSResetStep1Captcha.java
unity-idm/test-import
246b06505afe193167daf894dabff8cc7ffd6787
[ "BSD-3-Clause" ]
19
2017-11-02T18:08:58.000Z
2022-02-16T00:37:05.000Z
web-common/src/main/java/pl/edu/icm/unity/webui/authn/credreset/sms/SMSResetStep1Captcha.java
unity-idm/test-import
246b06505afe193167daf894dabff8cc7ffd6787
[ "BSD-3-Clause" ]
8
2017-11-17T13:40:47.000Z
2020-09-11T13:06:44.000Z
28.831776
96
0.771475
1,001,938
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.authn.credreset.sms; import java.util.function.Consumer; import com.vaadin.server.UserError; import com.vaadin.ui.Alignment; import com.vaadin.ui.Component; import com.vaadin.ui.VerticalLayout; import pl.edu.icm.unity.MessageSource; import pl.edu.icm.unity.exceptions.WrongArgumentException; import pl.edu.icm.unity.webui.authn.credreset.CredentialResetFlowConfig; import pl.edu.icm.unity.webui.authn.credreset.CredentialResetLayout; import pl.edu.icm.unity.webui.authn.credreset.TextFieldWithContextLabel; import pl.edu.icm.unity.webui.common.CaptchaComponent; /** * Bootstraps sms credential reset pipeline. * * @author P. Piernik */ public class SMSResetStep1Captcha extends CredentialResetLayout { private MessageSource msg; private TextFieldWithContextLabel username; private CaptchaComponent captcha; private Consumer<String> proceedCallback; private Runnable cancelCallback; private boolean requireCaptcha; private boolean compactLayout; private boolean collectUsername; public SMSResetStep1Captcha(CredentialResetFlowConfig credResetConfig, boolean requireCaptcha, Consumer<String> proceedCallback, boolean collectUsername) { super(credResetConfig); this.collectUsername = collectUsername; this.msg = credResetConfig.msg; this.requireCaptcha = requireCaptcha; this.proceedCallback = proceedCallback; this.cancelCallback = credResetConfig.cancelCallback; compactLayout = credResetConfig.compactLayout; initUI(msg.getMessage("CredentialReset.infoMobile"), getContents()); } private Component getContents() { VerticalLayout narrowCol = new VerticalLayout(); narrowCol.setMargin(false); narrowCol.setWidth(MAIN_WIDTH_EM, Unit.EM); username = new TextFieldWithContextLabel(compactLayout); username.setLabel(msg.getMessage("CredentialReset.username")); username.setWidth(100, Unit.PERCENTAGE); captcha = new CaptchaComponent(msg, compactLayout); narrowCol.addComponent(username); if (requireCaptcha) { Component captchaComp = captcha.getAsFullWidthComponent(); captchaComp.addStyleName("u-credreset-captcha"); narrowCol.addComponent(captchaComp); } Component buttons = getButtonsBar(msg.getMessage("CredentialReset.requestMobileReset"), this::onConfirm, msg.getMessage("cancel"), cancelCallback); narrowCol.addComponent(buttons); narrowCol.setComponentAlignment(buttons, Alignment.TOP_CENTER); if (!collectUsername) username.setVisible(false); return narrowCol; } private void onConfirm() { String user = null; if (collectUsername) { user = username.getValue(); if (user == null || user.equals("")) { username.setComponentError(new UserError(msg.getMessage("fieldRequired"))); return; } username.setComponentError(null); } if (requireCaptcha) { try { captcha.verify(); } catch (WrongArgumentException e) { return; } } proceedCallback.accept(user); } }
92418d855c639969d4298509b13071e00d523496
28,221
java
Java
src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/sysprocs/saverestore/TestSavedTableConverter.java
OpenMPDK/SMDK
8f19d32d999731242cb1ab116a4cb445d9993b15
[ "BSD-3-Clause" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/sysprocs/saverestore/TestSavedTableConverter.java
H2O0Lee/SMDK
eff49bc17a55a83ea968112feb2e2f2ea18c4ff5
[ "BSD-3-Clause" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/sysprocs/saverestore/TestSavedTableConverter.java
H2O0Lee/SMDK
eff49bc17a55a83ea968112feb2e2f2ea18c4ff5
[ "BSD-3-Clause" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
46.569307
134
0.599305
1,001,939
/* This file is part of VoltDB. * Copyright (C) 2008-2020 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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 org.voltdb.sysprocs.saverestore; import java.math.BigDecimal; import org.voltdb.MockVoltDB; import org.voltdb.VoltTable; import org.voltdb.VoltTable.ColumnInfo; import org.voltdb.VoltTableRow; import org.voltdb.VoltType; import org.voltdb.catalog.Table; import org.voltdb.utils.CatalogUtil; import junit.framework.TestCase; public class TestSavedTableConverter extends TestCase { private static final String TABLE_NAME = "TEST_TABLE"; private static int DEFAULT_INT = 1234; @Override public void tearDown() throws Exception { m_catalogCreator.shutdown(null); m_catalogTable = null; } @Override public void setUp() { m_catalogCreator = new MockVoltDB(); m_catalogCreator.addTable(TABLE_NAME, false); m_catalogCreator.addColumnToTable(TABLE_NAME, "HAS_DEFAULT", VoltType.INTEGER, true, Integer.toString(DEFAULT_INT), VoltType.INTEGER); m_catalogCreator.addColumnToTable(TABLE_NAME, "HAS_NULLABLE_STRING", VoltType.STRING, true, "", VoltType.INVALID); m_catalogCreator.addColumnToTable(TABLE_NAME, "HAS_NULLABLE_FLOAT", VoltType.FLOAT, true, "", VoltType.INVALID); m_catalogCreator.addColumnToTable(TABLE_NAME, "HAS_NADA", VoltType.FLOAT, false, "", VoltType.INVALID); m_catalogTable = m_catalogCreator.getTable(TABLE_NAME); } // Test cases: // NON-TYPE-CAST-RELATED: // unchanged table copies correctly public void testUnchangedTable() { VoltTable inputTable = CatalogUtil.getVoltTable(m_catalogTable); for (int i = 0; i < 10; i++) { inputTable.addRow(i, "name_" + i, new Double(i), new Double(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTable, m_catalogTable, false, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); return; } assertEquals(inputTable, result); } // Test the convert table with just the type change. public void testUnchangedTableWithTypeChange() { String inp = "i"; String outp = "o"; VoltType itypes[] = {VoltType.TINYINT, VoltType.SMALLINT, VoltType.INTEGER, VoltType.FLOAT, VoltType.DECIMAL }; Object max_vals[] = {Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Double.MAX_VALUE, new BigDecimal("99999999999999999999999999.999999999999") }; System.out.println("All Tests Should succeed."); //You should be able to convert anything after you. for (int i = 0; i < itypes.length; i++) { for (int j = i; j < itypes.length - i; j++) { String in = inp + i + j; String out = outp + i + j; runNumberConversion(in, out, itypes[i], itypes[j], false, max_vals[i]); } } System.out.println("All Tests Should Fail."); // All should fail for (int i = 1; i < itypes.length - 1; i++) { for (int j = i - 1; j >= 0; j--) { String in = inp + "x" + i + j; String out = outp + "x" + i + j; runNumberConversion(in, out, itypes[i], itypes[j], true, max_vals[i]); } } // Converting from decimal to double should succeed (this is assumed to be lossy anyway) int i = itypes.length - 1; int j = i - 1; String in = inp + "x" + i + j; String out = outp + "x" + i + j; runNumberConversion(in, out, itypes[i], itypes[j], false, max_vals[i]); // These out-of-range conversions should fail for (j = i - 2; j >= 0; j--) { in = inp + "x" + i + j; out = outp + "x" + i + j; runNumberConversion(in, out, itypes[i], itypes[j], true, max_vals[i]); } } //Run conversions for numbers. private void runNumberConversion(String in, String out, VoltType tin, VoltType tout, boolean expectfailure, Object maxval) { System.out.println("Testing : Input table: " + in + " Output Table: " + out + " In Type: " + tin.name() + " Out Type: " + tout.name() + " Class: " + tout.classFromType().getName()); m_catalogCreator.addTable(in, false); m_catalogCreator.addColumnToTable(in, "HAS_DEFAULT", tin, true, "INPUT_NUMBER", tin); m_catalogCreator.addTable(out, false); m_catalogCreator.addColumnToTable(out, "HAS_DEFAULT", tout, true, "OUTPUT_NUMBER", tout); Table catalogTable = m_catalogCreator.getTable(out); VoltTable inputTable = CatalogUtil.getVoltTable(m_catalogCreator.getTable(in)); //Add 10 Rows. for (int i = 0; i < 10; i++) { inputTable.addRow(maxval); } VoltTable result = null; boolean failed = false; try { result = SavedTableConverter.convertTable(inputTable, catalogTable, false, false, false, true); result.resetRowPosition(); assertEquals(10, result.getRowCount()); } catch (Exception e) { failed = true; } assertTrue((failed == expectfailure)); } // dropping a column fills in the remaining values, all correctly public void testDroppedColumn() { VoltTable inputTable = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo("GOES_AWAY", VoltType.INTEGER)); for (int i = 0; i < 10; i++) { inputTable.addRow(i, "name_" + i, new Double(i), new Double(i), i); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTable, m_catalogTable, false, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); return; } assertEquals(4, result.getColumnCount()); for (int i = 0; i < 10; i++) { assertEquals(i, result.fetchRow(i).getLong("HAS_DEFAULT")); assertEquals("name_" + i, result.fetchRow(i).getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), result.fetchRow(i).getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), result.fetchRow(i).getDouble("HAS_NADA")); } } // adding a column with a default value adds the column filled with default public void testAddDefaultColumn() { VoltTable inputTable = new VoltTable(new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT)); for (int i = 0; i < 10; i++) { inputTable.addRow("name_" + i, new Double(i), new Double(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTable, m_catalogTable, false, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); return; } assertEquals(4, result.getColumnCount()); for (int i = 0; i < 10; i++) { assertEquals(DEFAULT_INT, result.fetchRow(i).getLong("HAS_DEFAULT")); assertEquals("name_" + i, result.fetchRow(i).getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), result.fetchRow(i).getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), result.fetchRow(i).getDouble("HAS_NADA")); } } // adding columns with no default but nullable adds the // columns filled with null public void testAddNullColumn() { VoltTable inputTable = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NADA", VoltType.FLOAT)); for (int i = 0; i < 10; i++) { inputTable.addRow(i, new Double(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTable, m_catalogTable, false, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); return; } assertEquals(4, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(null, row.getString("HAS_NULLABLE_STRING")); assertTrue(row.wasNull()); assertEquals(VoltType.NULL_FLOAT, row.getDouble("HAS_NULLABLE_FLOAT")); assertTrue(row.wasNull()); assertEquals(new Double(i), row.getDouble("HAS_NADA")); } } // adding a column with no default and non-nullable results in fail public void testNoDefaultNoNullBoom() { VoltTable inputTable = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT)); for (int i = 0; i < 10; i++) { inputTable.addRow(i, "name_" + i, new Double(i)); } try { SavedTableConverter.convertTable(inputTable, m_catalogTable, false, false, false, true); } catch (Exception e) { assertTrue(true); return; } fail("SavedTableConverter should have thrown an exception"); } public void testDRPassiveToActive() { VoltTable inputTableWithoutDRCol = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT)); assertFalse(SavedTableConverter.needsConversion(inputTableWithoutDRCol, m_catalogTable, false, false, false, true)); assertTrue(SavedTableConverter.needsConversion(inputTableWithoutDRCol, m_catalogTable, true, false, false, true)); for (int i = 0; i < 10; i++) { inputTableWithoutDRCol.addRow(i, Integer.toString(i), new Double(i), new Double(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTableWithoutDRCol, m_catalogTable, true, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(4)); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.DR_HIDDEN_COLUMN_NAME)); } } public void testDRActiveToPassive() { VoltTable inputTableDifferent = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); VoltTable inputTableIdentical = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); // Missing HAS_NULLABLE_STRING and HAS_NULLABLE_FLOAT assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, false, false, false, true)); assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, true, false, false, true)); // Extra DR Column in input assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, false, false, false, true)); for (int i = 0; i < 10; i++) { inputTableIdentical.addRow(i, Integer.toString(i), new Double(i), new Double(i), new Long(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTableIdentical, m_catalogTable, false, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(4, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); } } public void testDRActiveToActiveMissing2Cols() { VoltTable inputTable = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertTrue(SavedTableConverter.needsConversion(inputTable, m_catalogTable, true, false, false, true)); for (int i = 0; i < 10; i++) { inputTable.addRow(i, new Double(i), new Long(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTable, m_catalogTable, true, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(null, row.getString("HAS_NULLABLE_STRING")); assertTrue(row.wasNull()); assertEquals(VoltType.NULL_FLOAT, row.getDouble("HAS_NULLABLE_FLOAT")); assertTrue(row.wasNull()); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(i, row.getLong(4)); assertEquals(i, row.getLong(CatalogUtil.DR_HIDDEN_COLUMN_NAME)); } } public void testDRActiveToActiveIdentical() { VoltTable inputTableWithDRCol = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertTrue(SavedTableConverter.needsConversion(inputTableWithDRCol, m_catalogTable, false, false, false, true)); assertFalse(SavedTableConverter.needsConversion(inputTableWithDRCol, m_catalogTable, true, false, false, true)); } public void testViewWithoutCountStar() { VoltTable inputTableWithViewCol = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.VIEW_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertTrue(SavedTableConverter.needsConversion(inputTableWithViewCol, m_catalogTable, false, false, false, true)); assertFalse(SavedTableConverter.needsConversion(inputTableWithViewCol, m_catalogTable, false, true, false, true)); } public void testDRPassiveMigrateToActiveNoMigrate() { VoltTable inputTableWithoutDRColWithMigrate = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertFalse(SavedTableConverter.needsConversion(inputTableWithoutDRColWithMigrate, m_catalogTable, false, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableWithoutDRColWithMigrate, m_catalogTable, false, false, true, false)); for (int i = 0; i < 10; i++) { inputTableWithoutDRColWithMigrate.addRow(i, Integer.toString(i), new Double(i), new Double(i), i); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTableWithoutDRColWithMigrate, m_catalogTable, true, false, false, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(4)); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.DR_HIDDEN_COLUMN_NAME)); } inputTableWithoutDRColWithMigrate.resetRowPosition(); VoltTable result2 = null; try { result2 = SavedTableConverter.convertTable(inputTableWithoutDRColWithMigrate, m_catalogTable, true, false, false, false); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result2.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result2.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(4)); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.DR_HIDDEN_COLUMN_NAME)); } } public void testDRActiveNoMigrateToPassiveMigrate() { VoltTable inputTableDifferent = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); VoltTable inputTableIdentical = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.DR_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, false, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, false, false, true, false)); // Remove DR Column and Add Migrate Column assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, false, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, false, false, true, false)); // Add Migrate Column After DR Column assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, true, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, true, false, true, false)); for (int i = 0; i < 10; i++) { inputTableIdentical.addRow(i, Integer.toString(i), new Double(i), new Double(i), new Long(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTableIdentical, m_catalogTable, false, false, true, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME)); } inputTableIdentical.resetRowPosition(); VoltTable result2 = null; try { result2 = SavedTableConverter.convertTable(inputTableIdentical, m_catalogTable, false, false, true, true); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result2.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result2.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME)); } } public void testMigrateToMigrateRestore() { VoltTable inputTableDifferent = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); VoltTable inputTableIdentical = new VoltTable(new ColumnInfo("HAS_DEFAULT", VoltType.INTEGER), new ColumnInfo("HAS_NULLABLE_STRING", VoltType.STRING), new ColumnInfo("HAS_NULLABLE_FLOAT", VoltType.FLOAT), new ColumnInfo("HAS_NADA", VoltType.FLOAT), new ColumnInfo(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME, VoltType.BIGINT)); assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, false, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableDifferent, m_catalogTable, false, false, true, false)); // Same Table schema with Recover and Restore assertFalse(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, false, false, true, true)); assertTrue(SavedTableConverter.needsConversion(inputTableIdentical, m_catalogTable, false, false, true, false)); for (int i = 0; i < 10; i++) { inputTableIdentical.addRow(i, Integer.toString(i), new Double(i), new Double(i), new Long(i)); } VoltTable result = null; try { result = SavedTableConverter.convertTable(inputTableIdentical, m_catalogTable, false, false, true, false); } catch (Exception e) { e.printStackTrace(); fail("SavedTableConverter.convert should not have thrown here"); } assertEquals(5, result.getColumnCount()); for (int i = 0; i < 10; i++) { VoltTableRow row = result.fetchRow(i); assertEquals(i, row.getLong("HAS_DEFAULT")); assertEquals(Integer.toString(i), row.getString("HAS_NULLABLE_STRING")); assertEquals(new Double(i), row.getDouble("HAS_NULLABLE_FLOAT")); assertEquals(new Double(i), row.getDouble("HAS_NADA")); assertEquals(VoltType.NULL_BIGINT, row.getLong(CatalogUtil.MIGRATE_HIDDEN_COLUMN_NAME)); } } private MockVoltDB m_catalogCreator; private Table m_catalogTable; }
92418dac35c0629c5187fc826534a3e0376adb6d
1,096
java
Java
cloud-consumer-order80/src/main/java/com/ucandoooh/springcloud/lb/MyLoadBalanceImpl.java
ucandoooh/com.ucandoooh.springcloud
8955e66c058a70d0f0c740a91cca38337259eb35
[ "Apache-2.0" ]
null
null
null
cloud-consumer-order80/src/main/java/com/ucandoooh/springcloud/lb/MyLoadBalanceImpl.java
ucandoooh/com.ucandoooh.springcloud
8955e66c058a70d0f0c740a91cca38337259eb35
[ "Apache-2.0" ]
null
null
null
cloud-consumer-order80/src/main/java/com/ucandoooh/springcloud/lb/MyLoadBalanceImpl.java
ucandoooh/com.ucandoooh.springcloud
8955e66c058a70d0f0c740a91cca38337259eb35
[ "Apache-2.0" ]
null
null
null
29.621622
84
0.660584
1,001,940
package com.ucandoooh.springcloud.lb; import org.springframework.cloud.client.ServiceInstance; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * @author zxn * @date 2021/6/21 11:18 */ @Component public class MyLoadBalanceImpl implements MyLoadBalance{ AtomicInteger invokeTimeAtomicInteger = new AtomicInteger(0); private final int getAndIncrease() { int expect = 0; int update = 0; do { expect = invokeTimeAtomicInteger.get(); update = update == Integer.MAX_VALUE ? 0 : expect + 1; } while (!invokeTimeAtomicInteger.compareAndSet(expect, update)); return update; } @Override public ServiceInstance getInstance(List<ServiceInstance> serviceInstanceList) { if (serviceInstanceList == null || serviceInstanceList.isEmpty()) { return null; } int index = getAndIncrease() % serviceInstanceList.size(); return serviceInstanceList.get(index); } }
92418f2e8c1d3cb88d2283e5d532e166a2e74885
1,254
java
Java
src/test/java/org/openstreetmap/atlas/tags/annotations/extraction/AltitudeExtractorTest.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
188
2017-08-08T17:26:54.000Z
2022-03-29T07:59:30.000Z
src/test/java/org/openstreetmap/atlas/tags/annotations/extraction/AltitudeExtractorTest.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
403
2017-08-09T16:15:25.000Z
2022-02-16T19:33:42.000Z
src/test/java/org/openstreetmap/atlas/tags/annotations/extraction/AltitudeExtractorTest.java
Huyuntj/atlas
bb1545ed2da7a1d51f133a4bb686c064c63892eb
[ "BSD-3-Clause" ]
79
2017-08-08T17:55:01.000Z
2021-11-10T20:51:57.000Z
24.588235
64
0.6563
1,001,941
package org.openstreetmap.atlas.tags.annotations.extraction; import java.util.Optional; import org.junit.Assert; import org.junit.Test; import org.openstreetmap.atlas.geography.Altitude; /** * Unit test for {@link AltitudeExtractor}. * * @author bbreithaupt */ public class AltitudeExtractorTest { @Test public void validMetersTest() { Assert.assertEquals(Optional.of(Altitude.meters(20)), AltitudeExtractor.validateAndExtract("20 m")); } @Test public void validNegativeMetersCapsTest() { Assert.assertEquals(Optional.of(Altitude.meters(-20)), AltitudeExtractor.validateAndExtract("-20 M")); } @Test public void validNegativeMetersTest() { Assert.assertEquals(Optional.of(Altitude.meters(-20)), AltitudeExtractor.validateAndExtract("-20 m")); } @Test public void validNegativeNumberTest() { Assert.assertEquals(Optional.of(Altitude.meters(-20.5)), AltitudeExtractor.validateAndExtract("-20.5")); } @Test public void validNumberTest() { Assert.assertEquals(Optional.of(Altitude.meters(20.5)), AltitudeExtractor.validateAndExtract("20.5")); } }
92418fa75cce3cb8d75267d9c3479d2172c20b4b
1,581
java
Java
src/main/java/com/github/jsqltool/sql/selectTable/impl/DefaultSelectTableHandler.java
zhihuayu/Jsqltools
24c91e156deddf85c73e41a19d94116f6b4b9a83
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/jsqltool/sql/selectTable/impl/DefaultSelectTableHandler.java
zhihuayu/Jsqltools
24c91e156deddf85c73e41a19d94116f6b4b9a83
[ "Apache-2.0" ]
2
2021-12-24T07:52:57.000Z
2021-12-24T07:53:17.000Z
src/main/java/com/github/jsqltool/sql/selectTable/impl/DefaultSelectTableHandler.java
zhihuayu/Jsqltools
24c91e156deddf85c73e41a19d94116f6b4b9a83
[ "Apache-2.0" ]
null
null
null
35.931818
102
0.776091
1,001,942
package com.github.jsqltool.sql.selectTable.impl; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.apache.commons.lang3.StringUtils; import com.github.jsqltool.enums.DBType; import com.github.jsqltool.exception.JsqltoolParamException; import com.github.jsqltool.param.SelectTableParam; import com.github.jsqltool.result.SqlResult; import com.github.jsqltool.sql.SqlPlus; import com.github.jsqltool.sql.selectTable.SelectTableHandler; import com.github.jsqltool.utils.JdbcUtil; public class DefaultSelectTableHandler implements SelectTableHandler { @Override public SqlResult selectTable(Connection connection, SelectTableParam param) throws SQLException { if (param == null || !StringUtils.isNoneBlank(param.getTableName())) { throw new JsqltoolParamException("表名不能为空!"); } long startTime = System.currentTimeMillis(); String tableInfo = JdbcUtil.getTableNameInfo(connection, param.getCatalog(), param.getSchema(), param.getTableName()); DatabaseMetaData metaData = connection.getMetaData(); // 获取行 SqlPlus.setPage(param.getPage(), param.getPageSize(), null, true, DBType.getDBTypeByDriverClassName(metaData.getDriverName()), "select count(*) from " + tableInfo); SqlResult result = SqlPlus.execute(connection, "select * from " + tableInfo); long endTime = System.currentTimeMillis(); if (result.getStatus() == SqlResult.success) result.setMessage("执行成功,耗时:" + (endTime - startTime) + "ms"); return result; } @Override public boolean support(DBType dbType) { return true; } }
924190127b520faf4ea9be0a8e279c1cdc8cd8bc
462
java
Java
src/main/java/com/toofifty/goaltracker/goal/factory/TaskFactory.java
Toofifty/rl-goal-tracker
2dcc28afd71d55b0eae602652613e0bc7c26dd71
[ "BSD-2-Clause" ]
null
null
null
src/main/java/com/toofifty/goaltracker/goal/factory/TaskFactory.java
Toofifty/rl-goal-tracker
2dcc28afd71d55b0eae602652613e0bc7c26dd71
[ "BSD-2-Clause" ]
null
null
null
src/main/java/com/toofifty/goaltracker/goal/factory/TaskFactory.java
Toofifty/rl-goal-tracker
2dcc28afd71d55b0eae602652613e0bc7c26dd71
[ "BSD-2-Clause" ]
null
null
null
24.315789
100
0.718615
1,001,943
package com.toofifty.goaltracker.goal.factory; import com.google.gson.JsonObject; import com.toofifty.goaltracker.goal.Task; import com.toofifty.goaltracker.goal.TaskStatus; abstract public class TaskFactory<T extends Task> { public T create(JsonObject json) { T task = create(); task.setResult(TaskStatus.valueOf(json.get("previous_result").getAsString().toUpperCase())); return task; } public abstract T create(); }
924190926ed88bf3051ee122263cd56c3cf86be5
4,368
java
Java
app/src/main/java/com/hongzebin/util/ApiConstant.java
HongZeBin98/HZB_ONE
9c9c823b0466467c547429e1e40433b17a1a2012
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/hongzebin/util/ApiConstant.java
HongZeBin98/HZB_ONE
9c9c823b0466467c547429e1e40433b17a1a2012
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/hongzebin/util/ApiConstant.java
HongZeBin98/HZB_ONE
9c9c823b0466467c547429e1e40433b17a1a2012
[ "Apache-2.0" ]
null
null
null
34.125
148
0.643086
1,001,944
package com.hongzebin.util; /** * api常量类 * Created by 洪泽彬 */ public class ApiConstant { //音乐列表最新的url public static final String MUSIC_ADDRESS = "http://v3.wufazhuce.com:8000/api/channel/music/more/0?platform=android"; //阅读列表最新的url public static final String READ_ADDRESS = "http://v3.wufazhuce.com:8000/api/channel/reading/more/0?channel=wdj&version=4.0.2&platform=android"; //影视列表最新的url public static final String VIDEO_ADDRESS = "http://v3.wufazhuce.com:8000/api/channel/movie/more/0?platform=android"; //插画列表最新的url public static final String PICTURE_ADDRESS = "http://v3.wufazhuce.com:8000/api/hp/idlist/0?version=3.5.0&platform=android"; /** * 通过id得到相应的音乐列表api * @param id 需要添加的 * @return 添加了新id的音乐列表api */ public static String refreshMusicApi(String id){ String musicAddress = "http://v3.wufazhuce.com:8000/api/channel/music/more/" + id + "?platform=android"; return musicAddress; } /** * 通过id得到相应的阅读列表api * @param id 需要添加的id * @return 添加了新id的阅读列表api */ public static String refreshReadApi(String id){ String readAddress = "http://v3.wufazhuce.com:8000/api/channel/reading/more/" + id + "?channel=wdj&version=4.0.2&platform=android"; return readAddress; } /** * 通过id得到相应的影视列表api * @param id 需要添加的id * @return 添加了新id的影视列表api */ public static String refreshVideoApi(String id){ String videoAddress = "http://v3.wufazhuce.com:8000/api/channel/movie/more/" + id + "?platform=android"; return videoAddress; } /** * 通过id得到相应的插画列表api * @param id 需要添加的id * @return 添加了新id的插画列表api */ public static String refreshPictureApi(String id){ String pictureAddress = "http://v3.wufazhuce.com:8000/api/hp/idlist/" + id + "?version=3.5.0&platform=android"; return pictureAddress; } /** * 通过itemId得到相应的阅读api * @param itemId 需要添加的itemId * @return 添加了新itemId的阅读api */ public static String getReadAddress(String itemId){ String ReadDetailAddress = "http://v3.wufazhuce.com:8000/api/essay/" + itemId + "?platform=android"; return ReadDetailAddress; } /** * 通过itemId得到相应的音乐api * @param itemId 需要添加的itemId * @return 添加了新itemId的音乐api */ public static String getMusicAddress(String itemId){ String MusicDetailAddress = "http://v3.wufazhuce.com:8000/api/music/detail/" + itemId + "?version=3.5.0&platform=android"; return MusicDetailAddress; } /** * 通过itemId得到相应的影视api * @param itemId 需要添加的itemId * @return 添加了新itemId的影视api */ public static String getVideoAddress(String itemId){ String VideoDetailAddress = "http://v3.wufazhuce.com:8000/api/movie/" + itemId + "/story/1/0?platform=android"; return VideoDetailAddress; } /** * 通过itemId得到相应的插画api * @param itemId 需要添加的itemId * @return 添加了新itemId的插画api */ public static String getPictureAddress(String itemId){ String PictureDetailAddress = "http://v3.wufazhuce.com:8000/api/hp/detail/" + itemId + "?version=3.5.0&platform=android"; return PictureDetailAddress; } /** * 通过itemId得到相应的影视评论api * @param itemId 需要添加的itemId * @return 添加了新itemId的影视评论api */ public static String getVideoComAddress(String itemId){ String VideoComAddress = "http://v3.wufazhuce.com:8000/api/comment/praiseandtime/movie/" + itemId + "/0?&platform=android"; return VideoComAddress; } /** * 通过itemId得到相应的音乐评论api * @param itemId 需要添加的itemId * @return 添加了新itemId的音乐评论api */ public static String getMusicComAddress(String itemId){ String MusicComAddress = "http://v3.wufazhuce.com:8000/api/comment/praiseandtime/music/" + itemId + "/0?platform=android"; return MusicComAddress; } /** * 通过itemId得到相应的阅读评论api * @param itemId 需要添加的itemId * @return 添加了新itemId的阅读评论api */ public static String getReadComAddress(String itemId){ String ReadComAddress = "http://v3.wufazhuce.com:8000/api/comment/praiseandtime/essay/" + itemId + "/0?&platform=android"; return ReadComAddress; } }
924194444b91f30de070eb797a1f503f3648cce8
9,259
java
Java
java/integration-tests/src/test/java/io/joynr/integration/MultipleVersionsEnd2EndTest.java
emundo/joynr
7f98e541da2ef4bbe12ba3cfcf36da7ed361e86a
[ "Apache-2.0" ]
151
2015-02-12T16:08:35.000Z
2022-03-10T06:58:22.000Z
java/integration-tests/src/test/java/io/joynr/integration/MultipleVersionsEnd2EndTest.java
emundo/joynr
7f98e541da2ef4bbe12ba3cfcf36da7ed361e86a
[ "Apache-2.0" ]
78
2015-09-28T05:53:22.000Z
2022-03-18T14:40:30.000Z
java/integration-tests/src/test/java/io/joynr/integration/MultipleVersionsEnd2EndTest.java
bmwcarit/joynr
d0a1399314489b840eda11d0c5e6023be1b97102
[ "Apache-2.0" ]
60
2015-06-19T14:07:45.000Z
2022-03-13T07:58:39.000Z
50.048649
173
0.655902
1,001,945
/* * #%L * %% * Copyright (C) 2018 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.HashSet; import org.junit.Test; import io.joynr.exceptions.JoynrRuntimeException; import joynr.tests.AnonymousVersionedStruct; import joynr.tests.DefaultMultipleVersionsInterfaceProvider; import joynr.tests.InterfaceVersionedStruct; import joynr.tests.MultipleVersionsInterfaceProxy; import joynr.tests.MultipleVersionsTypeCollection.VersionedStruct; public class MultipleVersionsEnd2EndTest extends AbstractMultipleVersionsEnd2EndTest { private static final String UNREGISTERING_FAILED_MESSAGE = "Unregistering of provider failed: "; /* * This test tests if 2 proxies of same interface (package versioned, unversioned) can connect to * one provider (unversioned) and communicate with this without mutual interference. */ @Test public void proxiesOfDifferentVersioningTypesVsUnversionedProviderInSingleRuntime() throws Exception { // register provider DefaultMultipleVersionsInterfaceProvider unversionedProvider = new DefaultMultipleVersionsInterfaceProvider(); registerProvider(unversionedProvider, domain); // build fitting proxies joynr.tests.v2.MultipleVersionsInterfaceProxy packageVersionedProxy = buildProxy(joynr.tests.v2.MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); MultipleVersionsInterfaceProxy unversionedProxy = buildProxy(MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); try { //set UInt8Attribute1 and check if it can be retrieved correctly unversionedProxy.setUInt8Attribute1((byte) 100); Byte value1 = packageVersionedProxy.getUInt8Attribute1(); Byte value2 = unversionedProxy.getUInt8Attribute1(); assertEquals((byte) value1, 100); assertEquals((byte) value2, 100); packageVersionedProxy.setUInt8Attribute1((byte) 50); value1 = packageVersionedProxy.getUInt8Attribute1(); value2 = unversionedProxy.getUInt8Attribute1(); assertEquals((byte) value1, 50); assertEquals((byte) value2, 50); // unregister provider providerRuntime.unregisterProvider(domain, unversionedProvider); } catch (JoynrRuntimeException e) { fail(UNREGISTERING_FAILED_MESSAGE + e); } } /* * This test tests if 2 providers of same interface and different versions can be registered in a single runtime * and 2 proxies can communicate with those without mutual interference. */ @Test public void twoPackageVersionedProvidersInSingleRuntime() throws Exception { // register providers joynr.tests.v1.DefaultMultipleVersionsInterfaceProvider provider1 = new joynr.tests.v1.DefaultMultipleVersionsInterfaceProvider(); joynr.tests.v2.DefaultMultipleVersionsInterfaceProvider provider2 = new joynr.tests.v2.DefaultMultipleVersionsInterfaceProvider(); registerProvider(provider1, domain); registerProvider(provider2, domain); // build fitting proxies joynr.tests.v1.MultipleVersionsInterfaceProxy proxy1 = buildProxy(joynr.tests.v1.MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); MultipleVersionsInterfaceProxy proxy2 = buildProxy(MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); //set UInt8Attribute1 and check if it can be retrieved correctly proxy1.setUInt8Attribute1((byte) 100); proxy2.setUInt8Attribute1((byte) 50); Byte value1 = proxy1.getUInt8Attribute1(); Byte value2 = proxy2.getUInt8Attribute1(); assertEquals((byte) value1, 100); assertEquals((byte) value2, 50); // unregister providers try { providerRuntime.unregisterProvider(domain, provider1); providerRuntime.unregisterProvider(domain, provider2); } catch (JoynrRuntimeException e) { fail(UNREGISTERING_FAILED_MESSAGE + e); } } private void testPackageVersionedTypes() throws Exception { final joynr.tests.v2.MultipleVersionsInterfaceProxy packageVersionedProxy = buildProxy(joynr.tests.v2.MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); final joynr.tests.v2.AnonymousVersionedStruct input1 = new joynr.tests.v2.AnonymousVersionedStruct(random.nextBoolean()); final joynr.tests.v2.AnonymousVersionedStruct output1 = packageVersionedProxy.getAnonymousVersionedStruct(input1); assertEquals(input1.getFlag2(), output1.getFlag2()); final joynr.tests.v2.MultipleVersionsTypeCollection.VersionedStruct input2 = new joynr.tests.v2.MultipleVersionsTypeCollection.VersionedStruct(random.nextBoolean()); final joynr.tests.v2.MultipleVersionsTypeCollection.VersionedStruct output2 = packageVersionedProxy.getVersionedStruct(input2); assertEquals(input2.getFlag2(), output2.getFlag2()); final joynr.tests.v2.InterfaceVersionedStruct input3 = new joynr.tests.v2.InterfaceVersionedStruct(random.nextBoolean(), random.nextBoolean()); final joynr.tests.v2.InterfaceVersionedStruct output3 = packageVersionedProxy.getInterfaceVersionedStruct(input3); assertEquals(input3.getFlag1(), output3.getFlag1()); assertEquals(input3.getFlag2(), output3.getFlag2()); } private void testUnversionedTypes() throws Exception { final MultipleVersionsInterfaceProxy unversionedProxy = buildProxy(MultipleVersionsInterfaceProxy.class, new HashSet<String>(Arrays.asList(domain)), true); final AnonymousVersionedStruct input1 = new AnonymousVersionedStruct(random.nextBoolean()); final AnonymousVersionedStruct output1 = unversionedProxy.getAnonymousVersionedStruct(input1); assertEquals(input1.getFlag2(), output1.getFlag2()); final VersionedStruct input2 = new VersionedStruct(random.nextBoolean()); final VersionedStruct output2 = unversionedProxy.getVersionedStruct(input2); assertEquals(input2.getFlag2(), output2.getFlag2()); final InterfaceVersionedStruct input3 = new InterfaceVersionedStruct(random.nextBoolean(), random.nextBoolean()); final InterfaceVersionedStruct output3 = unversionedProxy.getInterfaceVersionedStruct(input3); assertEquals(input3.getFlag1(), output3.getFlag1()); assertEquals(input3.getFlag2(), output3.getFlag2()); } @Test public void packageVersionedProxy_packageVersionedProvider_singleRuntime() throws Exception { registerPackageVersionedProvider(); testPackageVersionedTypes(); } @Test(timeout = CONST_GLOBAL_TEST_TIMEOUT_MS) public void packageVersionedProxy_packageVersionedProvider_separateRuntime() throws Exception { useGlobalCommunication(); registerPackageVersionedProvider(); testPackageVersionedTypes(); } @Test public void unversionedProxy_unversionedProvider_singleRuntime() throws Exception { registerUnversionedProvider(); testUnversionedTypes(); } @Test(timeout = CONST_GLOBAL_TEST_TIMEOUT_MS) public void unversionedProxy_UnversionedProvider_separateRuntime() throws Exception { useGlobalCommunication(); registerUnversionedProvider(); testUnversionedTypes(); } }
9241949871a9ef45680e56ed9c215cec6bb8dc16
316
java
Java
URI Online Judge - Pacote 1/Problema1933.java
ahmadkamel7/URI-Online-Judge
27502f133d382e7e4d55150b8634f0d515936df0
[ "MIT" ]
null
null
null
URI Online Judge - Pacote 1/Problema1933.java
ahmadkamel7/URI-Online-Judge
27502f133d382e7e4d55150b8634f0d515936df0
[ "MIT" ]
null
null
null
URI Online Judge - Pacote 1/Problema1933.java
ahmadkamel7/URI-Online-Judge
27502f133d382e7e4d55150b8634f0d515936df0
[ "MIT" ]
null
null
null
21.066667
51
0.531646
1,001,946
import java.util.Scanner; class Problema1933 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int A = s.nextInt(); int B = s.nextInt(); if (A==B || A>B) { System.out.println(A); } else { System.out.println(B); } s.close(); } }
924194baf378c433638ba426ec03f377ca7c062b
12,857
java
Java
src/test/java/com/starrocks/connector/flink/it/source/StarRocksSourceBaseTest.java
zhangpenggh/flink-connector-starrocks
52f723ccc5e1b160201e68048f1ac82c81e27c6c
[ "Apache-2.0" ]
48
2021-09-12T03:14:13.000Z
2022-03-29T06:24:56.000Z
src/test/java/com/starrocks/connector/flink/it/source/StarRocksSourceBaseTest.java
zhangpenggh/flink-connector-starrocks
52f723ccc5e1b160201e68048f1ac82c81e27c6c
[ "Apache-2.0" ]
39
2021-11-01T02:26:24.000Z
2022-03-31T03:36:17.000Z
src/test/java/com/starrocks/connector/flink/it/source/StarRocksSourceBaseTest.java
zhangpenggh/flink-connector-starrocks
52f723ccc5e1b160201e68048f1ac82c81e27c6c
[ "Apache-2.0" ]
36
2021-09-16T03:01:41.000Z
2022-03-31T11:19:58.000Z
41.608414
168
0.58754
1,001,947
/* * 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.starrocks.connector.flink.it.source; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSONObject; import com.starrocks.connector.flink.table.source.StarRocksSourceOptions; import com.starrocks.connector.flink.table.source.StarrocksExternalServiceImpl; import com.starrocks.connector.flink.table.source.struct.SelectColumn; import com.starrocks.thrift.TStarrocksExternalService; import org.apache.flink.table.api.DataTypes; import org.apache.flink.table.api.TableSchema; import com.starrocks.shade.org.apache.thrift.protocol.TBinaryProtocol; import com.starrocks.shade.org.apache.thrift.server.TServer; import com.starrocks.shade.org.apache.thrift.server.TThreadPoolServer; import com.starrocks.shade.org.apache.thrift.transport.TServerSocket; import com.starrocks.shade.org.apache.thrift.transport.TServerTransport; import com.starrocks.shade.org.apache.thrift.transport.TTransportException; import com.starrocks.shade.org.apache.thrift.transport.TTransportFactory; import org.junit.After; import org.junit.Before; public abstract class StarRocksSourceBaseTest { protected TableSchema TABLE_SCHEMA; protected TableSchema TABLE_SCHEMA_NOT_NULL; protected StarRocksSourceOptions OPTIONS; protected StarRocksSourceOptions OPTIONS_WITH_COLUMN_IS_COUNT; protected int[][] PROJECTION_ARRAY; protected SelectColumn[] SELECT_COLUMNS; protected int[][] PROJECTION_ARRAY_NULL; protected final String DATABASE = "test"; protected final String TABLE = "test_source"; protected final String USERNAME = "root"; protected final String PASSWORD = "root123"; private ServerSocket httpSocket; protected final int AVAILABLE_QUERY_PORT = 53329; protected final String JDBC_URL = "jdbc:mysql://127.0.0.1:53329,127.0.0.1:" + AVAILABLE_QUERY_PORT; protected final int AVAILABLE_HTTP_PORT = 29592; protected String SCAN_URL = "127.0.0.1:" + AVAILABLE_HTTP_PORT; private TServer thriftServer; private ServerSocket thriftSocket; protected int AVAILABLE_THRIFT_PORT = 21592; protected String mockResonse = ""; protected String querySQL = "select * from `test`.`test_source`"; protected int tabletCount = 50; @Before public void initializeCommon() { PROJECTION_ARRAY = new int[2][1]; PROJECTION_ARRAY[0] = new int[]{2}; PROJECTION_ARRAY[1] = new int[]{7}; PROJECTION_ARRAY_NULL = new int[0][0]; SELECT_COLUMNS = new SelectColumn[]{ new SelectColumn("char_1", 2), new SelectColumn("int_1", 7), }; } private void initializeCommonOptions() { StarRocksSourceOptions options = StarRocksSourceOptions.builder() .withProperty("scan-url", SCAN_URL) .withProperty("jdbc-url", JDBC_URL) .withProperty("username", USERNAME) .withProperty("password", PASSWORD) .withProperty("table-name", TABLE) .withProperty("database-name", DATABASE) .build(); OPTIONS = options; } private void initializeColumnIsCountOptions() { StarRocksSourceOptions options = StarRocksSourceOptions.builder() .withProperty("scan-url", SCAN_URL) .withProperty("jdbc-url", JDBC_URL) .withProperty("username", USERNAME) .withProperty("password", PASSWORD) .withProperty("table-name", DATABASE) .withProperty("database-name", TABLE) .withProperty("scan.columns", "count(1)") .build(); OPTIONS_WITH_COLUMN_IS_COUNT = options; } @Before public void initializeTableSchema() { TableSchema tableSchema = TableSchema.builder() .field("date_1", DataTypes.DATE()) .field("datetime_1", DataTypes.TIMESTAMP(6)) .field("char_1", DataTypes.CHAR(20)) .field("varchar_1", DataTypes.STRING()) .field("boolean_1", DataTypes.BOOLEAN()) .field("tinyint_1", DataTypes.TINYINT()) .field("smallint_1", DataTypes.SMALLINT()) .field("int_1", DataTypes.INT()) .field("bigint_1", DataTypes.BIGINT()) .field("largeint_1", DataTypes.STRING()) .field("float_1", DataTypes.FLOAT()) .field("double_1", DataTypes.DOUBLE()) .field("decimal_1", DataTypes.DECIMAL(27, 9)) .build(); TABLE_SCHEMA = tableSchema; } @Before public void initializeTableSchemaNotNull() { TableSchema tableSchema = TableSchema.builder() .field("date_1", DataTypes.DATE().notNull()) .field("datetime_1", DataTypes.TIMESTAMP(6).notNull()) .field("char_1", DataTypes.CHAR(20).notNull()) .field("varchar_1", DataTypes.STRING().notNull()) .field("boolean_1", DataTypes.BOOLEAN().notNull()) .field("tinyint_1", DataTypes.TINYINT().notNull()) .field("smallint_1", DataTypes.SMALLINT().notNull()) .field("int_1", DataTypes.INT().notNull()) .field("bigint_1", DataTypes.BIGINT().notNull()) .field("largeint_1", DataTypes.STRING().notNull()) .field("float_1", DataTypes.FLOAT().notNull()) .field("double_1", DataTypes.DOUBLE().notNull()) .field("decimal_1", DataTypes.DECIMAL(27, 9).notNull()) .build(); TABLE_SCHEMA_NOT_NULL = tableSchema; } @Before public void createHttpServer() throws IOException { tryBindingHttpServerSocket(); new Thread(new Runnable(){ @Override public void run() { try { while (true) { if (null == httpSocket || httpSocket.isClosed()) break; Socket ac = httpSocket.accept(); final Socket socket = ac; InputStream in = socket.getInputStream(); BufferedReader bd = new BufferedReader(new InputStreamReader(in)); String requestHeader; int contentLength = 0; while ((requestHeader = bd.readLine()) != null && !requestHeader.isEmpty()) { if (requestHeader.startsWith("Content-Length")) { int begin = requestHeader.indexOf("Content-Length") + "Content-Length:".length(); String postParamsLength = requestHeader.substring(begin).trim(); contentLength = Integer.parseInt(postParamsLength); } } StringBuffer sb = new StringBuffer(); if (contentLength > 0) { for (int i = 0; i < contentLength; i ++) { sb.append((char) bd.read()); } } assertEquals("{\"sql\":\""+ querySQL +"\"}", sb.toString()); PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println("HTTP/1.1 200 OK"); pw.println("Content-type:application/json"); pw.println(); pw.println(mockResonse); pw.flush(); socket.close(); } } catch (Exception e) {} } }).start(); } @Before public void createThriftServer() { tryBindingThriftServerSocket(); Thread thriftThread = new Thread(() -> { TStarrocksExternalService.Processor<StarrocksExternalServiceImpl> processor = new TStarrocksExternalService.Processor<>(new StarrocksExternalServiceImpl()); try (TServerTransport transport = new TServerSocket(thriftSocket)) { TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(transport); tArgs.processor(processor); tArgs.protocolFactory(new TBinaryProtocol.Factory()); tArgs.transportFactory(new TTransportFactory()); tArgs.minWorkerThreads(10); tArgs.maxWorkerThreads(20); thriftServer = new TThreadPoolServer(tArgs); thriftServer.serve(); } catch (TTransportException e) { e.printStackTrace(); } }); thriftThread.start(); } protected void mockResonsefunc() { String[] beNode = new String[]{ "127.0.0.1:" + AVAILABLE_THRIFT_PORT, "127.0.0.2:" + AVAILABLE_THRIFT_PORT, "127.0.0.3:" + AVAILABLE_THRIFT_PORT}; Map<String, Object> respMap = new HashMap<>(); respMap.put("opaqued_query_plan", "mockPlan"); respMap.put("status", "200"); Map<Integer, Object> partitionsSet = new HashMap<>(); for (int i = 0; i < tabletCount; i ++) { Map<String, Object> pMap = new HashMap<>(); pMap.put("version", 4); pMap.put("versionHash", 6318449679607016199L); pMap.put("schemaHash", 975114127); pMap.put("routings", new String[]{ beNode[i%beNode.length], beNode[i%beNode.length + 1 >= beNode.length ? 0 : i%beNode.length + 1] }); partitionsSet.put(i, pMap); } respMap.put("partitions", partitionsSet); JSONObject json = new JSONObject(respMap); mockResonse = json.toJSONString(); } protected void mockOneBeResonsefunc() { String[] beNode = new String[]{ "127.0.0.1:" + AVAILABLE_THRIFT_PORT}; Map<String, Object> respMap = new HashMap<>(); respMap.put("opaqued_query_plan", "mockPlan"); respMap.put("status", "200"); Map<Integer, Object> partitionsSet = new HashMap<>(); for (int i = 0; i < tabletCount; i ++) { Map<String, Object> pMap = new HashMap<>(); pMap.put("version", 4); pMap.put("versionHash", 6318449679607016199L); pMap.put("schemaHash", 975114127); pMap.put("routings", new String[]{ beNode[i%beNode.length], beNode[i%beNode.length + 1 >= beNode.length ? 0 : i%beNode.length + 1] }); partitionsSet.put(i, pMap); } respMap.put("partitions", partitionsSet); JSONObject json = new JSONObject(respMap); mockResonse = json.toJSONString(); } private void tryBindingHttpServerSocket() { int maxTryingPorts = 100; for (int i = 0; i < maxTryingPorts; i++) { try { int port = AVAILABLE_HTTP_PORT + i; httpSocket = new ServerSocket(port); SCAN_URL = "127.0.0.1:" + port; initializeCommonOptions(); initializeColumnIsCountOptions(); break; } catch (IOException e) {} } } private void tryBindingThriftServerSocket() { int maxTryingPorts = 100; for (int i = 0; i < maxTryingPorts; i++) { try { int port = AVAILABLE_THRIFT_PORT + i; thriftSocket = new ServerSocket(port); AVAILABLE_THRIFT_PORT = port; break; } catch (IOException e) {} } } @After public void stopHttpServer() throws IOException { if (httpSocket != null) { httpSocket.close(); } httpSocket = null; } @After public void stopThriftServer() { if (thriftServer != null) { thriftServer.stop(); } thriftServer = null; if (thriftSocket != null) { try { thriftSocket.close(); } catch (IOException e) {} } thriftSocket = null; } }
92419511a21179de6f7d4592f7cc0065d3d535f3
2,152
java
Java
src/main/java/q1000/Q958_CheckCompletenessOfABinaryTree.java
sunxuia/leetcode-solution-java
ad52d4b86e9cbbcfe10eb3dabd74a8b7b5d5add6
[ "MIT" ]
1
2020-10-13T06:08:14.000Z
2020-10-13T06:08:14.000Z
src/main/java/q1000/Q958_CheckCompletenessOfABinaryTree.java
sunxuia/leetcode-solution-java
ad52d4b86e9cbbcfe10eb3dabd74a8b7b5d5add6
[ "MIT" ]
null
null
null
src/main/java/q1000/Q958_CheckCompletenessOfABinaryTree.java
sunxuia/leetcode-solution-java
ad52d4b86e9cbbcfe10eb3dabd74a8b7b5d5add6
[ "MIT" ]
null
null
null
29.081081
118
0.636617
1,001,948
package q1000; import java.util.LinkedList; import java.util.Queue; import org.junit.runner.RunWith; import util.provided.TreeNode; import util.runner.Answer; import util.runner.LeetCodeRunner; import util.runner.TestData; import util.runner.data.DataExpectation; /** * [Medium] 958. Check Completeness of a Binary Tree * https://leetcode.com/problems/check-completeness-of-a-binary-tree/ * * Given a binary tree, determine if it is a complete binary tree. * * Definition of a complete binary tree from Wikipedia: * * In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last * level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. * * Example 1: * (图 Q958_PIC1.png) * Input: [1,2,3,4,5,6] * Output: true * Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the * last level ({4, 5, 6}) are as far left as possible. * * Example 2: * (图 Q958_PIC2.png) * Input: [1,2,3,4,5,null,7] * Output: false * Explanation: The node with value 7 isn't as far left as possible. * * Note: * * The tree will have between 1 and 100 nodes. */ @RunWith(LeetCodeRunner.class) public class Q958_CheckCompletenessOfABinaryTree { @Answer public boolean isCompleteTree(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node == null) { break; } queue.offer(node.left); queue.offer(node.right); } while (!queue.isEmpty()) { if (queue.poll() != null) { return false; } } return true; } @TestData public DataExpectation example1 = DataExpectation .create(TreeNode.createByLevel(1, 2, 3, 4, 5, 6)) .expect(true); @TestData public DataExpectation example2 = DataExpectation .create(TreeNode.createByLevel(1, 2, 3, 4, 5, null, 7)) .expect(false); }
9241953a79ce71c8392e9e72fcc184a3d1f6663c
4,863
java
Java
server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
78
2016-03-16T19:50:28.000Z
2022-01-29T10:36:15.000Z
server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
4,148
2015-09-14T15:59:06.000Z
2022-03-31T10:29:10.000Z
server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
64
2015-07-10T14:59:52.000Z
2021-12-24T09:40:29.000Z
46.759615
150
0.695455
1,001,949
/**************************************************************** * 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.james.webadmin.routes; import javax.inject.Inject; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.apache.james.task.TaskManager; import org.apache.james.webadmin.Constants; import org.apache.james.webadmin.Routes; import org.apache.james.webadmin.service.CassandraMappingsService; import org.apache.james.webadmin.tasks.TaskFromRequestRegistry; import org.apache.james.webadmin.tasks.TaskIdDto; import org.apache.james.webadmin.tasks.TaskRegistrationKey; import org.apache.james.webadmin.utils.JsonTransformer; import org.eclipse.jetty.http.HttpStatus; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; import spark.Route; import spark.Service; @Api(tags = "Cassandra Mappings Operations") @Path(CassandraMappingsRoutes.ROOT_PATH) @Produces(Constants.JSON_CONTENT_TYPE) public class CassandraMappingsRoutes implements Routes { public static final String ROOT_PATH = "cassandra/mappings"; private static final TaskRegistrationKey SOLVE_INCONSISTENCIES = TaskRegistrationKey.of("SolveInconsistencies"); private final CassandraMappingsService cassandraMappingsService; private final TaskManager taskManager; private final JsonTransformer jsonTransformer; private static final String INVALID_ACTION_ARGUMENT_REQUEST = "Invalid action argument for performing operation on mappings data"; private static final String ACTION_REQUEST_CAN_NOT_BE_DONE = "The action requested for performing operation on mappings data cannot be performed"; @Inject CassandraMappingsRoutes(CassandraMappingsService cassandraMappingsService, TaskManager taskManager, JsonTransformer jsonTransformer) { this.cassandraMappingsService = cassandraMappingsService; this.taskManager = taskManager; this.jsonTransformer = jsonTransformer; } @Override public String getBasePath() { return ROOT_PATH; } @Override public void define(Service service) { service.post(ROOT_PATH, performActionOnMappings(), jsonTransformer); } @POST @Path(ROOT_PATH) @ApiOperation(value = "Performing operations on cassandra data mappings") @ApiImplicitParams({ @ApiImplicitParam( required = true, dataType = "String", name = "action", paramType = "query", example = "?action=SolveInconsistencies", value = "Specify the action to perform on mappings. For now only 'SolveInconsistencies' is supported as an action, " + "and its purpose is to clean 'mappings_sources' projection table and repopulate it."), }) @ApiResponses(value = { @ApiResponse(code = HttpStatus.CREATED_201, message = "The taskId of the given scheduled task", response = TaskIdDto.class, responseHeaders = { @ResponseHeader(name = "Location", description = "URL of the resource associated with the scheduled task") }), @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = INVALID_ACTION_ARGUMENT_REQUEST), @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = ACTION_REQUEST_CAN_NOT_BE_DONE) }) public Route performActionOnMappings() { return TaskFromRequestRegistry.of(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies()) .asRoute(taskManager); } }
9241968a6c9a9a0926a8fff000f98610b032c257
5,523
java
Java
opensrp-goldsmith/src/main/java/org/smartregister/goldsmith/GoldsmithClientProcessor.java
opensrp/opensrp-client-goldsmith
563ed6390097573016c790498928ba597c937102
[ "Apache-2.0" ]
null
null
null
opensrp-goldsmith/src/main/java/org/smartregister/goldsmith/GoldsmithClientProcessor.java
opensrp/opensrp-client-goldsmith
563ed6390097573016c790498928ba597c937102
[ "Apache-2.0" ]
58
2020-08-10T08:29:44.000Z
2021-03-23T09:26:28.000Z
opensrp-goldsmith/src/main/java/org/smartregister/goldsmith/GoldsmithClientProcessor.java
opensrp/opensrp-client-goldsmith
563ed6390097573016c790498928ba597c937102
[ "Apache-2.0" ]
null
null
null
38.894366
169
0.615245
1,001,950
package org.smartregister.goldsmith; import android.content.ContentValues; import android.content.Context; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.smartregister.domain.Event; import org.smartregister.domain.Obs; import org.smartregister.domain.db.EventClient; import org.smartregister.goldsmith.processor.FamilyStructureRegistrationEventMiniProcessor; import org.smartregister.repository.EventClientRepository; import org.smartregister.sync.ClientProcessorForJava; import org.smartregister.view.activity.DrishtiApplication; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import timber.log.Timber; /** * Created by samuelgithengi on 11/9/20. */ public class GoldsmithClientProcessor extends ClientProcessorForJava { public GoldsmithClientProcessor(Context context) { super(context); addMiniProcessors(new FamilyStructureRegistrationEventMiniProcessor()); } public static ClientProcessorForJava getInstance(Context context) { if (instance == null) { instance = new GoldsmithClientProcessor(context); } return instance; } @Override public synchronized void processClient(List<EventClient> eventClientList) throws Exception { List<EventClient> local = new ArrayList<>(); List<EventClient> remote = new ArrayList<>(); for (EventClient eventClient : eventClientList) { if (StringUtils.isBlank(eventClient.getEvent().getEventId()) || eventClient.getEvent().getServerVersion() == 0L) { local.add(eventClient); } else { remote.add(eventClient); } } // TODO: Fix this issue at a better position // This is a pain for home visits which generate a lot of events for (EventClient eventClient : eventClientList) { Event event = eventClient.getEvent(); Map<String, String> details = event.getDetails(); if (details == null || !details.containsKey("planIdentifier")) { event.addDetails("planIdentifier", BuildConfig.PNC_PLAN_ID); JSONObject eventJson = DrishtiApplication.getInstance().getContext().getEventClientRepository().getEventsByFormSubmissionId(event.getFormSubmissionId()); if (eventJson.optJSONObject("details") == null) { eventJson.put("details", new JSONObject()); } eventJson.getJSONObject("details").put("planIdentifier", BuildConfig.PNC_PLAN_ID); updateEvent(event.getFormSubmissionId(), eventJson); } // TODO: Fix this in the event processing of each module later // This fixes an event where the event.obs.values can contain one item which is a literal null in JSON fixObsHavingNullValuesItem(event); Timber.i("Processing: %s", event.getEventType()); } super.processClient(local, true); super.processClient(remote); } protected void fixObsHavingNullValuesItem(Event event) throws JSONException { List<Obs> obsList = event.getObs(); if (obsList != null) { boolean obsUpdated = false; Obs[] obsArray = obsList.toArray(new Obs[]{}); for (int i = 0; i < obsArray.length; i++) { Obs observation = obsArray[i]; List<Object> observationValues = observation.getValues(); if (observationValues != null && observationValues.size() > 0 && observationValues.get(0) == null) { obsUpdated = true; observation.setValues(new ArrayList<>()); } } event.setObs(Arrays.asList(obsArray)); if (obsUpdated) { JSONObject eventJson = DrishtiApplication.getInstance().getContext().getEventClientRepository().getEventsByFormSubmissionId(event.getFormSubmissionId()); JSONArray obsJsonArray = eventJson.optJSONArray("obs"); if (obsJsonArray != null) { for (int i = 0; i < obsJsonArray.length(); i++) { JSONObject observation = obsJsonArray.optJSONObject(i); if (observation != null) { JSONArray valuesArray = observation.optJSONArray("values"); if (valuesArray != null && valuesArray.length() > 0) { observation.put("values", new JSONArray()); } } } } updateEvent(event.getFormSubmissionId(), eventJson); } } } public int updateEvent(String formSubmissionId, JSONObject eventJson) { try { ContentValues values = new ContentValues(); values.put(EventClientRepository.event_column.json.name(), eventJson.toString()); return DrishtiApplication.getInstance().getRepository().getWritableDatabase() .update(EventClientRepository.Table.event.name(), values, EventClientRepository.event_column.formSubmissionId.name() + " = ?", new String[]{formSubmissionId}); } catch (Exception e) { Timber.e(e); } return 0; } }
924197564f87154a0e3ea405d102fdbee5633449
274
java
Java
com/intkr/saas/dao/mms/EmailSignatureDAO.java
Beiden/Intkr_SAAS_BEIDEN
fb2b68f2e04a891523e3589dd3abebd2fcd5828d
[ "Apache-2.0" ]
null
null
null
com/intkr/saas/dao/mms/EmailSignatureDAO.java
Beiden/Intkr_SAAS_BEIDEN
fb2b68f2e04a891523e3589dd3abebd2fcd5828d
[ "Apache-2.0" ]
null
null
null
com/intkr/saas/dao/mms/EmailSignatureDAO.java
Beiden/Intkr_SAAS_BEIDEN
fb2b68f2e04a891523e3589dd3abebd2fcd5828d
[ "Apache-2.0" ]
1
2022-03-16T15:04:17.000Z
2022-03-16T15:04:17.000Z
17.125
70
0.729927
1,001,951
package com.intkr.saas.dao.mms; import com.intkr.saas.dao.BaseDAO; import com.intkr.saas.domain.dbo.mms.EmailSignatureDO; /** * * @author Beiden * @date 2017-03-13 18:55:30 * @version 1.0 */ public interface EmailSignatureDAO extends BaseDAO<EmailSignatureDO> { }
9241977c4008f84795dcd85a9f5c7bb2c86c8b7c
4,488
java
Java
app/src/main/java/com/tgcenter/demo/richox/activity/RichOXH5NativeActivity.java
webeyemob/HelloWeDemo
885079ac221981fd0fc1d70a8ed2a1c1ef0997b6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tgcenter/demo/richox/activity/RichOXH5NativeActivity.java
webeyemob/HelloWeDemo
885079ac221981fd0fc1d70a8ed2a1c1ef0997b6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tgcenter/demo/richox/activity/RichOXH5NativeActivity.java
webeyemob/HelloWeDemo
885079ac221981fd0fc1d70a8ed2a1c1ef0997b6
[ "Apache-2.0" ]
1
2021-06-28T09:31:58.000Z
2021-06-28T09:31:58.000Z
35.0625
129
0.496435
1,001,952
package com.tgcenter.demo.richox.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.richox.sdk.RichOXH5Error; import com.richox.sdk.core.scene.NativeScene; import com.richox.sdk.core.scene.SceneListener; import com.tgcenter.demo.R; import com.tgcenter.demo.ads.base.BaseActivity; import com.tgcenter.demo.richox.constance.Constants; public class RichOXH5NativeActivity extends BaseActivity { private static final String TAG = Constants.TAG; private TextView mEnter; private TextView mShow; private ImageView mIconView; private TextView mTitleView; private TextView mDescView; private TextView mCTAView; private ViewGroup mLayoutRoot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_richox_h5_native); initView(); } private void initView() { mIconView = findViewById(R.id.native_icon); mTitleView = findViewById(R.id.native_title); mDescView = findViewById(R.id.native_desc); mCTAView = findViewById(R.id.native_cta); mLayoutRoot = findViewById(R.id.native_root_layout); mEnter = findViewById(R.id.native_load); NativeScene scene = new NativeScene(getApplicationContext(), "50076"); mEnter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scene.setSceneListener(new SceneListener() { @Override public void onLoaded() { Log.d(TAG, "on loaded"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "加载成功", Toast.LENGTH_SHORT).show(); } }); } @Override public void onLoadFailed(RichOXH5Error error) { Log.d(TAG, "on onLoadFailed"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "加载失败:" + error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public void onShown() { Log.d(TAG, "on onShown"); } @Override public void onRenderSuccess() { } @Override public void onRenderFailed(RichOXH5Error error) { } @Override public void onClick() { Log.d(TAG, "on onClick"); } @Override public void onClose() { Log.d(TAG, "on onClose"); } }); scene.load(); } }); mShow = findViewById(R.id.native_show); mShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (scene.isReady()) { NativeScene.NativeInfo info = scene.getNativeInfo(); if (info != null) { mTitleView.setText(info.getTitle()); mDescView.setText(info.getDesc()); mCTAView.setText(info.getCTA()); Glide.with(RichOXH5NativeActivity.this) .load(info.getIconUrl()) .into(mIconView); scene.reportSceneShown(); mLayoutRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scene.showScene(); } }); } } } }); } }
924197d560d93a642bceb36e06a77fe108a0a780
1,547
java
Java
sample/src/main/java/com/lany192/box/sample/lifecycle/ActivityLifecycle.java
lany192/box
83de2eac887bee4e295be2aca54556424e3a5cc3
[ "Apache-2.0" ]
3
2021-12-25T15:01:01.000Z
2022-03-02T01:31:36.000Z
sample/src/main/java/com/lany192/box/sample/lifecycle/ActivityLifecycle.java
lany192/box
83de2eac887bee4e295be2aca54556424e3a5cc3
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/lany192/box/sample/lifecycle/ActivityLifecycle.java
lany192/box
83de2eac887bee4e295be2aca54556424e3a5cc3
[ "Apache-2.0" ]
null
null
null
31.571429
131
0.752424
1,001,953
package com.lany192.box.sample.lifecycle; import android.app.Activity; import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; import com.alibaba.android.arouter.launcher.ARouter; import com.elvishew.xlog.XLog; import com.github.lany192.interfaces.SimpleActivityLifecycleCallbacks; /** * Activity生命周期 */ public class ActivityLifecycle implements SimpleActivityLifecycleCallbacks { private final FragmentLifecycle fragmentLifecycle = new FragmentLifecycle(); @CallSuper @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { //给Activity界面注入参数 ARouter.getInstance().inject(activity); if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycle, false); } } @Override public void onActivityResumed(@NonNull Activity activity) { } @Override public void onActivityPaused(@NonNull Activity activity) { } @CallSuper @Override public void onActivityDestroyed(@NonNull Activity activity) { XLog.tag(activity.getClass().getSimpleName()).i(" onActivityDestroyed()"); if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager().unregisterFragmentLifecycleCallbacks(fragmentLifecycle); } } }
9241987ec807c08c04a4510da43de866a6a0da5c
856
java
Java
Java_11_error/src/test/java/log/HelloWorld.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
1
2021-03-01T08:33:42.000Z
2021-03-01T08:33:42.000Z
Java_11_error/src/test/java/log/HelloWorld.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
6
2021-03-10T23:33:09.000Z
2022-03-31T20:01:07.000Z
Java_11_error/src/test/java/log/HelloWorld.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
1
2021-03-01T08:33:44.000Z
2021-03-01T08:33:44.000Z
23.777778
102
0.713785
1,001,954
/** * */ package log; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * @author LiY * @time 下午2:20:45 */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class HelloWorld { @Test public static void test() { final Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); final Foo foo = new Foo(); foo.setVar(5); final Collection<String> list = Arrays.asList("stream", "string"); final List<String> filtered = list.stream().filter(s -> s.startsWith("s")).map(s -> s.toUpperCase()) .collect(Collectors.toList()); assertThat(Foo.testMethod()); final var list1 = new ArrayList<String>(); } }
9241989fa7eb840a439da2828c46e25939b9fb0f
679
java
Java
src/test/java/com/heynt/permutation/tests/LetterFrequenciesTest.java
cnibley/permutation-cipher
993c29ba621ce3443027e23bf2c297262e38d67d
[ "MIT" ]
null
null
null
src/test/java/com/heynt/permutation/tests/LetterFrequenciesTest.java
cnibley/permutation-cipher
993c29ba621ce3443027e23bf2c297262e38d67d
[ "MIT" ]
null
null
null
src/test/java/com/heynt/permutation/tests/LetterFrequenciesTest.java
cnibley/permutation-cipher
993c29ba621ce3443027e23bf2c297262e38d67d
[ "MIT" ]
null
null
null
26.115385
84
0.670103
1,001,955
package com.heynt.permutation.tests; import java.util.Collection; import com.heynt.permutation.types.LetterFrequenciesMap; //import junit.framework.Assert; public class LetterFrequenciesTest { /** * This test loosely sees that we have the right frequencies for all the letters */ public void allLetterFrequenciesShouldSumTo103() { Integer total = 0; Collection<Integer> allValues = LetterFrequenciesMap.MAP.values(); for (Integer value : allValues) { total += value; } // The total should be 103 when adding up all the frequencies // Assert.assertEquals(103, total.intValue()); } }
924198e5dc9e6f75a44d76a882f57a7be973dbd7
732
java
Java
minimeca-api/src/main/java/com/allyes/minimec/api/config/TopicRabbitConfig.java
liuwei-daer/minimec-full
3c16e5230a96eb55c7f0ddccdd41b0074df4034f
[ "Apache-2.0" ]
null
null
null
minimeca-api/src/main/java/com/allyes/minimec/api/config/TopicRabbitConfig.java
liuwei-daer/minimec-full
3c16e5230a96eb55c7f0ddccdd41b0074df4034f
[ "Apache-2.0" ]
null
null
null
minimeca-api/src/main/java/com/allyes/minimec/api/config/TopicRabbitConfig.java
liuwei-daer/minimec-full
3c16e5230a96eb55c7f0ddccdd41b0074df4034f
[ "Apache-2.0" ]
null
null
null
23.612903
89
0.678962
1,001,956
package com.allyes.minimec.api.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author liuwei * @date 2018-03-16 */ //@Configuration public class TopicRabbitConfig { // final static String message = "topic.message"; // // @Bean // public Queue queueMessage() { // return new Queue(TopicRabbitConfig.message); // } // // @Bean // public TopicExchange exchange() { // return new TopicExchange("exchange"); // } // // @Bean // public Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { // return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); // } }
9241992d4ee47ee690d6ff40fef8b252f006904b
4,509
java
Java
core/src/main/java/com/facebook/testing/screenshot/internal/RecordBuilderImpl.java
Opportunitylivetv/screenshot-tests-for-android
2393328abf64afefcb031d251f32f780014be671
[ "BSD-3-Clause" ]
1
2018-02-28T07:42:32.000Z
2018-02-28T07:42:32.000Z
core/src/main/java/com/facebook/testing/screenshot/internal/RecordBuilderImpl.java
martina6hall/screenshot-tests-for-android
2393328abf64afefcb031d251f32f780014be671
[ "BSD-3-Clause" ]
null
null
null
core/src/main/java/com/facebook/testing/screenshot/internal/RecordBuilderImpl.java
martina6hall/screenshot-tests-for-android
2393328abf64afefcb031d251f32f780014be671
[ "BSD-3-Clause" ]
1
2018-02-28T07:42:45.000Z
2018-02-28T07:42:45.000Z
24.241935
100
0.674429
1,001,957
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * <p>This source code is licensed under the BSD-style license found in the LICENSE file in the root * directory of this source tree. An additional grant of patent rights can be found in the PATENTS * file in the same directory. */ package com.facebook.testing.screenshot.internal; import android.graphics.Bitmap; import android.view.View; import com.facebook.testing.screenshot.RecordBuilder; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.HashMap; import java.util.Map; /** * A builder for all the metadata associated with a screenshot. * * <p>Use Screenshot#snap() or Screenshot#snapActivity() to get an instance of this, and commit the * record with #record(). */ public class RecordBuilderImpl implements RecordBuilder { private final ScreenshotImpl mScreenshotImpl; private final Map<String, String> mExtras = new HashMap<>(); private String mDescription; private String mName; private String mTestClass; private String mTestName; private String mError; private String mGroup; private Tiling mTiling = new Tiling(1, 1); private View mView; /* package */ RecordBuilderImpl(ScreenshotImpl screenshotImpl) { mScreenshotImpl = screenshotImpl; } public String getDescription() { return mDescription; } /** @inherit */ @Override public RecordBuilderImpl setDescription(String description) { mDescription = description; return this; } public String getName() { if (mName == null) { return getTestClass() + "_" + getTestName(); } return mName; } /** @inherit */ @Override public RecordBuilderImpl setName(String name) { CharsetEncoder charsetEncoder = Charset.forName("latin-1").newEncoder(); if (!charsetEncoder.canEncode(name)) { throw new IllegalArgumentException( "Screenshot names must have only latin characters: " + name); } if (name.contains(File.separator)) { throw new IllegalArgumentException( "Screenshot names cannot contain '" + File.separator + "': " + name); } mName = name; return this; } public String getTestName() { return mTestName; } /** * Set the name of the test from which this screenshot is generated. This should be detected by * default most of the time. */ public RecordBuilderImpl setTestName(String testName) { mTestName = testName; return this; } public String getTestClass() { return mTestClass; } /** * Set the class name of the TestCase from which this screenshot is generated. This should be * detected by default most of the time. */ public RecordBuilderImpl setTestClass(String testClass) { mTestClass = testClass; return this; } /** @inherit */ @Override public Bitmap getBitmap() { return mScreenshotImpl.getBitmap(this); } /** * Returns true if this record has been given an explicit name using setName(). If false, * getName() will still generate a name. */ public boolean hasExplicitName() { return mName != null; } /** Get's any error that was encountered while creating the screenshot. */ public String getError() { return mError; } RecordBuilderImpl setError(String error) { mError = error; return this; } /** @inherit */ @Override public void record() { mScreenshotImpl.record(this); checkState(); } /** Sanity checks that the record is ready to be persisted */ void checkState() { if (mError != null) { return; } for (int i = 0; i < mTiling.getWidth(); i++) { for (int j = 0; j < mTiling.getHeight(); j++) { if (mTiling.getAt(i, j) == null) { throw new IllegalStateException("expected all tiles to be filled"); } } } } public View getView() { return mView; } RecordBuilderImpl setView(View view) { mView = view; return this; } public Tiling getTiling() { return mTiling; } RecordBuilderImpl setTiling(Tiling tiling) { mTiling = tiling; return this; } @Override public RecordBuilderImpl addExtra(String key, String value) { mExtras.put(key, value); return this; } public Map<String, String> getExtras() { return mExtras; } public String getGroup() { return mGroup; } @Override public RecordBuilderImpl setGroup(String groupName) { mGroup = groupName; return this; } }
92419937bd8ec6b255c31da855a1279b5ca50949
4,398
java
Java
src/main/java/org/ggp/base/player/gamer/statemachine/sample/BeastMonteCarloTreeSearch.java
mattmahowald/cmd_shift_n_gamer
f417b8b001c1ab28bac7f0a5e43e0a2d193a9019
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/ggp/base/player/gamer/statemachine/sample/BeastMonteCarloTreeSearch.java
mattmahowald/cmd_shift_n_gamer
f417b8b001c1ab28bac7f0a5e43e0a2d193a9019
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/ggp/base/player/gamer/statemachine/sample/BeastMonteCarloTreeSearch.java
mattmahowald/cmd_shift_n_gamer
f417b8b001c1ab28bac7f0a5e43e0a2d193a9019
[ "BSD-3-Clause" ]
null
null
null
32.577778
134
0.718963
1,001,958
package org.ggp.base.player.gamer.statemachine.sample; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.ggp.base.util.statemachine.MachineState; import org.ggp.base.util.statemachine.Move; import org.ggp.base.util.statemachine.Role; import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException; import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException; import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException; public final class BeastMonteCarloTreeSearch extends SampleGamer { //Global Variable for the root of the MCST Node root; //Call initially to begin building the tree @Override public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { root = new Node(getCurrentState(), 0, 0, null, new ArrayList<Node>(), null); //stateMachineSelectMove(timeout); } @Override public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { long start = System.currentTimeMillis(); //Leaves 3 Seconds to then make the final decision while (System.currentTimeMillis() - start < timeout - 3000) { Node currNode = select(root); expand(currNode); int result = monteCarlo(currNode.state, 4); backPropogate(currNode, result); } int highestScore = 0; Move action = null; Node newRoot = null; for (int i = 0; i < root.children.size(); i++) { if (root.children.get(i).utility > highestScore) { highestScore = root.children.get(i).utility; action = root.children.get(i).action; newRoot = root.children.get(i); } } root = newRoot; //updates the root return action; //returns the final action } private Node select(Node node) { if (node.visits == 0) return node; for (int i = 0; i < node.children.size(); i++) { if (node.children.get(i).visits == 0) return node.children.get(i); } double score = 0; Node result = node; for (int i = 0; i < node.children.size(); i++) { double newScore = selectfn(node.children.get(i)); if (newScore > score) { score = newScore; result = node.children.get(i); } } return select(result); } private double selectfn(Node node) { return (node.utility + Math.sqrt( (double) 2*Math.log(node.parent.visits)/node.visits)); } private void expand(Node node) throws MoveDefinitionException, TransitionDefinitionException { List<Move> actions = getStateMachine().findLegals(getRole(), node.state); for (int i = 0; i < actions.size(); i++) { ArrayList<Move> moves = new ArrayList<Move>(); moves.add(actions.get(i)); MachineState newState = getStateMachine().findNext(moves, node.state); Node newNode = new Node(newState, 0, 0, node, new ArrayList<Node>(), actions.get(i)); node.children.add(newNode); } } private void backPropogate(Node node, int score) { node.visits++; node.utility += score; if (node.parent != null) backPropogate(node.parent, score); } private int monteCarlo(MachineState state, int count) throws MoveDefinitionException, GoalDefinitionException, TransitionDefinitionException { int total = 0; for (int i = 0; i < count; i++) { total += depthCharge(state); } return total / count; } private int depthCharge(MachineState state) throws MoveDefinitionException, GoalDefinitionException, TransitionDefinitionException { if (getStateMachine().findTerminalp(state)) return getStateMachine().findReward(getRole(), state); ArrayList<Move> moves = new ArrayList<Move>(); List<Role> roles = getStateMachine().findRoles(); for (int i = 0; i < roles.size(); i++) { List<Move> options = getStateMachine().findLegals(roles.get(i), state); Random r = new Random(); int randomMove = r.nextInt(options.size()); moves.add(options.get(randomMove)); } MachineState newState = getStateMachine().findNext(moves, state); return depthCharge(newState); } private class Node { int visits; int utility; MachineState state; Node parent; ArrayList<Node> children; Move action; public Node(MachineState state, int utility, int visits, Node parent, ArrayList<Node> children, Move action) { this.state = state; this.visits = visits; this.utility = utility; this.parent = parent; this.children = children; this.action = action; } } }
9241995848f1810afdb245a014cb68edacac7f78
142
java
Java
T07ReflectionAndAnnotation/exercise/P04_05BarracksWars/barracksWars/interfaces/Executable.java
1vaPetkova/JavaOOP
e9144e430e54515224fd38d9056489b3d920635f
[ "MIT" ]
null
null
null
T07ReflectionAndAnnotation/exercise/P04_05BarracksWars/barracksWars/interfaces/Executable.java
1vaPetkova/JavaOOP
e9144e430e54515224fd38d9056489b3d920635f
[ "MIT" ]
null
null
null
T07ReflectionAndAnnotation/exercise/P04_05BarracksWars/barracksWars/interfaces/Executable.java
1vaPetkova/JavaOOP
e9144e430e54515224fd38d9056489b3d920635f
[ "MIT" ]
null
null
null
17.75
87
0.838028
1,001,959
package T07ReflectionAndAnnotation.exercise.P04_05BarracksWars.barracksWars.interfaces; public interface Executable { String execute(); }
92419b13fb3bd737da8f232dc55ae8a533a2a753
1,387
java
Java
vertx-pin/zero-crud/src/main/java/io/vertx/tp/crud/uca/input/AdUpdatePre.java
evgreenhua/vertx-zero
e4fd363516427a13dd9664a06d8a49ed16be1e9f
[ "Apache-2.0" ]
454
2017-11-12T09:00:21.000Z
2022-03-10T14:26:04.000Z
vertx-pin/zero-crud/src/main/java/io/vertx/tp/crud/uca/input/AdUpdatePre.java
evgreenhua/vertx-zero
e4fd363516427a13dd9664a06d8a49ed16be1e9f
[ "Apache-2.0" ]
56
2017-11-28T05:36:25.000Z
2022-03-26T14:19:57.000Z
vertx-pin/zero-crud/src/main/java/io/vertx/tp/crud/uca/input/AdUpdatePre.java
evgreenhua/vertx-zero
e4fd363516427a13dd9664a06d8a49ed16be1e9f
[ "Apache-2.0" ]
103
2017-11-07T00:49:59.000Z
2022-03-31T10:22:59.000Z
29.510638
79
0.631579
1,001,960
package io.vertx.tp.crud.uca.input; import io.vertx.core.Future; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.User; import io.vertx.tp.crud.refine.Ix; import io.vertx.tp.crud.uca.desk.IxMod; import io.vertx.tp.ke.atom.specification.KField; import io.vertx.tp.ke.atom.specification.KModule; import io.vertx.up.unity.Ux; import io.vertx.up.util.Ut; import java.util.Objects; /** * @author <a href="http://www.origin-x.cn">Lang</a> */ class AdUpdatePre implements Pre { @Override public Future<JsonObject> inJAsync(final JsonObject data, final IxMod in) { /* UserId */ this.auditor(data, in); return Ux.future(data); } private void auditor(final JsonObject data, final IxMod in) { /* UserId */ final User user = in.user(); final KModule module = in.module(); if (Objects.nonNull(user)) { final String userId = Ux.keyUser(user); if (Ut.notNil(userId)) { final KField field = module.getField(); /* Created */ Ix.onAuditor(data, field.getUpdated(), userId); } } } @Override public Future<JsonArray> inAAsync(final JsonArray data, final IxMod in) { Ut.itJArray(data).forEach(json -> this.auditor(json, in)); return Ux.future(data); } }
92419b3a0e91a91854a470447d274a5ffa1a1a08
8,841
java
Java
Reveilles-Reels/GUI/AllContent.java
Zachhi/ReveillesReels
c01b4ce4f2777604181246ba144801411f6df519
[ "MIT" ]
1
2022-01-12T23:08:46.000Z
2022-01-12T23:08:46.000Z
Reveilles-Reels/GUI/AllContent.java
Zachhi/ReveillesReels
c01b4ce4f2777604181246ba144801411f6df519
[ "MIT" ]
null
null
null
Reveilles-Reels/GUI/AllContent.java
Zachhi/ReveillesReels
c01b4ce4f2777604181246ba144801411f6df519
[ "MIT" ]
1
2022-02-26T06:34:17.000Z
2022-02-26T06:34:17.000Z
33.11236
181
0.645289
1,001,961
import java.awt.*; import javax.swing.*; import javax.swing.border.Border; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import java.util.ArrayList; public class AllContent extends JPanel implements ActionListener { public static final int WIDTH = 1200; public static final int HEIGHT = 900; public static final Color MAROON = new Color(80, 0, 0); private JButton searchBtn = new JButton("Search"); private JButton backBtn = new JButton("Home"); private Connection conn; private JTextArea contentList; private JScrollPane contentListScroll; public AllContent() { super(); setSize(WIDTH, HEIGHT); // width,height setBackground(MAROON); conn = null; try { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection("jdbc:postgresql://csce-315-db.engr.tamu.edu/csce315903_13db", "csce315903_13user", "31590313"); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); } //JOptionPane.showMessageDialog(null,"Opened database successfully"); String name = ""; try{ //create a statement object Statement stmt = conn.createStatement(); String sqlStatement = "SELECT * FROM content LIMIT 1000"; //send statement to DBMS ResultSet result = stmt.executeQuery(sqlStatement); while (result.next()) { name += result.getString("title")+", "; name += result.getString("release_date")+", "; name += result.getString("title_type")+"\n"; } } catch (Exception e){ JOptionPane.showMessageDialog(null,"Error accessing Database."); } //setLayout(null); If i set to null unable to see buttons //JPanel jp2 = new JPanel(); GridBagLayout layout = new GridBagLayout(); setLayout(layout); GridBagConstraints c = new GridBagConstraints(); //All Content Button create searchBtn.setPreferredSize(new Dimension(100, 50)); searchBtn.addActionListener(this); backBtn.addActionListener(this); //create title Label JLabel titLabel = new JLabel("All Content"); titLabel.setFont(new Font("TimesRoman", Font.PLAIN, 50)); titLabel.setForeground(Color.WHITE); titLabel.setHorizontalAlignment(SwingConstants.CENTER); // create text area contentList = new JTextArea(name); contentList.setEditable(false); contentListScroll = new JScrollPane(contentList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //add labels c.fill = GridBagConstraints.BOTH; c.gridwidth = 3; c.gridheight = 1; c.weighty = 1; c.weightx = 1; c.ipady = 0; c.gridx = 0; c.gridy = 1; layout.setConstraints(titLabel, c); add(titLabel); //add text area c.gridx = 0; c.gridy = 2; c.gridwidth = 3; c.gridheight = 3; layout.setConstraints(contentListScroll, c); add(contentListScroll); // Buttons Added c.fill = GridBagConstraints.VERTICAL; c.ipady = 0; c.gridx = 2; c.gridy=0; c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.FIRST_LINE_START; layout.setConstraints(searchBtn, c); add(searchBtn); c.fill = GridBagConstraints.VERTICAL; c.ipady = 0; c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.FIRST_LINE_END; layout.setConstraints(backBtn, c); add(backBtn); try { conn.close(); // JOptionPane.showMessageDialog(null,"Connection Closed."); } catch(Exception e) { JOptionPane.showMessageDialog(null,"Connection NOT Closed."); } } @Override public void actionPerformed(ActionEvent e) { JButton button = (JButton)e.getSource(); JPanel buttonPanel = (JPanel)button.getParent(); JPanel cardPanel = (JPanel)buttonPanel.getParent(); CardLayout layout = (CardLayout)cardPanel.getLayout(); if(button == searchBtn) { JPanel panel = new JPanel(new GridLayout(5, 3)); JTextField titleLabel = new JTextField("Title"); JTextField titleText = new JTextField(10); JTextField genreLabel = new JTextField("Genre"); JTextField genreText = new JTextField(10); JTextField directorLabel = new JTextField("Director"); JTextField directorText = new JTextField(10); JTextField actorLabel = new JTextField("Actor"); JTextField actorText = new JTextField(10); String s1[] = {"All", "Movie", "Series"}; JComboBox<String> typeMenu = new JComboBox<String>(s1); titleLabel.setEditable(false); genreLabel.setEditable(false); directorLabel.setEditable(false); panel.add(titleLabel); panel.add(titleText); panel.add(genreLabel); panel.add(genreText); panel.add(directorLabel); panel.add(directorText); panel.add(actorLabel); panel.add(actorText); panel.add(typeMenu); JOptionPane.showMessageDialog(null, panel); try { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection("jdbc:postgresql://csce-315-db.engr.tamu.edu/csce315903_13db", "csce315903_13user", "31590313"); } catch (Exception es) { es.printStackTrace(); System.err.println(es.getClass().getName()+": "+es.getMessage()); System.exit(0); } String name = ""; try{ //create a statement object Statement stmt1 = conn.createStatement(); //create an SQL statement String sqlStatement = "SELECT * FROM content"; ArrayList<String> searchFields = new ArrayList<String>(); int whereCount = 0; if (!actorText.getText().equals("")) { // only has genre query rght now searchFields.add(" INNER JOIN (SELECT * FROM ACTORS INNER JOIN PEOPLE ON PEOPLE.PEOPLE_ID = ACTORS.PEOPLE_ID)a_p ON CONTENT.CONTENT_ID = a_p.content_id"); if (whereCount == 0) { searchFields.add(" WHERE name LIKE \'%\' || \'" + actorText.getText() + "\' || \'%\'"); whereCount++; } else { searchFields.add(" AND name LIKE \'%\' || \'" + actorText.getText() + "\' || \'%\'"); whereCount++; } } if (!directorText.getText().equals("")) { // only has director query now searchFields.add(" INNER JOIN (SELECT * FROM STAFF INNER JOIN PEOPLE ON STAFF.PEOPLE_ID = PEOPLE.PEOPLE_ID WHERE ROLE = 'director')s_p ON CONTENT.CONTENT_ID = s_p.content_id"); if (whereCount == 0) { searchFields.add(" WHERE name LIKE \'%\' || \'" + directorText.getText() + "\' || \'%\'"); whereCount++; } else { searchFields.add(" AND name LIKE \'%\' || \'" + directorText.getText() + "\' || \'%\'"); whereCount++; } } if (!(titleText.getText()).equals("")) { if (whereCount == 0) { searchFields.add(" WHERE title LIKE \'%\' || \'" + titleText.getText() + "\' || \'%\'"); whereCount++; } else { searchFields.add(" AND title LIKE \'%\' || \'" + titleText.getText() + "\' || \'%\'"); whereCount++; } } if (!genreText.getText().equals("")) { if (whereCount == 0) { searchFields.add(" WHERE genre LIKE \'%\' || \'" + genreText.getText() + "\' || \'%\'"); whereCount++; } else { searchFields.add(" AND genre LIKE \'%\' || \'" + genreText.getText() + "\' || \'%\'"); whereCount++; } } if (!typeMenu.getSelectedItem().equals("All")) { if (whereCount == 0) { String command = " WHERE title_type LIKE \'%\' || \'" + typeMenu.getSelectedItem() + "\' || \'%\'"; command += " OR title_type LIKE \'%\' || \'" + ((String) typeMenu.getSelectedItem()).toLowerCase() + "\' || \'%\'"; searchFields.add(command); whereCount++; } else { String command = " AND title_type LIKE \'%\' || \'" + typeMenu.getSelectedItem() + "\' || \'%\'"; command += " OR title_type LIKE \'%\' || \'" + ((String) typeMenu.getSelectedItem()).toLowerCase() + "\' || \'%\'"; searchFields.add(command); whereCount++; } } for (int i = 0; i < searchFields.size(); i++) { sqlStatement += searchFields.get(i); } sqlStatement += " ORDER BY title ASC LIMIT 1000;"; //send statement to DBMS ResultSet result = stmt1.executeQuery(sqlStatement); while (result.next()) { name += result.getString("title")+", "; name += result.getString("release_date") + ", "; name += result.getString("title_type")+"\n"; } if (name.equals("")) { JOptionPane.showMessageDialog(null, "Invalid Search. Try again."); } contentList.setText(name); try { conn.close(); // JOptionPane.showMessageDialog(null,"Connection Closed."); } catch(Exception et) { JOptionPane.showMessageDialog(null,"Connection NOT Closed."); } } catch (Exception em){ JOptionPane.showMessageDialog(null,"Error accessing Database."); } // layout.show(cardPanel, "allContent"); System.out.println("End of if"); } else if (button == backBtn) { layout.show(cardPanel, "clientPanel"); } } }
92419b42d02e9a5b5c10a0e9ad959ec646914a5f
54,243
java
Java
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/ImportServiceImpl.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
4
2017-03-22T16:57:42.000Z
2020-04-07T17:34:41.000Z
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/ImportServiceImpl.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
216
2016-06-23T14:02:32.000Z
2021-08-31T17:11:24.000Z
mneme-project/mneme/mneme-impl/impl/src/java/org/etudes/mneme/impl/ImportServiceImpl.java
mpellicer/sakai
cbccc0a810107050f284e7213183b2ecdfc1dd3a
[ "ECL-2.0" ]
4
2016-07-26T07:23:42.000Z
2020-10-07T12:21:53.000Z
27.618635
144
0.680493
1,001,962
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Etudes, Inc. * * Portions completed before September 1, 2008 * Copyright (c) 2007, 2008 The Regents of the University of Michigan & Foothill College, ETUDES Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.etudes.mneme.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.etudes.mneme.api.Assessment; import org.etudes.mneme.api.AssessmentPermissionException; import org.etudes.mneme.api.AssessmentService; import org.etudes.mneme.api.AttachmentService; import org.etudes.mneme.api.Ent; import org.etudes.mneme.api.GradesService; import org.etudes.mneme.api.ImportService; import org.etudes.mneme.api.MnemeService; import org.etudes.mneme.api.MnemeTransferService; import org.etudes.mneme.api.Pool; import org.etudes.mneme.api.PoolService; import org.etudes.mneme.api.Question; import org.etudes.mneme.api.QuestionService; import org.etudes.mneme.api.SecurityService; import org.etudes.util.DateHelper; import org.etudes.util.HtmlHelper; import org.etudes.util.api.Translation; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.content.cover.ContentTypeImageService; import org.sakaiproject.db.api.SqlReader; import org.sakaiproject.db.api.SqlService; import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.i18n.InternationalizedMessages; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * ImportServiceImpl implements ImportService * </p> */ public class ImportServiceImpl implements ImportService { public class AttachmentInfo { String fileName = null; Boolean isLink = null; String itemId = null; String mimeType = null; String ref = null; } public class PoolInfo { String description = null; String title = null; } public class SamigoQuestion { String answerMatchText; Integer answerSeq; Boolean caseSensitive; Boolean correct; String correctFeedback; Boolean exclusive; String generalFeedback; String incorrectFeedback; String instruction; String itemId; String questionChoiceText; Boolean randomize; Boolean reason; Float score; Integer type; } /** * Sort the Ents by description, case insensitive */ protected class EntComparator implements Comparator { public int compare(Object arg0, Object arg1) { int rv = ((Ent) arg0).getDescription().toLowerCase().compareTo(((Ent) arg1).getDescription().toLowerCase()); return rv; } } /** * Sort the Ents by term id */ protected class EntTermComparator implements Comparator { public int compare(Object arg0, Object arg1) { return (int) (((Ent) arg1).getTermId() - ((Ent) arg0).getTermId()); } } /** Our logger. */ private static Log M_log = LogFactory.getLog(ImportServiceImpl.class); /** Dependency: AssessmentService */ protected AssessmentService assessmentService = null; /** Dependency: AttachmentService */ protected AttachmentService attachmentService = null; /** Dependency: AuthzGroupService */ protected AuthzGroupService authzGroupService = null; /** Messages bundle name. */ protected String bundle = null; /** Dependency: EntityManager */ protected EntityManager entityManager = null; /** Dependency: EventTrackingService */ protected EventTrackingService eventTrackingService = null; /** Dependency: GradesService */ protected GradesService gradesService = null; /** Messages. */ protected transient InternationalizedMessages messages = null; /** Configuration: offer import from Samigo support. */ protected Boolean offerAssignment = Boolean.TRUE; /** Configuration: offer import from assignments support. */ protected Boolean offerSamigo = Boolean.TRUE; /** Dependency: PoolService */ protected PoolService poolService = null; /** Dependency: QuestionService */ protected QuestionService questionService = null; /** Dependency: SecurityService */ protected SecurityService securityService = null; /** Dependency: SessionManager */ protected SessionManager sessionManager = null; /** Dependency: SiteService */ protected SiteService siteService = null; /** Dependency: SqlService */ protected SqlService sqlService = null; /** Dependency: ThreadLocalManager. */ protected ThreadLocalManager threadLocalManager = null; /** Dependency: AssessmentService */ protected MnemeTransferService transferService = null; /** * Returns to uninitialized state. */ public void destroy() { M_log.info("destroy()"); } /** * {@inheritDoc} */ public List<Ent> getAssessments(String source, String destination) { List<Ent> rv = new ArrayList<Ent>(); List<Assessment> assessments = this.assessmentService.getContextAssessments(source, AssessmentService.AssessmentsSort.title_a, Boolean.FALSE); boolean includeFce = this.assessmentService.allowSetFormalCourseEvaluation(destination); // to check the title conflicts in the destination List<Assessment> existingAssessments = this.assessmentService.getContextAssessments(destination, AssessmentService.AssessmentsSort.cdate_a, Boolean.FALSE); // make an Ent from each assessment for (Assessment assessment : assessments) { // skip FCEs, unless user has permission if (assessment.getFormalCourseEval() && !includeFce) continue; Ent ent = new EntImpl(assessment.getId(), assessment.getTitle()); rv.add(ent); // mark any that have a title conflict in the destination for (Assessment candidate : existingAssessments) { if (!StringUtil.different(candidate.getTitle(), assessment.getTitle())) { ent.setMarked(Boolean.TRUE); break; } } } return rv; } /** * {@inheritDoc} */ public List<Ent> getAssignmentSites(String userId) { if (userId == null) userId = sessionManager.getCurrentSessionUserId(); return getAuthSites(userId, "asn.new", null); } /** * {@inheritDoc} */ public List<Ent> getMnemeSites(String userId, String context) { if (userId == null) userId = sessionManager.getCurrentSessionUserId(); return getAuthSites(userId, "mneme.manage", context); } /** * {@inheritDoc} */ public Boolean getOfferAssignment() { return this.offerAssignment; } /** * {@inheritDoc} */ public Boolean getOfferSamigo() { return this.offerSamigo; } /** * {@inheritDoc} */ public List<Ent> getSamigoAssessments(String context) { if (context == null) throw new IllegalArgumentException(); List<Ent> rv = readSamigoAssessments(context); Collections.sort(rv, new EntComparator()); return rv; } /** * {@inheritDoc} */ public List<Ent> getSamigoPools(String userId) { if (userId == null) userId = sessionManager.getCurrentSessionUserId(); List<Ent> rv = readSamigoPools(userId); // sort Collections.sort(rv, new EntComparator()); return rv; } /** * {@inheritDoc} */ public List<Ent> getSamigoSites(String userId) { if (userId == null) userId = sessionManager.getCurrentSessionUserId(); List<Ent> rv = new ArrayList<Ent>(); // get the authz groups in which this user has samigo permission Set refs = this.authzGroupService.getAuthzGroupsIsAllowed(userId, "assessment.createAssessment", null); for (Object o : refs) { String ref = (String) o; // each is a site ref Reference siteRef = this.entityManager.newReference(ref); // get the site display String display = this.siteService.getSiteDisplay(siteRef.getId()); // take only the site title (between first and last quotes) int firstPos = display.indexOf("\""); int lastPos = display.lastIndexOf("\""); if ((firstPos != -1) && (lastPos != -1)) { display = display.substring(firstPos + 1, lastPos); } // record for return Ent ent = new EntImpl(siteRef.getId(), display); rv.add(ent); } // sort Collections.sort(rv, new EntComparator()); return rv; } /** * {@inheritDoc} */ public void importAssessment(String id, String context) throws AssessmentPermissionException { // create the pool Pool pool = createAssessmentPool(id, context); if (pool != null) { // import the questions importSamigoAssessmentQuestions(id, pool); } } /** * {@inheritDoc} */ public List<Assessment> importMneme(Set<String> ids, String fromContext, String toContext) throws AssessmentPermissionException { return this.transferService.importFromSite(fromContext, toContext, ids); } /** * {@inheritDoc} */ public void importPool(String id, String context) throws AssessmentPermissionException { // create the pool Pool pool = createPool(id, context); if (pool != null) { // import the questions importSamigoPoolQuestions(id, pool); } } /** * Final initialization, once all dependencies are set. */ public void init() { // messages if (this.bundle != null) this.messages = new ResourceLoader(this.bundle); M_log.info("init()"); } /** * Dependency: AssessmentService. * * @param service * The AssessmentService. */ public void setAssessmentService(AssessmentService service) { this.assessmentService = service; } /** * Configuration: Assignment support. * * @param support * TRUE to offer support, FALSE to not. */ public void setAssignmentSupport(String support) { this.offerAssignment = Boolean.valueOf(support); } /** * Dependency: AttachmentService. * * @param service * The AttachmentService. */ public void setAttachmentService(AttachmentService service) { attachmentService = service; } /** * Dependency: AuthzGroupService. * * @param service * The AuthzGroupService. */ public void setAuthzGroupService(AuthzGroupService service) { authzGroupService = service; } /** * Set the message bundle. * * @param bundle * The message bundle. */ public void setBundle(String name) { this.bundle = name; } /** * Dependency: EntityManager. * * @param service * The EntityManager. */ public void setEntityManager(EntityManager service) { entityManager = service; } /** * Dependency: EventTrackingService. * * @param service * The EventTrackingService. */ public void setEventTrackingService(EventTrackingService service) { eventTrackingService = service; } /** * Dependency: GradesService. * * @param service * The GradesService. */ public void setGradesService(GradesService service) { gradesService = service; } /** * Set the PoolService. * * @param service * the PoolService. */ public void setPoolService(PoolService service) { this.poolService = service; } /** * Dependency: QuestionService. * * @param service * The QuestionService. */ public void setQuestionService(QuestionService service) { this.questionService = service; } /** * Configuration: Samigo support. * * @param support * TRUE to offer support, FALSE to not. */ public void setSamigoSupport(String support) { this.offerSamigo = Boolean.valueOf(support); } /** * Dependency: SecurityService. * * @param service * The SecurityService. */ public void setSecurityService(SecurityService service) { securityService = service; } /** * Dependency: SessionManager. * * @param service * The SessionManager. */ public void setSessionManager(SessionManager service) { sessionManager = service; } /** * Dependency: SiteService. * * @param service * The SiteService. */ public void setSiteService(SiteService service) { siteService = service; } /** * Dependency: SqlService. * * @param service * The SqlService. */ public void setSqlService(SqlService service) { sqlService = service; } /** * Dependency: ThreadLocalManager. * * @param service * The SqlService. */ public void setThreadLocalManager(ThreadLocalManager service) { threadLocalManager = service; } /** * Dependency: MnemeTransferService. * * @param service * The MnemeTransferService. */ public void setTransferService(MnemeTransferService service) { this.transferService = service; } /** * Add a formatted date to a source string, using a message selector. * * @param selector * The message selector. * @param source * The original string. * @param date * The date to format. * @return The source and date passed throught the selector message. */ protected String addDate(String selector, String source, Date date) { String fmt = DateHelper.formatDateForName(date, null); // the args Object[] args = new Object[2]; args[0] = source; args[1] = fmt; // format the works String rv = this.messages.getFormattedMessage(selector, args); return rv; } /** * Convert all references to embedded documents that have been imported to their new locations in the question and attachment data. * * @param questionData * The Samigo question data. * @param attachments * The attachments info. * @param translations * The translations for each imported embedded document reference. */ protected void convertDocumentsReferenced(List<SamigoQuestion> questionData, List<AttachmentInfo> attachments, List<Translation> translations) { for (Translation t : translations) { for (SamigoQuestion q : questionData) { if (q.answerMatchText != null) q.answerMatchText = this.attachmentService.translateEmbeddedReferences(q.answerMatchText, translations); if (q.correctFeedback != null) q.correctFeedback = this.attachmentService.translateEmbeddedReferences(q.correctFeedback, translations); if (q.generalFeedback != null) q.generalFeedback = this.attachmentService.translateEmbeddedReferences(q.generalFeedback, translations); if (q.incorrectFeedback != null) q.incorrectFeedback = this.attachmentService.translateEmbeddedReferences(q.incorrectFeedback, translations); if (q.instruction != null) q.instruction = this.attachmentService.translateEmbeddedReferences(q.instruction, translations); if (q.questionChoiceText != null) q.questionChoiceText = this.attachmentService.translateEmbeddedReferences(q.questionChoiceText, translations); } } for (AttachmentInfo a : attachments) { // not for links if ((a.isLink == null) || (!a.isLink.booleanValue())) { // find our translation for (Translation t : translations) { if (t.getFrom().equals(a.ref)) { a.ref = t.getTo(); break; } } } } } /** * Create a pool in Mneme from Samigo assessment information. * * @param assessmentId * The Samigo assessment id. * @return The pool, or null if it was not created. */ protected Pool createAssessmentPool(String assessmentId, final String context) throws AssessmentPermissionException { // read the details StringBuilder sql = new StringBuilder(); sql.append("SELECT A.TITLE FROM SAM_ASSESSMENTBASE_T A WHERE A.ID=?"); Object[] fields = new Object[1]; fields[0] = Long.valueOf(assessmentId); final PoolInfo info = new PoolInfo(); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { info.title = SqlHelper.readString(result, 1); info.description = null; return null; } catch (SQLException e) { M_log.warn("createAssessmentPool: reading pool details: " + e); return null; } } }); if (info.title != null) { Pool pool = this.poolService.newPool(context); pool.setTitle(addDate("import-text", info.title, new Date())); // pool.setDescription(info.description); this.poolService.savePool(pool); return pool; } return null; } /** * Create an essay question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @param upload * true for an upload type, false for inline. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createEssay(SamigoQuestion[] these, String attachments, Pool pool, boolean upload) throws AssessmentPermissionException { // validate: fist questionChoiceText for the question text not null boolean valid = (these[0].questionChoiceText != null); // there must be only one entry if (valid) { valid = (these.length == 1); } if (!valid) { M_log.info("createEssay: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:Essay"); EssayQuestionImpl e = (EssayQuestionImpl) (question.getTypeSpecificQuestion()); // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].questionChoiceText + attachments, true); question.getPresentation().setText(clean); // model answer if (these[0].answerMatchText != null) { clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].answerMatchText, true); e.setModelAnswer(clean); } // type e.setSubmissionType(upload ? EssayQuestionImpl.SubmissionType.attachments : EssayQuestionImpl.SubmissionType.inline); return question; } /** * Create a fillin question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @param text * true if text, false if numeric. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createFillin(SamigoQuestion[] these, String attachments, Pool pool, boolean text) throws AssessmentPermissionException { // validate: fist questionChoiceText for the question text not null boolean valid = (these[0].questionChoiceText != null); // answerMatchText from all for the choices not null if (valid) { for (int index = 0; index < these.length; index++) { if (these[index].answerMatchText == null) { valid = false; break; } } } if (!valid) { M_log.info("createFillin: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks"); FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion()); // detect these[0].exclusive and translate to our "any order" f.setAnyOrder(Boolean.FALSE.toString()); if ((these[0].exclusive != null) && (these[0].exclusive.booleanValue())) { // if we find that all the fill-in correct patterns are the same, // and there are is one for each answer (comma separated), // spread them out, one per fill-in, and set any-order boolean mutualExclusive = true; for (int index = 1; index < these.length; index++) { if (!these[index].answerMatchText.equals(these[0].answerMatchText)) { mutualExclusive = false; break; } } if (mutualExclusive) { String[] parts = these[0].answerMatchText.split("\\|"); if ((parts != null) && (parts.length == these.length)) { for (int index = 0; index < these.length; index++) { these[index].answerMatchText = parts[index]; } f.setAnyOrder(Boolean.TRUE.toString()); } } } // case sensitive if (these[0].caseSensitive != null) f.setCaseSensitive(these[0].caseSensitive.toString()); // text or numeric f.setResponseTextual(Boolean.toString(text)); // recreate the text, fillin in the "{}" with these answerMatchText String questionText = these[0].questionChoiceText; for (int index = 0; index < these.length; index++) { questionText = questionText.replaceFirst("\\{\\}", Matcher.quoteReplacement("{" + these[index].answerMatchText + "}")); } // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(questionText + attachments, true); f.setText(clean); return question; } /** * Create a Likert scale question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createLikert(SamigoQuestion[] these, String attachments, Pool pool) throws AssessmentPermissionException { // validate: fist questionChoiceText for the question text not null boolean valid = (these[0].questionChoiceText != null); // recognize a scale String scale = null; // "0" for our 5 point "strongly-agree" // "1" for our 4 point "excellent" // "2" for our 3 point "above-average" // "3" for our 2 point "yes" // "4" for our 5 point "5" // "5" for our 2 point "rocks" // 3 choices is below/average/above or disagree/undecided/agree if (these.length == 3) { if ("Below Average".equals(these[0].answerMatchText)) { scale = "2"; } else { scale = "0"; } } // 2 is yes/no, or agree / disagree else if (these.length == 2) { if ("No".equals(these[0].answerMatchText)) { scale = "3"; } else { scale = "0"; } } // 5 is strongly agree -> strongly disagree or unacceptable/below average/average/above average/excelent // or 1..5 else if (these.length == 5) { if ("1".equals(these[0].answerMatchText)) { scale = "4"; } else if ("Strongly Disagree".equals(these[0].answerMatchText)) { scale = "0"; } else { scale = "1"; } } // 10 is 1..10 else if (these.length == 10) { scale = "4"; } if (scale == null) { valid = false; } if (!valid) { M_log.info("createLikert: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:LikertScale"); LikertScaleQuestionImpl l = (LikertScaleQuestionImpl) (question.getTypeSpecificQuestion()); // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].questionChoiceText + attachments, true); question.getPresentation().setText(clean); // set the scale l.setScale(scale); return question; } /** * Create a match question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createMatch(SamigoQuestion[] these, String attachments, Pool pool) throws AssessmentPermissionException { // validate: fist instruction for the question text not null boolean valid = (these[0].instruction != null); // answerMatchText and questionChoiceText from all for the match and choices not null if (valid) { for (int index = 0; index < these.length; index++) { if ((these[index].answerMatchText == null) || (these[index].questionChoiceText == null)) { valid = false; break; } } } if (!valid) { M_log.info("createMatch: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:Match"); MatchQuestionImpl m = (MatchQuestionImpl) (question.getTypeSpecificQuestion()); // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].instruction + attachments, true); question.getPresentation().setText(clean); // set the # pairs m.consolidate("INIT:" + these.length); // set the pair values List<MatchQuestionImpl.MatchQuestionPair> pairs = m.getPairs(); for (int index = 0; index < these.length; index++) { clean = HtmlHelper.cleanAndAssureAnchorTarget(these[index].questionChoiceText, true); pairs.get(index).setChoice(clean); clean = HtmlHelper.cleanAndAssureAnchorTarget(these[index].answerMatchText, true); pairs.get(index).setMatch(clean); } return question; } /** * Create a multiple choice question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @param multiAllowed * true if we can have multiple answers, false if not. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createMc(SamigoQuestion[] these, String attachments, Pool pool, boolean multiAllowed) throws AssessmentPermissionException { // validate: fist questionChoiceText for the question text not null boolean valid = (these[0].questionChoiceText != null); // Note: answerMatchText may actually be null // we must have one or more marked correct boolean multiCorrect = false; if (valid) { boolean seenCorrect = false; for (int index = 0; index < these.length; index++) { if (these[index].answerMatchText != null) { if ((these[index].correct != null) && (these[index].correct.booleanValue())) { if (seenCorrect) multiCorrect = true; seenCorrect = true; } } } if (!seenCorrect) { valid = false; } } if (valid && multiCorrect && !multiAllowed) { valid = false; } if (!valid) { M_log.info("createMc: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:MultipleChoice"); MultipleChoiceQuestionImpl mc = (MultipleChoiceQuestionImpl) (question.getTypeSpecificQuestion()); // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].questionChoiceText + attachments, true); question.getPresentation().setText(clean); // randomize if (these[0].randomize != null) mc.setShuffleChoices(these[0].randomize.toString()); // single / multiple select mc.setSingleCorrect(Boolean.toString(!multiCorrect)); // set the choices List<String> choices = new ArrayList<String>(); for (int index = 0; index < these.length; index++) { if (these[index].answerMatchText != null) { clean = HtmlHelper.cleanAndAssureAnchorTarget(these[index].answerMatchText, true); choices.add(clean); } } mc.setAnswerChoices(choices); // corrects Set<Integer> correctAnswers = new HashSet<Integer>(); List<MultipleChoiceQuestionImpl.MultipleChoiceQuestionChoice> choicesAuthored = mc.getChoicesAsAuthored(); int authoredIndex = 0; for (int index = 0; index < these.length; index++) { if (these[index].answerMatchText != null) { if ((these[index].correct != null) && (these[index].correct.booleanValue())) { correctAnswers.add(Integer.valueOf(choicesAuthored.get(authoredIndex).getId())); } authoredIndex++; } } mc.setCorrectAnswerSet(correctAnswers); return question; } /** * Create a pool in Mneme from Samigo pool information. * * @param poolId * The Samigo pool id. * @return The pool, or null if it was not created. */ protected Pool createPool(String poolId, final String context) throws AssessmentPermissionException { // read the details StringBuilder sql = new StringBuilder(); sql.append("SELECT P.TITLE, P.DESCRIPTION FROM SAM_QUESTIONPOOL_T P WHERE P.QUESTIONPOOLID=?"); Object[] fields = new Object[1]; fields[0] = Long.valueOf(poolId); final PoolInfo info = new PoolInfo(); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { info.title = SqlHelper.readString(result, 1); info.description = SqlHelper.readString(result, 2); return null; } catch (SQLException e) { M_log.warn("createPool: reading pool details: " + e); return null; } } }); if (info.title != null) { Pool pool = this.poolService.newPool(context); pool.setTitle(addDate("import-text", info.title, new Date())); pool.setDescription(info.description); this.poolService.savePool(pool); return pool; } return null; } /** * Create a true false question from Samigo data. * * @param these * The Samigo data entries. * @param pool * The pool for the question. * @return The question, or null if it was not made * @throws AssessmentPermissionException */ protected Question createTf(SamigoQuestion[] these, String attachments, Pool pool) throws AssessmentPermissionException { // validate: fist questionChoiceText for the question text not null boolean valid = (these[0].questionChoiceText != null); // there must be two of these if (valid) { valid = (these.length == 2); } // they must have "true" and "false" marked in their answerMatchText if (valid) { valid = ("true".equals(these[0].answerMatchText) && "false".equals(these[1].answerMatchText)); } // one of these must be marked correct if (valid) { int count = 0; if ((these[0].correct != null) && (these[0].correct.booleanValue())) count++; if ((these[1].correct != null) && (these[1].correct.booleanValue())) count++; valid = (count == 1); } if (!valid) { M_log.info("createTf: invalid samigo question: " + these[0].itemId); return null; } // create the question Question question = this.questionService.newQuestion(pool, "mneme:TrueFalse"); TrueFalseQuestionImpl tf = (TrueFalseQuestionImpl) (question.getTypeSpecificQuestion()); // set the text String clean = HtmlHelper.cleanAndAssureAnchorTarget(these[0].questionChoiceText + attachments, true); question.getPresentation().setText(clean); // the correct answer tf.setCorrectAnswer((((these[0].correct != null) && (these[0].correct.booleanValue()))) ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); return question; } /** * Form html for attachments for this item. * * @param attachments * The attachments definitions. * @param id * The item id. * @return The html for attachments for this item. */ protected String formatAttachments(List<AttachmentInfo> attachments, String id) { StringBuilder attachmentsHtml = new StringBuilder(); for (AttachmentInfo a : attachments) { if (id.equals(a.itemId)) { if ((a.isLink != null) && (a.isLink.booleanValue())) { attachmentsHtml.append("<li><a href=\"" + a.fileName + "\" target=\"_blank\">" + a.fileName + "</a></li>"); } else { attachmentsHtml.append(formatRef(a.ref)); } } } if (attachmentsHtml.length() > 0) { attachmentsHtml.insert(0, "<p><ul>"); attachmentsHtml.append("</ul></p>"); } return attachmentsHtml.toString(); } /** * Form html for one attachment from a ref. * * @param refStr * The reference string. * @return The html for attachment. */ protected String formatRef(String refStr) { StringBuilder rv = new StringBuilder(); Reference ref = this.entityManager.newReference(refStr); // if we can't get the properties, assume that the attachment is to a deleted entity and skip it ResourceProperties props = ref.getProperties(); if (props != null) { try { // for folders if (props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION)) { rv.append("<li><img src=\"/library/image/" + ContentTypeImageService.getContentTypeImage("folder") + "\" style=\"border-style: none;\" />&nbsp;"); } // otherwise lookup the icon from the mime type else { String type = props.getProperty(ResourceProperties.PROP_CONTENT_TYPE); rv.append("<li><img src=\"/library/image/" + ContentTypeImageService.getContentTypeImage(type) + "\" style=\"border-style: none;\" alt=\"" + type + "\"/>&nbsp;"); } // the link rv.append("<a href=\"" + ref.getUrl() + "\" target=\"_blank\" title=\"" + Validator.escapeHtml(props.getPropertyFormatted("DAV:displayname")) + "\">" + Validator.escapeHtml(props.getPropertyFormatted("DAV:displayname")) + "</a>"); // size rv.append("&nbsp;(" + props.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH) + ")"); rv.append("</li>"); } catch (EntityPropertyNotDefinedException e) { } catch (EntityPropertyTypeException e) { } } return rv.toString(); } /** * Find the sites in which this user has this permission. * * @param userId * The user id. * @param permission * The security permission. * @param excludeContext * a context to skip. * @return The List of Ent's of sites in which this user has this permission. */ protected List<Ent> getAuthSites(String userId, String permission, String excludeContext) { List<Site> visibleSites = new ArrayList<Site>(); List<Site> hiddenSites = new ArrayList<Site>(); //this.siteService.getOrderedSites(userId, visibleSites, hiddenSites);//TODO List<Ent> rv = new ArrayList<Ent>(); for (Site site : visibleSites) { boolean ok = securityService.checkSecurity(userId, MnemeService.MANAGE_PERMISSION, site.getId()); if (ok) { if ((excludeContext != null) && site.getId().equals(excludeContext)) continue; // get the site display String display = this.siteService.getSiteDisplay(site.getId()); // take only the site title (between first and last quotes) int firstPos = display.indexOf("\""); int lastPos = display.lastIndexOf("\""); if ((firstPos != -1) && (lastPos != -1)) { display = display.substring(firstPos + 1, lastPos); } // record for return //Ent ent = new EntImpl(site.getId(), display, Long.parseLong(site.getTermId()), site.getTermDescription()); Ent ent = new EntImpl(site.getId(), display, 0, null); rv.add(ent); } } for (Site site : hiddenSites) { boolean ok = securityService.checkSecurity(userId, MnemeService.MANAGE_PERMISSION, site.getId()); if (ok) { if ((excludeContext != null) && site.getId().equals(excludeContext)) continue; // get the site display String display = this.siteService.getSiteDisplay(site.getId()); // take only the site title (between first and last quotes) int firstPos = display.indexOf("\""); int lastPos = display.lastIndexOf("\""); if ((firstPos != -1) && (lastPos != -1)) { display = display.substring(firstPos + 1, lastPos); } // record for return //Ent ent = new EntImpl(site.getId(), display, Long.parseLong(site.getTermId()), site.getTermDescription()); Ent ent = new EntImpl(site.getId(), display, 0, null); rv.add(ent); } } // get the authz groups in which this user has this permission Set refs = this.authzGroupService.getAuthzGroupsIsAllowed(userId, permission, null); for (Object o : refs) { String ref = (String) o; // each is a site ref Reference siteRef = this.entityManager.newReference(ref); // skip this one if ((excludeContext != null) && siteRef.getId().equals(excludeContext)) continue; // get the site display String display = this.siteService.getSiteDisplay(siteRef.getId()); // take only the site title (between first and last quotes) int firstPos = display.indexOf("\""); int lastPos = display.lastIndexOf("\""); if ((firstPos != -1) && (lastPos != -1)) { display = display.substring(firstPos + 1, lastPos); } // record for return Ent ent = new EntImpl(siteRef.getId(), display); rv.add(ent); } // sort //Collections.sort(rv, new EntTermComparator()); Collections.sort(rv, new EntComparator()); return rv; } /** * Collect all the attachment references in the Samigo question html data:<br /> * Anything referenced by a src= or href=. * * @param questionData * The Samigo question data. * @param attachments * The attachments info. * @return The set of attachment references. */ protected Set<String> harvestDocumentsReferenced(List<SamigoQuestion> questionData, List<AttachmentInfo> attachments) { Set<String> rv = new HashSet<String>(); // collect all the references for (SamigoQuestion q : questionData) { rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.answerMatchText, true)); rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.correctFeedback, true)); rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.generalFeedback, true)); rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.incorrectFeedback, true)); rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.instruction, true)); rv.addAll(this.attachmentService.harvestAttachmentsReferenced(q.questionChoiceText, true)); } for (AttachmentInfo a : attachments) { // not for links if ((a.isLink == null) || (!a.isLink.booleanValue())) { rv.addAll(this.attachmentService.harvestEmbedded(a.ref, true)); } } return rv; } /** * Import the embedded documents to the MnemeDocs for the pool's context. * * @param refs * The set of references to embedded document. * @param context * The destination context. * @return a Translation list for each imported document. */ protected List<Translation> importEmbeddedDocs(Set<String> refs, String context) { List<Translation> rv = this.attachmentService.importResources(AttachmentService.MNEME_APPLICATION, context, AttachmentService.DOCS_AREA, AttachmentService.NameConflictResolution.keepExisting, refs, AttachmentService.MNEME_THUMB_POLICY, AttachmentService.REFERENCE_ROOT); return rv; } /** * Import the questions from a Samigo assessment. * * @param assessmentId * The Samigo assessment id. * @param pool * The pool for the questions. */ protected void importSamigoAssessmentQuestions(String assessmentId, Pool pool) throws AssessmentPermissionException { // read the questions final List<SamigoQuestion> questionData = new ArrayList<SamigoQuestion>(); StringBuilder sql = new StringBuilder(); sql.append("SELECT "); sql.append(" I.ITEMID, I.TYPEID, I.SCORE, I.HASRATIONALE, I.INSTRUCTION, T.TEXT,"); sql.append(" A.TEXT, A.SEQUENCE, A.ISCORRECT,"); sql.append(" F1.TEXT, F2.TEXT, F3.TEXT,"); sql.append(" M1.ENTRY, M2.ENTRY, M3.ENTRY"); sql.append(" FROM SAM_SECTION_T S"); sql.append(" JOIN SAM_ITEM_T I ON I.SECTIONID=S.SECTIONID"); sql.append(" JOIN SAM_ITEMTEXT_T T ON I.ITEMID=T.ITEMID"); sql.append(" INNER JOIN SAM_SECTIONMETADATA_T M ON S.SECTIONID=M.SECTIONID AND M.LABEL='AUTHOR_TYPE' AND M.ENTRY='1'"); sql.append(" LEFT OUTER JOIN SAM_ANSWER_T A ON I.ITEMID=A.ITEMID AND ((I.TYPEID != 9) OR (A.ISCORRECT='1' AND A.ITEMTEXTID=T.ITEMTEXTID))"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F1 ON I.ITEMID=F1.ITEMID AND F1.TYPEID='INCORRECT FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F2 ON I.ITEMID=F2.ITEMID AND F2.TYPEID='CORRECT FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F3 ON I.ITEMID=F3.ITEMID AND F3.TYPEID='GENERAL FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M1 ON I.ITEMID=M1.ITEMID AND M1.LABEL='CASE_SENSITIVE'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M2 ON I.ITEMID=M2.ITEMID AND M2.LABEL='MUTUALLY_EXCLUSIVE'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M3 ON I.ITEMID=M3.ITEMID AND M3.LABEL='RANDOMIZE'"); sql.append(" WHERE S.ASSESSMENTID=?"); sql.append(" ORDER BY I.ITEMID ASC, A.SEQUENCE ASC "); Object[] fields = new Object[1]; fields[0] = Long.valueOf(assessmentId); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { SamigoQuestion sq = new SamigoQuestion(); questionData.add(sq); sq.itemId = SqlHelper.readId(result, 1); sq.type = SqlHelper.readInteger(result, 2); sq.score = SqlHelper.readFloat(result, 3); sq.reason = SqlHelper.readBitBoolean(result, 4); sq.instruction = SqlHelper.readString(result, 5); sq.questionChoiceText = SqlHelper.readString(result, 6); sq.answerMatchText = SqlHelper.readString(result, 7); sq.answerSeq = SqlHelper.readInteger(result, 8); sq.correct = SqlHelper.readBitBoolean(result, 9); sq.incorrectFeedback = SqlHelper.readString(result, 10); sq.correctFeedback = SqlHelper.readString(result, 11); sq.generalFeedback = SqlHelper.readString(result, 12); sq.caseSensitive = SqlHelper.readBitBoolean(result, 13); sq.exclusive = SqlHelper.readBitBoolean(result, 14); sq.randomize = SqlHelper.readBitBoolean(result, 15); return null; } catch (SQLException e) { M_log.warn("importSamigoQuestions-questions: " + e); return null; } } }); // read all attachment references for these questions final List<AttachmentInfo> attachments = new ArrayList<AttachmentInfo>(); sql = new StringBuilder(); sql.append("SELECT A.ITEMID, A.RESOURCEID, A.FILENAME, A.MIMETYPE, A.ISLINK"); sql.append(" FROM SAM_SECTION_T S"); sql.append(" JOIN SAM_ITEM_T I ON I.SECTIONID=S.SECTIONID"); sql.append(" JOIN SAM_ATTACHMENT_T A ON A.ITEMID=I.ITEMID"); sql.append(" WHERE S.ASSESSMENTID=?"); sql.append(" ORDER BY A.ATTACHMENTID ASC"); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { AttachmentInfo a = new AttachmentInfo(); attachments.add(a); a.itemId = SqlHelper.readId(result, 1); a.ref = SqlHelper.readString(result, 2); if (a.ref != null) a.ref = "/content" + a.ref; a.fileName = SqlHelper.readString(result, 3); a.mimeType = SqlHelper.readString(result, 4); a.isLink = SqlHelper.readBitBoolean(result, 5); return null; } catch (SQLException e) { M_log.warn("importSamigoQuestions-attachments: " + e); return null; } } }); // bring in these questions importSamigoQuestions(questionData, attachments, pool); } /** * Import the questions from a Samigo pool. * * @param poolId * The Samigo pool id. * @param pool * The pool for the questions. */ protected void importSamigoPoolQuestions(String poolId, Pool pool) throws AssessmentPermissionException { // read the questions final List<SamigoQuestion> questionData = new ArrayList<SamigoQuestion>(); StringBuilder sql = new StringBuilder(); sql.append("SELECT "); sql.append(" P.ITEMID, I.TYPEID, I.SCORE, I.HASRATIONALE, I.INSTRUCTION, T.TEXT,"); sql.append(" A.TEXT, A.SEQUENCE, A.ISCORRECT,"); sql.append(" F1.TEXT, F2.TEXT, F3.TEXT,"); sql.append(" M1.ENTRY, M2.ENTRY, M3.ENTRY"); sql.append(" FROM SAM_QUESTIONPOOLITEM_T P"); sql.append(" JOIN SAM_ITEM_T I ON P.ITEMID=I.ITEMID"); sql.append(" JOIN SAM_ITEMTEXT_T T ON P.ITEMID=T.ITEMID"); sql.append(" LEFT OUTER JOIN SAM_ANSWER_T A ON P.ITEMID=A.ITEMID AND ((I.TYPEID != 9) OR (A.ISCORRECT='1' AND A.ITEMTEXTID=T.ITEMTEXTID))"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F1 ON P.ITEMID=F1.ITEMID AND F1.TYPEID='INCORRECT FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F2 ON P.ITEMID=F2.ITEMID AND F2.TYPEID='CORRECT FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMFEEDBACK_T F3 ON P.ITEMID=F3.ITEMID AND F3.TYPEID='GENERAL FEEDBACK'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M1 ON P.ITEMID=M1.ITEMID AND M1.LABEL='CASE_SENSITIVE'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M2 ON P.ITEMID=M2.ITEMID AND M2.LABEL='MUTUALLY_EXCLUSIVE'"); sql.append(" LEFT OUTER JOIN SAM_ITEMMETADATA_T M3 ON P.ITEMID=M3.ITEMID AND M3.LABEL='RANDOMIZE'"); sql.append(" WHERE P.QUESTIONPOOLID=?"); sql.append(" ORDER BY P.ITEMID ASC, A.SEQUENCE ASC "); Object[] fields = new Object[1]; fields[0] = Long.valueOf(poolId); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { SamigoQuestion sq = new SamigoQuestion(); questionData.add(sq); sq.itemId = SqlHelper.readId(result, 1); sq.type = SqlHelper.readInteger(result, 2); sq.score = SqlHelper.readFloat(result, 3); sq.reason = SqlHelper.readBitBoolean(result, 4); sq.instruction = SqlHelper.readString(result, 5); sq.questionChoiceText = SqlHelper.readString(result, 6); sq.answerMatchText = SqlHelper.readString(result, 7); sq.answerSeq = SqlHelper.readInteger(result, 8); sq.correct = SqlHelper.readBitBoolean(result, 9); sq.incorrectFeedback = SqlHelper.readString(result, 10); sq.correctFeedback = SqlHelper.readString(result, 11); sq.generalFeedback = SqlHelper.readString(result, 12); sq.caseSensitive = SqlHelper.readBitBoolean(result, 13); sq.exclusive = SqlHelper.readBitBoolean(result, 14); sq.randomize = SqlHelper.readBitBoolean(result, 15); return null; } catch (SQLException e) { M_log.warn("importSamigoQuestions-questions: " + e); return null; } } }); // read all attachment references for these questions final List<AttachmentInfo> attachments = new ArrayList<AttachmentInfo>(); sql = new StringBuilder(); sql.append("SELECT A.ITEMID, A.RESOURCEID, A.FILENAME, A.MIMETYPE, A.ISLINK"); sql.append(" FROM SAM_ATTACHMENT_T A"); sql.append(" JOIN SAM_QUESTIONPOOLITEM_T P ON A.ITEMID=P.ITEMID AND P.QUESTIONPOOLID=?"); sql.append(" ORDER BY A.ATTACHMENTID ASC"); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { AttachmentInfo a = new AttachmentInfo(); attachments.add(a); a.itemId = SqlHelper.readId(result, 1); a.ref = SqlHelper.readString(result, 2); if (a.ref != null) a.ref = "/content" + a.ref; a.fileName = SqlHelper.readString(result, 3); a.mimeType = SqlHelper.readString(result, 4); a.isLink = SqlHelper.readBitBoolean(result, 5); return null; } catch (SQLException e) { M_log.warn("importSamigoQuestions-attachments: " + e); return null; } } }); // bring in these questions importSamigoQuestions(questionData, attachments, pool); } /** * Create questions from this data. * * @param questionData * The Samigo question data. * @param attachments * The attachments info. */ protected void importSamigoQuestions(List<SamigoQuestion> questionData, List<AttachmentInfo> attachments, Pool pool) throws AssessmentPermissionException { // find any additional docs references in the question data and attachments Set<String> docs = harvestDocumentsReferenced(questionData, attachments); // import those docs, returning the translation mapping List<Translation> translations = importEmbeddedDocs(docs, pool.getContext()); // modify the question and attachment data to reference the new doc locations convertDocumentsReferenced(questionData, attachments, translations); // build the questions float total = 0f; int count = 0; for (int i = 0; i < questionData.size(); i++) { SamigoQuestion sq = questionData.get(i); // accumulate the score for an average for the pool if (sq.score != null) { count++; total += sq.score.floatValue(); } // get the rest int next = i + 1; for (; next < questionData.size(); next++) { SamigoQuestion sqNext = questionData.get(next); if (!sqNext.itemId.equals(sq.itemId)) { next--; break; } } if (next == questionData.size()) next--; String attachmentsHtml = formatAttachments(attachments, sq.itemId); // we have from i .. next, inclusive SamigoQuestion[] these = new SamigoQuestion[(next - i) + 1]; for (int index = i; index <= next; index++) { these[index - i] = questionData.get(index); } i = next; Question question = null; switch (sq.type) { case 1: { // single correct question = createMc(these, attachmentsHtml, pool, false); break; } case 2: { // multi correct question = createMc(these, attachmentsHtml, pool, true); break; } case 3: { // mnemeType = "mneme:LikertScale"; question = createLikert(these, attachmentsHtml, pool); break; } case 4: { question = createTf(these, attachmentsHtml, pool); break; } case 5: { // inline essay question = createEssay(these, attachmentsHtml, pool, false); break; } case 6: { // upload essay question = createEssay(these, attachmentsHtml, pool, true); break; } case 8: { // text question = createFillin(these, attachmentsHtml.toString(), pool, true); break; } case 9: { question = createMatch(these, attachmentsHtml, pool); break; } case 11: { // numeric question = createFillin(these, attachmentsHtml, pool, false); break; } } if (question != null) { // reason if (sq.reason != null) question.setExplainReason(sq.reason); // feedback if (sq.generalFeedback != null) { question.setFeedback(sq.generalFeedback); } else if (sq.correctFeedback != null) { question.setFeedback(sq.correctFeedback); } else if (sq.incorrectFeedback != null) { question.setFeedback(sq.incorrectFeedback); } // save question.getTypeSpecificQuestion().consolidate(""); this.questionService.saveQuestion(question); } } // set the pool's points to the average if (count > 0) { Float average = Float.valueOf(total / count); pool.setPoints(average); this.poolService.savePool(pool); } } /** * Read the Samigo assessments for this context. * * @param context * The context. * @return The list of Ents describing the assessments for this context. */ protected List<Ent> readSamigoAssessments(String context) { final List<Ent> rv = new ArrayList<Ent>(); // test if the samigo table exists if (!tableExists("SAM_ASSESSMENTBASE_T")) return rv; StringBuilder sql = new StringBuilder(); sql.append("SELECT A.ID, A.TITLE FROM SAM_ASSESSMENTBASE_T A"); sql.append(" INNER JOIN SAM_AUTHZDATA_T Z ON A.ID=Z.QUALIFIERID AND Z.FUNCTIONID=? AND Z.AGENTID=?"); sql.append(" INNER JOIN SAM_SECTION_T S ON S.ASSESSMENTID=A.ID"); sql.append(" INNER JOIN SAM_SECTIONMETADATA_T M ON S.SECTIONID=M.SECTIONID AND M.LABEL='AUTHOR_TYPE' AND M.ENTRY='1'"); Object[] fields = new Object[2]; fields[0] = "EDIT_ASSESSMENT"; fields[1] = StringUtil.trimToNull(context); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String id = SqlHelper.readId(result, 1); String title = SqlHelper.readString(result, 2); Ent ent = new EntImpl(id, title); if (!rv.contains(ent)) rv.add(ent); return null; } catch (SQLException e) { M_log.warn("readSamigoAssessments: " + e); return null; } } }); return rv; } /** * Read the Samigo pools for this user id. * * @param userId * The user id. * @return The list of Ents describing the pools for this user id. */ protected List<Ent> readSamigoPools(String userId) { final List<Ent> rv = new ArrayList<Ent>(); // test if the samigo table exists if (!tableExists("SAM_QUESTIONPOOL_T")) return rv; StringBuilder sql = new StringBuilder(); sql.append("SELECT P.QUESTIONPOOLID, P.TITLE FROM SAM_QUESTIONPOOL_T P WHERE P.OWNERID=?"); Object[] fields = new Object[1]; fields[0] = StringUtil.trimToNull(userId); this.sqlService.dbRead(sql.toString(), fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String id = SqlHelper.readId(result, 1); String title = SqlHelper.readString(result, 2); Ent ent = new EntImpl(id, title); rv.add(ent); return null; } catch (SQLException e) { M_log.warn("readSamigoPools: " + e); return null; } } }); return rv; } /** * Check if this table exists. * * @param table * The table name. * @return true if the table exists, false if not. */ protected boolean tableExists(String table) { String sql = null; // for Oracle if (this.sqlService.getVendor().equals("oracle")) { sql = "SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME = '" + table + "'"; } // for MySQL else { sql = "SHOW TABLES LIKE '" + table + "'"; } List rv = this.sqlService.dbRead(sql); return !rv.isEmpty(); } }
92419b8cd9c7bce48561c4c46b4f55790fb195a4
1,046
java
Java
src/test/java/no/saua/remock/RemockContextConfigurationTest.java
ksaua/remock
096f6910da735b6a48263ae0b66bd10a06f485ec
[ "MIT" ]
20
2015-03-25T22:27:42.000Z
2020-03-26T11:08:25.000Z
src/test/java/no/saua/remock/RemockContextConfigurationTest.java
ksaua/remock
096f6910da735b6a48263ae0b66bd10a06f485ec
[ "MIT" ]
12
2015-03-03T21:13:42.000Z
2018-08-14T11:54:03.000Z
src/test/java/no/saua/remock/RemockContextConfigurationTest.java
ksaua/remock
096f6910da735b6a48263ae0b66bd10a06f485ec
[ "MIT" ]
5
2015-07-14T07:42:53.000Z
2018-08-25T16:45:10.000Z
32.6875
120
0.81262
1,001,963
package no.saua.remock; import no.saua.remock.RemockContextConfigurationTest.RemockConfig; import no.saua.remock.exampleapplication.AnInterfaceImplOne; import no.saua.remock.exampleapplication.AnInterfaceImplTwo; import no.saua.remock.exampleapplication.SomeServiceWithDependencies; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; /** * Tests {@link RemockContextConfiguration} correctly pulls in the remock annotations. */ @ContextConfiguration(classes = {SomeServiceWithDependencies.class, AnInterfaceImplOne.class, AnInterfaceImplTwo.class}) @RemockContextConfiguration(RemockConfig.class) public class RemockContextConfigurationTest extends CommonTest { @Inject private SomeServiceWithDependencies someServiceWithDependencies; @Test public void test() { isMock(someServiceWithDependencies.getDependency()); } @Reject(AnInterfaceImplTwo.class) @ReplaceWithMock(AnInterfaceImplOne.class) public static class RemockConfig { } }
92419b9d14056ef52229cf60ab95b4ce896bf07e
4,214
java
Java
guvnor-webapp/src/main/java/org/drools/guvnor/server/security/RoleBasedPermissionStore.java
Rikkola/guvnor
ee8f24c2a4a081dc4e7a85415dfd1fe4729da896
[ "Apache-2.0" ]
null
null
null
guvnor-webapp/src/main/java/org/drools/guvnor/server/security/RoleBasedPermissionStore.java
Rikkola/guvnor
ee8f24c2a4a081dc4e7a85415dfd1fe4729da896
[ "Apache-2.0" ]
null
null
null
guvnor-webapp/src/main/java/org/drools/guvnor/server/security/RoleBasedPermissionStore.java
Rikkola/guvnor
ee8f24c2a4a081dc4e7a85415dfd1fe4729da896
[ "Apache-2.0" ]
null
null
null
37.625
92
0.624347
1,001,964
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.server.security; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.drools.repository.RulesRepository; import org.drools.repository.security.PermissionManager; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; @Name("org.drools.guvnor.server.security.RoleBasedPermissionStore") @AutoCreate public class RoleBasedPermissionStore { @In public RulesRepository repository; public RoleBasedPermissionStore() { } public List<RoleBasedPermission> getRoleBasedPermissionsByUserName( String userName) { PermissionManager permissionManager = new PermissionManager(repository); List<RoleBasedPermission> permissions = new ArrayList<RoleBasedPermission>(); Map<String, List<String>> perms = permissionManager .retrieveUserPermissions(userName); for (Map.Entry<String, List<String>> permEntry : perms.entrySet()) { resolvePermissionsAndAdd( userName, permissions, permEntry ); } return permissions; } private void resolvePermissionsAndAdd(String userName, List<RoleBasedPermission> permissions, Map.Entry<String, List<String>> permEntry) { String roleType = permEntry.getKey(); if (RoleTypes.ADMIN.equals(roleType)) { permissions.add(new RoleBasedPermission(userName, RoleTypes.ADMIN, null, null)); } List<String> permissionsPerRole = permEntry.getValue(); for (String permissionPerRole : permissionsPerRole) { if (permissionPerRole.startsWith("package=")) { String packageName = permissionPerRole.substring("package=" .length()); permissions.add(new RoleBasedPermission(userName, roleType, packageName, null)); } else if (permissionPerRole.startsWith("category=")) { String categoryPath = permissionPerRole .substring("category=".length()); permissions.add(new RoleBasedPermission(userName, roleType, null, categoryPath)); } } } @SuppressWarnings("unchecked") public void addRoleBasedPermissionForTesting(String userName, RoleBasedPermission rbp) { PermissionManager permissionManager = new PermissionManager(repository); Map<String, List<String>> perms = permissionManager .retrieveUserPermissions(userName); Object permissionsPerRole = perms.get(rbp.getRole()); if (permissionsPerRole != null) { if (rbp.getPackageName() != null) { ((List<String>) permissionsPerRole).add("package=" + rbp.getPackageName()); } else if (rbp.getCategoryPath() != null) { ((List<String>) permissionsPerRole).add("category=" + rbp.getPackageName()); } } else { List<String> perm = new ArrayList<String>(); if (rbp.getPackageName() != null) { perm.add("package=" + rbp.getPackageName()); } else if (rbp.getCategoryPath() != null) { perm.add("category=" + rbp.getCategoryPath()); } perms.put(rbp.getRole(), perm); } permissionManager.updateUserPermissions(userName, perms); } }
92419bb5f7494e56f8d47b9ba2c219428ac1c75e
1,386
java
Java
src/test/java/no/unit/marc/Marc21RecordParserTest.java
BIBSYSDEV/marc21-xml-parser
13c2c7001a3ed9560658f945d22ed98a1ab720b0
[ "MIT" ]
1
2022-03-15T16:31:51.000Z
2022-03-15T16:31:51.000Z
src/test/java/no/unit/marc/Marc21RecordParserTest.java
BIBSYSDEV/marc21-xml-parser
13c2c7001a3ed9560658f945d22ed98a1ab720b0
[ "MIT" ]
11
2021-01-13T10:03:49.000Z
2022-03-30T01:26:59.000Z
src/test/java/no/unit/marc/Marc21RecordParserTest.java
BIBSYSDEV/marc21-xml-parser
13c2c7001a3ed9560658f945d22ed98a1ab720b0
[ "MIT" ]
null
null
null
39.6
112
0.767677
1,001,965
package no.unit.marc; import org.junit.jupiter.api.Test; import static no.unit.marc.TestData.INVALID_MARC21_XML_RECORD; import static no.unit.marc.TestData.VALID_MARC21_XML_RECORD; import static no.unit.marc.TestData.VALID_MARC21_XML_RECORD_ID; import static no.unit.marc.TestData.VALID_MARC21_XML_RECORD_TITLE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class Marc21RecordParserTest { @Test public void testXmlNotStartingWithRecordTag() { String recordWithWrongRootElement = "<recordData>" + VALID_MARC21_XML_RECORD + "</recordData>"; assertThrows(Marc21XmlParserException.class, () -> { Marc21RecordParser.getReferenceObjectFromMarc21XmlRecord(recordWithWrongRootElement); }); } @Test public void testXmlContainingErrors() { assertThrows(Marc21XmlParserException.class, () -> { Marc21RecordParser.getReferenceObjectFromMarc21XmlRecord(INVALID_MARC21_XML_RECORD); }); } @Test public void testParsing() throws Marc21XmlParserException { Reference reference = Marc21RecordParser.getReferenceObjectFromMarc21XmlRecord(VALID_MARC21_XML_RECORD); assertEquals(VALID_MARC21_XML_RECORD_ID, reference.getId()); assertEquals(VALID_MARC21_XML_RECORD_TITLE, reference.getMainTitle()); } }
92419c27265652b84bf03dabe2458d462b4fef2b
5,899
java
Java
terasoluna-gfw-common-libraries/terasoluna-gfw-web/src/test/java/org/terasoluna/gfw/web/token/transaction/TransactionTokenInfoStoreTest.java
sleepred/terasoluna-gfw
b5ae01ebbe456450dda530b4c2373037ad49461d
[ "Apache-2.0" ]
108
2015-01-14T03:13:45.000Z
2022-03-25T01:54:31.000Z
terasoluna-gfw-common-libraries/terasoluna-gfw-web/src/test/java/org/terasoluna/gfw/web/token/transaction/TransactionTokenInfoStoreTest.java
sleepred/terasoluna-gfw
b5ae01ebbe456450dda530b4c2373037ad49461d
[ "Apache-2.0" ]
734
2015-01-06T07:52:24.000Z
2022-03-31T08:12:02.000Z
terasoluna-gfw-common-libraries/terasoluna-gfw-web/src/test/java/org/terasoluna/gfw/web/token/transaction/TransactionTokenInfoStoreTest.java
sleepred/terasoluna-gfw
b5ae01ebbe456450dda530b4c2373037ad49461d
[ "Apache-2.0" ]
73
2015-01-20T02:01:56.000Z
2022-03-07T01:45:36.000Z
33.708571
152
0.701136
1,001,966
/* * Copyright(c) 2013 NTT DATA Corporation. * * 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.terasoluna.gfw.web.token.transaction; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.springframework.ui.Model; import org.springframework.web.method.HandlerMethod; public class TransactionTokenInfoStoreTest { TransactionTokenInfoStore store; @Before public void setup() { store = new TransactionTokenInfoStore(); } @Test public void testCreateTransactionTokenInfo01() throws Exception { HandlerMethod handlerMethod = new HandlerMethod(new TransactionTokenSampleController(), TransactionTokenSampleController.class .getDeclaredMethod("fourth", SampleForm.class, Model.class)); TransactionTokenInfo tokenInfo = store.createTransactionTokenInfo( handlerMethod); assertThat(tokenInfo, is(notNullValue())); } @Test public void testCreateTransactionTokenInfo02() throws Exception { HandlerMethod handlerMethod = new HandlerMethod(new TransactionTokenSampleController(), TransactionTokenSampleController.class .getDeclaredMethod("first", SampleForm.class, Model.class)); TransactionTokenInfo tokenInfo = store.createTransactionTokenInfo( handlerMethod); assertThat(tokenInfo, is(notNullValue())); } @Test public void testCreateTokenInfoName01() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = mock( TransactionTokenCheck.class); when(methodAnnotation.value()).thenReturn("test"); when(classAnnotation.value()).thenReturn("test"); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testCreateTokenInfoName02() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = null; when(methodAnnotation.value()).thenReturn("test"); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testCreateTokenInfoName03() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = null; when(methodAnnotation.value()).thenReturn(""); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testCreateTokenInfoName04() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = null; when(methodAnnotation.value()).thenReturn(null); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testCreateTokenInfoName05() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = mock( TransactionTokenCheck.class); when(methodAnnotation.value()).thenReturn("test"); when(classAnnotation.value()).thenReturn(""); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testCreateTokenInfoName06() throws Exception { TransactionTokenCheck methodAnnotation = mock( TransactionTokenCheck.class); TransactionTokenCheck classAnnotation = mock( TransactionTokenCheck.class); when(methodAnnotation.value()).thenReturn("test"); when(classAnnotation.value()).thenReturn(null); assertThat(store.createTokenName(classAnnotation, methodAnnotation), is( notNullValue())); } @Test public void testGetTransactionTokenInfo() throws NoSuchMethodException, SecurityException { HandlerMethod handlerMethod = new HandlerMethod(new TransactionTokenSampleController(), TransactionTokenSampleController.class .getDeclaredMethod("first", SampleForm.class, Model.class)); assertThat(store.getTransactionTokenInfo(handlerMethod), is( notNullValue())); } @Test public void testNamespaceCreateTransactionTokenInfo() throws Exception { HandlerMethod handlerMethod = new HandlerMethod(new TransactionTokenSampleNamespaceController(), TransactionTokenSampleNamespaceController.class .getDeclaredMethod("first")); TransactionTokenInfo tokenInfo = store.createTransactionTokenInfo( handlerMethod); assertThat(tokenInfo.getTokenName(), containsString( "testTokenAttrByNameSpace")); } }
92419c60a01344c99f68f7ff9a2214333df3a010
587
java
Java
testsrc/stc/TaskTest.java
singhsong/shiny-spoon
b60c47000440a2aa6cd42e3d919025fb1f2702a4
[ "MIT" ]
null
null
null
testsrc/stc/TaskTest.java
singhsong/shiny-spoon
b60c47000440a2aa6cd42e3d919025fb1f2702a4
[ "MIT" ]
3
2018-10-12T14:04:04.000Z
2018-10-12T14:07:44.000Z
testsrc/stc/TaskTest.java
singhsong/shiny-spoon
b60c47000440a2aa6cd42e3d919025fb1f2702a4
[ "MIT" ]
null
null
null
15.051282
91
0.589438
1,001,967
package stc; import com.singhblom.*; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class TaskTest { @Test void getTaskName() { Task testTask = new Task("Test task", "life", LocalDate.parse("2018-01-01"), true); assertEquals("Test task", testTask.getTaskName()); } @Test void setTaskName() { } @Test void getProjectName() { } @Test void setProjectName() { } @Test void getDueDate() { } @Test void setDueDate() { } }
92419dc3524a678c022485b1dd99186c6d3f96d3
372
java
Java
src/main/java/org/davidcampos/cassandra/commons/User.java
hands-on-tech/cassandra-jpa-example
82959085614240f3a304130a85f159735eb4de97
[ "MIT" ]
3
2018-11-20T08:53:50.000Z
2019-08-13T01:07:38.000Z
src/main/java/org/davidcampos/cassandra/commons/User.java
hands-on-tech/cassandra-jpa-example
82959085614240f3a304130a85f159735eb4de97
[ "MIT" ]
null
null
null
src/main/java/org/davidcampos/cassandra/commons/User.java
hands-on-tech/cassandra-jpa-example
82959085614240f3a304130a85f159735eb4de97
[ "MIT" ]
null
null
null
15.5
46
0.688172
1,001,968
package org.davidcampos.cassandra.commons; import java.util.UUID; public interface User { UUID getId(); void setId(UUID id); String getFirstName(); void setFirstName(final String firstName); String getLastName(); void setLastName(final String lastName); String getCity(); void setCity(final String city); String toString(); }
92419f718b78077c40edcf2391aeee919481e11c
389
java
Java
mobile_app1/module647/src/main/java/module647packageJava0/Foo13.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module647/src/main/java/module647packageJava0/Foo13.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module647/src/main/java/module647packageJava0/Foo13.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.441176
45
0.575835
1,001,969
package module647packageJava0; import java.lang.Integer; public class Foo13 { Integer int0; Integer int1; public void foo0() { new module647packageJava0.Foo12().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
92419f8474ed10a74c9af8aeb92e0bba2a98318d
426
java
Java
plugin2/src/main/java/com/hmj/demo/plugin2/Bean.java
humengjun/Dynamic_Plugin
51b43d0d2f1a8a9fb1091945a24e2ac6916d603b
[ "Apache-2.0" ]
null
null
null
plugin2/src/main/java/com/hmj/demo/plugin2/Bean.java
humengjun/Dynamic_Plugin
51b43d0d2f1a8a9fb1091945a24e2ac6916d603b
[ "Apache-2.0" ]
null
null
null
plugin2/src/main/java/com/hmj/demo/plugin2/Bean.java
humengjun/Dynamic_Plugin
51b43d0d2f1a8a9fb1091945a24e2ac6916d603b
[ "Apache-2.0" ]
null
null
null
18.521739
48
0.640845
1,001,970
package com.hmj.demo.plugin2; import com.hmj.demo.sharelibrary.IBean; public class Bean implements IBean { String value = "This is Plugin1"; @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public void setListener(Listener listener) { listener.onResult("bind success"); } }
9241a06173c99ee34f95093c4c5ede5033ac2596
1,165
java
Java
src/main/java/sa/sy/lxd/Project.java
xlmnxp/microcloud
6efb5e122d9113e24b7e547306cf063ad1d04fc7
[ "Unlicense" ]
1
2021-06-02T16:30:57.000Z
2021-06-02T16:30:57.000Z
src/main/java/sa/sy/lxd/Project.java
xlmnxp/microcloud
6efb5e122d9113e24b7e547306cf063ad1d04fc7
[ "Unlicense" ]
3
2021-05-06T15:31:03.000Z
2022-02-19T05:11:37.000Z
src/main/java/sa/sy/lxd/Project.java
xlmnxp/microcloud
6efb5e122d9113e24b7e547306cf063ad1d04fc7
[ "Unlicense" ]
null
null
null
25.326087
98
0.641202
1,001,971
package sa.sy.lxd; import elemental.json.JsonObject; import java.io.IOException; public class Project { private final Lxd client; private JsonObject project; private String name; private String description; private JsonObject config; private Instance[] usedBy; public Project(Lxd client, JsonObject project) throws Exception { this.client = client; this.project = project; this.name = this.project.getString("name"); this.description = this.project.getString("description"); this.config = this.project.getObject("config"); Instance[] instances = new Instance[this.project.getArray("used_by").length()]; for (int arrInd = 0; arrInd < instances.length; arrInd++) { instances[0] = client.getInstance(this.project.getArray("used_by").getString(arrInd)); } this.usedBy = instances; } public String getName() { return name; } public String getDescription() { return description; } public JsonObject getConfig() { return config; } public Instance[] getUsedBy() { return usedBy; } }
9241a067c90057c1915bc190fba599a40ae1a492
1,980
java
Java
src/main/java/Princeton/AlgorithmsI/kdTrees/PointSET.java
joeyhaohao/Algorithms-and-data-structures
f8148d62fff101d9556c2afb6ab672e7378f8f30
[ "MIT" ]
1
2020-08-31T20:23:24.000Z
2020-08-31T20:23:24.000Z
src/main/java/Princeton/AlgorithmsI/kdTrees/PointSET.java
joeyhaohao/Algorithms-and-data-structures
f8148d62fff101d9556c2afb6ab672e7378f8f30
[ "MIT" ]
null
null
null
src/main/java/Princeton/AlgorithmsI/kdTrees/PointSET.java
joeyhaohao/Algorithms-and-data-structures
f8148d62fff101d9556c2afb6ab672e7378f8f30
[ "MIT" ]
null
null
null
26.756757
122
0.634343
1,001,972
package Princeton.AlgorithmsI.kdTrees; import edu.princeton.cs.algs4.Point2D; import edu.princeton.cs.algs4.RectHV; import java.util.TreeSet; public class PointSET { private TreeSet<Point2D> pointSet; public PointSET(){ // construct an empty set of points pointSet = new TreeSet<Point2D>(); } public boolean isEmpty(){ // is the set empty? return pointSet.isEmpty(); } public int size(){ // number of points in the set return pointSet.size(); } public void insert(Point2D p){ // add the point to the set (if it is not already in the set) if (p==null) throw new java.lang.IllegalArgumentException(); pointSet.add(p); } public boolean contains(Point2D p){ // does the set contain point p? if (p==null) throw new java.lang.IllegalArgumentException(); return pointSet.contains(p); } public void draw(){ // draw all points to standard draw for (Point2D point: pointSet) point.draw(); } public Iterable<Point2D> range(RectHV rect){ // all points that are inside the rectangle (or on the boundary) if (rect==null) throw new java.lang.IllegalArgumentException(); TreeSet<Point2D> set = new TreeSet<Point2D>(); for (Point2D point: pointSet){ if (rect.contains(point)) set.add(point); } return set; } public Point2D nearest(Point2D p){ // a nearest neighbor in the set to point p; null if the set is empty if (p==null) throw new java.lang.IllegalArgumentException(); if (isEmpty()) return null; double minDis = Double.MAX_VALUE; Point2D nearestPt = null; for (Point2D point: pointSet){ if (point.distanceSquaredTo(p)<minDis){ nearestPt = point; minDis = point.distanceSquaredTo(p); } } return nearestPt; } public static void main(String[] args){ // unit testing of the methods (optional) } }
9241a07bf554bcdb6ccf383c07d3c439a0c04dc3
1,903
java
Java
src/main/java/com/authlete/jaxrs/spi/AuthorizationDecisionHandlerSpiAdapter.java
dcreado/authlete-java-jaxrs
fcacdf898b8cedec8885908dc1226bd018f61b50
[ "Apache-2.0" ]
14
2016-02-13T15:11:07.000Z
2021-08-04T11:37:18.000Z
src/main/java/com/authlete/jaxrs/spi/AuthorizationDecisionHandlerSpiAdapter.java
Exnadella/authlete-java-jaxrs
1978bbdba737e4d8667d3be90b5949e84f41c0cd
[ "Apache-2.0" ]
3
2018-05-08T17:55:57.000Z
2021-08-25T04:46:57.000Z
src/main/java/com/authlete/jaxrs/spi/AuthorizationDecisionHandlerSpiAdapter.java
Exnadella/authlete-java-jaxrs
1978bbdba737e4d8667d3be90b5949e84f41c0cd
[ "Apache-2.0" ]
8
2016-06-28T20:36:21.000Z
2021-08-03T17:00:59.000Z
20.031579
102
0.677352
1,001,973
/* * Copyright (C) 2016-2020 Authlete, 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.authlete.jaxrs.spi; import java.util.List; import com.authlete.common.assurance.VerifiedClaims; import com.authlete.common.assurance.constraint.VerifiedClaimsConstraint; import com.authlete.common.dto.Property; /** * Empty implementation of {@link AuthorizationDecisionHandlerSpi} interface. * * @author Takahiko Kawasaki */ public class AuthorizationDecisionHandlerSpiAdapter implements AuthorizationDecisionHandlerSpi { @Override public boolean isClientAuthorized() { return false; } @Override public long getUserAuthenticatedAt() { return 0; } @Override public String getUserSubject() { return null; } @Override public String getAcr() { return null; } @Override public Object getUserClaim(String claimName, String languageTag) { return null; } @Override public Property[] getProperties() { return null; } @Override public String[] getScopes() { return null; } @Override public String getSub() { return null; } @Override public List<VerifiedClaims> getVerifiedClaims(String subject, VerifiedClaimsConstraint constraint) { return null; } }