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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0b63d6e9baba7641ae6751109110761614a8a5 | 586 | java | Java | urule-core/src/main/java/com/bstek/urule/model/library/action/Parameter.java | lisongyan123/urule | 597b0659411486ab7a067ea8a2788f8ed6e75c20 | [
"Apache-2.0"
] | null | null | null | urule-core/src/main/java/com/bstek/urule/model/library/action/Parameter.java | lisongyan123/urule | 597b0659411486ab7a067ea8a2788f8ed6e75c20 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:11:34.000Z | 2021-09-20T21:01:11.000Z | urule-core/src/main/java/com/bstek/urule/model/library/action/Parameter.java | lisongyan123/urule | 597b0659411486ab7a067ea8a2788f8ed6e75c20 | [
"Apache-2.0"
] | null | null | null | 17.757576 | 60 | 0.634812 | 4,823 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.bstek.urule.model.library.action;
import com.bstek.urule.model.library.Datatype;
public class Parameter {
private String name;
private Datatype type;
public Parameter() {
}
public String getName() {
return this.name;
}
public void setName(String var1) {
this.name = var1;
}
public Datatype getType() {
return this.type;
}
public void setType(Datatype var1) {
this.type = var1;
}
}
|
3e0b65804b367544dd84b779fe9ae0941d629e01 | 1,475 | java | Java | orion-core/src/main/java/leemos/orion/remoting/ConnectionManager.java | leemos-xx/orion | 9099190e08d01329cf0b1fa0a9fc8f3ec5c67cb5 | [
"Apache-2.0"
] | 30 | 2021-07-22T08:51:36.000Z | 2022-03-16T02:32:53.000Z | orion-core/src/main/java/leemos/orion/remoting/ConnectionManager.java | leemos-xx/orion | 9099190e08d01329cf0b1fa0a9fc8f3ec5c67cb5 | [
"Apache-2.0"
] | 1 | 2022-02-27T08:58:14.000Z | 2022-02-27T08:58:14.000Z | orion-core/src/main/java/leemos/orion/remoting/ConnectionManager.java | leemos-xx/orion | 9099190e08d01329cf0b1fa0a9fc8f3ec5c67cb5 | [
"Apache-2.0"
] | null | null | null | 18.209877 | 69 | 0.595932 | 4,824 | package leemos.orion.remoting;
import java.util.List;
import leemos.orion.Lifecycle;
import leemos.orion.Scannable;
/**
* 连接管理器,用于维护连接池状态
*
* @author lihao
* @date 2020年8月11日
* @version 1.0
*/
public interface ConnectionManager extends Lifecycle, Scannable {
/**
* 将连接放入连接池{@link ConnectionPool}
*
* @param connection
*/
void add(Connection connection);
/**
* 从指定连接池{@link Connection}获取连接,当{@link ConnectionPool}中不存在可用连接时,
* 返回<code>null</code>
*
* @param poolKey
* @return
*/
Connection get(String poolKey);
/**
* 返回指定连接池{@link ConnectionPool}中的所有连接
*
* @param poolKey
* @return
*/
List<Connection> getAll(String poolKey);
/**
* 从所有连接池{@link ConnectionPool}中移除并关闭该连接
*
* @param connection
*/
void remove(Connection connection);
/**
* 从指定连接池{@link ConnectionPool}移除并关闭所有连接
*/
void removeAll();
/**
* 检查连接是否为可用状态
*
* @param connection
* @return
*/
boolean check(Connection connection);
/**
* 获取指定连接池{@link ConnectionPool}的可用连接数
*
* @param poolKey
* @return
*/
int count(String poolKey);
/**
* 通过url获取连接,如果为空,则创建连接
*
* @param url
* @return
* @throws RemotingException
* @throws InterruptedException
*/
Connection getAndCreateIfAbsent(Url url)
throws InterruptedException, RemotingException;
}
|
3e0b667cbc452792ea20a9fa3c265bc108d6a903 | 787 | java | Java | platform/duplicates-analysis/src/com/intellij/dupLocator/iterators/ArrayBackedNodeIterator.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 634 | 2015-01-01T19:14:25.000Z | 2022-03-22T11:42:50.000Z | platform/duplicates-analysis/src/com/intellij/dupLocator/iterators/ArrayBackedNodeIterator.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 410 | 2015-01-19T09:57:51.000Z | 2022-03-22T16:24:59.000Z | platform/duplicates-analysis/src/com/intellij/dupLocator/iterators/ArrayBackedNodeIterator.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 50 | 2015-03-10T04:14:49.000Z | 2022-03-22T07:08:45.000Z | 15.74 | 65 | 0.650572 | 4,825 | package com.intellij.dupLocator.iterators;
import com.intellij.psi.PsiElement;
/**
* Node iterator over array
*/
public final class ArrayBackedNodeIterator extends NodeIterator {
private final PsiElement[] nodes;
private int index;
public ArrayBackedNodeIterator(final PsiElement[] _nodes) {
nodes = _nodes;
index = 0;
}
@Override
public boolean hasNext() {
return index < nodes.length;
}
@Override
public void rewind(int number) {
index -= number;
}
@Override
public PsiElement current() {
if (index < nodes.length)
return nodes[index];
return null;
}
@Override
public void advance() {
++index;
}
@Override
public void rewind() {
--index;
}
@Override
public void reset() {
index = 0;
}
}
|
3e0b66eab3024730f857d8390a92eb562f103435 | 4,840 | java | Java | src/main/java/com/ms/bean/FeeFormBean.java | arpgupta/webmorningstar | af5d689166a953c6f8f05a738deb7648bc6897cb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ms/bean/FeeFormBean.java | arpgupta/webmorningstar | af5d689166a953c6f8f05a738deb7648bc6897cb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ms/bean/FeeFormBean.java | arpgupta/webmorningstar | af5d689166a953c6f8f05a738deb7648bc6897cb | [
"Apache-2.0"
] | null | null | null | 22.100457 | 81 | 0.686364 | 4,826 | /*******************************************************************************
* Copyright (c) 2017 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 com.ms.bean;
import java.util.List;
import com.ms.dto.FeeDTO;
import com.ms.dto.FeeMonthsDTO;
/**
* @author Amit.Agnihotri
*
*/
public class FeeFormBean extends FormBean{
private Integer studentId;
private Integer feeSummaryId;
private Byte[] selMonth;
private List<FeeMonthsDTO> monthList;
private List<FeeDTO> monthlyFeeList;
private List<FeeDTO> quarterlyFeeList;
private List<FeeDTO> halfyearlyFeeList;
private List<FeeDTO> anualFeeList;
private String totalAmt;
private String totalDiscAmt;
private String totalPaidAmt;
private String studentMSId;
private String studentName;
private String studentClass;
private String months;
/**
* @return the monthlyFeeList
*/
public List<FeeDTO> getMonthlyFeeList() {
return monthlyFeeList;
}
public List<FeeMonthsDTO> getMonthList() {
return monthList;
}
public void setMonthList(List<FeeMonthsDTO> monthList) {
this.monthList = monthList;
}
/**
* @param monthlyFeeList the monthlyFeeList to set
*/
public void setMonthlyFeeList(List<FeeDTO> monthlyFeeList) {
this.monthlyFeeList = monthlyFeeList;
}
/**
* @return the quarterlyFeeList
*/
public List<FeeDTO> getQuarterlyFeeList() {
return quarterlyFeeList;
}
/**
* @param quarterlyFeeList the quarterlyFeeList to set
*/
public void setQuarterlyFeeList(List<FeeDTO> quarterlyFeeList) {
this.quarterlyFeeList = quarterlyFeeList;
}
/**
* @return the halfyearlyFeeList
*/
public List<FeeDTO> getHalfyearlyFeeList() {
return halfyearlyFeeList;
}
/**
* @param halfyearlyFeeList the halfyearlyFeeList to set
*/
public void setHalfyearlyFeeList(List<FeeDTO> halfyearlyFeeList) {
this.halfyearlyFeeList = halfyearlyFeeList;
}
/**
* @return the anualFeeList
*/
public List<FeeDTO> getAnualFeeList() {
return anualFeeList;
}
/**
* @param anualFeeList the anualFeeList to set
*/
public void setAnualFeeList(List<FeeDTO> anualFeeList) {
this.anualFeeList = anualFeeList;
}
/**
* @return the studentId
*/
public Integer getStudentId() {
return studentId;
}
/**
* @param studentId the studentId to set
*/
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
/**
* @return the feeSummaryId
*/
public Integer getFeeSummaryId() {
return feeSummaryId;
}
/**
* @param feeSummaryId the feeSummaryId to set
*/
public void setFeeSummaryId(Integer feeSummaryId) {
this.feeSummaryId = feeSummaryId;
}
/**
* @return the totalAmt
*/
public String getTotalAmt() {
return totalAmt;
}
/**
* @param totalAmt the totalAmt to set
*/
public void setTotalAmt(String totalAmt) {
this.totalAmt = totalAmt;
}
/**
* @return the totalDiscAmt
*/
public String getTotalDiscAmt() {
return totalDiscAmt;
}
/**
* @param totalDiscAmt the totalDiscAmt to set
*/
public void setTotalDiscAmt(String totalDiscAmt) {
this.totalDiscAmt = totalDiscAmt;
}
/**
* @return the totalPaidAmt
*/
public String getTotalPaidAmt() {
return totalPaidAmt;
}
/**
* @param totalPaidAmt the totalPaidAmt to set
*/
public void setTotalPaidAmt(String totalPaidAmt) {
this.totalPaidAmt = totalPaidAmt;
}
/**
* @return the selMonth
*/
public Byte[] getSelMonth() {
return selMonth;
}
/**
* @param selMonth the selMonth to set
*/
public void setSelMonth(Byte[] selMonth) {
this.selMonth = selMonth;
}
/**
* @return the studentMSId
*/
public String getStudentMSId() {
return studentMSId;
}
/**
* @param studentMSId the studentMSId to set
*/
public void setStudentMSId(String studentMSId) {
this.studentMSId = studentMSId;
}
/**
* @return the studentName
*/
public String getStudentName() {
return studentName;
}
/**
* @param studentName the studentName to set
*/
public void setStudentName(String studentName) {
this.studentName = studentName;
}
/**
* @return the studentClass
*/
public String getStudentClass() {
return studentClass;
}
/**
* @param studentClass the studentClass to set
*/
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
/**
* @return the months
*/
public String getMonths() {
return months;
}
/**
* @param months the months to set
*/
public void setMonths(String months) {
this.months = months;
}
}
|
3e0b670a83a170e902e5fc4e4d551cad05a1dc43 | 2,106 | java | Java | module-vision/src/main/java/com/huawei/mlkit/sample/views/graphic/LocalImageClassificationGraphic.java | beizishaozi/hwaitest-MLkitSample | 5d0e0b99bcbcc6bc10b43a353af6cad8471b9773 | [
"Apache-2.0"
] | 288 | 2020-05-22T02:09:54.000Z | 2022-03-31T01:42:55.000Z | module-vision/src/main/java/com/huawei/mlkit/sample/views/graphic/LocalImageClassificationGraphic.java | beizishaozi/hwaitest-MLkitSample | 5d0e0b99bcbcc6bc10b43a353af6cad8471b9773 | [
"Apache-2.0"
] | 33 | 2020-05-25T10:19:07.000Z | 2022-03-13T11:37:29.000Z | module-vision/src/main/java/com/huawei/mlkit/sample/views/graphic/LocalImageClassificationGraphic.java | beizishaozi/hwaitest-MLkitSample | 5d0e0b99bcbcc6bc10b43a353af6cad8471b9773 | [
"Apache-2.0"
] | 98 | 2020-05-22T02:24:36.000Z | 2022-03-28T11:50:02.000Z | 36.310345 | 130 | 0.721273 | 4,827 | /**
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.mlkit.sample.views.graphic;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import com.huawei.hms.mlsdk.classification.MLImageClassification;
import com.huawei.mlkit.sample.util.CommonUtils;
import com.huawei.mlkit.sample.views.overlay.GraphicOverlay;
import java.util.List;
public class LocalImageClassificationGraphic extends BaseGraphic {
private final Paint textPaint;
private final GraphicOverlay overlay;
private Context mContext;
private final List<MLImageClassification> classifications;
public LocalImageClassificationGraphic(GraphicOverlay overlay, Context context, List<MLImageClassification> classifications) {
super(overlay);
this.overlay = overlay;
this.mContext = context;
this.classifications = classifications;
this.textPaint = new Paint();
this.textPaint.setColor(Color.WHITE);
this.textPaint.setTextSize(CommonUtils.dp2px(this.mContext, 16));
}
@Override
public synchronized void draw(Canvas canvas) {
float x = this.overlay.getWidth() / 4.0f;
float y = this.overlay.getHeight() / 1.5f;
for (MLImageClassification classification : this.classifications) {
canvas.drawText(classification.getName(), x, y, this.textPaint);
y = y - CommonUtils.dp2px(this.mContext, 18);
}
}
}
|
3e0b67842994a28f19db7071d99f2331c3b6d991 | 16,483 | java | Java | message-builder-hl7v3-release-on_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/on_cerx_v01_r04_3/iehr/repc_mt100001on/ProfessionalServiceBean.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | 1 | 2022-03-09T12:17:41.000Z | 2022-03-09T12:17:41.000Z | message-builder-hl7v3-release-on_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/on_cerx_v01_r04_3/iehr/repc_mt100001on/ProfessionalServiceBean.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | message-builder-hl7v3-release-on_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/on_cerx_v01_r04_3/iehr/repc_mt100001on/ProfessionalServiceBean.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | 33.502033 | 97 | 0.638658 | 4,828 | /**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy$
* Last modified: $LastChangedDate$
* Revision: $LastChangedRevision$
*/
/* This class was auto-generated by the message builder generator tools. */
package ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.iehr.repc_mt100001on;
import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping;
import ca.infoway.messagebuilder.annotation.Hl7RootType;
import ca.infoway.messagebuilder.annotation.Hl7XmlMapping;
import ca.infoway.messagebuilder.datatype.BL;
import ca.infoway.messagebuilder.datatype.CV;
import ca.infoway.messagebuilder.datatype.II;
import ca.infoway.messagebuilder.datatype.IVL;
import ca.infoway.messagebuilder.datatype.TS;
import ca.infoway.messagebuilder.datatype.impl.BLImpl;
import ca.infoway.messagebuilder.datatype.impl.CVImpl;
import ca.infoway.messagebuilder.datatype.impl.IIImpl;
import ca.infoway.messagebuilder.datatype.impl.IVLImpl;
import ca.infoway.messagebuilder.datatype.lang.Identifier;
import ca.infoway.messagebuilder.datatype.lang.Interval;
import ca.infoway.messagebuilder.domainvalue.ActProfessionalServiceCode;
import ca.infoway.messagebuilder.domainvalue.x_VeryBasicConfidentialityKind;
import ca.infoway.messagebuilder.model.MessagePartBean;
import ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.common.coct_mt050203on.PatientBean;
import ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.common.coct_mt090107on.ProviderBean;
import ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.common.coct_mt120600on.NotesBean;
import ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.iehr.merged.OrderForServiceBean;
import ca.infoway.messagebuilder.model.on_cerx_v01_r04_3.merged.RecordedAtBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>Business Name: Professional Service</p>
*
* <p>Annotation is only permitted if Annotation Indicator is
* not present and vice versa</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>May be pertinent information with respect to a patient's
* drug therapy regime.</p>
*
* <p>This is the information that is recorded and maintained
* on a consultative service provided to a patient. This
* service may or may not be related to a prescribed, dispensed
* or administered drug.</p>
*/
@Hl7PartTypeMapping({"REPC_MT100001ON.ProcedureEvent"})
@Hl7RootType
public class ProfessionalServiceBean extends MessagePartBean {
private static final long serialVersionUID = 20190731L;
private II id = new IIImpl();
private CV code = new CVImpl();
private IVL<TS, Interval<Date>> effectiveTime = new IVLImpl<TS, Interval<Date>>();
private CV confidentialityCode = new CVImpl();
private PatientBean subjectPatient;
private ProviderBean responsiblePartyAssignedPerson;
private ProviderBean performerAssignedPerson;
private RecordedAtBean location;
private OrderForServiceBean inFulfillmentOfActRequest;
private BL subjectOf1AnnotationIndicator = new BLImpl(false);
private List<NotesBean> subjectOf2Annotation = new ArrayList<NotesBean>();
/**
* <p>Business Name: A:Service Record Identifier</p>
*
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.id</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*
* <p>PatientConsultation.patientConsultationkey</p>
*
* <p>PatientConsultation.externalId</p>
*
* <p>ZRV.5</p>
*
* <p>ZPS.2</p>
*
* <p>ZPS.3</p>
*
* <p>Claim.455-EM (root)</p>
*
* <p>Claim.402-D2 (extension)</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows cognitive services to be uniquely referenced and
* is therefore mandatory.</p>
*
* <p>A unique identifier for a patient consultation service
* record.</p>
*/
@Hl7XmlMapping({"id"})
public Identifier getId() {
return this.id.getValue();
}
/**
* <p>Business Name: A:Service Record Identifier</p>
*
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.id</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*
* <p>PatientConsultation.patientConsultationkey</p>
*
* <p>PatientConsultation.externalId</p>
*
* <p>ZRV.5</p>
*
* <p>ZPS.2</p>
*
* <p>ZPS.3</p>
*
* <p>Claim.455-EM (root)</p>
*
* <p>Claim.402-D2 (extension)</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows cognitive services to be uniquely referenced and
* is therefore mandatory.</p>
*
* <p>A unique identifier for a patient consultation service
* record.</p>
*/
public void setId(Identifier id) {
this.id.setValue(id);
}
/**
* <p>Business Name: B:Service Code</p>
*
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.code</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*
* <p>PatientConsultation.category</p>
*
* <p>D57</p>
*
* <p>ZPS.5.1</p>
*
* <p>ZPS.5.2 (experience handled as qualifier)</p>
*
* <p>Claim.436-E1 (code system)</p>
*
* <p>Claim.407-D7 (mnemonic)</p>
*
* <p>Claim.459-ER (modifier)</p>
*
* <p>Claim.418-DI (modifier)</p>
*
* <p>DUR/PPS.474-8E (modifier)</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows the service to be sorted and filtered. Ensures
* consistency for analysis and reporting purposes and is
* therefore mandatory</p>
*
* <p>Identifies the specific service that has been performed.
* This is obtained from the professional service catalog
* pertaining to the discipline of the health service
* provider.</p>
*/
@Hl7XmlMapping({"code"})
public ActProfessionalServiceCode getCode() {
return (ActProfessionalServiceCode) this.code.getValue();
}
/**
* <p>Business Name: B:Service Code</p>
*
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.code</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*
* <p>PatientConsultation.category</p>
*
* <p>D57</p>
*
* <p>ZPS.5.1</p>
*
* <p>ZPS.5.2 (experience handled as qualifier)</p>
*
* <p>Claim.436-E1 (code system)</p>
*
* <p>Claim.407-D7 (mnemonic)</p>
*
* <p>Claim.459-ER (modifier)</p>
*
* <p>Claim.418-DI (modifier)</p>
*
* <p>DUR/PPS.474-8E (modifier)</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows the service to be sorted and filtered. Ensures
* consistency for analysis and reporting purposes and is
* therefore mandatory</p>
*
* <p>Identifies the specific service that has been performed.
* This is obtained from the professional service catalog
* pertaining to the discipline of the health service
* provider.</p>
*/
public void setCode(ActProfessionalServiceCode code) {
this.code.setValue(code);
}
/**
* <p>Business Name: C:Consultation Time and Length</p>
*
* <p>Relationship:
* REPC_MT100001ON.ProcedureEvent.effectiveTime</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*
* <p>Center date cannot be null But duration can be left
* unspecified if not known.</p>
*
* <p>PatientConsultation.eventTime(Low)</p>
*
* <p>patientConsultation.eventDuration(Width)</p>
*
* <p>ZPS.4 (center)</p>
*
* <p>ZPS.5.2(timing portion of code set)</p>
*
* <p>Claim.457-EP</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows the service-event to be located in a particular
* time. Because a time won't always be known, the attribute is
* only marked as "populated". The duration of the
* consultation may also be of clinical interest.</p>
*
* <p>The date and time on which the professional service was
* performed, as well as the duration of the service.</p>
*/
@Hl7XmlMapping({"effectiveTime"})
public Interval<Date> getEffectiveTime() {
return this.effectiveTime.getValue();
}
/**
* <p>Business Name: C:Consultation Time and Length</p>
*
* <p>Relationship:
* REPC_MT100001ON.ProcedureEvent.effectiveTime</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*
* <p>Center date cannot be null But duration can be left
* unspecified if not known.</p>
*
* <p>PatientConsultation.eventTime(Low)</p>
*
* <p>patientConsultation.eventDuration(Width)</p>
*
* <p>ZPS.4 (center)</p>
*
* <p>ZPS.5.2(timing portion of code set)</p>
*
* <p>Claim.457-EP</p>
*
* <p>A_BillableClinicalService</p>
*
* <p>Allows the service-event to be located in a particular
* time. Because a time won't always be known, the attribute is
* only marked as "populated". The duration of the
* consultation may also be of clinical interest.</p>
*
* <p>The date and time on which the professional service was
* performed, as well as the duration of the service.</p>
*/
public void setEffectiveTime(Interval<Date> effectiveTime) {
this.effectiveTime.setValue(effectiveTime);
}
/**
* <p>Business Name: D:Professional Service Masking Indicator</p>
*
* <p>Relationship:
* REPC_MT100001ON.ProcedureEvent.confidentialityCode</p>
*
* <p>Conformance/Cardinality: OPTIONAL (0-1)</p>
*
* <p>Allows the patient to have discrete control over access
* to their medication data.</p><p>The attribute is optional
* because not all systems will support masking.</p>
*
* <p>Communicates the intent of the patient to restrict access
* to their professional service records. Provides support for
* additional confidentiality constraint, giving patients a
* level of control over their information. Valid values are:
* 'NORMAL' (denotes 'Not Masked'); and 'RESTRICTED' (denotes
* 'Masked'). The default is 'NORMAL' signifying 'Not
* Masked'.</p>
*/
@Hl7XmlMapping({"confidentialityCode"})
public x_VeryBasicConfidentialityKind getConfidentialityCode() {
return (x_VeryBasicConfidentialityKind) this.confidentialityCode.getValue();
}
/**
* <p>Business Name: D:Professional Service Masking Indicator</p>
*
* <p>Relationship:
* REPC_MT100001ON.ProcedureEvent.confidentialityCode</p>
*
* <p>Conformance/Cardinality: OPTIONAL (0-1)</p>
*
* <p>Allows the patient to have discrete control over access
* to their medication data.</p><p>The attribute is optional
* because not all systems will support masking.</p>
*
* <p>Communicates the intent of the patient to restrict access
* to their professional service records. Provides support for
* additional confidentiality constraint, giving patients a
* level of control over their information. Valid values are:
* 'NORMAL' (denotes 'Not Masked'); and 'RESTRICTED' (denotes
* 'Masked'). The default is 'NORMAL' signifying 'Not
* Masked'.</p>
*/
public void setConfidentialityCode(x_VeryBasicConfidentialityKind confidentialityCode) {
this.confidentialityCode.setValue(confidentialityCode);
}
/**
* <p>Relationship: REPC_MT100001ON.Subject.patient</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
@Hl7XmlMapping({"subject/patient"})
public PatientBean getSubjectPatient() {
return this.subjectPatient;
}
/**
* <p>Relationship: REPC_MT100001ON.Subject.patient</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
public void setSubjectPatient(PatientBean subjectPatient) {
this.subjectPatient = subjectPatient;
}
/**
* <p>Relationship:
* REPC_MT100001ON.ResponsibleParty2.assignedPerson</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*/
@Hl7XmlMapping({"responsibleParty/assignedPerson"})
public ProviderBean getResponsiblePartyAssignedPerson() {
return this.responsiblePartyAssignedPerson;
}
/**
* <p>Relationship:
* REPC_MT100001ON.ResponsibleParty2.assignedPerson</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*/
public void setResponsiblePartyAssignedPerson(ProviderBean responsiblePartyAssignedPerson) {
this.responsiblePartyAssignedPerson = responsiblePartyAssignedPerson;
}
/**
* <p>Relationship: REPC_MT100001ON.Performer.assignedPerson</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
@Hl7XmlMapping({"performer/assignedPerson"})
public ProviderBean getPerformerAssignedPerson() {
return this.performerAssignedPerson;
}
/**
* <p>Relationship: REPC_MT100001ON.Performer.assignedPerson</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
public void setPerformerAssignedPerson(ProviderBean performerAssignedPerson) {
this.performerAssignedPerson = performerAssignedPerson;
}
/**
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.location</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
@Hl7XmlMapping({"location"})
public RecordedAtBean getLocation() {
return this.location;
}
/**
* <p>Relationship: REPC_MT100001ON.ProcedureEvent.location</p>
*
* <p>Conformance/Cardinality: MANDATORY (1)</p>
*/
public void setLocation(RecordedAtBean location) {
this.location = location;
}
/**
* <p>Relationship: REPC_MT100001ON.InFulfillmentOf.actRequest</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*/
@Hl7XmlMapping({"inFulfillmentOf/actRequest"})
public OrderForServiceBean getInFulfillmentOfActRequest() {
return this.inFulfillmentOfActRequest;
}
/**
* <p>Relationship: REPC_MT100001ON.InFulfillmentOf.actRequest</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*/
public void setInFulfillmentOfActRequest(OrderForServiceBean inFulfillmentOfActRequest) {
this.inFulfillmentOfActRequest = inFulfillmentOfActRequest;
}
/**
* <p>Relationship:
* REPC_MT100001ON.Subject3.annotationIndicator</p>
*
* <p>Conformance/Cardinality: POPULATED (1)</p>
*/
@Hl7XmlMapping({"subjectOf1/annotationIndicator"})
public Boolean getSubjectOf1AnnotationIndicator() {
return this.subjectOf1AnnotationIndicator.getValue();
}
/**
* <p>Relationship:
* REPC_MT100001ON.Subject3.annotationIndicator</p>
*
* <p>Conformance/Cardinality: POPULATED (1)</p>
*/
public void setSubjectOf1AnnotationIndicator(Boolean subjectOf1AnnotationIndicator) {
this.subjectOf1AnnotationIndicator.setValue(subjectOf1AnnotationIndicator);
}
/**
* <p>Relationship: REPC_MT100001ON.Subject2.annotation</p>
*
* <p>Conformance/Cardinality: REQUIRED (1)</p>
*/
@Hl7XmlMapping({"subjectOf2/annotation"})
public List<NotesBean> getSubjectOf2Annotation() {
return this.subjectOf2Annotation;
}
}
|
3e0b68ff558f0453dad2a991357478947e7d359e | 214 | java | Java | src/main/java/jvc/predicate/engine/evaluator/Evaluator.java | joacovela16/predicate-logic | 73ecd19e550d1c949ace64e3ee5a5067ddeb2e27 | [
"MIT"
] | null | null | null | src/main/java/jvc/predicate/engine/evaluator/Evaluator.java | joacovela16/predicate-logic | 73ecd19e550d1c949ace64e3ee5a5067ddeb2e27 | [
"MIT"
] | null | null | null | src/main/java/jvc/predicate/engine/evaluator/Evaluator.java | joacovela16/predicate-logic | 73ecd19e550d1c949ace64e3ee5a5067ddeb2e27 | [
"MIT"
] | null | null | null | 15.285714 | 49 | 0.626168 | 4,829 | package jvc.predicate.engine.evaluator;
public abstract class Evaluator<T> {
protected abstract EvaluatorResult<T> run();
public EvaluatorResult<T> eval() {
return run();
}
}
|
3e0b696857a43ba57dea243bd1357d40a9147096 | 1,506 | java | Java | src/main/java/mchorse/metamorph/client/model/custom/ModelSlime.java | Chunk7w/blockbuster | f8df3c8d2709135512a1cdd1e08cd3545c9975bc | [
"MIT"
] | 106 | 2016-06-25T04:41:34.000Z | 2022-03-27T16:13:28.000Z | src/main/java/mchorse/metamorph/client/model/custom/ModelSlime.java | Chunk7w/blockbuster | f8df3c8d2709135512a1cdd1e08cd3545c9975bc | [
"MIT"
] | 173 | 2016-06-26T16:04:08.000Z | 2022-03-02T23:42:40.000Z | src/main/java/mchorse/metamorph/client/model/custom/ModelSlime.java | Chunk7w/blockbuster | f8df3c8d2709135512a1cdd1e08cd3545c9975bc | [
"MIT"
] | 67 | 2016-07-11T18:27:32.000Z | 2022-02-20T11:14:56.000Z | 32.042553 | 145 | 0.723772 | 4,830 | package mchorse.metamorph.client.model.custom;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.blockbuster.client.model.parsing.IModelCustom;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
public class ModelSlime extends ModelCustom implements IModelCustom
{
public ModelCustomRenderer head;
public ModelCustomRenderer right_eye;
public ModelCustomRenderer left_eye;
public ModelCustomRenderer mouth;
public ModelCustomRenderer outer;
public ModelSlime(Model model)
{
super(model);
}
@Override
public void onGenerated()
{}
@Override
public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale)
{
GlStateManager.pushMatrix();
GlStateManager.translate(0, -1, 0);
this.head.render(scale);
if (!this.model.name.equals("Slime"))
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 0.8F);
}
GlStateManager.enableNormalize();
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
this.outer.render(scale);
GlStateManager.disableBlend();
GlStateManager.disableNormalize();
GlStateManager.popMatrix();
}
} |
3e0b6c030224e1b110e3cc7e706bba776be29b86 | 456 | java | Java | src/main/java/my/work/stock/system/domain/repository/ComputerMaterialsCategoryRepository.java | wangdengwu/stocksystem | 804ea93c7c14fbfea08e9cfb4f4ae8223a611aa0 | [
"Apache-2.0"
] | 5 | 2017-04-05T06:30:14.000Z | 2021-04-10T18:14:02.000Z | src/main/java/my/work/stock/system/domain/repository/ComputerMaterialsCategoryRepository.java | wangdengwu/stocksystem | 804ea93c7c14fbfea08e9cfb4f4ae8223a611aa0 | [
"Apache-2.0"
] | null | null | null | src/main/java/my/work/stock/system/domain/repository/ComputerMaterialsCategoryRepository.java | wangdengwu/stocksystem | 804ea93c7c14fbfea08e9cfb4f4ae8223a611aa0 | [
"Apache-2.0"
] | 6 | 2017-04-05T07:51:01.000Z | 2020-11-09T06:14:39.000Z | 38 | 139 | 0.872807 | 4,831 | package my.work.stock.system.domain.repository;
import my.work.stock.system.domain.entity.ComputerMaterialsCategory;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ComputerMaterialsCategoryRepository extends CrudRepository<ComputerMaterialsCategory, Integer>, JpaSpecificationExecutor {
}
|
3e0b6c301cc088e8a9d5df86d9f545ae27e807d8 | 6,681 | java | Java | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticMarkdownGenerator.java | svmk/openapi-generator | 245c654a0119467ee7423931ed7d81c0477447fd | [
"Apache-2.0"
] | null | null | null | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticMarkdownGenerator.java | svmk/openapi-generator | 245c654a0119467ee7423931ed7d81c0477447fd | [
"Apache-2.0"
] | null | null | null | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticMarkdownGenerator.java | svmk/openapi-generator | 245c654a0119467ee7423931ed7d81c0477447fd | [
"Apache-2.0"
] | null | null | null | 37.745763 | 163 | 0.653645 | 4,832 | /*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class StaticMarkdownGenerator extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "org.openapitools.client";
protected String groupId = "org.openapitools";
protected String artifactId = "openapi-client";
protected String artifactVersion = "1.0.0";
public StaticMarkdownGenerator() {
super();
embeddedTemplateDir = templateDir = "markdownDocs";
modelTemplateFiles.put("model.mustache", ".md");
apiOperationTemplateFiles.put("operation.mustache", ".md");
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
cliOptions.add(new CliOption("markdownBasePath", "base path to markdown root"));
cliOptions.add(new CliOption("tocFileName", "Enables sidebar file that contains table of content"));
}
@Override
public void processOpts() {
super.processOpts();
String tocFileName = (String) additionalProperties.get("tocFileName");
if (tocFileName != null) {
supportingFiles.add(new SupportingFile("toc.mustache", "", tocFileName));
}
}
@Override
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
@Override
public String getName() {
return "markdown";
}
@Override
public String getHelp() {
return "Generates a directory with markdown files.";
}
@Override
public String apiOperationFileFolder() {
return outputFolder + File.separator + File.separator + "operations";
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + File.separator + "models";
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty result = super.fromProperty(name, p);
boolean isComplexType = true;
if (
result.isPrimitiveType ||
result.isString ||
result.isNumeric ||
result.isInteger ||
result.isLong ||
result.isNumber ||
result.isFloat ||
result.isDouble ||
result.isByteArray ||
result.isBinary ||
result.isFile ||
result.isBoolean ||
result.isDate ||
result.isDateTime ||
result.isUuid ||
result.complexType.equals("object")
) {
isComplexType = false;
}
if (isComplexType) {
result.vendorExtensions.put("resolvedModelName", result.complexType.substring(0, 1).toUpperCase(Locale.ROOT) + result.complexType.substring(1));
}
return result;
}
@Override
public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
{
CodegenParameter result = super.fromParameter(parameter, imports);
if (!result.isPrimitiveType) {
result.vendorExtensions.put("resolvedModelName", result.baseType);
}
return result;
}
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[]" + getTypeDeclaration(inner);
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return "map[string]" + getTypeDeclaration(inner);
}
return super.getTypeDeclaration(p);
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.httpMethod = op.httpMethod.toUpperCase(Locale.ROOT);
prepareOperationParameters(op.allParams);
prepareOperationParameters(op.bodyParams);
prepareOperationParameters(op.pathParams);
prepareOperationParameters(op.queryParams);
prepareOperationParameters(op.headerParams);
prepareOperationParameters(op.formParams);
prepareOperationParameters(op.cookieParams);
prepareOperationParameters(op.requiredParams);
prepareOperationParameters(op.optionalParams);
prepareOperationParameters(op.cookieParams);
prepareOperationResponses(op.responses);
for (CodegenResponse response : op.responses) {
if ("0".equals(response.code)) {
response.code = "default";
}
}
}
return objs;
}
private void prepareOperationParameters(List<CodegenParameter> parameters) {
for (CodegenParameter parameter: parameters) {
if (parameter.dataType.length() >= 1 && !parameter.isPrimitiveType) {
parameter.vendorExtensions.put("resolvedModelName", parameter.dataType.substring(0, 1).toUpperCase(Locale.ROOT) + parameter.dataType.substring(1));
}
}
}
private void prepareOperationResponses(List<CodegenResponse> responses) {
for (CodegenResponse response: responses) {
if (response.dataType.length() >= 1 && !response.primitiveType) {
response.vendorExtensions.put("resolvedModelName", response.dataType.substring(0, 1).toUpperCase(Locale.ROOT) + response.dataType.substring(1));
}
}
}
}
|
3e0b6ff05eadfab38506a3776deb323bafce2b04 | 1,173 | java | Java | form/wicket/src/main/java/org/opensingular/form/wicket/model/SInstanceListItemModel.java | opensingular/singular-core | ecaf7eafc5de0354f422a4c5d19be6887c86adc0 | [
"Apache-2.0"
] | 5 | 2016-10-07T16:43:05.000Z | 2018-09-20T22:12:29.000Z | form/wicket/src/main/java/org/opensingular/form/wicket/model/SInstanceListItemModel.java | opensingular/singular-core | ecaf7eafc5de0354f422a4c5d19be6887c86adc0 | [
"Apache-2.0"
] | 2 | 2016-12-04T20:58:51.000Z | 2016-12-14T14:06:33.000Z | form/wicket/src/main/java/org/opensingular/form/wicket/model/SInstanceListItemModel.java | opensingular/singular-core | ecaf7eafc5de0354f422a4c5d19be6887c86adc0 | [
"Apache-2.0"
] | null | null | null | 27.27907 | 85 | 0.716965 | 4,833 | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.form.wicket.model;
import org.opensingular.form.SInstance;
import java.io.Serializable;
public class SInstanceListItemModel<I extends SInstance>
extends AbstractSInstanceItemListModel<I>
{
private int index;
public SInstanceListItemModel(Serializable rootTarget, int index) {
super(rootTarget);
this.index = index;
}
@Override
protected int index() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
|
3e0b7017dc625913c934ac4f9626e50f3f476ac2 | 3,777 | java | Java | src/com/makina/security/openfips201/PIVDataObject.java | spaikmos/OpenFIPS201 | cfa96bc3504263790d807cc64498b3e1fc9bd0da | [
"MIT"
] | 29 | 2018-01-25T15:24:44.000Z | 2022-03-09T21:25:05.000Z | src/com/makina/security/openfips201/PIVDataObject.java | spaikmos/OpenFIPS201 | cfa96bc3504263790d807cc64498b3e1fc9bd0da | [
"MIT"
] | 33 | 2017-12-20T03:00:34.000Z | 2021-07-30T05:57:46.000Z | src/com/makina/security/openfips201/PIVDataObject.java | spaikmos/OpenFIPS201 | cfa96bc3504263790d807cc64498b3e1fc9bd0da | [
"MIT"
] | 22 | 2017-11-26T22:37:43.000Z | 2022-03-06T16:24:49.000Z | 36.669903 | 97 | 0.689436 | 4,834 | /******************************************************************************
* MIT License
*
* Project: OpenFIPS201
* Copyright: (c) 2017 Commonwealth of Australia
* Author: Kim O'Sullivan - Makina (ychag@example.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package com.makina.security.openfips201;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;
/** Provides functionality for PIV data objects */
public final class PIVDataObject extends PIVObject {
// Note: Do NOT use content.length to determine the number of bytes in the content array
// rather use getLength().
public byte[] content;
// Indicates the number of bytes currently allocated. In the case where an object is
// reallocated with a smaller size this will be less than content.length
private short bytesAllocated;
public PIVDataObject(byte id, byte modeContact, byte modeContactless) {
super(id, modeContact, modeContactless);
}
/**
* @return the number of bytes allocated in content which may be less than content.length
*/
public short getLength() {
return bytesAllocated;
}
public void allocate(short length) throws ISOException {
Assert.isTrue(length > 0);
if (content == null) {
content = new byte[length];
} else if (length > (short) content.length) {
// Try to reclaim the resources and re-allocate. If this fails then this card does not
// support objection deletion and so we can't write an object greater than the initial size
if (!JCSystem.isObjectDeletionSupported()) ISOException.throwIt(ISO7816.SW_FILE_FULL);
clear();
content = new byte[length];
} else {
// Just clear the content object
Util.arrayFillNonAtomic(content, (short) 0, (short) content.length, (byte) 0x00);
}
bytesAllocated = length;
}
/**
* Returns true if this object is populated with data
*
* @return True if the object is initialised
*/
public boolean isInitialised() {
return (content != null);
}
/*
* Wipes all data from the current object
*/
public void clear() {
if (content == null) return;
PIVSecurityProvider.zeroise(content, (short) 0, (short) content.length);
bytesAllocated = 0;
// Wipe our reference to the data, let the GC collect and re-allocate
// NOTE: requestObjectDeletion doesn't necessarily do it straight away, so both objects may
// remain allocated until the next call to process()
if (JCSystem.isObjectDeletionSupported()) {
content = null;
JCSystem.requestObjectDeletion();
}
}
}
|
3e0b71366e35d42c1ec68b3b5a0c3b75def5af1b | 1,293 | java | Java | exporter-api/src/main/java/io/zeebe/exporter/api/record/value/MessageSubscriptionRecordValue.java | falko/zeebe | b9e526063d8dc6f237dd54a13db2cb2fa22b6351 | [
"Apache-2.0"
] | null | null | null | exporter-api/src/main/java/io/zeebe/exporter/api/record/value/MessageSubscriptionRecordValue.java | falko/zeebe | b9e526063d8dc6f237dd54a13db2cb2fa22b6351 | [
"Apache-2.0"
] | null | null | null | exporter-api/src/main/java/io/zeebe/exporter/api/record/value/MessageSubscriptionRecordValue.java | falko/zeebe | b9e526063d8dc6f237dd54a13db2cb2fa22b6351 | [
"Apache-2.0"
] | null | null | null | 33.128205 | 81 | 0.743034 | 4,835 | /*
* Copyright © 2017 camunda services GmbH (upchh@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.zeebe.exporter.api.record.value;
import io.zeebe.exporter.api.record.RecordValue;
/**
* Represents a message correlation subscription event or command.
*
* <p>See {@link io.zeebe.protocol.intent.MessageSubscriptionIntent} for intents.
*/
public interface MessageSubscriptionRecordValue extends RecordValue {
/** @return the workflow instance key tied to the subscription */
long getWorkflowInstanceKey();
/** @return the element instance key tied to the subscription */
long getElementInstanceKey();
/** @return the name of the message */
String getMessageName();
/** @return the correlation key */
String getCorrelationKey();
}
|
3e0b73a0f0973e57f0e9ea569e801ccd7bd90ba0 | 1,009 | java | Java | src/main/java/de/cosmocode/palava/ipc/json/custom/CustomProtocolModule.java | palava/palava-ipc-json-custom | 81bcad3c080ba8b0ddf89be182adb6ebbf5f50e0 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/cosmocode/palava/ipc/json/custom/CustomProtocolModule.java | palava/palava-ipc-json-custom | 81bcad3c080ba8b0ddf89be182adb6ebbf5f50e0 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/cosmocode/palava/ipc/json/custom/CustomProtocolModule.java | palava/palava-ipc-json-custom | 81bcad3c080ba8b0ddf89be182adb6ebbf5f50e0 | [
"Apache-2.0"
] | 1 | 2019-05-08T06:18:56.000Z | 2019-05-08T06:18:56.000Z | 28.027778 | 75 | 0.730426 | 4,836 | /**
* Copyright 2010 CosmoCode 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.cosmocode.palava.ipc.json.custom;
import com.google.inject.Binder;
import com.google.inject.Module;
/**
* Binds {@link CustomProtocol} as eager singleton.
*
* @since 1.0.1
* @author Willi Schoenborn
*/
public final class CustomProtocolModule implements Module {
@Override
public void configure(Binder binder) {
binder.bind(CustomProtocol.class).asEagerSingleton();
}
}
|
3e0b744fdc9990a1b89d89d3dca827fbf439e98c | 2,845 | java | Java | back/src/main/java/com/cortex/core/usecase/EleicaoUseCase.java | thiagohernandes/api-cortex | 7615f91707dab407dea9260e4dc0b4693575ddb5 | [
"MIT"
] | null | null | null | back/src/main/java/com/cortex/core/usecase/EleicaoUseCase.java | thiagohernandes/api-cortex | 7615f91707dab407dea9260e4dc0b4693575ddb5 | [
"MIT"
] | null | null | null | back/src/main/java/com/cortex/core/usecase/EleicaoUseCase.java | thiagohernandes/api-cortex | 7615f91707dab407dea9260e4dc0b4693575ddb5 | [
"MIT"
] | null | null | null | 40.070423 | 138 | 0.679438 | 4,837 | package com.cortex.core.usecase;
import com.cortex.core.usecase.http.VotacaoRegiao;
import com.cortex.dataprovider.EleicaoDataProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
@Component
public class EleicaoUseCase {
private final EleicaoDataProvider eleicaoDataProvider;
@Autowired
public EleicaoUseCase(final EleicaoDataProvider eleicaoDataProvider) {
this.eleicaoDataProvider = eleicaoDataProvider;
}
public List<Object> listaRegioes() {
return eleicaoDataProvider.listaRegioes();
}
public List<Object> listaEstadosPorRegioes(Integer regiaoId) {
return eleicaoDataProvider.listaEstadosPorRegiao(regiaoId);
}
public List<Object> listaMesorregioesPorEstado(String estadoSigla) {
return eleicaoDataProvider.listaMesorregioesPorEstado(estadoSigla);
}
public List<Object> listaMicrorregioesPorMesorregiao(String mesorregiaoId) {
return eleicaoDataProvider.listaMicrorregioesPorMesorregiao(mesorregiaoId);
}
public List<Object> listaMunicipiosPorMicrorregiao(String microrregiaoId) {
return eleicaoDataProvider.listaMunicipiosPorMicrorregiao(microrregiaoId);
}
public void importaCandidatos() throws IOException {
this.eleicaoDataProvider.importarCandidatos();
}
public List<VotacaoRegiao> votacaoPorRegioes() {
return this.eleicaoDataProvider.votacaoPorRegioes();
}
public List<VotacaoRegiao> votacaoPorRegioes(List<String> regioesSiglas) {
return this.eleicaoDataProvider.votacaoPorRegioes(regioesSiglas);
}
public List<VotacaoRegiao> votacaoPorRegioesEUfs(List<String> regioesSiglas, List<String> ufs){
return this.eleicaoDataProvider.votacaoPorRegioesEUfs(regioesSiglas, ufs);
}
public List<VotacaoRegiao> votacaoPorRegioesEUfsEMesorregioes(List<String> regioesSiglas,
List<String> ufs,
List<String> mesorregioes){
return this.eleicaoDataProvider.votacaoPorRegioesEUfsEMesorregioes(regioesSiglas, ufs, mesorregioes);
}
public List<VotacaoRegiao> votacaoPorRegioesEUfsEMesorregioesEMicrorregioes(List<String> regioesSiglas,
List<String> ufs,
List<String> mesorregioes,
List<String> microrregioes){
return this.eleicaoDataProvider.votacaoPorRegioesEUfsEMesorregioesEMicrorregioes(regioesSiglas, ufs, mesorregioes, microrregioes);
}
}
|
3e0b7456c0d05d82e6761e34b087f5b7e2b055dc | 2,904 | java | Java | pcc-event-handler/src/main/java/io/pivotal/pcc/server/event/SampleGatewayConflictResolver.java | Pivotal-Field-Engineering/pad-pcc-advanced-workshop | 749dedc99ed443d228e9df5764533ea1443ae86c | [
"Apache-2.0"
] | 1 | 2020-05-04T16:29:20.000Z | 2020-05-04T16:29:20.000Z | pcc-event-handler/src/main/java/io/pivotal/pcc/server/event/SampleGatewayConflictResolver.java | Pivotal-Field-Engineering/pad-pcc-advanced-workshop | 749dedc99ed443d228e9df5764533ea1443ae86c | [
"Apache-2.0"
] | null | null | null | pcc-event-handler/src/main/java/io/pivotal/pcc/server/event/SampleGatewayConflictResolver.java | Pivotal-Field-Engineering/pad-pcc-advanced-workshop | 749dedc99ed443d228e9df5764533ea1443ae86c | [
"Apache-2.0"
] | null | null | null | 39.243243 | 210 | 0.636364 | 4,838 | package io.pivotal.pcc.server.event;
import org.apache.geode.cache.Operation;
import org.apache.geode.cache.util.GatewayConflictHelper;
import org.apache.geode.cache.util.GatewayConflictResolver;
import org.apache.geode.cache.util.TimestampedEntryEvent;
import org.apache.geode.pdx.PdxInstance;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author Heng Yan
*/
public class SampleGatewayConflictResolver implements GatewayConflictResolver {
final static Logger logger = LogManager.getLogger(SampleGatewayConflictResolver.class);
@Override
public void onEvent(final TimestampedEntryEvent te, final GatewayConflictHelper conflictHelper) {
if (te.getOperation().isUpdate()) {
int newDisId = te.getNewDistributedSystemID();
long newTimestamp = te.getNewTimestamp();
int oldDisId = te.getOldDistributedSystemID();
long oldTimestamp = te.getOldTimestamp();
logger.info("The received update is from cluster:{} at {}. The current entry in the cache was last updated by cluster:{} at {}.", newDisId, newTimestamp, oldDisId, oldTimestamp);
final PdxInstance newValue = (PdxInstance)te.getNewValue();
final PdxInstance oldValue = (PdxInstance)te.getOldValue();
/**
* Extract one or multiple field(s) from local and remote cache entry and use them to build the logic.
*/
final int newAreaCode = (Integer) newValue.getField("areaCode");
final int oldAreaCode = (Integer) oldValue.getField("areaCode");
/**
* You need to decide how to resolve the conflict according to your business logic.
*
* In this example, to demonstrate the logic, let's assume there are only three possible area code (1: US, 2: EMEA: 3: Asia). US has the highest priority, EMEA has the second, and Asia has the last.
*
*/
if (newAreaCode == oldAreaCode) {
// When both local and remote have the same areaCode, compare their timestamp to decide who wins.
if (newTimestamp >= oldTimestamp) {
// Replace the local value with the new value.
conflictHelper.changeEventValue(newValue);
} else {
// Ignore the new value.
conflictHelper.disallowEvent();
}
} else if (newAreaCode < oldAreaCode) {
// Based on our assumption, US always win over EMEA/Aisa and EMEA always win over Aisa. Replace the local value with the new value.
conflictHelper.changeEventValue(newValue);
} else if (newAreaCode > oldAreaCode) {
// Ignore the new value.
conflictHelper.disallowEvent();
}
}
}
}
|
3e0b745ce96b55cea1717ab56e3ec6e43252480b | 1,618 | java | Java | src/main/java/com/chrisrm/idea/ui/MTPopupMenuBorder.java | jackwiy/material-theme-jetbrains | 6b230143ff860e6849b900e73b869afd1eca2ad5 | [
"MIT"
] | 2 | 2019-01-23T07:42:57.000Z | 2019-01-23T07:43:06.000Z | src/main/java/com/chrisrm/idea/ui/MTPopupMenuBorder.java | jackwiy/material-theme-jetbrains | 6b230143ff860e6849b900e73b869afd1eca2ad5 | [
"MIT"
] | null | null | null | src/main/java/com/chrisrm/idea/ui/MTPopupMenuBorder.java | jackwiy/material-theme-jetbrains | 6b230143ff860e6849b900e73b869afd1eca2ad5 | [
"MIT"
] | null | null | null | 33.708333 | 81 | 0.751545 | 4,839 | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Chris Magnussen and Elior Boukhobza
*
* 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.chrisrm.idea.ui;
import com.intellij.ide.ui.laf.darcula.ui.DarculaPopupMenuBorder;
import com.intellij.util.ui.JBUI;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public final class MTPopupMenuBorder extends DarculaPopupMenuBorder {
@Override
public Insets getBorderInsets(final Component c) {
return JBUI.insets(2).asUIResource();
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
|
3e0b7482d05d16f25a4757983d9b881e59d2a8e0 | 1,363 | java | Java | azure-iot-hub/src/main/java/io/pivotal/azureiot/source/AzureIotHubApplication.java | pivotal-partner-solution-architecture/azure-iot-demo | ea2f0d76f5bce61e17f386a049ce8ccc26de7785 | [
"Apache-2.0"
] | 2 | 2020-09-14T13:04:09.000Z | 2021-12-10T15:30:42.000Z | azure-iot-hub/src/main/java/io/pivotal/azureiot/source/AzureIotHubApplication.java | pivotal-partner-platform-architecture/azure-iot-demo | ea2f0d76f5bce61e17f386a049ce8ccc26de7785 | [
"Apache-2.0"
] | null | null | null | azure-iot-hub/src/main/java/io/pivotal/azureiot/source/AzureIotHubApplication.java | pivotal-partner-platform-architecture/azure-iot-demo | ea2f0d76f5bce61e17f386a049ce8ccc26de7785 | [
"Apache-2.0"
] | 2 | 2018-04-13T16:04:25.000Z | 2018-05-01T17:31:34.000Z | 42.59375 | 102 | 0.691123 | 4,840 | /*
* *****************************************************************************
* Copyright (c) 2017-Present Pivotal Software, Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
* *****************************************************************************
*/
package io.pivotal.azureiot.source;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class AzureIotHubApplication {
public static void main(String[] args) {
SpringApplication.run(AzureIotHubApplication.class, args);
}
}
|
3e0b7549c1d1f3cc3a6764ff2dde6f54b933f110 | 1,073 | java | Java | ledgers-middleware/ledgers-middleware-service-api/src/main/java/de/adorsys/ledgers/middleware/api/domain/account/ExchangeRateTO.java | Zeshadowz/ledgers | 0303f5931091588a15e715539cb07c8bf430bc2a | [
"Apache-2.0"
] | 25 | 2018-11-14T14:22:24.000Z | 2022-03-24T14:02:37.000Z | ledgers-middleware/ledgers-middleware-service-api/src/main/java/de/adorsys/ledgers/middleware/api/domain/account/ExchangeRateTO.java | Zeshadowz/ledgers | 0303f5931091588a15e715539cb07c8bf430bc2a | [
"Apache-2.0"
] | 7 | 2019-07-02T17:24:34.000Z | 2021-07-20T11:42:44.000Z | ledgers-middleware/ledgers-middleware-service-api/src/main/java/de/adorsys/ledgers/middleware/api/domain/account/ExchangeRateTO.java | Zeshadowz/ledgers | 0303f5931091588a15e715539cb07c8bf430bc2a | [
"Apache-2.0"
] | 12 | 2018-11-14T22:33:26.000Z | 2021-12-06T10:56:44.000Z | 29 | 75 | 0.764212 | 4,841 | /*
* Copyright 2018-2018 adorsys GmbH & Co KG
*
* 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.adorsys.ledgers.middleware.api.domain.account;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.Currency;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExchangeRateTO {
private Currency currencyFrom;
private String rateFrom;
private Currency currency;
private String rateTo;
private LocalDate rateDate;
private String rateContract;
}
|
3e0b762e9f59dcd66c9813cf0744fb08522635f8 | 1,250 | java | Java | view/GameTableCellRenderer.java | JeanPoffo/hnefatafl | 514036319d6ec5b80bed314dbe0115db4f94f9da | [
"MIT"
] | 4 | 2021-07-09T13:52:50.000Z | 2022-01-10T18:40:21.000Z | view/GameTableCellRenderer.java | JeanPoffo/hnefatafl | 514036319d6ec5b80bed314dbe0115db4f94f9da | [
"MIT"
] | null | null | null | view/GameTableCellRenderer.java | JeanPoffo/hnefatafl | 514036319d6ec5b80bed314dbe0115db4f94f9da | [
"MIT"
] | null | null | null | 28.409091 | 143 | 0.6216 | 4,842 | package view;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import model.CasaTabuleiro;
/**
* Classe de renderização de Cell do JTable do Game
* @author Jean Poffo
* @since 22/08/2018
*/
public class GameTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object casaAtual, boolean isSelected, boolean hasFocus, int row, int column) {
CasaTabuleiro casaTabuleiro = (CasaTabuleiro) casaAtual;
if(casaTabuleiro.isRefugio()) {
super.setBackground(new Color(242, 242, 234));
}
else if (casaTabuleiro.isTrono()){
super.setBackground(new Color(244, 255, 168));
}
else {
super.setBackground(new Color(247, 244, 175));
}
if(casaTabuleiro.getPeca() != null) {
super.setIcon(casaTabuleiro.getPeca().getIcone());
}
else {
super.setIcon(null);
}
super.setHorizontalAlignment(CENTER);
super.setVerticalAlignment(CENTER);
super.repaint();
return this;
}
} |
3e0b77312c22dfeae8cc480751be65c605531c5f | 3,979 | java | Java | jaggery/org.eclipse.php.debug.ui/src/org/eclipse/php/internal/debug/ui/console/PHPFileLink.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | null | null | null | jaggery/org.eclipse.php.debug.ui/src/org/eclipse/php/internal/debug/ui/console/PHPFileLink.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | null | null | null | jaggery/org.eclipse.php.debug.ui/src/org/eclipse/php/internal/debug/ui/console/PHPFileLink.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | 1 | 2018-10-26T12:52:03.000Z | 2018-10-26T12:52:03.000Z | 31.330709 | 81 | 0.716009 | 4,843 | /*******************************************************************************
* Copyright (c) 2009 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
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.debug.ui.console;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.ui.console.FileLink;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.php.internal.core.PHPLanguageToolkit;
import org.eclipse.php.internal.debug.ui.PHPDebugUIPlugin;
import org.eclipse.php.internal.ui.util.EditorUtility;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.console.IHyperlink;
import org.eclipse.ui.ide.IDE;
import com.ibm.icu.text.MessageFormat;
/**
*
* @author seva
*
* A version of {@link FileLink} which also supports external resources
*
*/
public class PHPFileLink implements IHyperlink {
protected String fileName;
protected int lineNumber;
/**
* Constructs a hyperlink to the specified file.
*
* @param fileName
* The file name to open
* @param lineNumber
* The line number to select
*/
public PHPFileLink(String fileName, int lineNumber) {
this.fileName = fileName;
this.lineNumber = lineNumber;
}
public void linkActivated() {
try {
Object element = findSourceModule(fileName);
if (element != null) {
openElementInEditor(element);
return;
}
if (EditorUtility.openLocalFile(fileName, lineNumber) != null) {
return;
}
} catch (CoreException e) {
PHPDebugUIPlugin.log(e);
}
// did not find source
MessageDialog.openInformation(PHPDebugUIPlugin
.getActiveWorkbenchShell(), Messages.PHPFileLink_0, MessageFormat
.format(Messages.PHPFileLink_1, new Object[] { fileName }));
}
protected void openElementInEditor(Object element) throws CoreException {
Assert.isNotNull(element);
IEditorInput input = null;
if (element instanceof IModelElement) {
input = EditorUtility.getEditorInput((IModelElement) element);
} else {
input = org.eclipse.dltk.internal.ui.editor.EditorUtility
.getEditorInput(element);
}
if (input == null) {
return;
}
IEditorDescriptor descriptor = IDE.getEditorDescriptor(input.getName());
IWorkbenchPage page = PHPDebugUIPlugin.getActivePage();
IEditorPart editor = page.openEditor(input, descriptor.getId());
org.eclipse.dltk.internal.ui.editor.EditorUtility.revealInEditor(
editor, lineNumber - 1);
}
/**
* Finds {@link IFile} or {@link ISourceModule} matching the specified file
* name
*
* @param fileName
* @return
*/
public static Object findSourceModule(String fileName) {
IPath path = Path.fromOSString(fileName);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile f = root.getFileForLocation(path);
if (f != null) {
return f;
}
IDLTKLanguageToolkit toolkit = PHPLanguageToolkit.getDefault();
PHPConsoleSourceModuleLookup lookup = new PHPConsoleSourceModuleLookup(
toolkit);
return lookup.findSourceModuleByLocalPath(path);
}
public void linkEntered() {
}
public void linkExited() {
}
} |
3e0b78e0f395958e4bf141d481c8307f3a5f68a5 | 3,123 | java | Java | zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java | slaveuser/zuul20190422 | 87c28cda6ecd2ec6d32dd97ef8575dd4fb7c7f7f | [
"Apache-2.0"
] | 2 | 2019-03-30T14:29:30.000Z | 2019-03-30T15:12:26.000Z | zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java | slaveuser/zuul20190422 | 87c28cda6ecd2ec6d32dd97ef8575dd4fb7c7f7f | [
"Apache-2.0"
] | 1 | 2019-10-16T11:41:14.000Z | 2019-10-17T01:04:30.000Z | zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java | slaveuser/zuul20190422 | 87c28cda6ecd2ec6d32dd97ef8575dd4fb7c7f7f | [
"Apache-2.0"
] | 1 | 2021-07-29T03:14:27.000Z | 2021-07-29T03:14:27.000Z | 27.910714 | 123 | 0.65771 | 4,844 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.zuul.niws;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
/**
* User: anpch@example.com
* Date: 6/25/15
* Time: 1:03 PM
*/
public class RequestAttempts extends ArrayList<RequestAttempt>
{
private static final Logger LOG = LoggerFactory.getLogger(RequestAttempts.class);
private static ThreadLocal<RequestAttempts> threadLocal = new ThreadLocal<>().withInitial(() -> new RequestAttempts());
private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();
public RequestAttempts()
{
super();
}
public RequestAttempt getFinalAttempt()
{
if (size() > 0) {
return get(size() - 1);
}
else {
return null;
}
}
public static RequestAttempts getFromSessionContext(SessionContext ctx)
{
return (RequestAttempts) ctx.get(CommonContextKeys.REQUEST_ATTEMPTS);
}
/**
* This is only intended for use when running on a blocking server (ie. tomcat).
* @return
*/
public static RequestAttempts getThreadLocalInstance()
{
return threadLocal.get();
}
public static void setThreadLocalInstance(RequestAttempts instance)
{
threadLocal.set(instance);
}
public static void removeThreadLocalInstance()
{
threadLocal.remove();
}
public static RequestAttempts parse(String attemptsJson) throws IOException
{
return JACKSON_MAPPER.readValue(attemptsJson, RequestAttempts.class);
}
public String toJSON()
{
ArrayNode array = JACKSON_MAPPER.createArrayNode();
for (RequestAttempt attempt : this) {
array.add(attempt.toJsonNode());
}
try {
return JACKSON_MAPPER.writeValueAsString(array);
}
catch (JsonProcessingException e) {
throw new RuntimeException("Error serializing RequestAttempts!", e);
}
}
@Override
public String toString()
{
try {
return toJSON();
}
catch (Throwable e) {
LOG.error(e.getMessage(), e);
return "";
}
}
}
|
3e0b7963e80c4540da895e6868dd17d54a3633a3 | 2,239 | java | Java | src/main/java/com/bapcraft/altruismgifts/CommandGift.java | BapCraft/AltruismGifts | 98e7b125eaae4343f34f4a58cd85dc8592896199 | [
"MIT"
] | null | null | null | src/main/java/com/bapcraft/altruismgifts/CommandGift.java | BapCraft/AltruismGifts | 98e7b125eaae4343f34f4a58cd85dc8592896199 | [
"MIT"
] | null | null | null | src/main/java/com/bapcraft/altruismgifts/CommandGift.java | BapCraft/AltruismGifts | 98e7b125eaae4343f34f4a58cd85dc8592896199 | [
"MIT"
] | null | null | null | 22.616162 | 103 | 0.677535 | 4,845 | package com.bapcraft.altruismgifts;
import static com.bapcraft.altruismgifts.AltruismGifts.message;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
import com.bapcraft.altruismgifts.gifts.GiftHelper;
import com.bapcraft.altruismgifts.gifts.GiftProfile;
import com.bapcraft.altruismgifts.gifts.GiftingResult;
public class CommandGift implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length != 1) return false;
if (!(sender instanceof Player)) {
message(sender, "You must be a player to use this command!");
return true;
}
Player snder = (Player) sender;
String recName = args[0];
Player recer = Bukkit.getPlayer(recName);
if (recer == null) {
message(sender, "That player isn't online!");
return true;
}
GiftProfile sp = GiftProfile.load(snder);
GiftProfile rp = GiftProfile.load(recer);
PlayerInventory pi = snder.getInventory();
int slot = pi.getHeldItemSlot();
if (pi.getItem(slot) == null) {
message(sender, "There's nothing in your hand!");
return true;
}
GiftingResult gr = GiftHelper.directSend(slot, sp, rp);
switch (gr) {
case RECIEVER_DISALLOW:
message(sender, "That player isn't allowing to be sent gifts.");
break;
case RECIEVER_FULL_INVENTORY:
message(sender, "That player has a full inventory!");
break;
case RECIEVER_NOT_ONLINE:
message(sender, "That player isn't online!");
break;
case SENDER_NOT_HAVE_ITEM:
message(sender, "You don't have that item? O.o?");
break;
case SENDER_NOT_ONLINE:
message(sender, "You're not online? O.o?");
break;
case SUCCESS:
message(sender, "Success! You gifted: " + recer.getDisplayName());
message(recer, "You were sent a gift by " + snder.getDisplayName() + ChatColor.LIGHT_PURPLE + "!");
break;
default:
break;
}
return true;
}
}
|
3e0b797f259a974cd153946384a5ad00caf9a40e | 2,503 | java | Java | card.io/src/main/java/io/card/payment/i18n/locales/LocalizedStringsAR.java | skillz/card.io-Android-source | e5a0d804ef867be9b7792916f0c835842d9ea930 | [
"MIT"
] | 623 | 2015-01-03T08:06:35.000Z | 2022-03-01T09:57:04.000Z | card.io/src/main/java/io/card/payment/i18n/locales/LocalizedStringsAR.java | skillz/card.io-Android-source | e5a0d804ef867be9b7792916f0c835842d9ea930 | [
"MIT"
] | 144 | 2015-01-15T18:03:31.000Z | 2018-12-21T11:04:03.000Z | card.io/src/main/java/io/card/payment/i18n/locales/LocalizedStringsAR.java | skillz/card.io-Android-source | e5a0d804ef867be9b7792916f0c835842d9ea930 | [
"MIT"
] | 469 | 2015-01-09T10:24:50.000Z | 2022-03-17T03:36:22.000Z | 43.912281 | 220 | 0.701958 | 4,846 | package io.card.payment.i18n.locales;
import java.util.HashMap;
import java.util.Map;
import io.card.payment.i18n.StringKey;
import io.card.payment.i18n.SupportedLocale;
// Class autogenerated! Do not modify.
// Generated on 2014-12-10 11:29:25.121072 via script:
// /Users/twhipple/Documents/buffalo/lib-i18n/i18n/script/generate_android_i18n.py -java_src_path src/ -java_gen_path gen/ -stringkey_path io/card/payment/i18n/ -strings_path ../strings/projects/card.io/strings/ --strict
public class LocalizedStringsAR implements SupportedLocale<StringKey> {
private static Map<StringKey, String> mDisplay = new HashMap<>();
private static Map<String, String> mAdapted = new HashMap<>();
@Override
public String getName() {
return "ar";
}
@Override
public String getAdaptedDisplay(StringKey key, String country) {
String adaptedKey = key.toString() + "|" + country;
if (mAdapted.containsKey(adaptedKey)) {
return mAdapted.get(adaptedKey);
} else {
return mDisplay.get(key);
}
}
public LocalizedStringsAR() {
mDisplay.put(StringKey.CANCEL, "إلغاء");
mDisplay.put(StringKey.CARDTYPE_AMERICANEXPRESS, "American Express");
mDisplay.put(StringKey.CARDTYPE_DISCOVER, "Discover");
mDisplay.put(StringKey.CARDTYPE_JCB, "JCB");
mDisplay.put(StringKey.CARDTYPE_MASTERCARD, "MasterCard");
mDisplay.put(StringKey.CARDTYPE_VISA, "Visa");
mDisplay.put(StringKey.DONE, "تم");
mDisplay.put(StringKey.ENTRY_CVV, "CVV");
mDisplay.put(StringKey.ENTRY_POSTAL_CODE, "الرمز البريدي");
mDisplay.put(StringKey.ENTRY_CARDHOLDER_NAME, "اسم صاحب البطاقة");
mDisplay.put(StringKey.ENTRY_EXPIRES, "تاريخ انتهاء الصلاحية");
mDisplay.put(StringKey.EXPIRES_PLACEHOLDER, "MM/YY");
mDisplay.put(StringKey.SCAN_GUIDE, "امسك البطاقة هنا.\n ستمسح تلقائيا.");
mDisplay.put(StringKey.KEYBOARD, "لوحة المفاتيح…");
mDisplay.put(StringKey.ENTRY_CARD_NUMBER, "رقم البطاقة");
mDisplay.put(StringKey.MANUAL_ENTRY_TITLE, "تفاصيل البطاقة");
mDisplay.put(StringKey.ERROR_NO_DEVICE_SUPPORT, "هذا الجهاز لا يمكنه استعمال الكاميرا لقراءة أرقام البطاقة.");
mDisplay.put(StringKey.ERROR_CAMERA_CONNECT_FAIL, "كاميرا الجهاز غير متاحة.");
mDisplay.put(StringKey.ERROR_CAMERA_UNEXPECTED_FAIL, "الجهاز حدث به خطا غير متوقع عند فتح الكاميرا.");
// no adapted_translations found
}
}
|
3e0b79c1808d548305f397fe8443b7847d369a05 | 8,909 | java | Java | src/org/sosy_lab/cpachecker/util/automaton/NondeterministicFiniteAutomaton.java | prokopk1n/cpachecker-1 | c2e1a6a0a7dddb896153e54458003edc9afeef11 | [
"Apache-2.0"
] | 16 | 2015-01-19T15:52:14.000Z | 2015-11-30T14:12:31.000Z | src/org/sosy_lab/cpachecker/util/automaton/NondeterministicFiniteAutomaton.java | prokopk1n/cpachecker-1 | c2e1a6a0a7dddb896153e54458003edc9afeef11 | [
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/util/automaton/NondeterministicFiniteAutomaton.java | prokopk1n/cpachecker-1 | c2e1a6a0a7dddb896153e54458003edc9afeef11 | [
"Apache-2.0"
] | 18 | 2015-02-17T19:22:41.000Z | 2015-11-24T09:12:39.000Z | 24.143631 | 120 | 0.640027 | 4,847 | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.cpachecker.util.automaton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public final class NondeterministicFiniteAutomaton<T> {
public static class State {
public final int ID;
private State(int pId) {
ID = pId;
}
}
private static class StatePool {
private static class StateIterable implements Iterable<State> {
private final NondeterministicFiniteAutomaton<?> mAutomaton;
public StateIterable(NondeterministicFiniteAutomaton<?> pAutomaton) {
mAutomaton = pAutomaton;
}
@Override
public Iterator<State> iterator() {
return new StateSetIterator(mAutomaton.mStatesCounter);
}
}
private static class StateSetIterator implements Iterator<State> {
private final int mSize;
private int mCounter;
public StateSetIterator(int pSize) {
mSize = pSize;
mCounter = 0;
}
@Override
public boolean hasNext() {
return mCounter < mSize;
}
@Override
public State next() {
State lState = STATE_POOL.mPool.get(mCounter);
mCounter++;
return lState;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private static final StatePool STATE_POOL = new StatePool();
private List<State> mPool;
private int mNextStateId;
private StatePool() {
mNextStateId = 0;
mPool = new ArrayList<>();
}
public State get(NondeterministicFiniteAutomaton<?> pAutomaton) {
State lState;
if (pAutomaton.mStatesCounter == mPool.size()) {
// we have to create a new state
lState = new State(mNextStateId++);
mPool.add(lState);
} else {
// the pool contains more states than the automaton
// so return the next state not used in the automaton
lState = mPool.get(pAutomaton.mStatesCounter);
}
// we add the state to the set of states of the automaton
pAutomaton.mStatesCounter++;
return lState;
}
}
public class Edge {
private State mSource;
private State mTarget;
private T mLabel;
private Edge(State pSource, State pTarget, T pLabel) {
mSource = pSource;
mTarget = pTarget;
mLabel = pLabel;
}
public State getSource() {
return mSource;
}
public State getTarget() {
return mTarget;
}
public T getLabel() {
return mLabel;
}
@Override
public int hashCode() {
return 31 * mSource.ID + mTarget.ID;
}
@Override
public boolean equals(Object pOther) {
if (this == pOther) {
return true;
}
if (pOther == null) {
return false;
}
if (!(pOther instanceof NondeterministicFiniteAutomaton.Edge)) {
return false;
}
@SuppressWarnings("unchecked")
Edge lEdge = (Edge) pOther;
if (lEdge.mSource.equals(mSource) && lEdge.mTarget.equals(mTarget)) {
if (mLabel == null) {
return lEdge.mLabel == null;
} else {
return mLabel.equals(lEdge.mLabel);
}
}
return false;
}
}
private State mInitialState;
private Set<State> mFinalStates;
private final List<Set<Edge>> mOutgoingEdges;
private final List<Set<Edge>> mIncomingEdges;
private final List<Edge> mEdges;
private int mStatesCounter;
private final StatePool.StateIterable mStateIterable;
public NondeterministicFiniteAutomaton() {
mStateIterable = new StatePool.StateIterable(this);
mFinalStates = new HashSet<>();
mOutgoingEdges = new ArrayList<>();
mIncomingEdges = new ArrayList<>();
mEdges = new ArrayList<>();
setInitialState(createState());
}
public State getInitialState() {
return mInitialState;
}
public Set<State> getFinalStates() {
return mFinalStates;
}
public void setInitialState(State pInitialState) {
mInitialState = pInitialState;
}
public void setFinalStates(Set<State> pFinalStates) {
mFinalStates.clear();
mFinalStates.addAll(pFinalStates);
}
public void addToFinalStates(State pFinalStates) {
mFinalStates.add(pFinalStates);
}
public boolean isFinalState(State pState) {
return mFinalStates.contains(pState);
}
public Iterable<State> getStates() {
return mStateIterable;
}
public State createState() {
State lState = StatePool.STATE_POOL.get(this);
mOutgoingEdges.add(new HashSet<>());
mIncomingEdges.add(new HashSet<>());
return lState;
}
/*
* if pLabel is null it is treated as lambda.
*/
public Edge createEdge(State pSource, State pTarget, T pLabel) {
Edge lEdge = new Edge(pSource, pTarget, pLabel);
addEdge(pSource, pTarget, lEdge);
return lEdge;
}
private void addEdge(State pSource, State pTarget, Edge pEdge) {
mOutgoingEdges.get(pSource.ID).add(pEdge);
mIncomingEdges.get(pTarget.ID).add(pEdge);
mEdges.add(pEdge);
}
public Iterable<Edge> getEdges() {
return mEdges;
}
public Collection<Edge> getOutgoingEdges(State pState) {
return mOutgoingEdges.get(pState.ID);
}
public Collection<Edge> getIncomingEdges(State pState) {
return mIncomingEdges.get(pState.ID);
}
public NondeterministicFiniteAutomaton<T> getLambdaFreeAutomaton() {
NondeterministicFiniteAutomaton<T> lLambdaFreeAutomaton = new NondeterministicFiniteAutomaton<>();
// mStatesCounter - 1 because the initial state of lLambdaFreeAutomaton
// exists already
for (int lIndex = 0; lIndex < mStatesCounter - 1; lIndex++) {
lLambdaFreeAutomaton.createState();
}
// we use the same states for lLambdaFreeAutomaton so we can use our
// final states as its final states
Set<State> lFinalStates = getFinalStates();
lLambdaFreeAutomaton.setFinalStates(getFinalStates());
State lInitialState = getInitialState();
for (State lState : getLambdaClosure(lInitialState)) {
if (lFinalStates.contains(lState)) {
lLambdaFreeAutomaton.addToFinalStates(lInitialState);
}
}
for (State lState : getStates()) {
for (State lClosureElement : getLambdaClosure(lState)) {
for (Edge lOutgoingEdge : getOutgoingEdges(lClosureElement)) {
if (lOutgoingEdge.getLabel() != null) {
// not a lambda edge
State lTarget = lOutgoingEdge.getTarget();
for (State lTargetClosureElement : getLambdaClosure(lTarget)) {
// again, we use the same states in lLambdaFreeAutomaton
if (lOutgoingEdge.getSource().equals(lState) && lOutgoingEdge.getTarget().equals(lTargetClosureElement)) {
lLambdaFreeAutomaton.addEdge(lState, lTargetClosureElement, lOutgoingEdge);
} else {
lLambdaFreeAutomaton.createEdge(lState, lTargetClosureElement, lOutgoingEdge.getLabel());
}
}
}
}
}
}
return lLambdaFreeAutomaton;
}
private Set<State> getLambdaClosure(State pState) {
Set<State> lClosure = new HashSet<>();
Set<State> lWorkset = new HashSet<>();
lWorkset.add(pState);
while (!lWorkset.isEmpty()) {
State lCurrentState = lWorkset.iterator().next();
lWorkset.remove(lCurrentState);
if (lClosure.contains(lCurrentState)) {
continue;
}
lClosure.add(lCurrentState);
for (Edge lOutgoingEdge : getOutgoingEdges(lCurrentState)) {
if (lOutgoingEdge.getLabel() == null) {
// lambda edge
State lTarget = lOutgoingEdge.getTarget();
lWorkset.add(lTarget);
}
}
}
return lClosure;
}
@Override
public String toString() {
StringBuilder lBuffer = new StringBuilder();
lBuffer.append("Initial State: " + getInitialState().ID + "\n");
lBuffer.append("Final States: { ");
boolean lFirst = true;
for (State lFinalState : getFinalStates()) {
if (lFirst) {
lFirst = false;
} else {
lBuffer.append(", ");
}
lBuffer.append(lFinalState.ID);
}
lBuffer.append(" }\n");
for (Edge lEdge : getEdges()) {
T lLabel = lEdge.getLabel();
String lLabelString;
if (lLabel != null) {
lLabelString = lLabel.toString();
} else {
lLabelString = "Lambda";
}
lBuffer.append(lEdge.getSource().ID + " -[" + lLabelString + "]> " + lEdge.getTarget().ID);
lBuffer.append("\n");
}
return lBuffer.toString();
}
}
|
3e0b7ac468993040513ed29aaf9db7e402a51dc7 | 5,155 | java | Java | src/main/java/net/earthcomputer/multiconnect/protocols/ProtocolRegistry.java | wagyourtail/multiconnect | 1329def61bfc4e0475663a2d084d246f1fd92d76 | [
"MIT"
] | null | null | null | src/main/java/net/earthcomputer/multiconnect/protocols/ProtocolRegistry.java | wagyourtail/multiconnect | 1329def61bfc4e0475663a2d084d246f1fd92d76 | [
"MIT"
] | null | null | null | src/main/java/net/earthcomputer/multiconnect/protocols/ProtocolRegistry.java | wagyourtail/multiconnect | 1329def61bfc4e0475663a2d084d246f1fd92d76 | [
"MIT"
] | null | null | null | 51.039604 | 107 | 0.791077 | 4,848 | package net.earthcomputer.multiconnect.protocols;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.earthcomputer.multiconnect.protocols.generic.AbstractProtocol;
import net.earthcomputer.multiconnect.protocols.v1_10.Protocol_1_10;
import net.earthcomputer.multiconnect.protocols.v1_11.Protocol_1_11;
import net.earthcomputer.multiconnect.protocols.v1_11_2.Protocol_1_11_2;
import net.earthcomputer.multiconnect.protocols.v1_12.Protocol_1_12;
import net.earthcomputer.multiconnect.protocols.v1_12_1.Protocol_1_12_1;
import net.earthcomputer.multiconnect.protocols.v1_12_2.Protocol_1_12_2;
import net.earthcomputer.multiconnect.protocols.v1_13.Protocol_1_13;
import net.earthcomputer.multiconnect.protocols.v1_13_1.Protocol_1_13_1;
import net.earthcomputer.multiconnect.protocols.v1_13_2.Protocol_1_13_2;
import net.earthcomputer.multiconnect.protocols.v1_14.Protocol_1_14;
import net.earthcomputer.multiconnect.protocols.v1_14_1.Protocol_1_14_1;
import net.earthcomputer.multiconnect.protocols.v1_14_2.Protocol_1_14_2;
import net.earthcomputer.multiconnect.protocols.v1_14_3.Protocol_1_14_3;
import net.earthcomputer.multiconnect.protocols.v1_14_4.Protocol_1_14_4;
import net.earthcomputer.multiconnect.protocols.v1_15.Protocol_1_15;
import net.earthcomputer.multiconnect.protocols.v1_15_1.Protocol_1_15_1;
import net.earthcomputer.multiconnect.protocols.v1_15_2.Protocol_1_15_2;
import net.earthcomputer.multiconnect.protocols.v1_16.Protocol_1_16;
import net.earthcomputer.multiconnect.protocols.v1_16_1.Protocol_1_16_1;
import net.earthcomputer.multiconnect.protocols.v1_16_2.Protocol_1_16_2;
import net.earthcomputer.multiconnect.protocols.v1_16_3.Protocol_1_16_3;
import net.earthcomputer.multiconnect.transformer.InboundTranslator;
import net.earthcomputer.multiconnect.transformer.OutboundTranslator;
import net.earthcomputer.multiconnect.transformer.TranslatorRegistry;
import net.minecraft.SharedConstants;
import static net.earthcomputer.multiconnect.api.Protocols.*;
public class ProtocolRegistry {
private static Int2ObjectOpenHashMap<AbstractProtocol> protocols = new Int2ObjectOpenHashMap<>();
private static TranslatorRegistry translatorRegistry = new TranslatorRegistry();
public static AbstractProtocol get(int version) {
return protocols.get(version);
}
public static AbstractProtocol latest() {
return protocols.get(SharedConstants.getGameVersion().getProtocolVersion());
}
public static TranslatorRegistry getTranslatorRegistry() {
return translatorRegistry;
}
// usually you want type and translator to handle the same type
public static <T> void registerInboundTranslator(Class<T> type, InboundTranslator<T> translator) {
translatorRegistry.registerInboundTranslator(registeringProtocol, type, translator);
}
public static void registerInboundTranslatorUnchecked(Class<?> type, InboundTranslator<?> translator) {
translatorRegistry.registerInboundTranslatorUnchecked(registeringProtocol, type, translator);
}
public static <T> void registerOutboundTranslator(Class<T> type, OutboundTranslator<T> translator) {
translatorRegistry.registerOutboundTranslator(registeringProtocol, type, translator);
}
private static int registeringProtocol;
private static void register(int version, AbstractProtocol protocol) {
register(version, protocol, () -> {});
}
private static void register(int version, AbstractProtocol protocol, Runnable registerTranslators) {
registeringProtocol = version;
protocols.put(version, protocol);
registerTranslators.run();
}
static {
register(V1_16_3, new Protocol_1_16_3());
register(V1_16_2, new Protocol_1_16_2());
register(V1_16_1, new Protocol_1_16_1(), Protocol_1_16_1::registerTranslators);
register(V1_16, new Protocol_1_16());
register(V1_15_2, new Protocol_1_15_2(), Protocol_1_15_2::registerTranslators);
register(V1_15_1, new Protocol_1_15_1());
register(V1_15, new Protocol_1_15());
register(V1_14_4, new Protocol_1_14_4(), Protocol_1_14_4::registerTranslators);
register(V1_14_3, new Protocol_1_14_3(), Protocol_1_14_3::registerTranslators);
register(V1_14_2, new Protocol_1_14_2(), Protocol_1_14_2::registerTranslators);
register(V1_14_1, new Protocol_1_14_1());
register(V1_14, new Protocol_1_14());
register(V1_13_2, new Protocol_1_13_2(), Protocol_1_13_2::registerTranslators);
register(V1_13_1, new Protocol_1_13_1(), Protocol_1_13_1::registerTranslators);
register(V1_13, new Protocol_1_13(), Protocol_1_13::registerTranslators);
register(V1_12_2, new Protocol_1_12_2(), Protocol_1_12_2::registerTranslators);
register(V1_12_1, new Protocol_1_12_1(), Protocol_1_12_1::registerTranslators);
register(V1_12, new Protocol_1_12());
register(V1_11_2, new Protocol_1_11_2(), Protocol_1_11_2::registerTranslators);
register(V1_11, new Protocol_1_11());
register(V1_10, new Protocol_1_10(), Protocol_1_10::registerTranslators);
}
}
|
3e0b7cf593abc7b76d50fed5dfd39180e8889f15 | 49,587 | java | Java | src/main/java/org/orekit/propagation/numerical/NumericalPropagator.java | Vyom-Yadav/Orekit | 4874bd4a3fb3161068340a7b3b2c2fbd31bf6d61 | [
"Apache-2.0"
] | 100 | 2015-08-20T05:43:49.000Z | 2022-03-24T10:13:40.000Z | src/main/java/org/orekit/propagation/numerical/NumericalPropagator.java | Vyom-Yadav/Orekit | 4874bd4a3fb3161068340a7b3b2c2fbd31bf6d61 | [
"Apache-2.0"
] | 15 | 2015-07-27T09:49:24.000Z | 2022-02-10T08:15:02.000Z | src/main/java/org/orekit/propagation/numerical/NumericalPropagator.java | Vyom-Yadav/Orekit | 4874bd4a3fb3161068340a7b3b2c2fbd31bf6d61 | [
"Apache-2.0"
] | 68 | 2015-07-24T00:44:05.000Z | 2022-03-18T09:02:11.000Z | 44.432796 | 163 | 0.63565 | 4,849 | /* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.propagation.numerical;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.linear.MatrixUtils;
import org.hipparchus.linear.QRDecomposition;
import org.hipparchus.linear.RealMatrix;
import org.hipparchus.ode.ODEIntegrator;
import org.hipparchus.util.FastMath;
import org.hipparchus.util.Precision;
import org.orekit.annotation.DefaultDataContext;
import org.orekit.attitudes.Attitude;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.data.DataContext;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitIllegalArgumentException;
import org.orekit.errors.OrekitInternalError;
import org.orekit.errors.OrekitMessages;
import org.orekit.forces.ForceModel;
import org.orekit.forces.gravity.NewtonianAttraction;
import org.orekit.forces.inertia.InertialForces;
import org.orekit.forces.maneuvers.Maneuver;
import org.orekit.forces.maneuvers.jacobians.Duration;
import org.orekit.forces.maneuvers.jacobians.MedianDate;
import org.orekit.forces.maneuvers.jacobians.TriggerDate;
import org.orekit.forces.maneuvers.trigger.AbstractManeuverTriggers;
import org.orekit.forces.maneuvers.trigger.ManeuverTriggers;
import org.orekit.frames.Frame;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.AbstractMatricesHarvester;
import org.orekit.propagation.AdditionalStateProvider;
import org.orekit.propagation.MatricesHarvester;
import org.orekit.propagation.PropagationType;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.events.ParameterDrivenDateIntervalDetector;
import org.orekit.propagation.integration.AbstractIntegratedPropagator;
import org.orekit.propagation.integration.AdditionalDerivativesProvider;
import org.orekit.propagation.integration.StateMapper;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.AbsolutePVCoordinates;
import org.orekit.utils.DoubleArrayDictionary;
import org.orekit.utils.PVCoordinates;
import org.orekit.utils.ParameterDriver;
import org.orekit.utils.ParameterDriversList;
import org.orekit.utils.ParameterDriversList.DelegatingDriver;
import org.orekit.utils.ParameterObserver;
import org.orekit.utils.TimeStampedPVCoordinates;
/** This class propagates {@link org.orekit.orbits.Orbit orbits} using
* numerical integration.
* <p>Numerical propagation is much more accurate than analytical propagation
* like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
* Keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
* Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
* Whereas analytical propagators are configured only thanks to their various
* constructors and can be used immediately after construction, numerical propagators
* configuration involve setting several parameters between construction time
* and propagation time.</p>
* <p>The configuration parameters that can be set are:</p>
* <ul>
* <li>the initial spacecraft state ({@link #setInitialState(SpacecraftState)})</li>
* <li>the central attraction coefficient ({@link #setMu(double)})</li>
* <li>the various force models ({@link #addForceModel(ForceModel)},
* {@link #removeForceModels()})</li>
* <li>the {@link OrbitType type} of orbital parameters to be used for propagation
* ({@link #setOrbitType(OrbitType)}),</li>
* <li>the {@link PositionAngle type} of position angle to be used in orbital parameters
* to be used for propagation where it is relevant ({@link
* #setPositionAngleType(PositionAngle)}),</li>
* <li>whether {@link MatricesHarvester state transition matrices and Jacobians matrices}
* should be propagated along with orbital state ({@link
* #setupMatricesComputation(String, RealMatrix, DoubleArrayDictionary)}),</li>
* <li>whether {@link org.orekit.propagation.integration.AdditionalDerivativesProvider additional derivatives}
* should be propagated along with orbital state ({@link
* #addAdditionalDerivativesProvider(AdditionalDerivativesProvider)}),</li>
* <li>the discrete events that should be triggered during propagation
* ({@link #addEventDetector(EventDetector)},
* {@link #clearEventsDetectors()})</li>
* <li>the binding logic with the rest of the application ({@link #getMultiplexer()})</li>
* </ul>
* <p>From these configuration parameters, only the initial state is mandatory. The default
* propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial} parameters with
* {@link PositionAngle#TRUE true} longitude argument. If the central attraction coefficient
* is not explicitly specified, the one used to define the initial orbit will be used.
* However, specifying only the initial state and perhaps the central attraction coefficient
* would mean the propagator would use only Keplerian forces. In this case, the simpler {@link
* org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
* perhaps be more effective.</p>
* <p>The underlying numerical integrator set up in the constructor may also have its own
* configuration parameters. Typical configuration parameters for adaptive stepsize integrators
* are the min, max and perhaps start step size as well as the absolute and/or relative errors
* thresholds.</p>
* <p>The state that is seen by the integrator is a simple seven elements double array.
* The six first elements are either:
* <ul>
* <li>the {@link org.orekit.orbits.EquinoctialOrbit equinoctial orbit parameters} (a, e<sub>x</sub>,
* e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>M</sub> or λ<sub>E</sub>
* or λ<sub>v</sub>) in meters and radians,</li>
* <li>the {@link org.orekit.orbits.KeplerianOrbit Keplerian orbit parameters} (a, e, i, ω, Ω,
* M or E or v) in meters and radians,</li>
* <li>the {@link org.orekit.orbits.CircularOrbit circular orbit parameters} (a, e<sub>x</sub>, e<sub>y</sub>, i,
* Ω, α<sub>M</sub> or α<sub>E</sub> or α<sub>v</sub>) in meters
* and radians,</li>
* <li>the {@link org.orekit.orbits.CartesianOrbit Cartesian orbit parameters} (x, y, z, v<sub>x</sub>,
* v<sub>y</sub>, v<sub>z</sub>) in meters and meters per seconds.
* </ul>
* <p> The last element is the mass in kilograms and changes only during thrusters firings
*
* <p>The following code snippet shows a typical setting for Low Earth Orbit propagation in
* equinoctial parameters and true longitude argument:</p>
* <pre>
* final double dP = 0.001;
* final double minStep = 0.001;
* final double maxStep = 500;
* final double initStep = 60;
* final double[][] tolerance = NumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
* AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tolerance[0], tolerance[1]);
* integrator.setInitialStepSize(initStep);
* propagator = new NumericalPropagator(integrator);
* </pre>
* <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
* thus allowing a new propagation to be started from there without recomputing the part already performed.
* This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
* </p>
* <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
* thread-safe.</p>
*
* @see SpacecraftState
* @see ForceModel
* @see org.orekit.propagation.sampling.OrekitStepHandler
* @see org.orekit.propagation.sampling.OrekitFixedStepHandler
* @see org.orekit.propagation.integration.IntegratedEphemeris
* @see TimeDerivativesEquations
*
* @author Mathieu Roméro
* @author Luc Maisonobe
* @author Guylaine Prat
* @author Fabien Maussion
* @author Véronique Pommier-Maurussane
*/
public class NumericalPropagator extends AbstractIntegratedPropagator {
/** Space dimension. */
private static final int SPACE_DIMENSION = 3;
/** State dimension. */
private static final int STATE_DIMENSION = 2 * SPACE_DIMENSION;
/** Threshold for matrix solving. */
private static final double THRESHOLD = Precision.SAFE_MIN;
/** Force models used during the extrapolation of the orbit. */
private final List<ForceModel> forceModels;
/** boolean to ignore or not the creation of a NewtonianAttraction. */
private boolean ignoreCentralAttraction;
/** Create a new instance of NumericalPropagator, based on orbit definition mu.
* After creation, the instance is empty, i.e. the attitude provider is set to an
* unspecified default law and there are no perturbing forces at all.
* This means that if {@link #addForceModel addForceModel} is not
* called after creation, the integrated orbit will follow a Keplerian
* evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
* for {@link #setOrbitType(OrbitType) propagation
* orbit type} and {@link PositionAngle#TRUE} for {@link
* #setPositionAngleType(PositionAngle) position angle type}.
*
* <p>This constructor uses the {@link DataContext#getDefault() default data context}.
*
* @param integrator numerical integrator to use for propagation.
* @see #NumericalPropagator(ODEIntegrator, AttitudeProvider)
*/
@DefaultDataContext
public NumericalPropagator(final ODEIntegrator integrator) {
this(integrator,
Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
}
/** Create a new instance of NumericalPropagator, based on orbit definition mu.
* After creation, the instance is empty, i.e. the attitude provider is set to an
* unspecified default law and there are no perturbing forces at all.
* This means that if {@link #addForceModel addForceModel} is not
* called after creation, the integrated orbit will follow a Keplerian
* evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
* for {@link #setOrbitType(OrbitType) propagation
* orbit type} and {@link PositionAngle#TRUE} for {@link
* #setPositionAngleType(PositionAngle) position angle type}.
* @param integrator numerical integrator to use for propagation.
* @param attitudeProvider the attitude law.
* @since 10.1
*/
public NumericalPropagator(final ODEIntegrator integrator,
final AttitudeProvider attitudeProvider) {
super(integrator, PropagationType.MEAN);
forceModels = new ArrayList<ForceModel>();
ignoreCentralAttraction = false;
initMapper();
setAttitudeProvider(attitudeProvider);
clearStepHandlers();
setOrbitType(OrbitType.EQUINOCTIAL);
setPositionAngleType(PositionAngle.TRUE);
}
/** Set the flag to ignore or not the creation of a {@link NewtonianAttraction}.
* @param ignoreCentralAttraction if true, {@link NewtonianAttraction} is <em>not</em>
* added automatically if missing
*/
public void setIgnoreCentralAttraction(final boolean ignoreCentralAttraction) {
this.ignoreCentralAttraction = ignoreCentralAttraction;
}
/** Set the central attraction coefficient μ.
* <p>
* Setting the central attraction coefficient is
* equivalent to {@link #addForceModel(ForceModel) add}
* a {@link NewtonianAttraction} force model.
* </p>
* @param mu central attraction coefficient (m³/s²)
* @see #addForceModel(ForceModel)
* @see #getAllForceModels()
*/
public void setMu(final double mu) {
if (ignoreCentralAttraction) {
superSetMu(mu);
} else {
addForceModel(new NewtonianAttraction(mu));
}
}
/** Set the central attraction coefficient μ only in upper class.
* @param mu central attraction coefficient (m³/s²)
*/
private void superSetMu(final double mu) {
super.setMu(mu);
}
/** Check if Newtonian attraction force model is available.
* <p>
* Newtonian attraction is always the last force model in the list.
* </p>
* @return true if Newtonian attraction force model is available
*/
private boolean hasNewtonianAttraction() {
final int last = forceModels.size() - 1;
return last >= 0 && forceModels.get(last) instanceof NewtonianAttraction;
}
/** Add a force model.
* <p>If this method is not called at all, the integrated orbit will follow
* a Keplerian evolution only.</p>
* @param model {@link ForceModel} to add (it can be either a perturbing force
* model or an instance of {@link NewtonianAttraction})
* @see #removeForceModels()
* @see #setMu(double)
*/
public void addForceModel(final ForceModel model) {
if (model instanceof NewtonianAttraction) {
// we want to add the central attraction force model
try {
// ensure we are notified of any mu change
model.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
/** {@inheritDoc} */
@Override
public void valueChanged(final double previousValue, final ParameterDriver driver) {
superSetMu(driver.getValue());
}
});
} catch (OrekitException oe) {
// this should never happen
throw new OrekitInternalError(oe);
}
if (hasNewtonianAttraction()) {
// there is already a central attraction model, replace it
forceModels.set(forceModels.size() - 1, model);
} else {
// there are no central attraction model yet, add it at the end of the list
forceModels.add(model);
}
} else {
// we want to add a perturbing force model
if (hasNewtonianAttraction()) {
// insert the new force model before Newtonian attraction,
// which should always be the last one in the list
forceModels.add(forceModels.size() - 1, model);
} else {
// we only have perturbing force models up to now, just append at the end of the list
forceModels.add(model);
}
}
}
/** Remove all force models (except central attraction).
* <p>Once all perturbing forces have been removed (and as long as no new force
* model is added), the integrated orbit will follow a Keplerian evolution
* only.</p>
* @see #addForceModel(ForceModel)
*/
public void removeForceModels() {
final int last = forceModels.size() - 1;
if (hasNewtonianAttraction()) {
// preserve the Newtonian attraction model at the end
final ForceModel newton = forceModels.get(last);
forceModels.clear();
forceModels.add(newton);
} else {
forceModels.clear();
}
}
/** Get all the force models, perturbing forces and Newtonian attraction included.
* @return list of perturbing force models, with Newtonian attraction being the
* last one
* @see #addForceModel(ForceModel)
* @see #setMu(double)
*/
public List<ForceModel> getAllForceModels() {
return Collections.unmodifiableList(forceModels);
}
/** Set propagation orbit type.
* @param orbitType orbit type to use for propagation, null for
* propagating using {@link org.orekit.utils.AbsolutePVCoordinates} rather than {@link Orbit}
*/
public void setOrbitType(final OrbitType orbitType) {
super.setOrbitType(orbitType);
}
/** Get propagation parameter type.
* @return orbit type used for propagation, null for
* propagating using {@link org.orekit.utils.AbsolutePVCoordinates} rather than {@link Orbit}
*/
public OrbitType getOrbitType() {
return super.getOrbitType();
}
/** Set position angle type.
* <p>
* The position parameter type is meaningful only if {@link
* #getOrbitType() propagation orbit type}
* support it. As an example, it is not meaningful for propagation
* in {@link OrbitType#CARTESIAN Cartesian} parameters.
* </p>
* @param positionAngleType angle type to use for propagation
*/
public void setPositionAngleType(final PositionAngle positionAngleType) {
super.setPositionAngleType(positionAngleType);
}
/** Get propagation parameter type.
* @return angle type to use for propagation
*/
public PositionAngle getPositionAngleType() {
return super.getPositionAngleType();
}
/** Set the initial state.
* @param initialState initial state
*/
public void setInitialState(final SpacecraftState initialState) {
resetInitialState(initialState);
}
/** {@inheritDoc} */
public void resetInitialState(final SpacecraftState state) {
super.resetInitialState(state);
if (!hasNewtonianAttraction()) {
// use the state to define central attraction
setMu(state.getMu());
}
setStartDate(state.getDate());
}
/** Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
* @return names of the parameters (i.e. columns) of the Jacobian matrix
*/
List<String> getJacobiansColumnsNames() {
final List<String> columnsNames = new ArrayList<>();
for (final ForceModel forceModel : getAllForceModels()) {
for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
if (driver.isSelected() && !columnsNames.contains(driver.getName())) {
columnsNames.add(driver.getName());
}
}
}
Collections.sort(columnsNames);
return columnsNames;
}
/** {@inheritDoc} */
@Override
protected AbstractMatricesHarvester createHarvester(final String stmName, final RealMatrix initialStm,
final DoubleArrayDictionary initialJacobianColumns) {
return new NumericalPropagationHarvester(this, stmName, initialStm, initialJacobianColumns);
}
/** {@inheritDoc} */
@Override
protected void setUpStmAndJacobianGenerators() {
final AbstractMatricesHarvester harvester = getHarvester();
if (harvester != null) {
// set up the additional equations and additional state providers
final StateTransitionMatrixGenerator stmGenerator = setUpStmGenerator();
final List<String> triggersDates = setUpTriggerDatesJacobiansColumns(stmGenerator.getName());
setUpRegularParametersJacobiansColumns(stmGenerator, triggersDates);
// as we are now starting the propagation, everything is configured
// we can freeze the names in the harvester
harvester.freezeColumnsNames();
}
}
/** Set up the State Transition Matrix Generator.
* @return State Transition Matrix Generator
* @since 11.1
*/
private StateTransitionMatrixGenerator setUpStmGenerator() {
final AbstractMatricesHarvester harvester = getHarvester();
// add the STM generator corresponding to the current settings, and setup state accordingly
StateTransitionMatrixGenerator stmGenerator = null;
for (final AdditionalDerivativesProvider equations : getAdditionalDerivativesProviders()) {
if (equations instanceof StateTransitionMatrixGenerator &&
equations.getName().equals(harvester.getStmName())) {
// the STM generator has already been set up in a previous propagation
stmGenerator = (StateTransitionMatrixGenerator) equations;
break;
}
}
if (stmGenerator == null) {
// this is the first time we need the STM generate, create it
stmGenerator = new StateTransitionMatrixGenerator(harvester.getStmName(), getAllForceModels(), getAttitudeProvider());
addAdditionalDerivativesProvider(stmGenerator);
}
if (!getInitialIntegrationState().hasAdditionalState(harvester.getStmName())) {
// add the initial State Transition Matrix if it is not already there
// (perhaps due to a previous propagation)
setInitialState(stmGenerator.setInitialStateTransitionMatrix(getInitialState(),
harvester.getInitialStateTransitionMatrix(),
getOrbitType(),
getPositionAngleType()));
}
return stmGenerator;
}
/** Set up the Jacobians columns generator dedicated to trigger dates.
* @param stmName name of the State Transition Matrix state
* @return names of the columns corresponding to trigger dates
* @since 11.1
*/
private List<String> setUpTriggerDatesJacobiansColumns(final String stmName) {
final List<String> names = new ArrayList<>();
for (final ForceModel forceModel : getAllForceModels()) {
if (forceModel instanceof Maneuver) {
final Maneuver maneuver = (Maneuver) forceModel;
final ManeuverTriggers maneuverTriggers = maneuver.getManeuverTriggers();
if (maneuverTriggers instanceof AbstractManeuverTriggers) {
// FIXME: when issue https://gitlab.orekit.org/orekit/orekit/-/issues/854 is solved
// the previous if statement and the following cast should be removed as the following
// code should really be done for all ManeuverTriggers and not only AbstractManeuverTriggers
final AbstractManeuverTriggers amt = (AbstractManeuverTriggers) maneuverTriggers;
amt.getEventsDetectors().
filter(d -> d instanceof ParameterDrivenDateIntervalDetector).
map (d -> (ParameterDrivenDateIntervalDetector) d).
forEach(d -> {
if (d.getStartDriver().isSelected() || d.getMedianDriver().isSelected() || d.getDurationDriver().isSelected()) {
final TriggerDate start =
manageTriggerDate(stmName, maneuver, amt, d.getStartDriver().getName(), true, d.getThreshold());
names.add(start.getName());
}
if (d.getStopDriver().isSelected() || d.getMedianDriver().isSelected() || d.getDurationDriver().isSelected()) {
final TriggerDate stop =
manageTriggerDate(stmName, maneuver, amt, d.getStopDriver().getName(), false, d.getThreshold());
names.add(stop.getName());
}
if (d.getMedianDriver().isSelected()) {
final MedianDate median =
manageMedianDate(d.getStartDriver().getName(), d.getStopDriver().getName(), d.getMedianDriver().getName());
names.add(median.getName());
}
if (d.getDurationDriver().isSelected()) {
final Duration duration =
manageManeuverDuration(d.getStartDriver().getName(), d.getStopDriver().getName(), d.getDurationDriver().getName());
names.add(duration.getName());
}
});
}
}
}
return names;
}
/** Manage a maneuver trigger date.
* @param stmName name of the State Transition Matrix state
* @param maneuver maneuver force model
* @param amt trigger to which the driver is bound
* @param driverName name of the date driver
* @param start if true, the driver is a maneuver start
* @param threshold event detector threshold
* @return generator for the date driver
* @since 11.1
*/
private TriggerDate manageTriggerDate(final String stmName,
final Maneuver maneuver,
final AbstractManeuverTriggers amt,
final String driverName,
final boolean start,
final double threshold) {
TriggerDate triggerGenerator = null;
// check if we already have set up the provider
for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
if (provider instanceof TriggerDate &&
provider.getName().equals(driverName)) {
// the Jacobian column generator has already been set up in a previous propagation
triggerGenerator = (TriggerDate) provider;
break;
}
}
if (triggerGenerator == null) {
// this is the first time we need the Jacobian column generator, create it
triggerGenerator = new TriggerDate(stmName, driverName, start, maneuver, threshold);
amt.addResetter(triggerGenerator);
addAdditionalDerivativesProvider(triggerGenerator.getMassDepletionDelay());
addAdditionalStateProvider(triggerGenerator);
}
if (!getInitialIntegrationState().hasAdditionalState(driverName)) {
// add the initial Jacobian column if it is not already there
// (perhaps due to a previous propagation)
setInitialColumn(triggerGenerator.getMassDepletionDelay().getName(), new double[6]);
setInitialColumn(driverName, getHarvester().getInitialJacobianColumn(driverName));
}
return triggerGenerator;
}
/** Manage a maneuver median date.
* @param startName name of the start driver
* @param stopName name of the stop driver
* @param medianName name of the median driver
* @return generator for the median driver
* @since 11.1
*/
private MedianDate manageMedianDate(final String startName, final String stopName, final String medianName) {
MedianDate medianGenerator = null;
// check if we already have set up the provider
for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
if (provider instanceof MedianDate &&
provider.getName().equals(medianName)) {
// the Jacobian column generator has already been set up in a previous propagation
medianGenerator = (MedianDate) provider;
break;
}
}
if (medianGenerator == null) {
// this is the first time we need the Jacobian column generator, create it
medianGenerator = new MedianDate(startName, stopName, medianName);
addAdditionalStateProvider(medianGenerator);
}
if (!getInitialIntegrationState().hasAdditionalState(medianName)) {
// add the initial Jacobian column if it is not already there
// (perhaps due to a previous propagation)
setInitialColumn(medianName, getHarvester().getInitialJacobianColumn(medianName));
}
return medianGenerator;
}
/** Manage a maneuver duration.
* @param startName name of the start driver
* @param stopName name of the stop driver
* @param durationName name of the duration driver
* @return generator for the median driver
* @since 11.1
*/
private Duration manageManeuverDuration(final String startName, final String stopName, final String durationName) {
Duration durationGenerator = null;
// check if we already have set up the provider
for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
if (provider instanceof Duration &&
provider.getName().equals(durationName)) {
// the Jacobian column generator has already been set up in a previous propagation
durationGenerator = (Duration) provider;
break;
}
}
if (durationGenerator == null) {
// this is the first time we need the Jacobian column generator, create it
durationGenerator = new Duration(startName, stopName, durationName);
addAdditionalStateProvider(durationGenerator);
}
if (!getInitialIntegrationState().hasAdditionalState(durationName)) {
// add the initial Jacobian column if it is not already there
// (perhaps due to a previous propagation)
setInitialColumn(durationName, getHarvester().getInitialJacobianColumn(durationName));
}
return durationGenerator;
}
/** Set up the Jacobians columns generator for regular parameters.
* @param stmGenerator generator for the State Transition Matrix
* @param triggerDates names of the columns already managed as trigger dates
* @since 11.1
*/
private void setUpRegularParametersJacobiansColumns(final StateTransitionMatrixGenerator stmGenerator,
final List<String> triggerDates) {
// first pass: gather all parameters (excluding trigger dates), binding similar names together
final ParameterDriversList selected = new ParameterDriversList();
for (final ForceModel forceModel : getAllForceModels()) {
for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
if (!triggerDates.contains(driver.getName())) {
selected.add(driver);
}
}
}
// second pass: now that shared parameter names are bound together,
// their selections status have been synchronized, we can filter them
selected.filter(true);
// third pass: sort parameters lexicographically
selected.sort();
// add the Jacobians column generators corresponding to parameters, and setup state accordingly
for (final DelegatingDriver driver : selected.getDrivers()) {
IntegrableJacobianColumnGenerator generator = null;
// check if we already have set up the providers
for (final AdditionalDerivativesProvider provider : getAdditionalDerivativesProviders()) {
if (provider instanceof IntegrableJacobianColumnGenerator &&
provider.getName().equals(driver.getName())) {
// the Jacobian column generator has already been set up in a previous propagation
generator = (IntegrableJacobianColumnGenerator) provider;
break;
}
}
if (generator == null) {
// this is the first time we need the Jacobian column generator, create it
generator = new IntegrableJacobianColumnGenerator(stmGenerator, driver.getName());
addAdditionalDerivativesProvider(generator);
}
if (!getInitialIntegrationState().hasAdditionalState(driver.getName())) {
// add the initial Jacobian column if it is not already there
// (perhaps due to a previous propagation)
setInitialColumn(driver.getName(), getHarvester().getInitialJacobianColumn(driver.getName()));
}
}
}
/** Add the initial value of the column to the initial state.
* <p>
* The initial state must already contain the Cartesian State Transition Matrix.
* </p>
* @param columnName name of the column
* @param dYdQ column of the Jacobian ∂Y/∂qₘ with respect to propagation type,
* if null (which is the most frequent case), assumed to be 0
* @since 11.1
*/
private void setInitialColumn(final String columnName, final double[] dYdQ) {
final SpacecraftState state = getInitialState();
if (dYdQ.length != STATE_DIMENSION) {
throw new OrekitException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
dYdQ.length, STATE_DIMENSION);
}
// convert to Cartesian Jacobian
final double[][] dYdC = new double[STATE_DIMENSION][STATE_DIMENSION];
getOrbitType().convertType(state.getOrbit()).getJacobianWrtCartesian(getPositionAngleType(), dYdC);
final double[] column = new QRDecomposition(MatrixUtils.createRealMatrix(dYdC), THRESHOLD).
getSolver().
solve(MatrixUtils.createRealVector(dYdQ)).
toArray();
// set additional state
setInitialState(state.addAdditionalState(columnName, column));
}
/** {@inheritDoc} */
@Override
public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
return propagate(date).getPVCoordinates(frame);
}
/** {@inheritDoc} */
@Override
protected StateMapper createMapper(final AbsoluteDate referenceDate, final double mu,
final OrbitType orbitType, final PositionAngle positionAngleType,
final AttitudeProvider attitudeProvider, final Frame frame) {
return new OsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
}
/** Internal mapper using directly osculating parameters. */
private static class OsculatingMapper extends StateMapper {
/** Simple constructor.
* <p>
* The position parameter type is meaningful only if {@link
* #getOrbitType() propagation orbit type}
* support it. As an example, it is not meaningful for propagation
* in {@link OrbitType#CARTESIAN Cartesian} parameters.
* </p>
* @param referenceDate reference date
* @param mu central attraction coefficient (m³/s²)
* @param orbitType orbit type to use for mapping (can be null for {@link AbsolutePVCoordinates})
* @param positionAngleType angle type to use for propagation
* @param attitudeProvider attitude provider
* @param frame inertial frame
*/
OsculatingMapper(final AbsoluteDate referenceDate, final double mu,
final OrbitType orbitType, final PositionAngle positionAngleType,
final AttitudeProvider attitudeProvider, final Frame frame) {
super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
}
/** {@inheritDoc} */
public SpacecraftState mapArrayToState(final AbsoluteDate date, final double[] y, final double[] yDot,
final PropagationType type) {
// the parameter type is ignored for the Numerical Propagator
final double mass = y[6];
if (mass <= 0.0) {
throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
}
if (getOrbitType() == null) {
// propagation uses absolute position-velocity-acceleration
final Vector3D p = new Vector3D(y[0], y[1], y[2]);
final Vector3D v = new Vector3D(y[3], y[4], y[5]);
final Vector3D a;
final AbsolutePVCoordinates absPva;
if (yDot == null) {
absPva = new AbsolutePVCoordinates(getFrame(), new TimeStampedPVCoordinates(date, p, v));
} else {
a = new Vector3D(yDot[3], yDot[4], yDot[5]);
absPva = new AbsolutePVCoordinates(getFrame(), new TimeStampedPVCoordinates(date, p, v, a));
}
final Attitude attitude = getAttitudeProvider().getAttitude(absPva, date, getFrame());
return new SpacecraftState(absPva, attitude, mass);
} else {
// propagation uses regular orbits
final Orbit orbit = getOrbitType().mapArrayToOrbit(y, yDot, getPositionAngleType(), date, getMu(), getFrame());
final Attitude attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());
return new SpacecraftState(orbit, attitude, mass);
}
}
/** {@inheritDoc} */
public void mapStateToArray(final SpacecraftState state, final double[] y, final double[] yDot) {
if (getOrbitType() == null) {
// propagation uses absolute position-velocity-acceleration
final Vector3D p = state.getAbsPVA().getPosition();
final Vector3D v = state.getAbsPVA().getVelocity();
y[0] = p.getX();
y[1] = p.getY();
y[2] = p.getZ();
y[3] = v.getX();
y[4] = v.getY();
y[5] = v.getZ();
y[6] = state.getMass();
}
else {
getOrbitType().mapOrbitToArray(state.getOrbit(), getPositionAngleType(), y, yDot);
y[6] = state.getMass();
}
}
}
/** {@inheritDoc} */
protected MainStateEquations getMainStateEquations(final ODEIntegrator integrator) {
return new Main(integrator);
}
/** Internal class for osculating parameters integration. */
private class Main implements MainStateEquations, TimeDerivativesEquations {
/** Derivatives array. */
private final double[] yDot;
/** Current state. */
private SpacecraftState currentState;
/** Jacobian of the orbital parameters with respect to the Cartesian parameters. */
private double[][] jacobian;
/** Simple constructor.
* @param integrator numerical integrator to use for propagation.
*/
Main(final ODEIntegrator integrator) {
this.yDot = new double[7];
this.jacobian = new double[6][6];
for (final ForceModel forceModel : forceModels) {
forceModel.getEventsDetectors().forEach(detector -> setUpEventDetector(integrator, detector));
}
if (getOrbitType() == null) {
// propagation uses absolute position-velocity-acceleration
// we can set Jacobian once and for all
for (int i = 0; i < jacobian.length; ++i) {
Arrays.fill(jacobian[i], 0.0);
jacobian[i][i] = 1.0;
}
}
}
/** {@inheritDoc} */
@Override
public void init(final SpacecraftState initialState, final AbsoluteDate target) {
forceModels.forEach(fm -> fm.init(initialState, target));
}
/** {@inheritDoc} */
@Override
public double[] computeDerivatives(final SpacecraftState state) {
currentState = state;
Arrays.fill(yDot, 0.0);
if (getOrbitType() != null) {
// propagation uses regular orbits
currentState.getOrbit().getJacobianWrtCartesian(getPositionAngleType(), jacobian);
}
// compute the contributions of all perturbing forces,
// using the Kepler contribution at the end since
// NewtonianAttraction is always the last instance in the list
for (final ForceModel forceModel : forceModels) {
forceModel.addContribution(state, this);
}
if (getOrbitType() == null) {
// position derivative is velocity, and was not added above in the force models
// (it is added when orbit type is non-null because NewtonianAttraction considers it)
final Vector3D velocity = currentState.getPVCoordinates().getVelocity();
yDot[0] += velocity.getX();
yDot[1] += velocity.getY();
yDot[2] += velocity.getZ();
}
return yDot.clone();
}
/** {@inheritDoc} */
@Override
public void addKeplerContribution(final double mu) {
if (getOrbitType() == null) {
// if mu is neither 0 nor NaN, we want to include Newtonian acceleration
if (mu > 0) {
// velocity derivative is Newtonian acceleration
final Vector3D position = currentState.getPVCoordinates().getPosition();
final double r2 = position.getNormSq();
final double coeff = -mu / (r2 * FastMath.sqrt(r2));
yDot[3] += coeff * position.getX();
yDot[4] += coeff * position.getY();
yDot[5] += coeff * position.getZ();
}
} else {
// propagation uses regular orbits
currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
}
}
/** {@inheritDoc} */
public void addNonKeplerianAcceleration(final Vector3D gamma) {
for (int i = 0; i < 6; ++i) {
final double[] jRow = jacobian[i];
yDot[i] += jRow[3] * gamma.getX() + jRow[4] * gamma.getY() + jRow[5] * gamma.getZ();
}
}
/** {@inheritDoc} */
@Override
public void addMassDerivative(final double q) {
if (q > 0) {
throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
}
yDot[6] += q;
}
}
/** Estimate tolerance vectors for integrators when propagating in absolute position-velocity-acceleration.
* @param dP user specified position error
* @param absPva reference absolute position-velocity-acceleration
* @return a two rows array, row 0 being the absolute tolerance error and row 1
* being the relative tolerance error
* @see NumericalPropagator#tolerances(double, Orbit, OrbitType)
*/
public static double[][] tolerances(final double dP, final AbsolutePVCoordinates absPva) {
final double relative = dP / absPva.getPosition().getNorm();
final double dV = relative * absPva.getVelocity().getNorm();
final double[] absTol = new double[7];
final double[] relTol = new double[7];
absTol[0] = dP;
absTol[1] = dP;
absTol[2] = dP;
absTol[3] = dV;
absTol[4] = dV;
absTol[5] = dV;
// we set the mass tolerance arbitrarily to 1.0e-6 kg, as mass evolves linearly
// with trust, this often has no influence at all on propagation
absTol[6] = 1.0e-6;
Arrays.fill(relTol, relative);
return new double[][] {
absTol, relTol
};
}
/** Estimate tolerance vectors for integrators when propagating in orbits.
* <p>
* The errors are estimated from partial derivatives properties of orbits,
* starting from a scalar position error specified by the user.
* Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
* we get at constant energy (i.e. on a Keplerian trajectory):
* <pre>
* V² r |dV| = mu |dr|
* </pre>
* <p> So we deduce a scalar velocity error consistent with the position error.
* From here, we apply orbits Jacobians matrices to get consistent errors
* on orbital parameters.
*
* <p>
* The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
* are only local estimates, not global ones. So some care must be taken when using
* these tolerances. Setting 1mm as a position error does NOT mean the tolerances
* will guarantee a 1mm error position after several orbits integration.
* </p>
* @param dP user specified position error
* @param orbit reference orbit
* @param type propagation type for the meaning of the tolerance vectors elements
* (it may be different from {@code orbit.getType()})
* @return a two rows array, row 0 being the absolute tolerance error and row 1
* being the relative tolerance error
*/
public static double[][] tolerances(final double dP, final Orbit orbit, final OrbitType type) {
// estimate the scalar velocity error
final PVCoordinates pv = orbit.getPVCoordinates();
final double r2 = pv.getPosition().getNormSq();
final double v = pv.getVelocity().getNorm();
final double dV = orbit.getMu() * dP / (v * r2);
return tolerances(dP, dV, orbit, type);
}
/** Estimate tolerance vectors for integrators when propagating in orbits.
* <p>
* The errors are estimated from partial derivatives properties of orbits,
* starting from scalar position and velocity errors specified by the user.
* <p>
* The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
* are only local estimates, not global ones. So some care must be taken when using
* these tolerances. Setting 1mm as a position error does NOT mean the tolerances
* will guarantee a 1mm error position after several orbits integration.
* </p>
* @param dP user specified position error
* @param dV user specified velocity error
* @param orbit reference orbit
* @param type propagation type for the meaning of the tolerance vectors elements
* (it may be different from {@code orbit.getType()})
* @return a two rows array, row 0 being the absolute tolerance error and row 1
* being the relative tolerance error
* @since 10.3
*/
public static double[][] tolerances(final double dP, final double dV,
final Orbit orbit, final OrbitType type) {
final double[] absTol = new double[7];
final double[] relTol = new double[7];
// we set the mass tolerance arbitrarily to 1.0e-6 kg, as mass evolves linearly
// with trust, this often has no influence at all on propagation
absTol[6] = 1.0e-6;
if (type == OrbitType.CARTESIAN) {
absTol[0] = dP;
absTol[1] = dP;
absTol[2] = dP;
absTol[3] = dV;
absTol[4] = dV;
absTol[5] = dV;
} else {
// convert the orbit to the desired type
final double[][] jacobian = new double[6][6];
final Orbit converted = type.convertType(orbit);
converted.getJacobianWrtCartesian(PositionAngle.TRUE, jacobian);
for (int i = 0; i < 6; ++i) {
final double[] row = jacobian[i];
absTol[i] = FastMath.abs(row[0]) * dP +
FastMath.abs(row[1]) * dP +
FastMath.abs(row[2]) * dP +
FastMath.abs(row[3]) * dV +
FastMath.abs(row[4]) * dV +
FastMath.abs(row[5]) * dV;
if (Double.isNaN(absTol[i])) {
throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
}
}
}
Arrays.fill(relTol, dP / FastMath.sqrt(orbit.getPVCoordinates().getPosition().getNormSq()));
return new double[][] {
absTol, relTol
};
}
/** {@inheritDoc} */
@Override
protected void beforeIntegration(final SpacecraftState initialState, final AbsoluteDate tEnd) {
if (!getFrame().isPseudoInertial()) {
// inspect all force models to find InertialForces
for (ForceModel force : forceModels) {
if (force instanceof InertialForces) {
return;
}
}
// throw exception if no inertial forces found
throw new OrekitException(OrekitMessages.INERTIAL_FORCE_MODEL_MISSING, getFrame().getName());
}
}
}
|
3e0b7d0cc3ca90a3abd390a8a4689a51d45d3290 | 5,656 | java | Java | aws-java-sdk-iotsitewise/src/main/java/com/amazonaws/services/iotsitewise/model/GatewayPlatform.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:11:16.000Z | 2022-01-04T04:11:16.000Z | aws-java-sdk-iotsitewise/src/main/java/com/amazonaws/services/iotsitewise/model/GatewayPlatform.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-iotsitewise/src/main/java/com/amazonaws/services/iotsitewise/model/GatewayPlatform.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | 29.768421 | 137 | 0.62005 | 4,850 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iotsitewise.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Contains a gateway's platform information.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotsitewise-2019-12-02/GatewayPlatform" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GatewayPlatform implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* A gateway that runs on IoT Greengrass.
* </p>
*/
private Greengrass greengrass;
/**
* <p>
* A gateway that runs on IoT Greengrass V2.
* </p>
*/
private GreengrassV2 greengrassV2;
/**
* <p>
* A gateway that runs on IoT Greengrass.
* </p>
*
* @param greengrass
* A gateway that runs on IoT Greengrass.
*/
public void setGreengrass(Greengrass greengrass) {
this.greengrass = greengrass;
}
/**
* <p>
* A gateway that runs on IoT Greengrass.
* </p>
*
* @return A gateway that runs on IoT Greengrass.
*/
public Greengrass getGreengrass() {
return this.greengrass;
}
/**
* <p>
* A gateway that runs on IoT Greengrass.
* </p>
*
* @param greengrass
* A gateway that runs on IoT Greengrass.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GatewayPlatform withGreengrass(Greengrass greengrass) {
setGreengrass(greengrass);
return this;
}
/**
* <p>
* A gateway that runs on IoT Greengrass V2.
* </p>
*
* @param greengrassV2
* A gateway that runs on IoT Greengrass V2.
*/
public void setGreengrassV2(GreengrassV2 greengrassV2) {
this.greengrassV2 = greengrassV2;
}
/**
* <p>
* A gateway that runs on IoT Greengrass V2.
* </p>
*
* @return A gateway that runs on IoT Greengrass V2.
*/
public GreengrassV2 getGreengrassV2() {
return this.greengrassV2;
}
/**
* <p>
* A gateway that runs on IoT Greengrass V2.
* </p>
*
* @param greengrassV2
* A gateway that runs on IoT Greengrass V2.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GatewayPlatform withGreengrassV2(GreengrassV2 greengrassV2) {
setGreengrassV2(greengrassV2);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getGreengrass() != null)
sb.append("Greengrass: ").append(getGreengrass()).append(",");
if (getGreengrassV2() != null)
sb.append("GreengrassV2: ").append(getGreengrassV2());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GatewayPlatform == false)
return false;
GatewayPlatform other = (GatewayPlatform) obj;
if (other.getGreengrass() == null ^ this.getGreengrass() == null)
return false;
if (other.getGreengrass() != null && other.getGreengrass().equals(this.getGreengrass()) == false)
return false;
if (other.getGreengrassV2() == null ^ this.getGreengrassV2() == null)
return false;
if (other.getGreengrassV2() != null && other.getGreengrassV2().equals(this.getGreengrassV2()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getGreengrass() == null) ? 0 : getGreengrass().hashCode());
hashCode = prime * hashCode + ((getGreengrassV2() == null) ? 0 : getGreengrassV2().hashCode());
return hashCode;
}
@Override
public GatewayPlatform clone() {
try {
return (GatewayPlatform) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iotsitewise.model.transform.GatewayPlatformMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
3e0b7d6dae85256a91f07312c412b61d7158302a | 18,169 | java | Java | mcr-constraints/src/main/java/edu/tamu/aser/trace/Trace.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 45 | 2017-11-22T19:40:44.000Z | 2021-06-07T03:20:39.000Z | mcr-constraints/src/main/java/edu/tamu/aser/trace/Trace.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 5 | 2017-11-28T16:05:54.000Z | 2020-09-13T06:23:43.000Z | mcr-constraints/src/main/java/edu/tamu/aser/trace/Trace.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 15 | 2017-08-29T20:43:15.000Z | 2020-11-18T14:17:51.000Z | 27.321805 | 135 | 0.68138 | 4,851 | /*******************************************************************************
* Copyright (c) 2013 University of Illinois
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER 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 edu.tamu.aser.trace;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.Vector;
/**
* Representation of the execution trace. Each event is created as a node
* with a corresponding type. Events are indexed by their thread Id, Type,
* and memory address.
*
* @author jeffhuang
*
*/
public class Trace {
//rawfulltrace represents all the raw events in the global order
Vector<AbstractNode> rawfulltrace = new Vector<AbstractNode>();
//indexed by address, the set of read/write threads
//used to prune away local data accesses
HashMap<String,HashSet<Long>> indexedReadThreads = new HashMap<String,HashSet<Long>>();
HashMap<String,HashSet<Long>> indexedWriteThreads = new HashMap<String,HashSet<Long>>();
//the set of shared memory locations
HashSet<String> sharedAddresses = new HashSet<String>();
//the set of threads
HashSet<Long> threads = new HashSet<Long>();
//fulltrace represents all the critical events in the global order
Vector<AbstractNode> fulltrace = new Vector<AbstractNode>();
//keep a node GID to tid Map, used for generating schedules
HashMap<Long, Long> nodeGIDTidMap = new HashMap<Long, Long>();
//per thread node map
HashMap<Long,Vector<AbstractNode>> threadNodesMap = new HashMap<Long,Vector<AbstractNode>>();
//the first node and last node map of each thread
HashMap<Long, AbstractNode> threadFirstNodeMap = new HashMap<Long, AbstractNode>();
HashMap<Long, AbstractNode> threadLastNodeMap = new HashMap<Long, AbstractNode>();
//per thread per lock lock/unlock pair
HashMap<Long,HashMap<String,Vector<LockPair>>> threadIndexedLockPairs = new HashMap<Long,HashMap<String,Vector<LockPair>>>();
HashMap<Long,Stack<ISyncNode>> threadSyncStack = new HashMap<Long,Stack<ISyncNode>>();
//per thread branch nodes and basicblock nodes
HashMap<Long,Vector<BranchNode>> threadBranchNodes = new HashMap<Long,Vector<BranchNode>>();
HashMap<Long,Vector<BBNode>> threadBBNodes = new HashMap<Long,Vector<BBNode>>();
//per thead synchronization nodes
HashMap<String,Vector<ISyncNode>> syncNodesMap = new HashMap<String,Vector<ISyncNode>>();
//per address read and write nodes
HashMap<String,Vector<ReadNode>> indexedReadNodes = new HashMap<String,Vector<ReadNode>>();
HashMap<String,Vector<WriteNode>> indexedWriteNodes = new HashMap<String,Vector<WriteNode>>();
//per address map from thread id to read/write nodes
HashMap<String,HashMap<Long,Vector<IMemNode>>> indexedThreadReadWriteNodes = new HashMap<String,HashMap<Long,Vector<IMemNode>>>();
//per type per address property node map
HashMap<String,HashMap<Integer,Vector<PropertyNode>>> propertyMonitors = new HashMap<String,HashMap<Integer,Vector<PropertyNode>>>();
HashMap<Long,Vector<PropertyNode>> threadPropertyNodes = new HashMap<Long,Vector<PropertyNode>>();
//per address initial write value
HashMap<String,String> initialWriteValueMap = new HashMap<String,String>();
TraceInfo info;
public static String appname;
public Trace(String name, TraceInfo info)
{
appname = name;
this.info = info;
}
public Trace(TraceInfo info)
{
this.info = info;
}
public String getApplicationName()
{
return appname;
}
Vector<ReadNode> allReadNodes;
/**
* return true if sharedAddresses is not empty
* @return
*/
public boolean hasSharedVariable()
{
return !sharedAddresses.isEmpty();
}
public TraceInfo getTraceInfo()
{
return this.info;
}
public Vector<AbstractNode> getFullTrace()
{
return fulltrace;
}
public HashSet<String> getSharedVariables()
{
return sharedAddresses;
}
public HashMap<String,String> getInitialWriteValueMap()
{
return initialWriteValueMap;
}
public void setInitialWriteValueMap(HashMap<String,String> map)
{
initialWriteValueMap = map;
}
public HashMap<Long, Long> getNodeGIDTIdMap() {
return nodeGIDTidMap;
}
public HashMap<Integer, String> getSharedVarIdMap() {
return info.getSharedVarIdMap();
}
public HashMap<Integer, String> getStmtSigIdMap() {
return info.getStmtSigIdMap();
}
public HashMap<Long, String> getThreadIdNameMap()
{
return info.getThreadIdNameMap();
}
public HashMap<String,HashMap<Integer,Vector<PropertyNode>>> getPropertyMonitors()
{
return propertyMonitors;
}
public HashMap<Long,Vector<PropertyNode>> getThreadPropertyNodes()
{
return threadPropertyNodes;
}
public HashMap<Long, AbstractNode> getThreadFirstNodeMap()
{
return threadFirstNodeMap;
}
public HashMap<Long, AbstractNode> getThreadLastNodeMap()
{
return threadLastNodeMap;
}
/**
* get the vector of the events of each thread
*/
public HashMap<Long,Vector<AbstractNode>> getThreadNodesMap()
{
return threadNodesMap;
}
public HashMap<String,Vector<ISyncNode>> getSyncNodesMap()
{
return syncNodesMap;
}
public HashMap<Long,HashMap<String,Vector<LockPair>>> getThreadIndexedLockPairs()
{
return threadIndexedLockPairs;
}
public HashMap<String,Vector<ReadNode>> getIndexedReadNodes()
{
return indexedReadNodes;
}
public HashMap<String,Vector<WriteNode>> getIndexedWriteNodes()
{
return indexedWriteNodes;
}
public HashMap<String,HashMap<Long,Vector<IMemNode>>> getIndexedThreadReadWriteNodes()
{
return indexedThreadReadWriteNodes;
}
public void saveLastWriteValues(
HashMap<String, String> valueMap) {
Iterator<String> addrIt = indexedWriteNodes.keySet().iterator();
while(addrIt.hasNext())
{
String addr = addrIt.next();
valueMap.put(addr, indexedWriteNodes.get(addr).lastElement().getValue());
}
}
public Vector<ReadNode> getAllReadNodes()
{
if(allReadNodes == null)
{
allReadNodes = new Vector<ReadNode>();
Iterator<Vector<ReadNode>> it = indexedReadNodes.values().iterator();
while(it.hasNext())
{
allReadNodes.addAll(it.next());
}
}
return allReadNodes;
}
//TODO: NEED to include the dependent nodes from other threads
public Vector<ReadNode> getDependentReadNodes(IMemNode rnode, boolean nobranch) {
Vector<ReadNode> readnodes = new Vector<ReadNode>();
long tid = rnode.getTid();
long POS = rnode.getGID()-1;
if(!nobranch)
{
long pos = -1;
Vector<BranchNode> branchNodes = threadBranchNodes.get(tid);
if(branchNodes!=null)
//TODO: improve to log(n) complexity
for(int i =0;i<branchNodes.size();i++)
{
long id = branchNodes.get(i).getGID();
if(id>POS)
break;
else
pos =id;
}
POS = pos;
}
if(POS>=0)
{
Vector<AbstractNode> nodes = threadNodesMap.get(tid);//TODO: optimize here to check only READ node
for(int i =0;i<nodes.size();i++)
{
AbstractNode node = nodes.get(i);
if(node.getGID()>POS)
break;
else
{
if(node instanceof ReadNode)
readnodes.add((ReadNode) node);
}
}
}
return readnodes;
}
/**
* add a new event to the trace in the order of its appearance
*
* @param node
*/
public void addRawNode(AbstractNode node)
{
rawfulltrace.add(node);
if(node instanceof IMemNode)
{
String addr = ((IMemNode) node).getAddr();
Long tid = node.getTid();
if(node instanceof ReadNode)
{
HashSet<Long> set = indexedReadThreads.get(addr);
if(set==null)
{
set = new HashSet<Long>();
indexedReadThreads.put(addr, set);
}
set.add(tid);
}
else
{
HashSet<Long> set = indexedWriteThreads.get(addr);
if(set==null)
{
set = new HashSet<Long>();
indexedWriteThreads.put(addr, set);
}
set.add(tid);
}
}
}
/**
* update the initial value of a memory location
* @param addr
* @param value
*/
public void updateInitWriteValueToAddress(String addr, String value)
{
initialWriteValueMap.put(addr,value);
info.incrementInitWriteNumber();
}
/**
* add a new filtered event to the trace in the order of its appearance
* @param node
*/
private void addNode(AbstractNode node)
{
Long tid = node.getTid();
threads.add(tid);
if(node instanceof BBNode)
{
//basicblock node
Vector<BBNode> bbnodes = threadBBNodes.get(tid);
if(bbnodes == null)
{
bbnodes = new Vector<BBNode>();
threadBBNodes.put(tid, bbnodes);
}
bbnodes.add((BBNode)node);
}
else if(node instanceof BranchNode)
{
//branch node
info.incrementBranchNumber();
Vector<BranchNode> branchnodes = threadBranchNodes.get(tid);
if(branchnodes == null)
{
branchnodes = new Vector<BranchNode>();
threadBranchNodes.put(tid, branchnodes);
}
branchnodes.add((BranchNode)node);
}
else if (node instanceof InitNode)
{
//initial write node
initialWriteValueMap.put(((InitNode) node).getAddr(),((InitNode) node).getValue());
info.incrementInitWriteNumber();
}
else
{
//all critical nodes -- read/write/synchronization events
fulltrace.add(node);
nodeGIDTidMap.put(node.getGID(), node.getTid());
Vector<AbstractNode> threadNodes = threadNodesMap.get(tid);
if(threadNodes ==null)
{
threadNodes = new Vector<AbstractNode>();
threadNodesMap.put(tid, threadNodes);
threadFirstNodeMap.put(tid, node);
}
threadNodes.add(node);
//TODO: Optimize it -- no need to update it every time
threadLastNodeMap.put(tid, node);
if(node instanceof PropertyNode
//&&node.getTid()!=1
)
{
info.incrementPropertyNumber();
PropertyNode pnode = (PropertyNode)node;
//System.out.println(node);
{
//add to per thread property nodes
Vector<PropertyNode> nodes = threadPropertyNodes.get(tid);
if(nodes==null)
{
nodes = new Vector<PropertyNode>();
threadPropertyNodes.put(tid, nodes);
}
nodes.add(pnode);
}
int ID = pnode.getID();
String addr = pnode.getAddr();
HashMap<Integer,Vector<PropertyNode>> indexedPropertyNodeMap = propertyMonitors.get(addr);
if(indexedPropertyNodeMap==null)
{
indexedPropertyNodeMap = new HashMap<Integer,Vector<PropertyNode>>();
propertyMonitors.put(addr, indexedPropertyNodeMap);
}
Vector<PropertyNode> pnodes = indexedPropertyNodeMap.get(ID);
if(pnodes == null)
{
pnodes = new Vector<PropertyNode>();
indexedPropertyNodeMap.put(ID, pnodes);
}
pnodes.add(pnode);
}
//memory nodes
else if(node instanceof IMemNode)
{
info.incrementSharedReadWriteNumber();
IMemNode mnode = (IMemNode)node;
String addr = mnode.getAddr();
HashMap<Long, Vector<IMemNode>> threadReadWriteNodes = indexedThreadReadWriteNodes.get(addr);
if(threadReadWriteNodes==null) //never appear before
{
threadReadWriteNodes = new HashMap<Long, Vector<IMemNode>>();
indexedThreadReadWriteNodes.put(addr, threadReadWriteNodes);
}
Vector<IMemNode> rwnodes = threadReadWriteNodes.get(tid);
if(rwnodes==null)
{
rwnodes = new Vector<IMemNode>();
threadReadWriteNodes.put(tid, rwnodes);
}
rwnodes.add(mnode);
//set previous branch node and sync node
Vector<BranchNode> branchnodes = threadBranchNodes.get(tid);
if(branchnodes != null)
mnode.setPrevBranchId(branchnodes.lastElement().getGID());
if(node instanceof ReadNode)
{
Vector<ReadNode> readNodes = indexedReadNodes.get(addr);
if(readNodes == null)
{
readNodes = new Vector<ReadNode>();
indexedReadNodes.put(addr, readNodes);
}
readNodes.add((ReadNode)node);
}
else //write node
{
Vector<WriteNode> writeNodes = indexedWriteNodes.get(addr);
if(writeNodes ==null)
{
writeNodes = new Vector<WriteNode>();
indexedWriteNodes.put(addr, writeNodes);
}
writeNodes.add((WriteNode)node);
}
}
else if(node instanceof ISyncNode)
{
//synchronization nodes
info.incrementSyncNumber();
String addr = ((ISyncNode)node).getAddr();
Vector<ISyncNode> syncNodes = syncNodesMap.get(addr);
if(syncNodes==null)
{
syncNodes = new Vector<ISyncNode>();
syncNodesMap.put(addr, syncNodes);
}
syncNodes.add((ISyncNode)node);
if (node instanceof LockNode)
{
Stack<ISyncNode> stack = threadSyncStack.get(tid);
if(stack==null)
{
stack = new Stack<ISyncNode>();
threadSyncStack.put(tid, stack);
}
stack.push((LockNode)node);
}
else if (node instanceof UnlockNode)
{
HashMap<String,Vector<LockPair>> indexedLockpairs = threadIndexedLockPairs.get(tid);
if(indexedLockpairs==null)
{
indexedLockpairs = new HashMap<String,Vector<LockPair>>();
threadIndexedLockPairs.put(tid, indexedLockpairs);
}
Vector<LockPair> lockpairs = indexedLockpairs.get(addr);
if(lockpairs==null)
{
lockpairs = new Vector<LockPair>();
indexedLockpairs.put(addr, lockpairs);
}
Stack<ISyncNode> stack = threadSyncStack.get(tid);
if(stack==null)
{
stack = new Stack<ISyncNode>();
threadSyncStack.put(tid, stack);
}
//assert(stack.size()>0); //this is possible when segmented
if(stack.size()==0)
lockpairs.add(new LockPair(null,(UnlockNode)node));
else if(stack.size()==1)
lockpairs.add(new LockPair(stack.pop(),(UnlockNode)node));
else
stack.pop();//handle reentrant lock
}
}
}
}
public boolean isLocalAddress(String addr)
{
return !sharedAddresses.contains(addr);
}
/**
* once trace is completely loaded, do two things:
* 1. prune away local data accesses
* 2. process the remaining trace
* 3. if needsReplay, don't remove any local access node
* @param needsReplay
*/
public void finishedLoading(boolean needsReplay)
{
HashSet<String> addrs = new HashSet<String>();
addrs.addAll(indexedReadThreads.keySet());
addrs.addAll(indexedWriteThreads.keySet());
//profile the shared addr
//this method is not accurate
//e.g., two threads execute the same function, the local variable in the function
//will be treated as shared
for(Iterator<String> addrIt = addrs.iterator();addrIt.hasNext();)
{
String addr = addrIt.next();
HashSet<Long> wtids = indexedWriteThreads.get(addr);
if(wtids!=null&&wtids.size()>0)
{
if(wtids.size()>1)
{
sharedAddresses.add(addr);
}
else
{
HashSet<Long> rtids = indexedReadThreads.get(addr);
if(rtids!=null)
{
HashSet<Long> set = new HashSet<Long>(rtids);
set.addAll(wtids);
if(set.size()>1)
sharedAddresses.add(addr);
}
}
}
}
//add trace
for(int i=0;i<rawfulltrace.size();i++)
{
AbstractNode node = rawfulltrace.get(i);
if(node instanceof IMemNode)
{
String addr = ((IMemNode) node).getAddr();
if(sharedAddresses.contains(addr))
addNode(node);
else
{
info.incrementLocalReadWriteNumber();
if(needsReplay)
addNode(node);
}
}
else
addNode(node);
}
//process sync stack to handle windowing
checkSyncStack();
//clear rawfulltrace
rawfulltrace.clear();
//add info
info.addSharedAddresses(sharedAddresses);
info.addThreads(threads);
}
public Vector<AbstractNode> getRawFullTrace()
{
return rawfulltrace;
}
/**
* compute the lock/unlock pairs because we analyze the trace window by window,
* lock/unlock may not be in the same window, so we may have null lock or unlock
* node in the pair.
*/
private void checkSyncStack()
{
//check threadSyncStack - only to handle when segmented
Iterator<Entry<Long,Stack<ISyncNode>>> entryIt = threadSyncStack.entrySet().iterator();
while(entryIt.hasNext())
{
Entry<Long,Stack<ISyncNode>> entry = entryIt.next();
Long tid = entry.getKey();
Stack<ISyncNode> stack = entry.getValue();
if(!stack.isEmpty())
{
HashMap<String,Vector<LockPair>> indexedLockpairs = threadIndexedLockPairs.get(tid);
if(indexedLockpairs==null)
{
indexedLockpairs = new HashMap<String,Vector<LockPair>>();
threadIndexedLockPairs.put(tid, indexedLockpairs);
}
while(!stack.isEmpty())
{
ISyncNode syncnode = stack.pop();//lock or wait
Vector<LockPair> lockpairs = indexedLockpairs.get(syncnode.getAddr());
if(lockpairs==null)
{
lockpairs = new Vector<LockPair>();
indexedLockpairs.put(syncnode.getAddr(), lockpairs);
}
lockpairs.add(new LockPair(syncnode,null));
}
}
}
}
public boolean isAddressVolatile(String addr) {
return info.isAddressVolatile(addr);
}
}
|
3e0b7ea09554d2ee7fa2f3233f7f8e56d64e9fbe | 2,023 | java | Java | yggdrasil-node/src/main/java/org/yggdrasil/node/network/messages/handlers/AddressResponseMessageHandler.java | stoicswe/yggdrasil | 46e8e881deae88f52b58ef88cd3e87651a8b259d | [
"MIT"
] | 1 | 2021-03-27T01:45:00.000Z | 2021-03-27T01:45:00.000Z | yggdrasil-node/src/main/java/org/yggdrasil/node/network/messages/handlers/AddressResponseMessageHandler.java | stoicswe/yggdrasil | 46e8e881deae88f52b58ef88cd3e87651a8b259d | [
"MIT"
] | 1 | 2021-04-03T15:33:09.000Z | 2021-04-03T15:33:09.000Z | yggdrasil-node/src/main/java/org/yggdrasil/node/network/messages/handlers/AddressResponseMessageHandler.java | stoicswe/yggdrasil | 46e8e881deae88f52b58ef88cd3e87651a8b259d | [
"MIT"
] | null | null | null | 43.978261 | 142 | 0.766189 | 4,852 | package org.yggdrasil.node.network.messages.handlers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yggdrasil.core.utils.CryptoHasher;
import org.yggdrasil.node.network.Node;
import org.yggdrasil.node.network.NodeConfig;
import org.yggdrasil.node.network.messages.MessagePayload;
import org.yggdrasil.node.network.messages.MessagePool;
import org.yggdrasil.node.network.messages.payloads.AcknowledgeMessage;
import org.yggdrasil.node.network.messages.payloads.AddressMessage;
import org.yggdrasil.node.network.messages.payloads.AddressPayload;
import org.yggdrasil.node.network.peer.PeerRecord;
import org.yggdrasil.node.network.peer.PeerRecordIndexer;
import org.yggdrasil.node.network.runners.NodeConnection;
import java.security.NoSuchAlgorithmException;
@Component
public class AddressResponseMessageHandler implements MessageHandler<AddressMessage> {
@Autowired
private PeerRecordIndexer peerRecordIndexer;
@Autowired
private NodeConfig nodeConfig;
@Override
public MessagePayload handleMessagePayload(AddressMessage addressMessage, NodeConnection nodeConnection) throws NoSuchAlgorithmException {
// if the count of IPs does not match the length of addressMessages in the message
// then send an acknowledgement and ignore the payload data
if(addressMessage.getIpAddressCount() == addressMessage.getIpAddresses().length) {
for(AddressPayload addressPayload : addressMessage.getIpAddresses()) {
// add connections to the active connections and store connection data
PeerRecord peerRecord = PeerRecord.Builder.newBuilder()
.buildFromAddressPayload(addressPayload);
this.peerRecordIndexer.addPeerRecord(peerRecord);
}
}
return AcknowledgeMessage.Builder.newBuilder()
.setAcknowledgeChecksum(CryptoHasher.hash(addressMessage))
.build();
}
}
|
3e0b7f590674959a3eb293850a13477893d2c7a1 | 1,704 | java | Java | exemplos-logica/src/main/java/br/senac/tads/pi1/exemploslogica/ExemploVariavel.java | ftsuda-senac/tads-exemplos-pi1-2021-2 | e7a50ffc2f0145d1a3ed508af9583f3b546a2510 | [
"MIT"
] | null | null | null | exemplos-logica/src/main/java/br/senac/tads/pi1/exemploslogica/ExemploVariavel.java | ftsuda-senac/tads-exemplos-pi1-2021-2 | e7a50ffc2f0145d1a3ed508af9583f3b546a2510 | [
"MIT"
] | 1 | 2021-10-19T01:39:32.000Z | 2021-10-19T01:39:32.000Z | exemplos-logica/src/main/java/br/senac/tads/pi1/exemploslogica/ExemploVariavel.java | ftsuda-senac/tads-exemplos-pi1-2021-2 | e7a50ffc2f0145d1a3ed508af9583f3b546a2510 | [
"MIT"
] | null | null | null | 37.043478 | 152 | 0.617371 | 4,853 | package br.senac.tads.pi1.exemploslogica;
/**
*
* @author ftsuda
*/
public class ExemploVariavel {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String mensagemNatal = "Feliz Natal!!!"; // camelCase
String OUTRA_Mensagem = "Feliz Ano novo!!!"; // <-- está correto, mas inadequado por não seguir boa pratica Java (camelCase + palavra maiúscula)
String MaisOutraMensagem = "Feliz páscoa!!!"; // <-- está correto, mas não segue boa prática, pois a primeira letra está Maiúsucla
System.out.println("Mensagem de natal: " + mensagemNatal);
System.out.println("Outra mensagem: " + OUTRA_Mensagem);
System.out.println("Mais outra mensagem: " + MaisOutraMensagem);
int valor1 = 123;
Integer valor2 = 123; // wrapper do tipo primitivo int
//int valor3 = null; // Não pode fazer isso em tipos primitivos
Integer valor4 = null;
String string1 = new String("abc");
String string2 = new String("abc");
System.out.println("Comparacao 1 usando == : " + (string1 == string2));
System.out.println("Comparacao 2 usando equals: " + string1.equals(string2));
// Exemplos para ver algumas funcionalidades que podem ser usadas
// para verificar/manipular a string.
String str1 = "Abc";
boolean str1igual = str1.equals("abc");
boolean strIgual2 = str1.equalsIgnoreCase("abc");
int qtdeCaracteres = str1.length();
String str1Maiuscula = str1.toUpperCase();
// TODO mostrar a saída de cada resultado no console
}
}
|
3e0b7fcac7a325f207fe343b8432ec91b5530f1f | 2,548 | java | Java | src/main/java/com/buptcpr/demo/controller/AdminController.java | Alpaca4610/BUPTSSE--JavaEE-CPR | 9394e52a9b9b1fe019050fe8b012c20150130b66 | [
"Apache-2.0"
] | 1 | 2021-10-01T04:14:45.000Z | 2021-10-01T04:14:45.000Z | src/main/java/com/buptcpr/demo/controller/AdminController.java | Alpaca4610/BUPTSSE--JavaEE-CPR | 9394e52a9b9b1fe019050fe8b012c20150130b66 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/buptcpr/demo/controller/AdminController.java | Alpaca4610/BUPTSSE--JavaEE-CPR | 9394e52a9b9b1fe019050fe8b012c20150130b66 | [
"Apache-2.0"
] | null | null | null | 29.976471 | 132 | 0.675432 | 4,854 | package com.buptcpr.demo.controller;
import com.buptcpr.demo.DAO.AdminRepository;
import com.buptcpr.demo.common.Jwt;
import com.buptcpr.demo.common.Result;
import com.buptcpr.demo.entity.Student;
import com.buptcpr.demo.entity.Admin;
import com.buptcpr.demo.service.StatisticsService;
import com.buptcpr.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@Controller
@RequestMapping(path="/admin")
@SuppressWarnings("unchecked")
public class AdminController {
@Autowired
private AdminService adminService;
@Autowired
private StatisticsService statisticsService;
@Autowired
private AdminRepository adminRepository;
@PostMapping(path="/register")
@SuppressWarnings("unchecked")
public @ResponseBody
Result<Object> adminSignUp (@RequestParam String name, @RequestParam String id, @RequestParam String password) {
int i = adminService.signUp(name, id, password);
if(i==1) {
return Result.error("1","超级管理员已注册");
}else{
return Result.success(Jwt.createJWT(3600000));
}
}
@PostMapping(path="/login")
public @ResponseBody Result<Admin> adminSignIn(@RequestParam String id, @RequestParam String password) {
if(adminService.signIn(id, password)) {
return Result.success(null);
}else{
return Result.error("1","用户名或密码错误");
}
}
@PostMapping(path="/delete")
public @ResponseBody Result<String> adminDelete(@RequestParam String id) {
int delete = adminService.delete(id);
if(delete==1){
return Result.error("1","用户名不存在");
}else{
return Result.success(null);
}
}
@PostMapping(path="/update")
public @ResponseBody Result<Admin> adminUpdate(@RequestParam String id,@RequestParam String name, @RequestParam String password)
{
int update = adminService.update(id, name, password);
if(update==1){
return Result.error("1","用户名不存在");
}else {
return Result.success(null);
}
}
@GetMapping("/all")
public @ResponseBody
Result<List<Admin>> getadmin() {
return Result.success(adminRepository.findAll());
}
@GetMapping("/ranking")
public @ResponseBody
Result getRanking(){
return adminService.ranking();
}
} |
3e0b800bbc805744322fc4ef18743c211ae79be6 | 237 | java | Java | app/src/main/java/com/zarkorunjevac/codepathtodo/ui/callback/TodoClickCallback.java | ZarkoRunjevac/ToDo | 1417dde5d7e25e5fac2baeff54b1c7a2f65fb125 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zarkorunjevac/codepathtodo/ui/callback/TodoClickCallback.java | ZarkoRunjevac/ToDo | 1417dde5d7e25e5fac2baeff54b1c7a2f65fb125 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zarkorunjevac/codepathtodo/ui/callback/TodoClickCallback.java | ZarkoRunjevac/ToDo | 1417dde5d7e25e5fac2baeff54b1c7a2f65fb125 | [
"Apache-2.0"
] | null | null | null | 19.75 | 54 | 0.729958 | 4,855 | package com.zarkorunjevac.codepathtodo.ui.callback;
import com.zarkorunjevac.codepathtodo.db.entity.Todo;
/**
* Created by zarko.runjevac on 8/11/2017.
*/
public interface TodoClickCallback {
void onClick(Todo todo);
}
|
3e0b806a0432659d1b61a7b5c6930e189f3bf56e | 2,384 | java | Java | src/test/java/uk/gov/hmcts/reform/sscs/ccd/presubmit/writefinaldecision/gen/GenWriteFinalDecisionMidEventValidationHandlerTest.java | uk-gov-mirror/hmcts.sscs-tribunals-case-api | 6518b7b96596a2131a09d4afe3ccf10f850766b7 | [
"MIT"
] | null | null | null | src/test/java/uk/gov/hmcts/reform/sscs/ccd/presubmit/writefinaldecision/gen/GenWriteFinalDecisionMidEventValidationHandlerTest.java | uk-gov-mirror/hmcts.sscs-tribunals-case-api | 6518b7b96596a2131a09d4afe3ccf10f850766b7 | [
"MIT"
] | null | null | null | src/test/java/uk/gov/hmcts/reform/sscs/ccd/presubmit/writefinaldecision/gen/GenWriteFinalDecisionMidEventValidationHandlerTest.java | uk-gov-mirror/hmcts.sscs-tribunals-case-api | 6518b7b96596a2131a09d4afe3ccf10f850766b7 | [
"MIT"
] | null | null | null | 35.058824 | 153 | 0.790688 | 4,856 | package uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.gen;
import javax.validation.Validator;
import junitparams.JUnitParamsRunner;
import org.junit.runner.RunWith;
import uk.gov.hmcts.reform.sscs.ccd.domain.SscsCaseData;
import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.AwardType;
import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.WriteFinalDecisionMidEventValidationHandlerBase;
import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.WriteFinalDecisionMidEventValidationHandlerTestBase;
import uk.gov.hmcts.reform.sscs.service.DecisionNoticeService;
@RunWith(JUnitParamsRunner.class)
public class GenWriteFinalDecisionMidEventValidationHandlerTest extends WriteFinalDecisionMidEventValidationHandlerTestBase {
@Override
protected WriteFinalDecisionMidEventValidationHandlerBase createValidationHandler(Validator validator, DecisionNoticeService decisionNoticeService) {
return new GenWriteFinalDecisionMidEventValidationHandler(validator, decisionNoticeService);
}
@Override
protected String getBenefitType() {
return "GEN";
}
@Override
protected void setValidPointsAndActivitiesScenario(SscsCaseData caseData, String descriptorFlowValue) {
sscsCaseData.setWriteFinalDecisionIsDescriptorFlow(descriptorFlowValue);
}
@Override
protected void setNoAwardsScenario(SscsCaseData sscsCaseData) {
// N/A for GEN
}
@Override
protected void setEmptyActivitiesListScenario(SscsCaseData caseData) {
// N/A for GEN
}
@Override
protected void setNullActivitiesListScenario(SscsCaseData caseData) {
// N/A for GEN
}
@Override
protected void shouldExhibitBenefitSpecificBehaviourWhenNoAwardsAreGivenAndNoActivitiesAreSelected() {
// N/A for GEN
}
@Override
protected void shouldExhibitBenefitSpecificBehaviourWhenNoAwardsAreGivenAndNoActivitiesAreSelectedAndEndDateTypeIsSetEndDate() {
// N/A for GEN
}
@Override
protected void shouldExhibitBenefitSpecificBehaviourWhenNoAwardsAreGivenAndNoActivitiesAreSelectedAndEndDateTypeIsIndefinite() {
// N/A for GEN
}
@Override
protected void shouldExhibitBenefitSpecificBehaviourWhenAnAnAwardIsGivenAndNoActivitiesSelected(AwardType dailyLiving, AwardType mobility) {
// N/A for GEN
}
}
|
3e0b80d9b80fac8b5402c369de71d7c8e64f6653 | 2,006 | java | Java | src/main/java/at/o2xfs/xfs/siu/SIUProximitySensorState.java | AndreasFagschlunger/o2xfs-xfs-api | 3c3b1ac86fe647a38755edddfa9e6efcc0cdaf23 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/at/o2xfs/xfs/siu/SIUProximitySensorState.java | AndreasFagschlunger/o2xfs-xfs-api | 3c3b1ac86fe647a38755edddfa9e6efcc0cdaf23 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/at/o2xfs/xfs/siu/SIUProximitySensorState.java | AndreasFagschlunger/o2xfs-xfs-api | 3c3b1ac86fe647a38755edddfa9e6efcc0cdaf23 | [
"BSD-2-Clause"
] | null | null | null | 34 | 77 | 0.725823 | 4,857 | /*
* Copyright (c) 2017, Andreas Fagschlunger. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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 at.o2xfs.xfs.siu;
import at.o2xfs.xfs.api.XfsConstant;
public enum SIUProximitySensorState implements XfsConstant {
/**
* The status is not available.
*/
NOT_AVAILABLE(0x0000L),
/**
* The sensor is showing that there is someone present at the terminal.
*/
PRESENT(0x0001L),
/**
* The sensor can not sense any people around the terminal.
*/
NOT_PRESENT(0x0002L);
private final long value;
private SIUProximitySensorState(final long value) {
this.value = value;
}
@Override
public long getValue() {
return value;
}
} |
3e0b822ff98831833f86e1903cfc707f99a6a9c0 | 3,855 | java | Java | src/main/java/com/criteo/marketing/model/PublisherFileStatsMessage.java | criteo/criteo-java-marketing-sdk | 09e25162f7e61ba1a0bd25436399347ce8eef65d | [
"Apache-2.0"
] | 7 | 2019-03-27T14:31:26.000Z | 2020-10-10T08:13:01.000Z | src/main/java/com/criteo/marketing/model/PublisherFileStatsMessage.java | criteo/criteo-java-marketing-sdk | 09e25162f7e61ba1a0bd25436399347ce8eef65d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/criteo/marketing/model/PublisherFileStatsMessage.java | criteo/criteo-java-marketing-sdk | 09e25162f7e61ba1a0bd25436399347ce8eef65d | [
"Apache-2.0"
] | 5 | 2019-03-29T09:16:53.000Z | 2022-02-21T11:27:44.000Z | 23.796296 | 121 | 0.706615 | 4,858 | /*
* Marketing API v.1.0
* IMPORTANT: This swagger links to Criteo production environment. Any test applied here will thus impact real campaigns.
*
* The version of the OpenAPI document: v.1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.criteo.marketing.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.time.OffsetDateTime;
/**
* PublisherFileStatsMessage
*/
public class PublisherFileStatsMessage {
public static final String SERIALIZED_NAME_FILE_NAME = "fileName";
@SerializedName(SERIALIZED_NAME_FILE_NAME)
private String fileName;
public static final String SERIALIZED_NAME_TOKEN_VALID_UNTIL = "tokenValidUntil";
@SerializedName(SERIALIZED_NAME_TOKEN_VALID_UNTIL)
private OffsetDateTime tokenValidUntil;
public static final String SERIALIZED_NAME_URL = "url";
@SerializedName(SERIALIZED_NAME_URL)
private String url;
public PublisherFileStatsMessage fileName(String fileName) {
this.fileName = fileName;
return this;
}
/**
* Get fileName
* @return fileName
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public PublisherFileStatsMessage tokenValidUntil(OffsetDateTime tokenValidUntil) {
this.tokenValidUntil = tokenValidUntil;
return this;
}
/**
* Get tokenValidUntil
* @return tokenValidUntil
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public OffsetDateTime getTokenValidUntil() {
return tokenValidUntil;
}
public void setTokenValidUntil(OffsetDateTime tokenValidUntil) {
this.tokenValidUntil = tokenValidUntil;
}
public PublisherFileStatsMessage url(String url) {
this.url = url;
return this;
}
/**
* Get url
* @return url
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PublisherFileStatsMessage publisherFileStatsMessage = (PublisherFileStatsMessage) o;
return Objects.equals(this.fileName, publisherFileStatsMessage.fileName) &&
Objects.equals(this.tokenValidUntil, publisherFileStatsMessage.tokenValidUntil) &&
Objects.equals(this.url, publisherFileStatsMessage.url);
}
@Override
public int hashCode() {
return Objects.hash(fileName, tokenValidUntil, url);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PublisherFileStatsMessage {\n");
sb.append(" fileName: ").append(toIndentedString(fileName)).append("\n");
sb.append(" tokenValidUntil: ").append(toIndentedString(tokenValidUntil)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e0b826bb3a66186e180c3752d959d40e7d7d7e7 | 3,015 | java | Java | nam/nam-view/src/main/java/nam/model/command/CommandWizard.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | 2 | 2019-09-16T10:06:07.000Z | 2021-02-25T11:46:23.000Z | nam/nam-view/src/main/java/nam/model/command/CommandWizard.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | null | null | null | nam/nam-view/src/main/java/nam/model/command/CommandWizard.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | null | null | null | 21.382979 | 97 | 0.743284 | 4,859 | package nam.model.command;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang.StringUtils;
import org.aries.util.NameUtil;
import nam.model.Command;
import nam.model.Project;
import nam.model.util.CommandUtil;
import nam.ui.design.AbstractDomainElementWizard;
import nam.ui.design.SelectionContext;
@SessionScoped
@Named("commandWizard")
@SuppressWarnings("serial")
public class CommandWizard extends AbstractDomainElementWizard<Command> implements Serializable {
@Inject
private CommandDataManager commandDataManager;
@Inject
private CommandPageManager commandPageManager;
@Inject
private CommandEventManager commandEventManager;
@Inject
private SelectionContext selectionContext;
@Override
public String getName() {
return "Command";
}
@Override
public String getUrlContext() {
return commandPageManager.getCommandWizardPage();
}
@Override
public void initialize(Command command) {
setOrigin(getSelectionContext().getUrl());
assignPages(commandPageManager.getSections());
super.initialize(command);
}
@Override
public boolean isBackEnabled() {
return super.isBackEnabled();
}
@Override
public boolean isNextEnabled() {
return super.isNextEnabled();
}
@Override
public boolean isFinishEnabled() {
return super.isFinishEnabled();
}
@Override
public String refresh() {
String url = super.showPage();
selectionContext.setUrl(url);
commandPageManager.updateState();
return url;
}
@Override
public String first() {
String url = super.first();
commandPageManager.updateState();
return url;
}
@Override
public String back() {
String url = super.back();
commandPageManager.updateState();
return url;
}
@Override
public String next() {
String url = super.next();
commandPageManager.updateState();
return url;
}
@Override
public boolean isValid() {
return super.isValid();
}
@Override
public String finish() {
Command command = getInstance();
commandDataManager.saveCommand(command);
commandEventManager.fireSavedEvent(command);
String url = selectionContext.popOrigin();
return url;
}
@Override
public String cancel() {
Command command = getInstance();
//TODO take this out soon
if (command == null)
command = new Command();
commandEventManager.fireCancelledEvent(command);
String url = selectionContext.popOrigin();
return url;
}
public String populateDefaultValues() {
Command command = selectionContext.getSelection("command");
String name = command.getName().name();
if (StringUtils.isEmpty(name)) {
display = getFromSession("display");
display.setModule("commandWizard");
display.error("Command name must be specified");
return null;
}
Project project = selectionContext.getSelection("project");
String nameCapped = NameUtil.capName(name);
String nameUncapped = NameUtil.uncapName(name);
return getUrl();
}
}
|
3e0b82df1ced1e8bf76138216cc5e87c799a61b8 | 1,018 | java | Java | tests-arquillian/src/test/java/org/jboss/weld/tests/specialization/weld1651/SpecializedGenericBean.java | Daniel-Dos/core | 6e7cc55f54fa2b07482abd3fee7ff8103425c0e2 | [
"Apache-2.0"
] | 1 | 2021-05-23T09:03:26.000Z | 2021-05-23T09:03:26.000Z | tests-arquillian/src/test/java/org/jboss/weld/tests/specialization/weld1651/SpecializedGenericBean.java | Daniel-Dos/core | 6e7cc55f54fa2b07482abd3fee7ff8103425c0e2 | [
"Apache-2.0"
] | 18 | 2021-07-01T07:03:11.000Z | 2022-02-01T07:04:16.000Z | tests-arquillian/src/test/java/org/jboss/weld/tests/specialization/weld1651/SpecializedGenericBean.java | Daniel-Dos/core | 6e7cc55f54fa2b07482abd3fee7ff8103425c0e2 | [
"Apache-2.0"
] | 1 | 2020-03-05T09:50:44.000Z | 2020-03-05T09:50:44.000Z | 37.703704 | 99 | 0.756385 | 4,860 | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.specialization.weld1651;
import java.util.Collection;
import java.util.List;
/**
* @author Matus Abaffy
*/
public class SpecializedGenericBean<S extends List<Integer> & Collection<Integer>, T extends Bar> {
}
|
3e0b8324d647cc35705847e134afa1f0cf780150 | 49 | java | Java | corpus/norm-class/eclipse.jdt.core/769.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | corpus/norm-class/eclipse.jdt.core/769.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | corpus/norm-class/eclipse.jdt.core/769.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | 49 | 49 | 0.877551 | 4,861 | test itpjcore win search missing reference length |
3e0b8325a1beafaf82c8202f1cc5ea2c26985b24 | 1,151 | java | Java | db4o.j/db4o-core/tutorial/src/com/db4odoc/f1/chapter6/StopServer.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | 24 | 2019-08-25T12:58:07.000Z | 2022-03-04T11:20:37.000Z | db4o.j/db4o-core/tutorial/src/com/db4odoc/f1/chapter6/StopServer.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | null | null | null | db4o.j/db4o-core/tutorial/src/com/db4odoc/f1/chapter6/StopServer.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | 10 | 2019-08-30T10:25:41.000Z | 2022-02-13T17:40:23.000Z | 24.489362 | 77 | 0.706342 | 4,862 | package com.db4odoc.f1.chapter6;
import com.db4o.*;
import com.db4o.cs.*;
import com.db4o.messaging.*;
/**
* stops the db4o Server started with {@link StartServer}. <br>
* <br>
* This is done by opening a client connection to the server and by sending a
* StopServer object as a message. {@link StartServer} will react in it's
* processMessage method.
*/
public class StopServer implements ServerInfo {
/**
* stops a db4o Server started with StartServer.
*
* @throws Exception
*/
public static void main(String[] args) {
ObjectContainer objectContainer = null;
try {
// connect to the server
objectContainer = Db4oClientServer.openClient(Db4oClientServer
.newClientConfiguration(), HOST, PORT, USER, PASS);
} catch (Exception e) {
e.printStackTrace();
}
if (objectContainer != null) {
// get the messageSender for the ObjectContainer
MessageSender messageSender = objectContainer.ext().configure()
.clientServer().getMessageSender();
// send an instance of a StopServer object
messageSender.send(new StopServer());
// close the ObjectContainer
objectContainer.close();
}
}
}
|
3e0b83c502a05ecb3f9ccaadb735d1e16d1ac7ff | 920 | java | Java | acm-module-dc1/src/main/java/com/wisdom/acm/dc1/vo/TrafficLineMonthlyVo.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-dc1/src/main/java/com/wisdom/acm/dc1/vo/TrafficLineMonthlyVo.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-dc1/src/main/java/com/wisdom/acm/dc1/vo/TrafficLineMonthlyVo.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | 21.395349 | 69 | 0.717391 | 4,863 | package com.wisdom.acm.dc1.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author zll
* @date 2020/7/20/020 14:06
* Description:<月累计线路客运量,按日汇总>
*/
@Data
public class TrafficLineMonthlyVo {
private Integer id;
private Integer sortNum;
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date creatTime;
private Integer creator;
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date recordTime;
private String line;
//线路分期
private String linePeriod;
//日均客运量
private BigDecimal transferVolume;
//月统计客运量
private BigDecimal trafficVolume;
//本月单日最大客流量
private BigDecimal maxTrafficVolume;
//本月单日最大客流量发生日期
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date maxTrafficDate;
}
|
3e0b8463af77e8088f4b04daedaa8e8c9cfcca6d | 320 | java | Java | test-app/src/main/java/com/github/ruediste/rise/testApp/assetDir/TestAssetDir.java | ruediste/laf | c060186f1f1449647110b21e3f8fe5ff31820cd4 | [
"Apache-2.0"
] | 1 | 2016-01-28T19:46:45.000Z | 2016-01-28T19:46:45.000Z | test-app/src/main/java/com/github/ruediste/rise/testApp/assetDir/TestAssetDir.java | ruediste/rise | c060186f1f1449647110b21e3f8fe5ff31820cd4 | [
"Apache-2.0"
] | null | null | null | test-app/src/main/java/com/github/ruediste/rise/testApp/assetDir/TestAssetDir.java | ruediste/rise | c060186f1f1449647110b21e3f8fe5ff31820cd4 | [
"Apache-2.0"
] | null | null | null | 17.777778 | 59 | 0.66875 | 4,864 | package com.github.ruediste.rise.testApp.assetDir;
import com.github.ruediste.rise.core.web.assetDir.AssetDir;
public class TestAssetDir extends AssetDir {
@Override
protected String getLocation() {
return "./";
}
@Override
protected String getName() {
return "testDir";
}
}
|
3e0b84de00a14fd3818fec8a44b075492a1003a0 | 2,783 | java | Java | src/main/java/org/janelia/saalfeldlab/n5/metadata/N5ViewerMultiscaleMetadataParser.java | cmhulbert/n5-imglib2 | acea7364264a2b9b1e460df920146b6a5af5075e | [
"BSD-2-Clause"
] | null | null | null | src/main/java/org/janelia/saalfeldlab/n5/metadata/N5ViewerMultiscaleMetadataParser.java | cmhulbert/n5-imglib2 | acea7364264a2b9b1e460df920146b6a5af5075e | [
"BSD-2-Clause"
] | 17 | 2018-02-27T16:44:51.000Z | 2022-03-15T18:46:40.000Z | src/main/java/org/janelia/saalfeldlab/n5/metadata/N5ViewerMultiscaleMetadataParser.java | cmhulbert/n5-imglib2 | acea7364264a2b9b1e460df920146b6a5af5075e | [
"BSD-2-Clause"
] | 6 | 2017-06-19T15:26:58.000Z | 2020-05-23T18:50:29.000Z | 42.815385 | 148 | 0.768595 | 4,865 | /**
* Copyright (c) 2018--2020, Saalfeld lab
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* <p>
* 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.janelia.saalfeldlab.n5.metadata;
import org.janelia.saalfeldlab.n5.N5Reader;
import org.janelia.saalfeldlab.n5.N5TreeNode;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class N5ViewerMultiscaleMetadataParser implements N5MetadataParser<N5MultiScaleMetadata> {
/**
* Called by the {@link org.janelia.saalfeldlab.n5.N5DatasetDiscoverer}
* while discovering the N5 tree and filling the metadata for datasets or groups.
*
* @param reader the n5 reader
* @param node the node
* @return the metadata
*/
@Override public Optional<N5MultiScaleMetadata> parseMetadata(final N5Reader reader, final N5TreeNode node) {
final Map<String, N5TreeNode> scaleLevelNodes = new HashMap<>();
for (final N5TreeNode childNode : node.childrenList()) {
if (MultiscaleMetadata.scaleLevelPredicate.test(childNode.getNodeName()) &&
childNode.isDataset() &&
childNode.getMetadata() instanceof N5SingleScaleMetadata) {
scaleLevelNodes.put(childNode.getNodeName(), childNode);
}
}
if (scaleLevelNodes.isEmpty())
return Optional.empty();
final N5SingleScaleMetadata[] childMetadata = scaleLevelNodes.values().stream().map(N5TreeNode::getMetadata).toArray(N5SingleScaleMetadata[]::new);
MultiscaleMetadata.sortScaleMetadata(childMetadata);
return Optional.of(new N5MultiScaleMetadata(node.getPath(), childMetadata));
}
}
|
3e0b84e5a5638a9a6ea6a1624b8b44b855a300bf | 4,545 | java | Java | src/main/java/com/github/hindol/commons/util/AhoCorasickMatcher.java | Hindol/commons | 577eb940a27b082c58712e726c4385280f92eb96 | [
"MIT"
] | 11 | 2017-01-16T12:01:11.000Z | 2020-05-29T05:22:19.000Z | src/main/java/com/github/hindol/commons/util/AhoCorasickMatcher.java | hindol/commons | 577eb940a27b082c58712e726c4385280f92eb96 | [
"MIT"
] | 2 | 2019-01-28T17:21:16.000Z | 2020-04-12T15:18:17.000Z | src/main/java/com/github/hindol/commons/util/AhoCorasickMatcher.java | Hindol/commons | 577eb940a27b082c58712e726c4385280f92eb96 | [
"MIT"
] | 5 | 2016-12-09T19:02:26.000Z | 2019-05-29T16:52:52.000Z | 29.134615 | 87 | 0.618262 | 4,866 | package com.github.hindol.commons.util;
import org.arabidopsis.ahocorasick.AhoCorasick;
import org.arabidopsis.ahocorasick.SearchResult;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* An immutable wrapper for the AhoCorasick class. The mutation of the class
* state is limited within the constructors only. Once constructed, the class
* cannot change state.
*
* Instances of this class can be accessed from multiple threads.
*/
public class AhoCorasickMatcher {
private static final Pattern DEFAULT_DELIMITERS = Pattern.compile("\\W");
private final AhoCorasick mTree;
// Configuration
private final boolean mMatchWholeWords;
private final boolean mCaseInsensitive;
private final Pattern mDelimiters;
private AhoCorasickMatcher(Set<String> needles, boolean matchWholeWords,
Pattern delimiters, boolean caseInsensitive) {
mTree = new AhoCorasick();
mMatchWholeWords = matchWholeWords;
mDelimiters = delimiters;
mCaseInsensitive = caseInsensitive;
for (String needle : needles) {
addNeedle(transform(needle), needle);
}
mTree.prepare();
}
private AhoCorasickMatcher(Map<String, ?> needleOutputMap, boolean matchWholeWords,
Pattern delimiters, boolean caseInsensitive) {
mTree = new AhoCorasick();
mMatchWholeWords = matchWholeWords;
mDelimiters = delimiters;
mCaseInsensitive = caseInsensitive;
for (Map.Entry<String, ?> entry : needleOutputMap.entrySet()) {
addNeedle(transform(entry.getKey()), entry.getValue());
}
mTree.prepare();
}
public static Builder builder() {
return new Builder();
}
@SuppressWarnings("unchecked")
private static <T> Iterator<T> cast(Iterator<?> rawIterator) {
return (Iterator<T>) rawIterator;
}
@SuppressWarnings("unchecked")
private static <T> Set<T> cast(Set<?> rawSet) {
return (Set<T>) rawSet;
}
private String transform(String input) {
if (mMatchWholeWords) {
input = " " + mDelimiters.matcher(input).replaceAll(" ") + " ";
}
if (mCaseInsensitive) {
input = input.toLowerCase();
}
return input; // Transformed input
}
/**
* Find all occurrences of <em>all</em> needles in the provided haystack.
*
* @param haystack The haystack.
* @return An iterable object where each next() moves on to the next needle.
*/
public <T> Set<T> searchIn(String haystack) {
Set<T> outputs = new HashSet<>();
Iterator<SearchResult> iter = cast(
mTree.search(transform(haystack).getBytes())
);
while (iter.hasNext()) {
SearchResult result = iter.next();
outputs.addAll(
cast(result.getOutputs())
);
}
return outputs;
}
/**
* Add a string that needs to be searched in our haystack.
* See {@link #searchIn(String)}
*
* @param needle The needle.
* @param output The output to produce when this needle is found.
*/
private void addNeedle(String needle, Object output) {
mTree.add(needle.getBytes(), output);
}
public static class Builder {
private boolean mMatchWholeWords = false;
private boolean mCaseInsensitive = false;
private Pattern mDelimiters = DEFAULT_DELIMITERS;
public Builder matchWholeWords() {
mMatchWholeWords = true;
return this;
}
public Builder withDelimiters(String delimiters) {
return withDelimiters(Pattern.compile(delimiters));
}
public Builder withDelimiters(Pattern delimiters) {
mDelimiters = delimiters;
return this;
}
public Builder caseInsensitive() {
mCaseInsensitive = true;
return this;
}
public AhoCorasickMatcher build(Set<String> needles) {
return new AhoCorasickMatcher(
needles, mMatchWholeWords, mDelimiters, mCaseInsensitive
);
}
public AhoCorasickMatcher build(Map<String, ?> needleOutputMap) {
return new AhoCorasickMatcher(
needleOutputMap, mMatchWholeWords, mDelimiters, mCaseInsensitive
);
}
}
}
|
3e0b85bdcc22fa622995d97cbb97c1eacab97952 | 3,170 | java | Java | src/main/java/com/netment/monitor/MemoryWarningSystem.java | zongpingdeng/oakville | 72e2c8c40ed37ef2a80dfe124fd1c4c07eba9f01 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/netment/monitor/MemoryWarningSystem.java | zongpingdeng/oakville | 72e2c8c40ed37ef2a80dfe124fd1c4c07eba9f01 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/netment/monitor/MemoryWarningSystem.java | zongpingdeng/oakville | 72e2c8c40ed37ef2a80dfe124fd1c4c07eba9f01 | [
"Apache-2.0"
] | null | null | null | 34.456522 | 101 | 0.667823 | 4,867 | package com.netment.monitor;
import org.apache.log4j.Logger;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import java.lang.management.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jeff on 16/8/14.
*/
public class MemoryWarningSystem {
private static final Logger log = Logger.getLogger(MemoryWarningSystem.class);
List<MemoryWarningListener> listeners = new ArrayList<>();
private static final MemoryPoolMXBean tenurePool = findTenureGenPool();
private static MemoryPoolMXBean findTenureGenPool(){
List<MemoryPoolMXBean> memPool = ManagementFactory.getMemoryPoolMXBeans();
for(MemoryPoolMXBean pool : memPool){
String s1 = pool.getName();
String[] s2 = pool.getMemoryManagerNames();
MemoryUsage usage = pool.getUsage();
if (pool.getType().equals(MemoryType.HEAP) && pool.isUsageThresholdSupported()){
return pool;
}
}
throw new RuntimeException("Can not find heap memory pool");
}
public interface MemoryWarningListener {
public void memoryUsage(long usedMemory , long maxMemory);
}
public void addMemoryListener(MemoryWarningListener listener){
this.listeners.add(listener);
}
public void removeMemoryListener(MemoryWarningListener listener){
this.listeners.remove(listener);
}
public MemoryWarningSystem(){
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
String vmName = runtimeBean.getVmName();
String vmVendor = runtimeBean.getVmVendor();
String vmVersion = runtimeBean.getVmVersion();
String specVersion = runtimeBean.getManagementSpecVersion();
log.info(vmName + vmVendor + vmVersion + specVersion);
System.out.println(runtimeBean.getVmName());
List<String> args = runtimeBean.getInputArguments();
MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
NotificationEmitter emitter = (NotificationEmitter) mbean;
emitter.addNotificationListener(new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
if (notification.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)){
long maxMemory = tenurePool.getUsage().getMax();
long usedMemory = tenurePool.getUsage().getUsed();
for (MemoryWarningListener listener : listeners){
listener.memoryUsage(usedMemory , maxMemory);
}
}
}
}, null , null);
}
public static void setPercentageUsageThreshold(double percentage){
if (percentage <= 0.0 || percentage >1.0){
throw new IllegalArgumentException("Arg not in range");
}
long maxMemory = tenurePool.getUsage().getMax();
long warningThreshold = (long) (maxMemory * percentage);
tenurePool.setUsageThreshold(warningThreshold);
}
}
|
3e0b86c11743023977b8d999399919ce311e53c0 | 3,062 | java | Java | src/main/java/com/vaadin/crm/security/SecurityConfiguration.java | ergashevnurik/vaadin-crm | 72421df08d186f73ba390228dca7216320810241 | [
"Unlicense"
] | null | null | null | src/main/java/com/vaadin/crm/security/SecurityConfiguration.java | ergashevnurik/vaadin-crm | 72421df08d186f73ba390228dca7216320810241 | [
"Unlicense"
] | null | null | null | src/main/java/com/vaadin/crm/security/SecurityConfiguration.java | ergashevnurik/vaadin-crm | 72421df08d186f73ba390228dca7216320810241 | [
"Unlicense"
] | null | null | null | 37.341463 | 107 | 0.65774 | 4,868 | package com.vaadin.crm.security;
import com.vaadin.crm.backend.Users.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserServices userServices;
private final EncryptionPassword encryptionPassword;
private static final String LOGIN_PROCESSING_URL = "/login";
private static final String LOGIN_FAILURE_URL = "/login?error";
private static final String LOGIN_URL = "/login";
private static final String LOGOUT_SUCCESS_URL = "/login";
@Autowired
public SecurityConfiguration(UserServices userServices, EncryptionPassword encryptionPassword) {
this.userServices = userServices;
this.encryptionPassword = encryptionPassword;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestCache().requestCache(new CustomRequestCache())
.and().authorizeRequests()
.requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
.anyRequest().authenticated()
.and().formLogin()
.loginPage(LOGIN_URL).permitAll()
.loginProcessingUrl(LOGIN_PROCESSING_URL)
.failureUrl(LOGIN_FAILURE_URL)
.and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);
}
// @Bean // WE will use this in order to have only one account
// @Override
// public UserDetailsService userDetailsService() {
// UserDetails user =
// User.withUsername("user")
// .password("{noop}password")
// .roles("USER")
// .build();
//
// return new InMemoryUserDetailsManager(user);
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userServices)
.passwordEncoder(encryptionPassword.getPasswordEncoder());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(
"/VAADIN/**",
"/favicon.ico",
"/robots.txt",
"/manifest.webmanifest",
"/sw.js",
"/offline.html",
"/icons/**",
"/images/**",
"/styles/**",
"/h2-console/**");
}
} |
3e0b876b714f58595cc32e82cc2631b32e5e1721 | 522 | java | Java | src/main/java/models/Patient.java | Rain0193/AppiumCucumber | 281a86b4dd105fa854fccab364c6df7b0814fec1 | [
"Unlicense"
] | null | null | null | src/main/java/models/Patient.java | Rain0193/AppiumCucumber | 281a86b4dd105fa854fccab364c6df7b0814fec1 | [
"Unlicense"
] | null | null | null | src/main/java/models/Patient.java | Rain0193/AppiumCucumber | 281a86b4dd105fa854fccab364c6df7b0814fec1 | [
"Unlicense"
] | 1 | 2020-08-08T01:56:12.000Z | 2020-08-08T01:56:12.000Z | 17.4 | 65 | 0.605364 | 4,869 | package models;
/**
* Created by gjx2998 on 15/02/2018.
*/
public class Patient {
private String username ;
private String password ;
private String pid;
public Patient(String username, String password, String pid){
this.username = username;
this.password = password;
this.pid = pid;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public String getPid(){
return pid;
}
}
|
3e0b87efaa073dbf5cb2b853c22e20fbd9fc9ef3 | 125 | java | Java | src/main/java/org/openaudible/util/queues/IQueueJob.java | machshev/openaudible | 7ba5e8f8fb4b8517ca7ae48085abd62ef67c22b7 | [
"Apache-2.0"
] | 1,216 | 2018-01-11T10:16:40.000Z | 2022-03-30T11:28:29.000Z | src/main/java/org/openaudible/util/queues/IQueueJob.java | machshev/openaudible | 7ba5e8f8fb4b8517ca7ae48085abd62ef67c22b7 | [
"Apache-2.0"
] | 837 | 2018-01-21T10:22:55.000Z | 2022-03-31T04:06:11.000Z | src/main/java/org/openaudible/util/queues/IQueueJob.java | machshev/openaudible | 7ba5e8f8fb4b8517ca7ae48085abd62ef67c22b7 | [
"Apache-2.0"
] | 161 | 2018-01-11T10:03:03.000Z | 2022-03-30T11:28:33.000Z | 15.625 | 36 | 0.76 | 4,870 | package org.openaudible.util.queues;
public interface IQueueJob {
void processJob() throws Exception;
void quitJob();
}
|
3e0b884e4be348871f6996bb4ce26cf3d9ecbbe6 | 2,511 | java | Java | utils/src/main/java/org/elastos/did/util/DeleteRootIdentity.java | chenyukaola/Elastos.DID.Java.SDK | 74c1405a892f9024c6651d67ac019e773afb2e2d | [
"MIT"
] | 8 | 2019-12-10T12:55:25.000Z | 2021-03-17T16:20:45.000Z | utils/src/main/java/org/elastos/did/util/DeleteRootIdentity.java | chenyukaola/Elastos.DID.Java.SDK | 74c1405a892f9024c6651d67ac019e773afb2e2d | [
"MIT"
] | 2 | 2020-06-16T15:08:09.000Z | 2020-10-10T10:05:29.000Z | utils/src/main/java/org/elastos/did/util/DeleteRootIdentity.java | chenyukaola/Elastos.DID.Java.SDK | 74c1405a892f9024c6651d67ac019e773afb2e2d | [
"MIT"
] | 7 | 2019-12-10T12:44:40.000Z | 2021-12-13T08:07:44.000Z | 37.477612 | 108 | 0.741537 | 4,871 | /*
* Copyright (c) 2019 Elastos Foundation
*
* 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.elastos.did.util;
import java.util.concurrent.Callable;
import org.elastos.did.DIDStore;
import org.elastos.did.exception.DIDException;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
@Command(name = "deleteidentity", mixinStandardHelpOptions = true, version = "deleteidentity 2.0",
description = "Delete the root identity.")
public class DeleteRootIdentity extends CommandBase implements Callable<Integer> {
@Option(names = {"-s", "--store"}, description = "DID Store path, default: ~/.elastos/did/store")
private String storeDir = null;
@Option(names = {"-e", "--verbose-errors"}, description = "Verbose error output, default false.")
private boolean verboseErrors = false;
@Parameters(paramLabel = "ID", index = "0", description = "The root identity to be delete from the store.")
private String id;
@Override
public Integer call() throws Exception {
try {
DIDStore store = openDIDStore(storeDir);
boolean deleted = store.deleteRootIdentity(id);
if (deleted)
System.out.format(Colorize.green("RootIdentity %s deleted\n"), id);
else
System.out.format(Colorize.red("RootIdentity %s not exists\n"), id);
} catch (DIDException e) {
if (verboseErrors)
e.printStackTrace(System.err);
else
System.err.println("Error: " + e.getMessage());
}
return 0;
}
}
|
3e0b89e0903ba037735e014fd66e01801394ce76 | 195 | java | Java | java/java-tests/testData/refactoring/introduceVariable/AnonymousClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 5 | 2015-12-19T15:27:30.000Z | 2019-08-17T10:07:23.000Z | java/java-tests/testData/refactoring/introduceVariable/AnonymousClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | java/java-tests/testData/refactoring/introduceVariable/AnonymousClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 19.5 | 37 | 0.364103 | 4,872 | class Test {
public void method() {
1 + 2 <caret>
Runnable r = new Runnable() {
public void run() {
int i = 1 + 2;
}
};
}
} |
3e0b8a6709d79fd8e00fb77380f994bf3fe4d0eb | 1,939 | java | Java | bukkit/rpk-locks-bukkit/src/main/java/com/rpkit/locks/bukkit/database/jooq/Keys.java | WorldOfCasus/RPKit | a78d9204a7ef4bd45998107a97e464878fbc9618 | [
"Apache-2.0"
] | 11 | 2019-08-15T20:53:59.000Z | 2022-01-08T13:21:10.000Z | bukkit/rpk-locks-bukkit/src/main/java/com/rpkit/locks/bukkit/database/jooq/Keys.java | WorldOfCasus/RPKit | a78d9204a7ef4bd45998107a97e464878fbc9618 | [
"Apache-2.0"
] | 469 | 2016-12-30T13:45:20.000Z | 2021-12-26T23:04:37.000Z | bukkit/rpk-locks-bukkit/src/main/java/com/rpkit/locks/bukkit/database/jooq/Keys.java | WorldOfCasus/RPKit | a78d9204a7ef4bd45998107a97e464878fbc9618 | [
"Apache-2.0"
] | 8 | 2019-07-28T14:35:33.000Z | 2022-03-04T23:04:38.000Z | 55.4 | 321 | 0.760701 | 4,873 | /*
* This file is generated by jOOQ.
*/
package com.rpkit.locks.bukkit.database.jooq;
import com.rpkit.locks.bukkit.database.jooq.tables.RpkitKeyring;
import com.rpkit.locks.bukkit.database.jooq.tables.RpkitPlayerGettingKey;
import com.rpkit.locks.bukkit.database.jooq.tables.RpkitPlayerUnclaiming;
import com.rpkit.locks.bukkit.database.jooq.tables.records.RpkitKeyringRecord;
import com.rpkit.locks.bukkit.database.jooq.tables.records.RpkitPlayerGettingKeyRecord;
import com.rpkit.locks.bukkit.database.jooq.tables.records.RpkitPlayerUnclaimingRecord;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.Internal;
/**
* A class modelling foreign key relationships and constraints of tables in
* rpkit_locks.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Keys {
// -------------------------------------------------------------------------
// UNIQUE and PRIMARY KEY definitions
// -------------------------------------------------------------------------
public static final UniqueKey<RpkitKeyringRecord> KEY_RPKIT_KEYRING_PRIMARY = Internal.createUniqueKey(RpkitKeyring.RPKIT_KEYRING, DSL.name("KEY_rpkit_keyring_PRIMARY"), new TableField[] { RpkitKeyring.RPKIT_KEYRING.CHARACTER_ID }, true);
public static final UniqueKey<RpkitPlayerGettingKeyRecord> KEY_RPKIT_PLAYER_GETTING_KEY_PRIMARY = Internal.createUniqueKey(RpkitPlayerGettingKey.RPKIT_PLAYER_GETTING_KEY, DSL.name("KEY_rpkit_player_getting_key_PRIMARY"), new TableField[] { RpkitPlayerGettingKey.RPKIT_PLAYER_GETTING_KEY.MINECRAFT_PROFILE_ID }, true);
public static final UniqueKey<RpkitPlayerUnclaimingRecord> KEY_RPKIT_PLAYER_UNCLAIMING_PRIMARY = Internal.createUniqueKey(RpkitPlayerUnclaiming.RPKIT_PLAYER_UNCLAIMING, DSL.name("KEY_rpkit_player_unclaiming_PRIMARY"), new TableField[] { RpkitPlayerUnclaiming.RPKIT_PLAYER_UNCLAIMING.MINECRAFT_PROFILE_ID }, true);
}
|
3e0b8aaf76712144ca6bc7bfd83e8a336c5064e0 | 6,272 | java | Java | rober-runtime/src/main/java/group/rober/runtime/lang/MapData.java | nic-luo/rober-cabin | c93d27f7f05208a6dbda88fd6193805eb5c20a3e | [
"MIT"
] | null | null | null | rober-runtime/src/main/java/group/rober/runtime/lang/MapData.java | nic-luo/rober-cabin | c93d27f7f05208a6dbda88fd6193805eb5c20a3e | [
"MIT"
] | null | null | null | rober-runtime/src/main/java/group/rober/runtime/lang/MapData.java | nic-luo/rober-cabin | c93d27f7f05208a6dbda88fd6193805eb5c20a3e | [
"MIT"
] | 1 | 2019-11-07T02:52:10.000Z | 2019-11-07T02:52:10.000Z | 28.775229 | 107 | 0.604336 | 4,874 | package group.rober.runtime.lang;
import group.rober.runtime.kit.BeanKit;
import group.rober.runtime.kit.JSONKit;
import group.rober.runtime.kit.MapKit;
import org.apache.commons.jxpath.AbstractFactory;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathNotFoundException;
import org.apache.commons.jxpath.Pointer;
import org.apache.commons.lang3.Validate;
import org.springframework.util.LinkedCaseInsensitiveMap;
import java.util.Locale;
import java.util.Map;
/**
* Created by tisir envkt@example.com on 2017-05-19
*/
public class MapData extends LinkedCaseInsensitiveMap<Object> {
private static final long serialVersionUID = -8545051570671246562L;
JXPathContext context = null;
public MapData() {
}
public static <V> MapData valueOf(Map<String,?> value){
MapData object = new MapData();
object.putAll(value);
return object;
}
public static <V> MapData valueOf(String k1,V v1){
MapData object = new MapData();
object.putAll(MapKit.mapOf(k1,v1));
return object;
}
public static <V> MapData valueOf(String k1,V v1,String k2,V v2){
MapData object = new MapData();
object.putAll(MapKit.mapOf(k1,v1,k2,v2));
return object;
}
public static <V> MapData valueOf(String k1,V v1,String k2,V v2,String k3,V v3){
MapData object = new MapData();
object.putAll(MapKit.mapOf(k1,v1,k2,v2,k3,v3));
return object;
}
public MapData(Locale locale) {
super(locale);
}
public MapData(int initialCapacity) {
super(initialCapacity);
}
public MapData(int initialCapacity, Locale locale) {
super(initialCapacity, locale);
}
public static MapData build(Map<String,?> mapData){
MapData dataObject = new MapData();
dataObject.putAll(mapData);
return dataObject;
}
public static MapData buildFromBean(Object bean){
MapData dataObject = new MapData();
dataObject.putFromBean(bean);
return dataObject;
}
protected void toggleInit(){
if(context==null){
context = JXPathContext.newContext(this);
//xpath路径中,自动创建对象使用的factory
context.setFactory(getCreateObjectFactory());
}
}
/**
* 把JavaBean转为DataBox
*
* @param bean bean
* @return map
*/
public MapData putFromBean(Object bean) {
Map<String, Object> data = BeanKit.bean2Map(bean);
this.putAll(data);
return this;
}
/**
* 将DataBox转换为JavaBean
*
* @param classType classType
* @param <T> T
* @return toBean
*/
public <T> T toBean(Class<T> classType){
return BeanKit.map2Bean(this,classType);
}
public Map<String,Object> toMap(){
return (Map<String,Object>)this;
}
protected AbstractFactory getCreateObjectFactory(){
return new AbstractFactory(){
public boolean createObject(JXPathContext context, Pointer pointer,
Object parent, String name, int index){
if (parent instanceof MapData){
MapData dtx = (MapData)parent;
dtx.put(name,new MapData());
return true;
}else{
return false;
}
}
};
}
protected String xpath(String p){
if(p==null)return null;
return p.replaceAll("\\.","/");
}
@SuppressWarnings("unchecked")
public <T> T getObject(String expression, boolean strict, Class<T> classType){
Object object = getObject(expression,strict);
if(object==null)return null;
if(classType.isAssignableFrom(object.getClass())){
T ret = (T)object;
//如果获取一个结果是Map类型,但是目标类型是DataBox,则封装转换一下
if(classType.isAssignableFrom(MapData.class)&&!(ret instanceof MapData)&&ret instanceof Map){
Map<String,Object> mapObject = (Map<String, Object>)ret;
MapData dataBox = new MapData();
dataBox.putAll(mapObject);
ret = (T)dataBox;
}
return ret;
}else{
throw new ClassCastException(object.getClass()+" can not cast to "+classType);
}
}
public <T> T getObject(String expression, Class<T> classType){
return this.getObject(expression,false,classType);
}
/**
* 取一个子对象
*
* @param expression expression
* @param strict strict
* @return object
*/
public Object getObject(String expression, boolean strict){
Object value = null;
if(expression.indexOf(".")<0||expression.indexOf("/")<0){
value = get(expression);
}else{
toggleInit();
try{
value = context.getValue(xpath(expression));
}catch(JXPathNotFoundException e){ //如果表达式不存在,在严格模式下,也抛出错
if(strict){
throw new NullPointerException(e.getMessage());
}
}
}
if(strict) Validate.notNull(value,"expression:"+expression,",not exits in object:"+toJsonString());
return value;
}
/**
* 获取一个值对象
*
* @param expression xpath表达式
* @param strict 是否使用严格模式
* @return valueObject
*/
public ValueObject get(String expression, boolean strict){
Object value = getObject(expression,strict);
return new ValueObject(value);
}
public MapData getSubDataObject(String expression, boolean strict){
Object value = getObject(expression,strict);
if(value instanceof MapData){
return ((MapData)value);
}else{
return null;
}
}
public MapData getSubDataObject(String expression){
return getSubDataObject(expression,false);
}
public ValueObject getValue(String expression){
return get(expression,false);
}
public void putValue(String expression, Object value){
toggleInit();
context.createPathAndSetValue(xpath(expression),value);
}
public String toJsonString(){
return JSONKit.toJsonString(this);
}
}
|
3e0b8ab616f5e687db333725590bc017485e63df | 2,067 | java | Java | api/metrics-api-jaxrs/src/test/java/org/hawkular/metrics/api/jaxrs/param/InvalidTagsConverterTest.java | jkandasa/rhq-metrics | ff994a55b8173a89aa2ff80be9b46b994313bc81 | [
"Apache-2.0"
] | 226 | 2015-02-07T03:46:42.000Z | 2021-09-19T22:28:13.000Z | api/metrics-api-jaxrs/src/test/java/org/hawkular/metrics/api/jaxrs/param/InvalidTagsConverterTest.java | jkandasa/rhq-metrics | ff994a55b8173a89aa2ff80be9b46b994313bc81 | [
"Apache-2.0"
] | 648 | 2015-02-06T16:20:39.000Z | 2019-08-02T05:51:11.000Z | api/metrics-api-jaxrs/src/test/java/org/hawkular/metrics/api/jaxrs/param/InvalidTagsConverterTest.java | jkandasa/rhq-metrics | ff994a55b8173a89aa2ff80be9b46b994313bc81 | [
"Apache-2.0"
] | 70 | 2015-02-09T18:00:07.000Z | 2022-02-21T18:50:57.000Z | 29.956522 | 80 | 0.634253 | 4,875 | /*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.api.jaxrs.param;
import static org.hamcrest.CoreMatchers.equalTo;
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* @author Thomas Segismont
*/
@RunWith(Parameterized.class)
public class InvalidTagsConverterTest {
@Parameters(name = "{0}")
public static Iterable<Object[]> params() {
return Arrays.asList(
new Object[][]{
{" "},
{","},
{",,"},
{",dsqqs"},
{":"},
{"7:5, 3 , a:b"},
{"7:5,, a:b"},
}
);
}
@Rule
public final ExpectedException expectedException = ExpectedException.none();
private String value;
public InvalidTagsConverterTest(String value) {
this.value = value;
}
@Test
public void testFromString() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(equalTo("Invalid tags: " + value));
//noinspection ResultOfMethodCallIgnored
new TagsConverter().fromString(value);
}
} |
3e0b8adadbf67b92430b4e56a8fba302f1b2b392 | 10,687 | java | Java | Android/app/src/main/java/com/sequencing/weather/service/SendLoggingReceiver.java | SequencingDOTcom/Weather-My-Way-RTP-App | 9bad3f1fd52f8752b24686f8177e582f98a0608f | [
"MIT"
] | 1 | 2022-01-14T20:51:35.000Z | 2022-01-14T20:51:35.000Z | Android/app/src/main/java/com/sequencing/weather/service/SendLoggingReceiver.java | SequencingDOTcom/Weather-My-Way-RTP-App | 9bad3f1fd52f8752b24686f8177e582f98a0608f | [
"MIT"
] | null | null | null | Android/app/src/main/java/com/sequencing/weather/service/SendLoggingReceiver.java | SequencingDOTcom/Weather-My-Way-RTP-App | 9bad3f1fd52f8752b24686f8177e582f98a0608f | [
"MIT"
] | 2 | 2022-02-10T03:12:39.000Z | 2022-02-10T11:43:11.000Z | 38.442446 | 138 | 0.689997 | 4,876 | package com.sequencing.weather.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.sequencing.weather.activity.RTPApplication;
import com.sequencing.weather.database.DatabaseCreater;
import com.sequencing.weather.database.LoggingQueries;
import com.sequencing.weather.database.SQLiteAccessData;
import com.sequencing.weather.helper.AccountHelper;
import com.sequencing.weather.helper.InstancesContainer;
import com.sequencing.weather.logging.EventEntity;
import com.sequencing.weather.logging.events.Interaction;
import com.sequencing.weather.logging.events.Request;
import com.sequencing.weather.logging.events.Usage;
import com.sequencing.weather.logging.listeners.UsageEventListener;
import com.sequencing.weather.requests.RestLoggingInterface;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EReceiver;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.rest.spring.annotations.RestService;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.prefs.Preferences;
import javax.inject.Inject;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
/**
* Created by omazurova on 5/18/2017.
*/
@EReceiver
public class SendLoggingReceiver extends BroadcastReceiver {
private static int EXTRA_BROADCAST_CODE = 222;
@RestService
RestLoggingInterface restInterface;
@Inject
UsageEventListener usageEventListener;
@Inject
SQLiteAccessData sqLiteAccessData;
private Context context;
private SharedPreferences settings;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
this.settings = PreferenceManager.getDefaultSharedPreferences(context);
if(isTimeRefreshExpired(480)){
RTPApplication application = RTPApplication.create(context);
application.getDaggerComponent().inject(this);
if(!usageEventListener.isRegistered()){
EventBus.getDefault().register(usageEventListener);
usageEventListener.setIsUsageEventListenerRegistered(true);
}
sendLoggingData();
}
}
public static void setAlarm(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, SendLoggingReceiver_.class);
PendingIntent pi = PendingIntent.getBroadcast(context, EXTRA_BROADCAST_CODE, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_HALF_DAY, AlarmManager.INTERVAL_DAY, pi);
}
public static void cancelAlarm(Context context) {
Intent intent = new Intent(context, SendLoggingReceiver_.class);
PendingIntent sender = PendingIntent.getBroadcast(context, EXTRA_BROADCAST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (sender != null) {
alarmManager.cancel(sender);
sender.cancel();
}
}
public static boolean checkAlarmIsSet(Context context) {
Intent intent = new Intent(context, SendLoggingReceiver_.class);
return PendingIntent.getBroadcast(context, EXTRA_BROADCAST_CODE, intent, PendingIntent.FLAG_NO_CREATE) != null;
}
@Background
protected void sendLoggingData() {
EventEntity eventEntity = buildJsonEvents();
try{
restInterface.sendEvents(eventEntity);
updateTimeSendReport();
cleanDB();
} catch (Exception e){
Log.d("Send logging", e.getMessage());
}
EventBus.getDefault().unregister(usageEventListener);
usageEventListener.setIsUsageEventListenerRegistered(false);
}
@UiThread
protected void updateTimeSendReport() {
SharedPreferences.Editor editor = settings.edit();
Date currentDate = new Date();
editor.putLong("lastTimeSendReport", currentDate.getTime()).commit();
}
private void cleanDB(){
SQLiteDatabase database = sqLiteAccessData.getDatabase();
database.delete(DatabaseCreater.TABLE_USAGE, null, null);
database.delete(DatabaseCreater.TABLE_EVENT, null, null);
database.delete(DatabaseCreater.TABLE_INTERACTION, null, null);
database.delete(DatabaseCreater.TABLE_REQUEST, null, null);
Usage usage = new Usage();
usage.start = System.currentTimeMillis();
EventBus.getDefault().post(usage);
}
private int getAvgNumber(List<Request> requests) {
int i = 0;
for (Request request : requests) {
i = i + request.requestTime;
}
return i / requests.size();
}
private EventEntity buildJsonEvents() {
EventEntity eventEntity = new EventEntity();
eventEntity.user = settings.getString("email", "");
eventEntity.os = getOSData();
eventEntity.app = getAppVersion();
eventEntity.usage = getUsageData();
return eventEntity;
}
private EventEntity.App getAppVersion() {
PackageManager manager = context.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = info.versionName;
EventEntity.App app = new EventEntity.App();
app.ver = version;
return app;
}
private EventEntity.OS getOSData() {
EventEntity.OS os = new EventEntity.OS();
os.name = "Android";
os.ver = "Android SDK: " + Build.VERSION.SDK_INT + "(" + Build.VERSION.RELEASE + ")";
os.arch = System.getProperty("os.arch");
return os;
}
private EventEntity.Usage getUsageData() {
SQLiteAccessData sqLiteAccessData = new SQLiteAccessData(context);
LoggingQueries loggingQueries = new LoggingQueries(sqLiteAccessData);
EventEntity.Usage usageLogging = new EventEntity.Usage();
//usage
Usage usage = loggingQueries.getUsage();
usageLogging.start = usage.start;
usageLogging.end = usage.end;
//events
usageLogging.events = loggingQueries.getEvents();
//background wu
EventEntity.Services services = new EventEntity.Services();
//wu
List<Request> backgroundDataWU = loggingQueries.getBackgroundData(Request.REQUEST_SERVICE_WU);
if (backgroundDataWU.size() > 0) {
EventEntity.Stats statsWU = getStats(loggingQueries, backgroundDataWU);
services.wu = statsWU;
}
//appchains
List<Request> backgroundDataAppchains = loggingQueries.getBackgroundData(Request.REQUEST_SERVICE_APPCHAINS);
if (backgroundDataAppchains.size() > 0) {
EventEntity.Stats statsAppchains = getStats(loggingQueries, backgroundDataAppchains);
services.appchains = statsAppchains;
}
usageLogging.background = services;
//interactions
List<Interaction> interactions = loggingQueries.getInteractions();
List<EventEntity.Interactions> interactionsLogging = new ArrayList<>();
List<Request> foregrAppchainsRequests;
List<Request> foregrWURequests;
for (Interaction interaction : interactions) {
EventEntity.Services interactionServices = new EventEntity.Services();
EventEntity.Interactions interactionLog = new EventEntity.Interactions();
interactionLog.location = interaction.lat + "," + interaction.lng;
interactionLog.place = interaction.place;
interactionLog.ts = interaction.ts;
interactionLog.duration = interaction.duration;
interactionLog.media = interaction.media;
foregrWURequests = loggingQueries.getRequestsByInteractionTimestamp(interaction.ts, Request.REQUEST_SERVICE_WU);
if(foregrWURequests.size() > 0){
EventEntity.Stats statsForegWU = getStats(loggingQueries, foregrWURequests);
interactionServices.wu = statsForegWU;
}
foregrAppchainsRequests = loggingQueries.getRequestsByInteractionTimestamp(interaction.ts, Request.REQUEST_SERVICE_APPCHAINS);
if(foregrAppchainsRequests.size() > 0) {
EventEntity.Stats statsForegAppChains = getStats(loggingQueries, foregrAppchainsRequests);
interactionServices.appchains = statsForegAppChains;
}
interactionLog.services = interactionServices;
interactionsLogging.add(interactionLog);
}
usageLogging.interactions = interactionsLogging;
return usageLogging;
}
@NonNull
private EventEntity.Stats getStats(LoggingQueries loggingQueries, List<Request> requests) {
EventEntity.Stats stats = new EventEntity.Stats();
stats.h = requests.get(0).requestTime;
stats.l = requests.get(requests.size() - 1).requestTime;
stats.n = requests.size();
stats.avg = getAvgNumber(requests);
List<EventEntity.Failures> failuresWU = new ArrayList<>();
for (Request request : requests) {
if (request.failureTimestamp != 0) {
EventEntity.Failures failure = new EventEntity.Failures();
failure.ts = request.failureTimestamp;
failure.reason = request.failureReason;
failuresWU.add(failure);
}
}
stats.failures = failuresWU;
return stats;
}
public boolean isTimeRefreshExpired(int intervalMinutes) {
long maxInterval = MILLISECONDS.convert(intervalMinutes, MINUTES);
long lastTimeRefresh = settings.getLong("lastTimeSendReport", 0);
if(lastTimeRefresh == 0){
return true;
}
Date currentDate = new Date();
long currentInterval = currentDate.getTime() - lastTimeRefresh;
if (currentInterval > maxInterval) {
return true;
}
return false;
}
}
|
3e0b8b61dc7ab78424464c3a48ad9542308c0ba9 | 1,620 | java | Java | src/main/java/tech/guiyom/anscapes/RgbColor.java | LimeiloN/anscapes | 812d29cf411951174b82fb085d303219b0500389 | [
"MIT"
] | null | null | null | src/main/java/tech/guiyom/anscapes/RgbColor.java | LimeiloN/anscapes | 812d29cf411951174b82fb085d303219b0500389 | [
"MIT"
] | null | null | null | src/main/java/tech/guiyom/anscapes/RgbColor.java | LimeiloN/anscapes | 812d29cf411951174b82fb085d303219b0500389 | [
"MIT"
] | null | null | null | 21.038961 | 74 | 0.492593 | 4,877 | package tech.guiyom.anscapes;
import java.awt.Color;
public class RgbColor implements AnsiColor {
private final int r;
private final int g;
private final int b;
public RgbColor(Color c) {
this(c.getRed(), c.getGreen(), c.getBlue());
}
public RgbColor(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
/**
* Uses a color parsing method similar to {@link Color#Color(int)}
*
* @param rgb
*/
public RgbColor(int rgb) {
this((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff);
}
/**
* Create a new AWT Color object each time.
*
* @return the corresponding AWT Color
*/
@Override
public Color color() {
return new Color(r, g, b);
}
@Override
public int r() {
return r;
}
@Override
public int g() {
return g;
}
@Override
public int b() {
return b;
}
@Override
public String fg() {
return Anscapes.CSI + "38;2;" + r() + ';' + g() + ';' + b() + 'm';
}
@Override
public String bg() {
return Anscapes.CSI + "48;2;" + r() + ';' + g() + ';' + b() + 'm';
}
@Override
public boolean equals(Object obj) {
if (obj instanceof RgbColor) {
RgbColor other = (RgbColor) obj;
return r == other.r && g == other.g && b == other.b;
} else if (obj instanceof AnsiColor) {
AnsiColor other = (AnsiColor) obj;
return r == other.r() && g == other.g() && b == other.b();
}
return false;
}
}
|
3e0b8b75405b35adf06ef80e3aba0009f6056bf6 | 3,615 | java | Java | activemq-http/src/test/java/org/apache/activemq/transport/ws/SocketTest.java | sho25/activemq | d34b61b56206883e6570ae7207c3ddb074311adf | [
"Apache-2.0"
] | null | null | null | activemq-http/src/test/java/org/apache/activemq/transport/ws/SocketTest.java | sho25/activemq | d34b61b56206883e6570ae7207c3ddb074311adf | [
"Apache-2.0"
] | 7 | 2020-06-18T17:27:51.000Z | 2022-02-01T01:05:30.000Z | activemq-http/src/test/java/org/apache/activemq/transport/ws/SocketTest.java | sho25/activemq | d34b61b56206883e6570ae7207c3ddb074311adf | [
"Apache-2.0"
] | null | null | null | 17.720588 | 811 | 0.79751 | 4,878 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|ws
package|;
end_package
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|ws
operator|.
name|jetty9
operator|.
name|MQTTSocket
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|ws
operator|.
name|jetty9
operator|.
name|StompSocket
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
specifier|public
class|class
name|SocketTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|testStompSocketRemoteAddress
parameter_list|()
block|{
name|StompSocket
name|stompSocketJetty8
init|=
operator|new
name|StompSocket
argument_list|(
literal|"ws://localhost:8080"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"ws://localhost:8080"
argument_list|,
name|stompSocketJetty8
operator|.
name|getRemoteAddress
argument_list|()
argument_list|)
expr_stmt|;
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|ws
operator|.
name|jetty9
operator|.
name|StompSocket
name|stompSocketJetty9
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|ws
operator|.
name|jetty9
operator|.
name|StompSocket
argument_list|(
literal|"ws://localhost:8080"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"ws://localhost:8080"
argument_list|,
name|stompSocketJetty9
operator|.
name|getRemoteAddress
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testMqttSocketRemoteAddress
parameter_list|()
block|{
name|MQTTSocket
name|mqttSocketJetty8
init|=
operator|new
name|MQTTSocket
argument_list|(
literal|"ws://localhost:8080"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"ws://localhost:8080"
argument_list|,
name|mqttSocketJetty8
operator|.
name|getRemoteAddress
argument_list|()
argument_list|)
expr_stmt|;
name|MQTTSocket
name|mqttSocketJetty9
init|=
operator|new
name|MQTTSocket
argument_list|(
literal|"ws://localhost:8080"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"ws://localhost:8080"
argument_list|,
name|mqttSocketJetty9
operator|.
name|getRemoteAddress
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
3e0b8c97a4cb325dd0f39f8cd0463afe7fa2cb1f | 3,595 | java | Java | smart-applications/application-security-authorization/src/main/java/com/sct/application/authorization/support/formlogin/CustomFormLoginConfigurer.java | hubeixiang/smart-city | ff178d300da40d22bfd09d067c5fe6c615a30c98 | [
"Apache-2.0"
] | 2 | 2020-12-18T02:19:14.000Z | 2021-05-06T08:51:30.000Z | smart-applications/application-security-authorization/src/main/java/com/sct/application/authorization/support/formlogin/CustomFormLoginConfigurer.java | hubeixiang/smart-city | ff178d300da40d22bfd09d067c5fe6c615a30c98 | [
"Apache-2.0"
] | null | null | null | smart-applications/application-security-authorization/src/main/java/com/sct/application/authorization/support/formlogin/CustomFormLoginConfigurer.java | hubeixiang/smart-city | ff178d300da40d22bfd09d067c5fe6c615a30c98 | [
"Apache-2.0"
] | 4 | 2020-11-24T10:23:07.000Z | 2021-08-19T16:06:54.000Z | 41.802326 | 125 | 0.767177 | 4,879 | package com.sct.application.authorization.support.formlogin;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler;
import org.springframework.security.web.authentication.ForwardAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
public final class CustomFormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
AbstractAuthenticationFilterConfigurer<H, CustomFormLoginConfigurer<H>, CustomUsernamePasswordAuthenticationFilter> {
public CustomFormLoginConfigurer() {
super(new CustomUsernamePasswordAuthenticationFilter(), null);
usernameParameter("username");
passwordParameter("password");
}
@Override
public CustomFormLoginConfigurer<H> loginPage(String loginPage) {
return super.loginPage(loginPage);
}
public CustomUsernamePasswordAuthenticationFilter getCustomAuthenticationFilter() {
return getAuthenticationFilter();
}
public CustomFormLoginConfigurer<H> usernameParameter(String usernameParameter) {
getAuthenticationFilter().setUsernameParameter(usernameParameter);
return this;
}
public CustomFormLoginConfigurer<H> passwordParameter(String passwordParameter) {
getAuthenticationFilter().setPasswordParameter(passwordParameter);
return this;
}
public CustomFormLoginConfigurer<H> passwordPublicKey(String publicKeyParameter) {
getAuthenticationFilter().setPasswordPublicKeyParameter(publicKeyParameter);
return this;
}
public CustomFormLoginConfigurer<H> failureForwardUrl(String forwardUrl) {
failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl));
return this;
}
public CustomFormLoginConfigurer<H> successForwardUrl(String forwardUrl) {
successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl));
return this;
}
@Override
public void init(H http) throws Exception {
super.init(http);
initDefaultLoginFilter(http);
}
@Override
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
return new AntPathRequestMatcher(loginProcessingUrl, "POST");
}
private String getUsernameParameter() {
return getAuthenticationFilter().getUsernameParameter();
}
private String getPasswordParameter() {
return getAuthenticationFilter().getPasswordParameter();
}
private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setFormLoginEnabled(true);
loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter());
loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter());
loginPageGeneratingFilter.setLoginPageUrl(getLoginPage());
loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl());
}
}
}
|
3e0b8cdd118c6a8814a9a2205493a57906638d93 | 10,296 | java | Java | app/src/main/java/edu/miami/c11173414/smartcommunitydrawer/ClassifyFragment.java | blakemaune/smartcommunity_blake | 8c08bd72253f8c0984a2e101821785f72c4d3749 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/edu/miami/c11173414/smartcommunitydrawer/ClassifyFragment.java | blakemaune/smartcommunity_blake | 8c08bd72253f8c0984a2e101821785f72c4d3749 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/edu/miami/c11173414/smartcommunitydrawer/ClassifyFragment.java | blakemaune/smartcommunity_blake | 8c08bd72253f8c0984a2e101821785f72c4d3749 | [
"Apache-2.0"
] | null | null | null | 41.01992 | 144 | 0.562549 | 4,880 | package edu.miami.c11173414.smartcommunitydrawer;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class ClassifyFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
Spinner dropDown1, dropDown2, dropDown3;
Button continueButton;
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.fragment_classify, container,false);
if(((MainActivity)getActivity()).currentLocation != null){
DecodeLocation d = new DecodeLocation(getActivity().getApplicationContext(), getActivity());
((TextView)(fragView.findViewById(R.id.current_location))).setText(d.doInBackground(((MainActivity)getActivity()).currentLocation));
}
dropDown1 = (Spinner) fragView.findViewById(R.id.classification_spinner1);
dropDown2 = (Spinner) fragView.findViewById(R.id.classification_spinner2);
dropDown3 = (Spinner) fragView.findViewById(R.id.classification_spinner3);
dropDown1.setOnItemSelectedListener(this);
dropDown2.setOnItemSelectedListener(this);
dropDown3.setOnItemSelectedListener(this);
dropDown2.setVisibility(View.GONE);
dropDown3.setVisibility(View.GONE);
continueButton = (Button)fragView.findViewById(R.id.classify_continue_button);
continueButton.setOnClickListener(this);
setSpinnerArray(dropDown1, R.array.classifications_array);
return(fragView);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.classify_continue_button:
String selectionText = "";
if(dropDown1.getSelectedItem() != null){
selectionText += dropDown1.getSelectedItem().toString()+"/";
}
if(dropDown2.getSelectedItem() != null){
selectionText += dropDown2.getSelectedItem().toString()+"/";
}
if(dropDown3.getSelectedItem() != null){
selectionText += dropDown3.getSelectedItem().toString();
}
Toast.makeText(getActivity(), selectionText, Toast.LENGTH_LONG).show();
Log.i("Classification:", selectionText);
ArrayList<Integer> duplicateIDs = checkDuplicates(selectionText);
if(duplicateIDs.size() == 0) {
// Send directly to new report fragment
Log.i("Classify", "no duplicates found, starting new report");
Fragment newReport = new ReportFragment();
Bundle bundle = new Bundle();
bundle.putString("Classification", selectionText);
newReport.setArguments(bundle);
((MainActivity)getActivity()).displayView(newReport);
}else{
Log.i("Classify", "duplicates found, displaying");
Fragment duplicateList = new DuplicateListFragment();
Bundle bundle = new Bundle();
bundle.putIntArray("reportIDArray", SearchFragment.ArrayConvert(duplicateIDs));
bundle.putString("Classification", selectionText);
duplicateList.setArguments(bundle);
((MainActivity)getActivity()).displayView(duplicateList);
}
default:
break;
}
}
private ArrayList<Integer> checkDuplicates(String classString){
// Initialize the report id array we will send in bundle
ArrayList<Integer> reportIDs = new ArrayList<Integer>();
// Get the location from main
Location loc = ((MainActivity)getActivity()).currentLocation;
// Get our JSON to search through
JSONArray jsonArray = new JSONArray();
try {
jsonArray = JsonReader.readJsonFromUrl("http://smart-community-dev.us-east-1.elasticbeanstalk.com/api/reports");
Log.i("output", jsonArray.toString());
} catch (Exception e) {
Log.e("exceptions", "are annoying");
e.printStackTrace();
}
// Get the classification of our new report
int classification = ReportFragment.parseClassification(classString);
// Search for report ids that match location, then classification
ArrayList<Integer> nearbyReportIDs = SearchFragment.searchByRadius(jsonArray, loc, 1500);
ArrayList<Integer> sameClassIDs = SearchFragment.searchByClassification(jsonArray, classification);
// Find the report ids that are in both, add them to our output array
for(int i: nearbyReportIDs){
for(int j:sameClassIDs){
if(i == j){
reportIDs.add(i);
}
}
}
return reportIDs;
}
private void setSpinnerArray(Spinner s, int i){
if (i == -1){
s.setVisibility(View.GONE);
s.setAdapter(null);
}else {
s.setVisibility(View.VISIBLE);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
i,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
continueButton.setClickable(false);
Log.i("onItemSelected: ", "Button set unclickable");
String selection = adapterView.getItemAtPosition(position).toString();
int arrayId = -1;
if(adapterView.equals(dropDown1)){
// If the spinner triggering this is dropdown1
Log.i("DropDown1: ", selection);
// Set the array for dropdown2
switch (selection) {
case "Water":
// Dropdown 1 selection is water
arrayId = R.array.water_subarray;
break;
case "Transportation":
// Dropdown 1 selection is transportation
arrayId = R.array.transportation_subarray;
break;
case "Electricity":
// Dropdown 1 selection is electricity
arrayId = R.array.electricity_subarray;
break;
case "Wildlife":
// Dropdown 1 selection is wildlife
arrayId = R.array.wildlife_subarray;
break;
default:
break;
}
setSpinnerArray(dropDown2, arrayId);
}
else if(adapterView.equals(dropDown2)){
switch (selection){
case "Broken/Missing Water Cover":
arrayId = -1;
continueButton.setClickable(true);
break;
case "Flooding":
// Dropdown 2 selection is flooding
arrayId = R.array.flooding_subarray;
break;
case "Water Quality":
// Dropdown 2 selection is water quality
arrayId = R.array.quality_subarray;
break;
case "Waste Water":
// Dropdown 2 selection is waste water
arrayId = R.array.waste_subarray;
break;
case "Canals":
// Dropdown 2 selection is canals
arrayId = R.array.canals_subarray;
break;
case "Signs":
// Dropdown 2 selection is signs
arrayId = R.array.signs_subarray;
break;
case "Roads":
// Dropdown 2 selection is roads
arrayId = R.array.roads_subarray;
break;
case "Traffic Lights":
arrayId = -1;
continueButton.setClickable(true);
break;
case "Lights":
arrayId = R.array.lights_subarray;
break;
case "Power Lines":
arrayId = R.array.powerline_subarray;
break;
case "Outage/Blackout/Surges":
arrayId = -1;
continueButton.setClickable(true);
break;
case "Lost Animal":
arrayId = -1;
continueButton.setClickable(true);
break;
case "Dead Animal Removal":
arrayId = R.array.dead_animal_subarray;
break;
case "Animal Bite":
arrayId = -1;
continueButton.setClickable(true);
break;
case "Animal Infestation":
arrayId = R.array.animal_infestation_subarray;
break;
default:
break;
}
setSpinnerArray(dropDown3, arrayId);
}
else if(adapterView.equals(dropDown3)){
// If the spinner triggering this is dropdown3
Log.i("DropDown3: ", selection);
}
if((dropDown3.getSelectedItem() != null) && !(dropDown3.getSelectedItem().toString().equals("Select one..."))){
Log.i("onItemSelected: ","Button set clickable");
continueButton.setClickable(true);
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
|
3e0b8d0f5c831ea34dccb3236585f2c2886bd234 | 3,154 | java | Java | opentaps/opentaps-common/src/common/org/opentaps/domain/order/ProductStore.java | opentaps/opentaps-1 | 49f3ebcd3645b7e76fe3d71f43904ce65d7901b8 | [
"Apache-2.0"
] | 10 | 2015-12-10T11:53:32.000Z | 2022-02-28T13:00:09.000Z | opentaps/opentaps-common/src/common/org/opentaps/domain/order/ProductStore.java | alainrk/opentaps | 1b234c74a55c0eb39170b9a9e88a0586a0408c77 | [
"Apache-2.0"
] | null | null | null | opentaps/opentaps-common/src/common/org/opentaps/domain/order/ProductStore.java | alainrk/opentaps | 1b234c74a55c0eb39170b9a9e88a0586a0408c77 | [
"Apache-2.0"
] | 13 | 2015-11-16T10:01:22.000Z | 2021-12-05T06:47:00.000Z | 37.105882 | 109 | 0.731769 | 4,881 | /*
* Copyright (c) Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.domain.order;
import java.util.List;
import org.opentaps.foundation.repository.RepositoryException;
import org.opentaps.base.entities.ProdCatalog;
import org.opentaps.base.entities.ProductStoreCatalog;
import org.opentaps.base.entities.ProductStoreShipmentMeth;
import org.opentaps.base.entities.ProductStoreShipmentMethView;
/**
* Product Store entity.
*/
public class ProductStore extends org.opentaps.base.entities.ProductStore {
private List<ProdCatalog> prodCatalogs;
private List<ProductStoreCatalog> productStoreCatalogs;
private List<ProductStoreShipmentMeth> productStoreShipmentMeths;
private List<ProductStoreShipmentMethView> productStoreShipmentMethViews;
/**
* Default constructor.
*/
public ProductStore() {
super();
}
/**
* Gets the list of <code>ProdCatalog</code> for this product store.
* @return list of <code>ProdCatalog</code>
* @throws RepositoryException if an error occurs
*/
public List<ProdCatalog> getProdCatalogs() throws RepositoryException {
if (prodCatalogs == null) {
prodCatalogs = getRepository().getRelatedProdCatalogs(this);
}
return prodCatalogs;
}
/**
* Gets the list of <code>ProductStoreShipmentMeth</code> for this product store.
* @return list of <code>ProductStoreShipmentMeth</code>
* @throws RepositoryException if an error occurs
*/
public List<ProductStoreShipmentMeth> getProductStoreShipmentMeths() throws RepositoryException {
if (productStoreShipmentMeths == null) {
productStoreShipmentMeths = getRepository().getRelatedProductStoreShipmentMeths(this);
}
return productStoreShipmentMeths;
}
/**
* Gets the list of <code>ProductStoreShipmentMethView</code> for this product store.
* @return list of <code>ProductStoreShipmentMethView</code>
* @throws RepositoryException if an error occurs
*/
public List<ProductStoreShipmentMethView> getProductStoreShipmentMethViews() throws RepositoryException {
if (productStoreShipmentMethViews == null) {
productStoreShipmentMethViews = getRepository().getRelatedProductStoreShipmentMethViews(this);
}
return productStoreShipmentMethViews;
}
private OrderRepositoryInterface getRepository() {
return OrderRepositoryInterface.class.cast(repository);
}
}
|
3e0b8d5dda358ffe62eb96cec7c548fc85a88ec0 | 13,474 | java | Java | rest-frontend/src/main/java/com/fluxhydravault/restfrontend/view/LandingView.java | ojoakua-10bit/MPPL-GAME-TANK | c984e92401a6ef7c846f318865034a35d4cc51bd | [
"MIT"
] | null | null | null | rest-frontend/src/main/java/com/fluxhydravault/restfrontend/view/LandingView.java | ojoakua-10bit/MPPL-GAME-TANK | c984e92401a6ef7c846f318865034a35d4cc51bd | [
"MIT"
] | null | null | null | rest-frontend/src/main/java/com/fluxhydravault/restfrontend/view/LandingView.java | ojoakua-10bit/MPPL-GAME-TANK | c984e92401a6ef7c846f318865034a35d4cc51bd | [
"MIT"
] | null | null | null | 62.962617 | 328 | 0.690664 | 4,882 | package com.fluxhydravault.restfrontend.view;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LandingView extends JFrame {
private JPanel rootPanel;
private JPanel contentPanel;
private ImagePanel imagePanel1;
private JPanel playerMenu;
private JPanel itemMenu;
private JPanel adminMenu;
private JPanel logoutMenu;
private JPanel homeMenu;
private JFrame parentFrame;
private Image image;
public LandingView() {
image = new ImageIcon(getClass().getResource("/logo.png")).getImage();
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
parentFrame = this;
homeMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
playerMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
itemMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
adminMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
logoutMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("War Tanks - Admin Portal");
setContentPane(rootPanel);
setIconImage(image);
setSize(1280, 720);
setResizable(false);
homeMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
System.out.println("Load home view");
}
});
playerMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
System.out.println("Load player view");
}
});
itemMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
System.out.println("Load item view");
}
});
adminMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
System.out.println("Load admin view");
setContentPane(new AdminEditView(parentFrame, rootPanel).getRootPanel());
revalidate();
}
});
logoutMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
System.out.println("Ask confirmation then logout.");
}
});
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
rootPanel = new JPanel();
rootPanel.setLayout(new GridLayoutManager(11, 9, new Insets(8, 8, 8, 8), -1, -1));
final Spacer spacer1 = new Spacer();
rootPanel.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
rootPanel.add(spacer2, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
rootPanel.add(spacer3, new GridConstraints(1, 8, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final Spacer spacer4 = new Spacer();
rootPanel.add(spacer4, new GridConstraints(1, 0, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
rootPanel.add(imagePanel1, new GridConstraints(1, 1, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(64, 64), null, null, 0, false));
final Spacer spacer5 = new Spacer();
rootPanel.add(spacer5, new GridConstraints(1, 3, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(6, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(contentPanel, new GridConstraints(8, 1, 1, 7, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(848, 480), null, 0, false));
final JLabel label1 = new JLabel();
Font label1Font = this.$$$getFont$$$(null, Font.BOLD, 20, label1.getFont());
if (label1Font != null) label1.setFont(label1Font);
label1.setText("Welcome to War Tanks - Admin Portal");
contentPanel.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer6 = new Spacer();
contentPanel.add(spacer6, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final JLabel label2 = new JLabel();
Font label2Font = this.$$$getFont$$$(null, -1, 16, label2.getFont());
if (label2Font != null) label2.setFont(label2Font);
label2.setText("Sub-message 1");
contentPanel.add(label2, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
Font label3Font = this.$$$getFont$$$(null, -1, 16, label3.getFont());
if (label3Font != null) label3.setFont(label3Font);
label3.setText("Sub-message 2");
contentPanel.add(label3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer7 = new Spacer();
contentPanel.add(spacer7, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final Spacer spacer8 = new Spacer();
contentPanel.add(spacer8, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final Spacer spacer9 = new Spacer();
rootPanel.add(spacer9, new GridConstraints(9, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(11, 66), null, 0, false));
final JLabel label4 = new JLabel();
Font label4Font = this.$$$getFont$$$(null, -1, 16, label4.getFont());
if (label4Font != null) label4.setFont(label4Font);
label4.setText("This is footer");
rootPanel.add(label4, new GridConstraints(10, 1, 1, 7, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 64), null, 0, false));
playerMenu = new JPanel();
playerMenu.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(playerMenu, new GridConstraints(1, 4, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(80, -1), null, 0, false));
final JLabel label5 = new JLabel();
Font label5Font = this.$$$getFont$$$(null, -1, 14, label5.getFont());
if (label5Font != null) label5.setFont(label5Font);
label5.setText("Player");
playerMenu.add(label5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
itemMenu = new JPanel();
itemMenu.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(itemMenu, new GridConstraints(1, 5, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(80, -1), null, 0, false));
final JLabel label6 = new JLabel();
Font label6Font = this.$$$getFont$$$(null, -1, 14, label6.getFont());
if (label6Font != null) label6.setFont(label6Font);
label6.setText("Item");
itemMenu.add(label6, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
adminMenu = new JPanel();
adminMenu.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(adminMenu, new GridConstraints(1, 6, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(80, -1), null, 0, false));
final JLabel label7 = new JLabel();
Font label7Font = this.$$$getFont$$$(null, -1, 14, label7.getFont());
if (label7Font != null) label7.setFont(label7Font);
label7.setText("<PlayerName>");
adminMenu.add(label7, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
logoutMenu = new JPanel();
logoutMenu.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(logoutMenu, new GridConstraints(1, 7, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(80, -1), null, 0, false));
final JLabel label8 = new JLabel();
Font label8Font = this.$$$getFont$$$(null, -1, 14, label8.getFont());
if (label8Font != null) label8.setFont(label8Font);
label8.setText("Logout");
logoutMenu.add(label8, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
homeMenu = new JPanel();
homeMenu.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPanel.add(homeMenu, new GridConstraints(1, 2, 6, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label9 = new JLabel();
Font label9Font = this.$$$getFont$$$(null, -1, 14, label9.getFont());
if (label9Font != null) label9.setFont(label9Font);
label9.setText("War Tanks");
homeMenu.add(label9, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
if (currentFont == null) return null;
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return rootPanel;
}
private void createUIComponents() {
// TODO: place custom component creation code here
imagePanel1 = new ImagePanel();
imagePanel1.setImageSize(64, 64);
imagePanel1.setImage(image);
}
}
|
3e0b8f8c194f22bd9a53d18b4d6036d373fb1ba3 | 340 | java | Java | monolith-complex/monolith-complex-rocketmq/src/main/java/com/mochen/rocketmq/RocketMqStarterApplication.java | yaoguangju/springboot | eaaa3cd458fdb35d9f5c96a3d4545ac5f63e2fa9 | [
"Apache-2.0"
] | null | null | null | monolith-complex/monolith-complex-rocketmq/src/main/java/com/mochen/rocketmq/RocketMqStarterApplication.java | yaoguangju/springboot | eaaa3cd458fdb35d9f5c96a3d4545ac5f63e2fa9 | [
"Apache-2.0"
] | null | null | null | monolith-complex/monolith-complex-rocketmq/src/main/java/com/mochen/rocketmq/RocketMqStarterApplication.java | yaoguangju/springboot | eaaa3cd458fdb35d9f5c96a3d4545ac5f63e2fa9 | [
"Apache-2.0"
] | null | null | null | 28.333333 | 70 | 0.805882 | 4,883 | package com.mochen.rocketmq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RocketMqStarterApplication {
public static void main(String[] args) {
SpringApplication.run(RocketMqStarterApplication.class, args);
}
}
|
3e0b8fbffd8e122a97f10ba2e7cdc8a7e911ab93 | 1,797 | java | Java | src/main/java/Main.java | mrojaczy/splay_tree | a8812e401249c704625b9447c03a72d42f80f823 | [
"MIT"
] | null | null | null | src/main/java/Main.java | mrojaczy/splay_tree | a8812e401249c704625b9447c03a72d42f80f823 | [
"MIT"
] | null | null | null | src/main/java/Main.java | mrojaczy/splay_tree | a8812e401249c704625b9447c03a72d42f80f823 | [
"MIT"
] | null | null | null | 32.089286 | 105 | 0.567056 | 4,884 | import java.text.MessageFormat;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static final Integer MAX = 10;
public static final Random RANDOM = new Random(System.currentTimeMillis());
public static final List<Integer> RANDOM_ELEMENTS = getRandomElements();
public static void main(String[] args) {
Splay splay = new Splay();
Long timeBeforeInsertion = System.currentTimeMillis();
for (int i = 0; i < MAX; i++) {
System.out.println("=================");
splay.insert(RANDOM_ELEMENTS.get(i));
System.out.println(RANDOM_ELEMENTS.get(i));
System.out.println();
splay.printTree();
System.out.println("=================");
System.out.println();
System.out.println();
System.out.println();
}
Long timeAfterInsertion = System.currentTimeMillis();
Long elapsedTime = timeAfterInsertion - timeBeforeInsertion;
System.out.println(MessageFormat.format("{0} sec(s)", elapsedTime));
System.out.println("=================");
for (var node : splay) {
System.out.println(node);
}
System.out.println("=================");
// System.out.println("=================");
// var iterator = splay.iterator();
// while (iterator.hasNext()) {
// Integer node = iterator.next();
// System.out.println(node);
// }
// System.out.println("=================");
}
public static List<Integer> getRandomElements() {
return IntStream.range(0, MAX).mapToObj(i -> RANDOM.nextInt(10000)).collect(Collectors.toList());
}
}
|
3e0b9039e571ec2090afb297532221f64bbf5e0a | 597 | java | Java | src/ai/state/AIState.java | Zypherous/SoloGameCMP428F21 | c18e8221c59fc5a322d09426cbdea32554f0df10 | [
"MIT"
] | null | null | null | src/ai/state/AIState.java | Zypherous/SoloGameCMP428F21 | c18e8221c59fc5a322d09426cbdea32554f0df10 | [
"MIT"
] | null | null | null | src/ai/state/AIState.java | Zypherous/SoloGameCMP428F21 | c18e8221c59fc5a322d09426cbdea32554f0df10 | [
"MIT"
] | null | null | null | 22.961538 | 72 | 0.723618 | 4,885 | package ai.state;
import ai.AITransition;
import entity.NPC;
import state.State;
public abstract class AIState {
private AITransition transition;
public AIState() {
this.transition = initializeTransition();
}
protected abstract AITransition initializeTransition();
public abstract void update(State state, NPC currentCharacter);
public boolean shouldTransition(State state, NPC currentCharacter) {
return transition.shouldTransition(state, currentCharacter);
}
public String getNextState() {
return transition.getNextState();
}
}
|
3e0b90e45ba1c7b4b5f48e7ac6bb85489e61ca42 | 4,266 | java | Java | pepper-apis/src/test/java/org/broadinstitute/ddp/db/dao/JdbiInstitutionTest.java | ogii-test/ddp-study-server | fc24b081fbc0abb2fa37f11688903150e7a2c002 | [
"BSD-3-Clause"
] | 7 | 2019-12-12T20:17:25.000Z | 2021-12-10T13:28:27.000Z | pepper-apis/src/test/java/org/broadinstitute/ddp/db/dao/JdbiInstitutionTest.java | ogii-test/ddp-study-server | fc24b081fbc0abb2fa37f11688903150e7a2c002 | [
"BSD-3-Clause"
] | 397 | 2019-12-12T20:15:20.000Z | 2022-03-31T20:18:19.000Z | pepper-apis/src/test/java/org/broadinstitute/ddp/db/dao/JdbiInstitutionTest.java | ogii-test/ddp-study-server | fc24b081fbc0abb2fa37f11688903150e7a2c002 | [
"BSD-3-Clause"
] | 4 | 2021-04-19T18:43:57.000Z | 2022-02-01T18:30:27.000Z | 34.403226 | 93 | 0.675809 | 4,886 | package org.broadinstitute.ddp.db.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.List;
import java.util.Optional;
import org.broadinstitute.ddp.TxnAwareBaseTest;
import org.broadinstitute.ddp.db.TransactionWrapper;
import org.broadinstitute.ddp.db.dto.InstitutionDto;
import org.broadinstitute.ddp.db.dto.InstitutionSuggestionDto;
import org.broadinstitute.ddp.model.activity.types.InstitutionType;
import org.jdbi.v3.core.Handle;
import org.junit.Test;
public class JdbiInstitutionTest extends TxnAwareBaseTest {
private long cityId;
private long institutionId;
private long institutionAliasId;
private long insertTestInstitution(Handle handle) {
return handle.attach(JdbiInstitution.class).insert(
new InstitutionDto(
TestInstitutionData.GUID,
cityId,
TestInstitutionData.NAME
)
);
}
private long insertTestInstitutionAlias(Handle handle) {
return handle.attach(JdbiInstitution.class).insertAlias(
institutionId,
TestInstitutionData.ALIAS
);
}
private long insertTestCity(Handle handle) {
return handle.attach(JdbiCity.class).insert(
TestInstitutionData.STATE,
TestInstitutionData.CITY
);
}
private void insertTestData(Handle handle) {
cityId = insertTestCity(handle);
institutionId = insertTestInstitution(handle);
institutionAliasId = insertTestInstitutionAlias(handle);
}
private void deleteTestData(Handle handle) {
deleteTestInstitutionAlias(handle);
deleteTestInstitution(handle);
deleteTestCity(handle);
}
private void deleteTestInstitutionAlias(Handle handle) {
handle.attach(JdbiInstitution.class).deleteAlias(institutionId, institutionAliasId);
}
private void deleteTestInstitution(Handle handle) {
handle.attach(JdbiInstitution.class).deleteByGuid(TestInstitutionData.GUID);
}
private void deleteTestCity(Handle handle) {
handle.attach(JdbiCity.class).deleteById(cityId);
}
private Long getTestInstitutionTypeIdByCode(Handle handle, InstitutionType type) {
return handle.attach(JdbiInstitutionType.class).getIdByType(type).get();
}
private Optional<InstitutionDto> getTestInstitution(Handle handle) {
return handle.attach(JdbiInstitution.class).getByGuid(TestInstitutionData.GUID);
}
@Test
public void testInsert() {
TransactionWrapper.useTxn(handle -> {
insertTestData(handle);
assertFalse(institutionId == 0);
assertFalse(institutionAliasId == 0);
deleteTestData(handle);
});
}
@Test
public void testGetSuggestions() {
TransactionWrapper.useTxn(handle -> {
insertTestData(handle);
List<InstitutionSuggestionDto> suggestions = handle.attach(JdbiInstitution.class)
.getSuggestionsByNamePattern("%Hea%");
InstitutionSuggestionDto suggestion = suggestions.get(0);
assertEquals(suggestion.getName(), TestInstitutionData.NAME);
assertEquals(suggestion.getCity(), TestInstitutionData.CITY);
assertEquals(suggestion.getState(), TestInstitutionData.STATE);
deleteTestData(handle);
});
}
@Test
public void testDeleteByGuid() {
TransactionWrapper.useTxn(handle -> {
insertTestData(handle);
deleteTestData(handle);
Optional<InstitutionDto> inst = getTestInstitution(handle);
assertFalse(inst.isPresent());
});
}
private static final class TestInstitutionData {
public static final String GUID = "FEFE0BB8080";
public static final long CITY_ID = 1;
public static final String CITY = "Los Angeles";
public static final String STATE = "California";
public static final String NAME = "Sacred Heart Hospital";
public static final InstitutionType INSTITUTION_TYPE = InstitutionType.INSTITUTION;
public static final String ALIAS = "SHH";
}
}
|
3e0b92a9bdfd6d7cea704b20b51ebb14009ecf8d | 2,652 | java | Java | src/main/java/com/bynder/sdk/query/MediaModifyQuery.java | Bynder/bynder-java-sdk | b8095e67386e3d5ac1e5d0637b9dffc90e519cb6 | [
"MIT"
] | 3 | 2017-04-25T16:12:16.000Z | 2020-11-14T03:32:36.000Z | src/main/java/com/bynder/sdk/query/MediaModifyQuery.java | Bynder/bynder-java-sdk | b8095e67386e3d5ac1e5d0637b9dffc90e519cb6 | [
"MIT"
] | 55 | 2017-07-11T20:07:33.000Z | 2022-02-21T08:49:44.000Z | src/main/java/com/bynder/sdk/query/MediaModifyQuery.java | Bynder/bynder-java-sdk | b8095e67386e3d5ac1e5d0637b9dffc90e519cb6 | [
"MIT"
] | 22 | 2017-04-27T14:41:54.000Z | 2021-02-08T03:03:31.000Z | 23.891892 | 91 | 0.66365 | 4,887 | /*
* Copyright (c) 2017 Bynder B.V. All rights reserved.
*
* Licensed under the MIT License. See LICENSE file in the project root for full license
* information.
*/
package com.bynder.sdk.query;
import com.bynder.sdk.query.decoder.ApiField;
import com.bynder.sdk.query.decoder.MetapropertyAttributesDecoder;
import java.util.ArrayList;
import java.util.List;
/**
* Query to specify the media metadata to be modified.
*/
public class MediaModifyQuery {
/**
* Id of the media for which we want to modify its metadata.
*/
@ApiField(name = "id")
private final String mediaId;
/**
* Name new value.
*/
@ApiField
private String name;
/**
* Description new value.
*/
@ApiField
private String description;
/**
* Copyright new value.
*/
@ApiField
private String copyright;
/**
* Archive new status.
*/
@ApiField
private Boolean archive;
/**
* Date published new value.
*/
@ApiField
private String datePublished;
/**
* Dictionary with (metaproperty) options to set on the asset.
*/
@ApiField(name = "metaproperty", decoder = MetapropertyAttributesDecoder.class)
private List<MetapropertyAttribute> metaproperties;
public MediaModifyQuery(final String mediaId) {
this.mediaId = mediaId;
this.metaproperties = new ArrayList<>();
}
public MediaModifyQuery setName(final String name) {
this.name = name;
return this;
}
public MediaModifyQuery setDescription(final String description) {
this.description = description;
return this;
}
public MediaModifyQuery setCopyright(final String copyright) {
this.copyright = copyright;
return this;
}
public MediaModifyQuery setArchive(final Boolean archive) {
this.archive = archive;
return this;
}
public MediaModifyQuery setDatePublished(final String datePublished) {
this.datePublished = datePublished;
return this;
}
public MediaModifyQuery setMetaproperties(List<MetapropertyAttribute> metaproperties) {
this.metaproperties = metaproperties;
return this;
}
/**
* @deprecated use {@link #addMetaproperty(MetapropertyAttribute)} instead.
*/
@Deprecated
public MediaModifyQuery setMetaproperty(final MetapropertyAttribute metaproperty) {
return addMetaproperty(metaproperty);
}
public MediaModifyQuery addMetaproperty(final MetapropertyAttribute metaproperty) {
this.metaproperties.add(metaproperty);
return this;
}
}
|
3e0b92f3f7712301cd885eb967c2f20f6cf6d3a0 | 1,129 | java | Java | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v4/credential/CredentialListAction.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | null | null | null | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v4/credential/CredentialListAction.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | null | null | null | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v4/credential/CredentialListAction.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | null | null | null | 43.423077 | 141 | 0.759079 | 4,888 | package com.sequenceiq.it.cloudbreak.action.v4.credential;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sequenceiq.it.cloudbreak.CloudbreakClient;
import com.sequenceiq.it.cloudbreak.action.Action;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.credential.CredentialTestDto;
public class CredentialListAction implements Action<CredentialTestDto, CloudbreakClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(CredentialListAction.class);
@Override
public CredentialTestDto action(TestContext testContext, CredentialTestDto testDto, CloudbreakClient cloudbreakClient) throws Exception {
// Collection<CredentialV4Response> responses = cloudbreakClient.getCloudbreakClient()
// .credentialV4Endpoint()
// .list(cloudbreakClient.getWorkspaceId())
// .getResponses();
// testDto.setResponses(responses.stream().collect(Collectors.toSet()));
// Log.logJSON(LOGGER, " Credential listed successfully:\n", testDto.getResponses());
return testDto;
}
}
|
3e0b9333ab255c94faf162cf3233590f8a0a8109 | 2,750 | java | Java | src/pixLab/classes/PictureTester.java | SAarronB/SamplePhotoShopProject | 020b51fae480d6f632b2430c779701d0b8c2c47d | [
"MIT"
] | null | null | null | src/pixLab/classes/PictureTester.java | SAarronB/SamplePhotoShopProject | 020b51fae480d6f632b2430c779701d0b8c2c47d | [
"MIT"
] | null | null | null | src/pixLab/classes/PictureTester.java | SAarronB/SamplePhotoShopProject | 020b51fae480d6f632b2430c779701d0b8c2c47d | [
"MIT"
] | null | null | null | 24.336283 | 59 | 0.648727 | 4,889 | package pixLab.classes;
/**
* This class contains class (static) methods
* that will help you test the Picture class
* methods. Uncomment the methods and the code
* in the main to test.
*
* @author Barbara Ericson
*/
public class PictureTester
{
/** Method to test zeroBlue */
public static void testZeroBlue()
{
Picture beach = new Picture("RainbowSix.jpg");
beach.explore();
beach.zeroBlue();
beach.explore();
}
public static void testMirrorGull() {
Picture gull = new Picture("RainbowSix.jpg");
gull.explore();
gull.mirrorTemple();
gull.explore();
}
public static void testZeroRed() {
Picture beach = new Picture("RainbowSix.jpg");
beach.explore();
beach.zeroRed();
beach.explore();
}
/** Method to test mirrorVertical */
public static void testMirrorVertical()
{
Picture caterpillar = new Picture("caterpillar.jpg");
caterpillar.explore();
caterpillar.mirrorVertical();
caterpillar.explore();
}
/** Method to test mirrorTemple */
public static void testMirrorTemple()
{
Picture temple = new Picture("temple.jpg");
temple.explore();
temple.mirrorTemple();
temple.explore();
}
/** Method to test the collage method */
public static void testCollage()
{
Picture canvas = new Picture("640x480.jpg");
canvas.createCollage();
canvas.explore();
}
/** Method to test edgeDetection */
public static void testEdgeDetection()
{
Picture swan = new Picture("swan.jpg");
swan.edgeDetection(10);
swan.explore();
}
public static void testSteganography() {
Picture source = new Picture("Sneaky.jpg");
Picture message = new Picture("NicolBolas.jpg");
source.explore();
message.explore();
source.hidePicture(message);
source.explore();
source.revealPicture();
source.explore();
}
/** Main method for testing. Every class can have a main
* method in Java */
public static void main(String[] args)
{
testSteganography();
//testMirrorGull();
// uncomment a call here to run a test
// and comment out the ones you don't want
// to run
//testZeroBlue();
//testKeepOnlyBlue();
//testKeepOnlyRed();
//testKeepOnlyGreen();
//testNegate();
//testGrayscale();
//testFixUnderwater();
//testMirrorVertical();
//testMirrorTemple();
//testMirrorArms();
//testMirrorGull();
//testMirrorDiagonal();
//testCollage();
//testCopy();
//testEdgeDetection();
//testEdgeDetection2();
//testChromakey();
//testEncodeAndDecode();
//testGetCountRedOverValue(250);
//testSetRedToHalfValueInTopHalf();
//testClearBlueOverValue(200);
//testGetAverageForColumn(0);
}
} |
3e0b940114e444f3ee824e3f4c6892332bfd07fd | 14,373 | java | Java | java/src/org/apache/qetest/xalanj2/LoggingTransformState.java | plutext/xalan-test | c529abdf9ee18deefda6f6571b66a3e988728c15 | [
"Apache-2.0"
] | 1 | 2019-05-21T17:43:30.000Z | 2019-05-21T17:43:30.000Z | java/src/org/apache/qetest/xalanj2/LoggingTransformState.java | plutext/xalan-test | c529abdf9ee18deefda6f6571b66a3e988728c15 | [
"Apache-2.0"
] | null | null | null | java/src/org/apache/qetest/xalanj2/LoggingTransformState.java | plutext/xalan-test | c529abdf9ee18deefda6f6571b66a3e988728c15 | [
"Apache-2.0"
] | 2 | 2019-05-21T17:43:19.000Z | 2021-11-04T11:46:53.000Z | 30.08159 | 108 | 0.602406 | 4,890 | /*
* 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.
*/
/*
* $Id$
*/
/*
*
* LoggingTransformState.java
*
*/
package org.apache.qetest.xalanj2;
import java.lang.reflect.Method;
import org.apache.qetest.Logger;
import org.apache.qetest.LoggingHandler;
import org.apache.xalan.templates.ElemLiteralResult;
import org.apache.xalan.templates.ElemTemplateElement;
import org.apache.xalan.transformer.TransformState;
import org.apache.xalan.transformer.TransformerClient;
import org.apache.xpath.XPath;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
/**
* Cheap-o ContentHandler that logs info about TransformState interface.
* <p>Implements ContentHandler and dumps simplistic info
* everything to a Logger; a way to debug TransformState.</p>
* <p>This class could use improvement, but currently serves both
* as a 'layer' for a ContentHandler (i.e. you can stick
* setDefaultHandler in which we'll call for you, thus actually
* getting output from your transform) as well as a logging
* service for the TransformState interface. We dump to our
* Logger various interesting info from the TransformState
* object during each of our startElement(), endElement(), and
* characters() calls about both the source node being processed
* and about the xsl: element doing the processing.
* @author envkt@example.com
* @version $Id$
*/
public class LoggingTransformState extends LoggingHandler
implements ContentHandler, TransformerClient
{
/** No-op sets logger to default. */
public LoggingTransformState()
{
setLogger(getDefaultLogger());
}
/**
* Ctor that calls setLogger automatically.
*
* @param r Logger we should log to
*/
public LoggingTransformState(Logger l)
{
setLogger(l);
}
/**
* A TransformState object that we use to log state data.
* This is the equivalent of the defaultHandler, even though
* that's not really the right metaphor. This class could be
* upgraded to have both a default ContentHandler and a
* defaultTransformerClient in the future.
*/
protected TransformState transformState = null;
/**
* Implement TransformerClient.setTransformState interface.
* Pass in a reference to a TransformState object, which
* can be used during SAX ContentHandler events to obtain
* information about he state of the transformation. This
* method will be called before each startDocument event.
*
* @param ts A reference to a TransformState object
*/
public void setTransformState(TransformState ts)
{
transformState = ts;
}
/**
* Accessor method for our TransformState object.
*
* @param TransformState object we are using
*/
public TransformState getTransformState()
{
return transformState;
}
/**
* Our default handler that we pass all events through to.
*/
protected ContentHandler defaultHandler = null;
/**
* Set a default handler for us to wrapper.
* Set a ContentHandler for us to use.
*
* @param default Object of the correct type to pass-through to;
* throws IllegalArgumentException if null or incorrect type
*/
public void setDefaultHandler(Object defaultC)
{
try
{
defaultHandler = (ContentHandler)defaultC;
}
catch (Throwable t)
{
throw new java.lang.IllegalArgumentException("setDefaultHandler illegal type: " + t.toString());
}
}
/**
* Accessor method for our default handler.
*
* @return default (Object) our default handler; null if unset
*/
public Object getDefaultHandler()
{
return (Object)defaultHandler;
}
/** Prefixed to all logger msg output for ContentHandler. */
public final String prefix = "LTS:";
/** Prefixed to all logger msg output for TransformState. */
public final String prefix2 = "LTS2:";
/** Cheap-o string representation of last event we got. */
protected String lastItem = NOTHING_HANDLED;
/**
* Cheap-o Verbosity flag: should we log all ContentHandler
* messages or not.
* //@todo should have accessors and be integrated better
*/
public boolean verbose = false;
/**
* Accessor for string representation of last event we got.
* @param s string to set
*/
protected void setLastItem(String s)
{
lastItem = s;
}
/**
* Accessor for string representation of last event we got.
* @return last event string we had
*/
public String getLast()
{
return lastItem;
}
/** setExpected, etc. not yet implemented. */
/** How many characters to report from characters event. */
private int charLimit = 30;
/**
* How many characters to report from characters event.
* @param l charLimit for us to use
*/
public void setCharLimit(int l)
{
charLimit = l;
}
/**
* How many characters to report from characters event.
* @return charLimit we use
*/
public int getCharLimit()
{
return charLimit;
}
////////////////// Utility methods for TransformState //////////////////
/**
* Utility method to gather data about current node.
* @return String describing node
*/
protected String getCurrentNodeInfo(TransformState ts, String x)
{
StringBuffer buf = new StringBuffer();
Node n = ts.getCurrentNode();
if(null != n)
{
buf.append(n.getNodeName());
if(Node.TEXT_NODE == n.getNodeType())
{
buf.append("[");
buf.append(n.getNodeValue());
buf.append("]");
}
}
else
buf.append("[NULL-NODE]");
if (null != x)
buf.append("[" + x + "]");
return buf.toString();
}
/**
* Utility method to gather data about current element in xsl.
* @return String describing element
*/
protected String getCurrentElementInfo(TransformState ts)
{
StringBuffer buf = new StringBuffer();
ElemTemplateElement templ = ts.getCurrentElement();
if(null != templ)
{
// Note for user if it's an LRE or an xsl element
if(templ instanceof ElemLiteralResult)
buf.append("LRE:");
else
buf.append("xsl:");
buf.append(templ.getNodeName());
buf.append(", line# "+templ.getLineNumber());
buf.append(", col# "+templ.getColumnNumber());
try
{
Class cl = ((Object)templ).getClass();
Method getSelect = cl.getMethod("getSelect", null);
if(null != getSelect)
{
buf.append(", select='");
XPath xpath = (XPath)getSelect.invoke(templ, null);
buf.append(xpath.getPatternString()+"'");
}
}
catch(java.lang.reflect.InvocationTargetException ite)
{
// no-op: just don't put in the select info for these items
// buf.append("(threw: InvocationTargetException)");
}
catch(IllegalAccessException iae)
{
// no-op
}
catch(NoSuchMethodException nsme)
{
// no-op
}
}
else
buf.append("[NULL-ELEMENT]");
return buf.toString();
}
////////////////// Implement ContentHandler //////////////////
protected Locator ourLocator = null;
/** Implement ContentHandler.setDocumentLocator. */
public void setDocumentLocator (Locator locator)
{
// Note: this implies this class is !not! threadsafe
setLastItem("setDocumentLocator");
ourLocator = locator; // future use
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.setDocumentLocator(locator);
}
/** Implement ContentHandler.startDocument. */
public void startDocument ()
throws SAXException
{
setLastItem("startDocument");
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.startDocument();
}
/** Implement ContentHandler.endDocument. */
public void endDocument()
throws SAXException
{
setLastItem("endDocument");
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.endDocument();
}
/** Implement ContentHandler.startPrefixMapping. */
public void startPrefixMapping (String prefix, String uri)
throws SAXException
{
setLastItem("startPrefixMapping: " + prefix + ", " + uri);
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.startPrefixMapping(prefix, uri);
}
/** Implement ContentHandler.endPrefixMapping. */
public void endPrefixMapping (String prefix)
throws SAXException
{
setLastItem("endPrefixMapping: " + prefix);
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.endPrefixMapping(prefix);
}
/** Implement ContentHandler.startElement. */
public void startElement (String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException
{
final String START_ELEMENT = "startElement: ";
StringBuffer buf = new StringBuffer();
buf.append(namespaceURI + ", "
+ namespaceURI + ", " + qName);
int n = atts.getLength();
for(int i = 0; i < n; i++)
{
buf.append(", " + atts.getQName(i));
}
setLastItem(START_ELEMENT + buf.toString());
if (verbose)
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.startElement(namespaceURI, localName, qName, atts);
// Also handle TransformerState
if(null != transformState)
{
logger.logMsg(level, prefix2 + START_ELEMENT
+ getCurrentElementInfo(transformState) + " is processing: "
+ getCurrentNodeInfo(transformState, buf.toString()));
}
}
/** Implement ContentHandler.endElement. */
public void endElement (String namespaceURI, String localName, String qName)
throws SAXException
{
final String END_ELEMENT = "endElement: ";
setLastItem(END_ELEMENT + namespaceURI + ", " + namespaceURI + ", " + qName);
if (verbose)
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.endElement(namespaceURI, localName, qName);
// Also handle TransformerState
if(null != transformState)
{
logger.logMsg(level, prefix2 + END_ELEMENT
+ getCurrentElementInfo(transformState) + " is processing: "
+ getCurrentNodeInfo(transformState, null));
}
}
/** Implement ContentHandler.characters. */
public void characters (char ch[], int start, int length)
throws SAXException
{
final String CHARACTERS = "characters: ";
String s = new String(ch, start, (length > charLimit) ? charLimit : length);
String tmp = null;
if(length > charLimit)
tmp = "\"" + s + "\"...";
else
tmp = "\"" + s + "\"";
setLastItem(CHARACTERS + tmp);
if (verbose)
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.characters(ch, start, length);
// Also handle TransformerState
if(null != transformState)
{
logger.logMsg(level, prefix2 + CHARACTERS
+ getCurrentElementInfo(transformState) + " is processing: "
+ getCurrentNodeInfo(transformState, tmp));
}
}
/** Implement ContentHandler.ignorableWhitespace. */
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException
{
setLastItem("ignorableWhitespace: len " + length);
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.ignorableWhitespace(ch, start, length);
}
/** Implement ContentHandler.processingInstruction. */
public void processingInstruction (String target, String data)
throws SAXException
{
setLastItem("processingInstruction: " + target + ", " + data);
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.processingInstruction(target, data);
}
/** Implement ContentHandler.skippedEntity. */
public void skippedEntity (String name)
throws SAXException
{
setLastItem("skippedEntity: " + name);
logger.logMsg(level, prefix + getLast());
if (null != defaultHandler)
defaultHandler.skippedEntity(name);
}
}
|
3e0b94b6f9a5d3e4d0de951061e1fd007052f0a1 | 1,052 | java | Java | WebBookmark/src/java/com/sam/servlet/DelBookMarkServlet.java | wang6642080/BookMark-JSP | 61bbaa8710654317ef286ab21d4d98608cf870c2 | [
"Apache-2.0"
] | null | null | null | WebBookmark/src/java/com/sam/servlet/DelBookMarkServlet.java | wang6642080/BookMark-JSP | 61bbaa8710654317ef286ab21d4d98608cf870c2 | [
"Apache-2.0"
] | null | null | null | WebBookmark/src/java/com/sam/servlet/DelBookMarkServlet.java | wang6642080/BookMark-JSP | 61bbaa8710654317ef286ab21d4d98608cf870c2 | [
"Apache-2.0"
] | null | null | null | 27.684211 | 84 | 0.677757 | 4,891 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sam.servlet;
import com.sam.dao.ListDao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author sam
*/
public class DelBookMarkServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String bid = request.getParameter("bid");
if(ListDao.delBookMark(bid)){
response.sendRedirect("List.do");
} else {
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
|
3e0b955a51c42b2896871acbdb73833a41780c18 | 154 | java | Java | libraries/ulibcomponentax/src/main/java/com/un/componentax/net/OnNetStateChange.java | cyxm/UnlimAndroidUtil | 283a152eef6a868f198634214cc73683d27c8924 | [
"BSD-3-Clause"
] | null | null | null | libraries/ulibcomponentax/src/main/java/com/un/componentax/net/OnNetStateChange.java | cyxm/UnlimAndroidUtil | 283a152eef6a868f198634214cc73683d27c8924 | [
"BSD-3-Clause"
] | null | null | null | libraries/ulibcomponentax/src/main/java/com/un/componentax/net/OnNetStateChange.java | cyxm/UnlimAndroidUtil | 283a152eef6a868f198634214cc73683d27c8924 | [
"BSD-3-Clause"
] | null | null | null | 15.4 | 35 | 0.779221 | 4,892 | package com.un.componentax.net;
public interface OnNetStateChange {
void onAvailable();
void onCellularAvailable();
void onCellularUnavailable();
}
|
3e0b95b7d8fbd4c0ae8a5cabc631b46d84fb5524 | 2,258 | java | Java | selfunction/src/main/java/com/example/selfunction/utils/Utils.java | wanghuaixin1201/LinkagePicker | b13af92a3a19925c6a1e0557bf032bca225400f7 | [
"Apache-2.0"
] | null | null | null | selfunction/src/main/java/com/example/selfunction/utils/Utils.java | wanghuaixin1201/LinkagePicker | b13af92a3a19925c6a1e0557bf032bca225400f7 | [
"Apache-2.0"
] | null | null | null | selfunction/src/main/java/com/example/selfunction/utils/Utils.java | wanghuaixin1201/LinkagePicker | b13af92a3a19925c6a1e0557bf032bca225400f7 | [
"Apache-2.0"
] | null | null | null | 31.802817 | 84 | 0.681134 | 4,893 | package com.example.selfunction.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
/**
* Created by ZQiong on 2018/3/22.
*/
public final class Utils {
private Utils() throws InstantiationException {
throw new InstantiationException("This class is not for instantiation");
}
public static String toBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static Bitmap toBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap decodeResource(Context context, int resId) {
return BitmapFactory.decodeResource(context.getResources(), resId);
}
public static long getCurrentTime() {
return System.currentTimeMillis();
}
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
}
|
3e0b964205ced1b4b0a0dbb0722ad947c9af9ecd | 224 | java | Java | abstractfactory/Duck.java | ioneone/design-pattern | f4496496b21a5e13ea5ab539dd37344104985731 | [
"MIT"
] | null | null | null | abstractfactory/Duck.java | ioneone/design-pattern | f4496496b21a5e13ea5ab539dd37344104985731 | [
"MIT"
] | null | null | null | abstractfactory/Duck.java | ioneone/design-pattern | f4496496b21a5e13ea5ab539dd37344104985731 | [
"MIT"
] | null | null | null | 14.933333 | 37 | 0.59375 | 4,894 | package abstractfactory;
public class Duck implements Animal {
@Override
public String getAnimal() {
return "Duck";
}
@Override
public String makeSound() {
return "Squeks";
}
}
|
3e0b968de82c8a2b2c91d38665787be6a04a17b1 | 1,018 | java | Java | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/IntFieldConverter.java | YuanWenqing/protoframework | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"MIT"
] | 1 | 2021-03-12T09:15:12.000Z | 2021-03-12T09:15:12.000Z | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/IntFieldConverter.java | YuanWenqing/protoframework | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"MIT"
] | 14 | 2019-07-20T09:20:54.000Z | 2020-08-17T01:52:28.000Z | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/IntFieldConverter.java | YuanWenqing/protobuf4j | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"Apache-2.0"
] | null | null | null | 29.085714 | 92 | 0.749509 | 4,895 | package protobuf4j.orm.converter;
import com.google.protobuf.Descriptors;
public class IntFieldConverter implements IFieldConverter {
@Override
public boolean supports(Descriptors.FieldDescriptor fieldDescriptor) {
return fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.INT;
}
@Override
public Class<?> getSqlValueType() {
return Integer.class;
}
@Override
public Object toSqlValue(Descriptors.FieldDescriptor fieldDescriptor, Object fieldValue) {
if (fieldValue instanceof Integer) {
return fieldValue;
}
throw new FieldConversionException(Descriptors.FieldDescriptor.JavaType.INT, fieldValue,
getSqlValueType());
}
@Override
public Object fromSqlValue(Descriptors.FieldDescriptor fieldDescriptor, Object sqlValue) {
if (sqlValue == null) {
return 0;
} else if (sqlValue instanceof Integer) {
return sqlValue;
}
throw new FieldConversionException(Descriptors.FieldDescriptor.JavaType.INT, sqlValue);
}
}
|
3e0b9753541fc88721ecb307222a48ed339894d8 | 1,428 | java | Java | src/main/java/structuralDesignPatterns/facadeDesignPattern/projectHomeTheaterSystem/Main/Main.java | RawadAlaryan/Design-Patterns | 6879cfddef136f73c1f0d7cf2082f1d3177c341e | [
"MIT"
] | 2 | 2020-11-05T12:50:13.000Z | 2022-02-24T13:16:36.000Z | src/main/java/structuralDesignPatterns/facadeDesignPattern/projectHomeTheaterSystem/Main/Main.java | RawadAlaryan/Design-Patterns | 6879cfddef136f73c1f0d7cf2082f1d3177c341e | [
"MIT"
] | null | null | null | src/main/java/structuralDesignPatterns/facadeDesignPattern/projectHomeTheaterSystem/Main/Main.java | RawadAlaryan/Design-Patterns | 6879cfddef136f73c1f0d7cf2082f1d3177c341e | [
"MIT"
] | 1 | 2022-02-24T13:16:27.000Z | 2022-02-24T13:16:27.000Z | 52.888889 | 119 | 0.719188 | 4,896 | package structuralDesignPatterns.facadeDesignPattern.projectHomeTheaterSystem.Main;
import structuralDesignPatterns.facadeDesignPattern.projectHomeTheaterSystem.Facade.HomeTheaterFacade;
import structuralDesignPatterns.facadeDesignPattern.projectHomeTheaterSystem.Subsystem.*;
//Facade Design Pattern Home Theater System.
//Using a HomeTheater Facade to control a lot of subsystems needed to watch a Movie.
public class Main {
public static void main(String[] args) {
System.out.println("Facade Design Pattern Home Theater System.");
System.out.println("Using a HomeTheater Facade to control a lot of subsystems needed to watch a Movie:\n");
Amplifier amp = new Amplifier("Top-O-Line Amplifier");
Tuner tuner = new Tuner("Top-O-Line AM/FM Tuner", amp);
DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp);
CdPlayer cd = new CdPlayer("Top-O-Line CD Player", amp);
Projector projector = new Projector("Top-O-Line Projector", dvd);
TheaterLights lights = new TheaterLights("Theater Ceiling Lights");
Screen screen = new Screen("Theater Screen");
PopcornPopper popper = new PopcornPopper("Popcorn Popper");
HomeTheaterFacade homeTheater = new HomeTheaterFacade(amp, tuner, dvd, cd, projector, screen, lights, popper);
homeTheater.watchMovie("Inception");
homeTheater.endMovie();
}
}
|
3e0b9792182010dcdac895e9347db4a127f59eba | 2,621 | java | Java | MUDServer/src/mud/commands/GreetCommand.java | jnharton/mud-server | 6d682541c0b4d53bacd4b8aec349edf3d226a3ca | [
"MIT"
] | 32 | 2015-12-13T06:31:31.000Z | 2022-02-01T21:48:17.000Z | MUDServer/src/mud/commands/GreetCommand.java | jnharton/mud-server | 6d682541c0b4d53bacd4b8aec349edf3d226a3ca | [
"MIT"
] | 6 | 2015-03-28T06:35:13.000Z | 2021-03-04T22:00:53.000Z | MUDServer/src/mud/commands/GreetCommand.java | jnharton/mud-server | 6d682541c0b4d53bacd4b8aec349edf3d226a3ca | [
"MIT"
] | 11 | 2018-07-28T18:41:14.000Z | 2022-02-22T02:03:35.000Z | 26.744898 | 105 | 0.619611 | 4,897 | package mud.commands;
import mud.Command;
import mud.Constants;
import mud.net.Client;
import mud.objects.NPC;
import mud.objects.Player;
/*
* Copyright (c) 2012 Jeremy N. Harton
*
* Released under the MIT License:
* LICENSE.txt, http://opensource.org/licenses/MIT
*
* NOTE: license provided with code controls, if any
* changes are made to the one referred to.
*/
public class GreetCommand extends Command {
public GreetCommand() {
super("Greet another player/npc (this tells them your name with some specificity).");
}
@Override
public void execute(final String arg, final Client client) {
// TODO figure out whether we are tryng to greet an NPC and respond accordingly
final Player self = getPlayer(client);
// TODO need to make this locality dependent
final Player player = getPlayer(arg);
final NPC npc = getNPC(arg);
debug("player: " + self.getName());
debug("player1: " + player.getName());
if ( player != null ) {
// TODO this is a poor test indeed
if( player.getClient() == null ) {
send("Game> That player is not logged-in", client);
return;
}
if ( !player.knowsName( self.getName() ) ) {
player.addName( self.getName() );
String msg = "";
// message to you
if ( self.knowsName( player.getName() ) ) {
msg = String.format("You tell %s that your name is %s.", player.getName(), self.getName());
}
else {
msg = String.format("You tell %s that your name is %s.", arg, self.getName());
}
send( msg, client );
// message to other player
send(self.getCName() + " tells you that their name is " + self.getName() + ".", player.getClient());
}
else {
send("You've already greeted that player.", client);
}
}
else if ( npc != null ) {
// TODO exists so NPC can greet you by name only if they know it
if ( !npc.knowsName( self.getName() ) ) {
npc.addName( self.getName() );
String msg = "";
// message to you
if ( self.knowsName( npc.getName() ) ) {
msg = String.format("You tell %s that your name is %s.", npc.getName(), self.getName());
}
else {
msg = String.format("You tell %s that your name is %s.", arg, self.getName());
}
send( msg, client );
// message to NPC?
//send(self.getCName) + " tells you that their name is " + self.getName() + ".", player.getClient());
}
else {
send("You've already greeted that npc?", client);
}
}
else {
send("There is no one by that name here.", client);
}
}
@Override
public int getAccessLevel() {
return Constants.USER;
}
} |
3e0b98267bf52114d8603bbe8f33f79dda70c520 | 1,017 | java | Java | src/com/rc/portal/dao/TPharmacistDAO.java | Marlon992058/111_portal | 55d82445f9b2a9eb41b803cb905a79aa7d4b29bc | [
"Apache-2.0"
] | null | null | null | src/com/rc/portal/dao/TPharmacistDAO.java | Marlon992058/111_portal | 55d82445f9b2a9eb41b803cb905a79aa7d4b29bc | [
"Apache-2.0"
] | null | null | null | src/com/rc/portal/dao/TPharmacistDAO.java | Marlon992058/111_portal | 55d82445f9b2a9eb41b803cb905a79aa7d4b29bc | [
"Apache-2.0"
] | null | null | null | 29.057143 | 101 | 0.812193 | 4,898 | package com.rc.portal.dao;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.TPharmacist;
import com.rc.portal.vo.TPharmacistExample;
public interface TPharmacistDAO {
int countByExample(TPharmacistExample example) throws SQLException;
int deleteByExample(TPharmacistExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(TPharmacist record) throws SQLException;
Long insertSelective(TPharmacist record) throws SQLException;
List selectByExample(TPharmacistExample example) throws SQLException;
TPharmacist selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(TPharmacist record, TPharmacistExample example) throws SQLException;
int updateByExample(TPharmacist record, TPharmacistExample example) throws SQLException;
int updateByPrimaryKeySelective(TPharmacist record) throws SQLException;
int updateByPrimaryKey(TPharmacist record) throws SQLException;
}
|
3e0b9a4f7a8fd35aec939c9b5b8cb13f5a3b8e3b | 5,309 | java | Java | omoponfhir-omopv5-sqlrender/src/main/java/edu/gatech/chai/omopv5/dba/service/TransactionServiceImp.java | JLLeitschuh/GT-FHIR2 | 5afddf4d9fe2dce359903a0a50cd68eb4ac2c26b | [
"Apache-2.0"
] | 20 | 2018-03-14T17:53:39.000Z | 2020-03-02T13:10:04.000Z | omoponfhir-omopv5-sqlrender/src/main/java/edu/gatech/chai/omopv5/dba/service/TransactionServiceImp.java | JLLeitschuh/GT-FHIR2 | 5afddf4d9fe2dce359903a0a50cd68eb4ac2c26b | [
"Apache-2.0"
] | 11 | 2019-11-13T07:29:01.000Z | 2021-12-09T21:01:51.000Z | omoponfhir-omopv5-sqlrender/src/main/java/edu/gatech/chai/omopv5/dba/service/TransactionServiceImp.java | JLLeitschuh/GT-FHIR2 | 5afddf4d9fe2dce359903a0a50cd68eb4ac2c26b | [
"Apache-2.0"
] | 4 | 2018-02-03T01:23:53.000Z | 2020-02-11T06:08:52.000Z | 34.927632 | 103 | 0.683745 | 4,899 | /*******************************************************************************
* Copyright (c) 2019 Georgia Tech Research Institute
*
* 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 edu.gatech.chai.omopv5.dba.service;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import edu.gatech.chai.omopv5.model.entity.BaseEntity;
import edu.gatech.chai.omopv5.model.entity.FPerson;
import edu.gatech.chai.omopv5.model.entity.Measurement;
import edu.gatech.chai.omopv5.model.entity.Observation;
import edu.gatech.chai.omopv5.sqlrender.dao.ConditionOccurrenceDao;
import edu.gatech.chai.omopv5.sqlrender.dao.FPersonDao;
import edu.gatech.chai.omopv5.sqlrender.dao.MeasurementDao;
import edu.gatech.chai.omopv5.sqlrender.dao.ObservationDao;
import edu.gatech.chai.omopv5.sqlrender.dao.ProcedureOccurrenceDao;
@Service
public class TransactionServiceImp implements TransactionService {
// @Autowired
// private TransactionDao transactionDao;
@Autowired
private FPersonDao fPersonDao;
@Autowired
private ConditionOccurrenceDao conditionDao;
@Autowired
private ProcedureOccurrenceDao procedureDao;
@Autowired
private MeasurementDao measurementDao;
@Autowired
private ObservationDao observationDao;
// public TransactionDao getEntityDao() {
// return transactionDao;
// }
@Transactional
public int writeTransaction(Map<String, List<BaseEntity>> transactionMap) {
// EntityManager em = transactionDao.getEntityManager();
System.out.println("At the writeTransaction");
// It's not efficient. But, we need to process patients first. so...
for (String key : transactionMap.keySet()) {
String[] keyInfo = key.split("\\^");
System.out.println("working on patient key=" + key + " with keyInfo length=" + keyInfo.length);
if (keyInfo.length != 2) {
// something is wrong.
return -1;
}
String entityName = keyInfo[1];
if (entityName.equals("FPerson")) {
// process it.
List<BaseEntity> entityClasses = transactionMap.get(key);
if (entityClasses != null) {
// We have patients, process this.
for (BaseEntity entity : entityClasses) {
FPerson fPerson = (FPerson) entity;
System.out.println("Writing fPerson name="+fPerson.getFamilyName()+", "+fPerson.getGivenName1());
fPersonDao.add(fPerson);
}
}
} else {
continue;
}
}
for (String key : transactionMap.keySet()) {
String[] keyInfo = key.split("\\^");
System.out.println("working on key=" + key + " with keyInfo length=" + keyInfo.length);
if (keyInfo.length != 2) {
// something is wrong.
return -1;
}
// 2nd part of keyInfo should be the entity table name.
String entityName = keyInfo[1];
if (entityName.equals("FPerson")) {
// we have alreay done this.
continue;
}
List<BaseEntity> entities = transactionMap.get(key);
if (entities == null) {
System.out.println("null entities for transactionMap.....");
continue;
}
System.out.println("About to process " + entityName + " from Service");
String subjectKey = keyInfo[0]+"^"+"FPerson";
// list of the entity classes
try {
for (BaseEntity entity : entities) {
if (entityName.equals("Measurement")) {
System.out.println("Adding Measurement with subjectKey ("+key+") to OMOP");
// Get patient information from subject key.
FPerson subjectEntity = (FPerson) transactionMap.get(subjectKey).get(0);
if (subjectEntity == null) {
// This is an error. We must have subject.
System.out.println("FPerson info not available for the Measurement");
throw new Exception("FPerson info not available for the Measurement");
}
Measurement measurement = (Measurement) entity;
measurement.setFPerson(subjectEntity);
measurementDao.add(measurement);
} else if (entityName.equals("Observation")) {
System.out.println("Adding Observation to OMOP");
FPerson subjectEntity = (FPerson) transactionMap.get(subjectKey).get(0);
if (subjectEntity == null) {
// This is an error. We must have subject.
System.out.println("FPerson info not available for the Observation");
throw new Exception("FPerson info not available for the Observation");
}
Observation observation = (Observation) entity;
observation.setFPerson(subjectEntity);
observationDao.add(observation);
}
}
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
return 0;
}
} |
3e0b9aed8757f175d035adc6b0253bf38b4d23b7 | 10,288 | java | Java | src/main/java/com/skanders/rms/service/RapidMicroService.java | alexskanders/RapidMicroService | 1bd478aa2ab557adeceb07892996cf5e9c9a7d57 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/skanders/rms/service/RapidMicroService.java | alexskanders/RapidMicroService | 1bd478aa2ab557adeceb07892996cf5e9c9a7d57 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/skanders/rms/service/RapidMicroService.java | alexskanders/RapidMicroService | 1bd478aa2ab557adeceb07892996cf5e9c9a7d57 | [
"Apache-2.0"
] | null | null | null | 33.294498 | 119 | 0.675739 | 4,900 | /*
* Copyright (c) 2020 Alexander Iskander
*
* 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.skanders.rms.service;
import com.skanders.commons.atsql.AtSQL;
import com.skanders.commons.atsql.AtSQLFactory;
import com.skanders.commons.def.LogPattern;
import com.skanders.commons.def.Verify;
import com.skanders.rms.config.RMSConfig;
import com.skanders.rms.def.RMSException;
import org.glassfish.grizzly.GrizzlyFuture;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.ssl.SSLContextConfigurator;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.grizzly.websockets.WebSocketAddOn;
import org.glassfish.grizzly.websockets.WebSocketApplication;
import org.glassfish.grizzly.websockets.WebSocketEngine;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
public abstract class RapidMicroService
{
private static final Logger LOG = LoggerFactory.getLogger(RapidMicroService.class);
private AtSQL atSQL;
private HttpServer server;
/**
* Constructs an instance of RapidMicroService.
*
* @param config a Config instance
* @param resourcePath package names for jersey to find components
* @see RMSConfig
*/
protected RapidMicroService(@Nonnull RMSConfig config, @Nonnull String... resourcePath)
{
Verify.notNull(config, "config cannot be null");
Verify.notNull(resourcePath, "resourcePath cannot be null");
LOG.info(LogPattern.INIT, "RapidMicroService");
if (config.isDbService())
initConnectionPool(config);
RMSResourceConfig rmsResourceConfig = new RMSResourceConfig(resourcePath)
.withRMSSettings(config);
if (config.isSslSecure())
initHTTPSecureServer(config, rmsResourceConfig);
else
initHTTPServer(config, rmsResourceConfig);
LOG.info(LogPattern.INIT_DONE, "RapidMicroService");
}
/**
* Constructs an instance of RapidMicroService.
*
* @param config a RMSConfig instance
* @param resourceConfig a RMSResourceConfig instance
* @see RMSConfig
*/
protected RapidMicroService(@Nonnull RMSConfig config, @Nonnull RMSResourceConfig resourceConfig)
{
Verify.notNull(config, "config cannot be null");
Verify.notNull(resourceConfig, "resourceConfig cannot be null");
LOG.info(LogPattern.INIT, "RapidMicroService");
if (config.isDbService())
initConnectionPool(config);
RMSResourceConfig rmsResourceConfig = resourceConfig.withRMSSettings(config);
if (config.isSslSecure())
initHTTPSecureServer(config, rmsResourceConfig);
else
initHTTPServer(config, rmsResourceConfig);
LOG.info(LogPattern.INIT_DONE, "RapidMicroService");
}
/**
* Registers {@link WebSocketApplication} with the server at the given
* contextPath and urlLogPattern
*
* @param contextPath the context path for the WebSocket
* @param urlPattern the url pattern for the WebSocket
* @param app an instance of WebSocketApplication
* @see WebSocketApplication
*/
public void registerWebSocket(
@Nonnull String contextPath, @Nonnull String urlPattern, @Nonnull WebSocketApplication app)
{
Verify.notTrue(server.isStarted(), "cannot add WebSocket after server has started!");
Verify.notNull(contextPath, "config cannot be null");
Verify.notNull(urlPattern, "urlLogPattern cannot be null");
Verify.notNull(app, "app cannot be null");
LOG.info(LogPattern.INIT, "WebSocket Attachment");
WebSocketAddOn webSocketAddOn = new WebSocketAddOn();
for (NetworkListener networkListener : server.getListeners())
networkListener.registerAddOn(webSocketAddOn);
WebSocketEngine.getEngine().register(contextPath, urlPattern, app);
LOG.info(LogPattern.INIT_DONE, "WebSocket Attachment");
}
/**
* Starts the server.
*/
public void start()
{
LOG.trace(LogPattern.ENTER, "Grizzly Server Start");
try {
server.start();
} catch (IOException e) {
LOG.error(LogPattern.EXIT_FAIL, "Grizzly Server Start", e.getClass(), e.getMessage());
throw new RMSException("Server failed to start: IOException");
}
}
/**
* Shutdown server by calling {@link HttpServer#shutdown()}
*
* @return an instance of GrizzlyFuture
*/
public GrizzlyFuture<HttpServer> shutdown()
{
LOG.trace(LogPattern.ENTER, "Grizzly Server Shutdown");
return server.shutdown();
}
/**
* Shutdown server by calling {@link HttpServer#shutdown(long, TimeUnit)}
*
* @param gracePeriod grace period to pass to HttpServer's shutdown
* function
* @param timeUnit time unit to pass to HttpServer's shutdown function
* @return an instance of GrizzlyFuture
*/
public GrizzlyFuture<HttpServer> shutdown(long gracePeriod, TimeUnit timeUnit)
{
LOG.trace(LogPattern.ENTER, "Grizzly Server Shutdown");
return server.shutdown(gracePeriod, timeUnit);
}
/**
* Shutdown server by calling {@link HttpServer#shutdownNow()}
*/
public void shutdownNow()
{
LOG.trace(LogPattern.ENTER, "Grizzly Server Shutdown");
server.shutdown();
}
/**
* Initializes the connection pool stored within the MicroService.
* Initializes using the type of connection stated in RMSConfig
*
* @param config a RMSConfig instance
* @see RMSConfig
*/
private void initConnectionPool(@Nonnull RMSConfig config)
{
LOG.info(LogPattern.INIT, "Connection Pool");
AtSQLFactory factory = AtSQLFactory.newInstance(
config.getDbUsername(),
config.getDbPassword(),
config.getDbMaxLifetime(),
config.getDbMaxPoolSize());
if (config.isDbTypeUrl())
factory = factory.withJdbcUrl(config.getDbUrl());
else
factory = factory.withDriver(
config.getDbDriver(),
config.getDbHostname(),
config.getDbPort(),
config.getDbName());
if (config.isMySQLService())
factory.withMySQLPerformanceSettings();
if (config.getDbProperties() != null)
factory.withDataSourceProperties(config.getDbProperties());
atSQL = factory.build();
LOG.info(LogPattern.INIT_DONE, "Connection Pool");
}
/**
* Creates a none-secure instance of the Grizzly server setting it to use
* Jackson and to find components in the given resourcePath
*
* @param config a RMSConfig instance
* @param rmsResourceConfig a RMSResourceConfig instance
* @see RMSConfig
*/
private void initHTTPServer(@Nonnull RMSConfig config, @Nonnull RMSResourceConfig rmsResourceConfig)
{
LOG.info(LogPattern.INIT, "HTTP Server");
URI uri = config.buildServiceUri();
LOG.info("HTTP Server URI: " + uri);
server = GrizzlyHttpServerFactory.createHttpServer(uri, rmsResourceConfig, false);
LOG.info(LogPattern.INIT_DONE, "HTTP Server");
}
/**
* Creates a secure instance of the Grizzly server setting it to use Jackson
* and to find components in the given resourcePath.
*
* @param config a RMSConfig instance
* @param rmsResourceConfig a RMSResourceConfig instance
* @see RMSConfig
*/
private void initHTTPSecureServer(@Nonnull RMSConfig config, @Nonnull RMSResourceConfig rmsResourceConfig)
{
LOG.info(LogPattern.INIT, "HTTP Secure Server");
URI uri = config.buildServiceUri();
LOG.info("HTTP Secure Server URI: " + uri);
SSLEngineConfigurator sslEngineConfigurator = createSSLEngineConfigurator(config);
server = GrizzlyHttpServerFactory.createHttpServer(uri, rmsResourceConfig, true, sslEngineConfigurator, false);
LOG.info(LogPattern.INIT_DONE, "HTTP Secure Server");
}
/**
* Creates an instance of SSLEngineConfigurator with the KeyStore and
* TrustStore properties given in the RMSConfig
*
* @param config a RMSConfig instance
* @return an SSLEngineConfigurator with the KeyStore and TrustStore file
* and pass
* @see RMSConfig
*/
private SSLEngineConfigurator createSSLEngineConfigurator(@Nonnull RMSConfig config)
{
SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();
if (config.isKeyStore()) {
sslContextConfigurator.setKeyStoreFile(config.getSslKeyStoreFile());
sslContextConfigurator.setKeyStorePass(config.getSslKeyStorePass());
}
if (config.isTrustStore()) {
sslContextConfigurator.setTrustStoreFile(config.getSslTrustStoreFile());
sslContextConfigurator.setTrustStorePass(config.getSslTrustStorePass());
}
return new SSLEngineConfigurator(sslContextConfigurator.createSSLContext(true), false, false, false);
}
/**
* Simple getter for AtSQL
*
* @return the MicroServices instance of AtSQL
* @see AtSQL
*/
public AtSQL getAtSQL()
{
Verify.notNull(atSQL, "AtSQL has not been initialized.");
return atSQL;
}
}
|
3e0b9b556ad831351abac85cdc95aa8213916d51 | 327 | java | Java | src/test/java/com/github/steveice10/mc/protocol/packet/login/serverbound/ServerboundHelloPacketTest.java | MWHunter/MCProtocolLib | 3d5119d0e53640178e0ed38131ff0c59ebfe213e | [
"MIT"
] | 84 | 2020-08-10T09:55:40.000Z | 2022-03-27T18:23:34.000Z | src/test/java/com/github/steveice10/mc/protocol/packet/login/serverbound/ServerboundHelloPacketTest.java | MWHunter/MCProtocolLib | 3d5119d0e53640178e0ed38131ff0c59ebfe213e | [
"MIT"
] | 25 | 2021-09-23T20:08:46.000Z | 2022-03-20T23:02:37.000Z | src/test/java/com/github/steveice10/mc/protocol/packet/login/serverbound/ServerboundHelloPacketTest.java | MWHunter/MCProtocolLib | 3d5119d0e53640178e0ed38131ff0c59ebfe213e | [
"MIT"
] | 37 | 2020-08-06T09:49:50.000Z | 2022-03-19T20:09:45.000Z | 27.25 | 67 | 0.767584 | 4,901 | package com.github.steveice10.mc.protocol.packet.login.serverbound;
import com.github.steveice10.mc.protocol.packet.PacketTest;
import org.junit.Before;
public class ServerboundHelloPacketTest extends PacketTest {
@Before
public void setup() {
this.setPackets(new ServerboundHelloPacket("Username"));
}
}
|
3e0b9babef3a050b3c92aa0a16123379fcdd4755 | 1,293 | java | Java | src/test/java/com/microsoft/bingads/v13/api/test/entities/ads/expandedText/write/BulkExpandedTextAdWriteToRowValuesPath1Test.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 30 | 2016-02-29T03:23:52.000Z | 2021-12-10T03:57:30.000Z | src/test/java/com/microsoft/bingads/v13/api/test/entities/ads/expandedText/write/BulkExpandedTextAdWriteToRowValuesPath1Test.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 61 | 2016-03-01T02:20:29.000Z | 2022-03-25T08:50:56.000Z | src/test/java/com/microsoft/bingads/v13/api/test/entities/ads/expandedText/write/BulkExpandedTextAdWriteToRowValuesPath1Test.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 37 | 2016-03-05T00:52:54.000Z | 2022-02-18T09:51:01.000Z | 32.325 | 127 | 0.709203 | 4,902 | package com.microsoft.bingads.v13.api.test.entities.ads.expandedText.write;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.v13.api.test.entities.ads.expandedText.BulkExpandedTextAdTest;
import com.microsoft.bingads.v13.bulk.entities.BulkExpandedTextAd;
@RunWith(Parameterized.class)
public class BulkExpandedTextAdWriteToRowValuesPath1Test extends BulkExpandedTextAdTest {
@Parameter(value = 1)
public String propertyValue;
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"path1", "path1"},
{"delete_value", ""},
{null, null},});
}
@Test
public void testWrite() {
this.<String>testWriteProperty("Path 1", this.datum, this.propertyValue, new BiConsumer<BulkExpandedTextAd, String>() {
@Override
public void accept(BulkExpandedTextAd c, String v) {
c.getExpandedTextAd().setPath1(v);
}
});
}
}
|
3e0b9bbdaf88e344405a1fcb3f067399d7b0f4b1 | 8,609 | java | Java | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/tests/jdbcapi/LargeDataLocksTest.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 282 | 2015-01-06T02:30:11.000Z | 2022-03-23T06:40:17.000Z | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/tests/jdbcapi/LargeDataLocksTest.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | null | null | null | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/tests/jdbcapi/LargeDataLocksTest.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 163 | 2015-01-07T00:07:53.000Z | 2022-03-07T08:35:03.000Z | 35.721992 | 104 | 0.616564 | 4,903 | /**
* Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.LargeDataLocksTest
*
* 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.derbyTesting.functionTests.tests.jdbcapi;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
import org.apache.derbyTesting.junit.Utilities;
public class LargeDataLocksTest extends BaseJDBCTestCase {
public LargeDataLocksTest(String name) {
super(name);
}
/**
* Test that ResultSet.getCharacterStream does not hold locks after the
* ResultSet is closed
*
* @throws SQLException
* @throws IOException
*/
public void testGetCharacterStream() throws SQLException, IOException {
// getCharacterStream() no locks expected after retrieval
int numChars = 0;
Statement stmt = createStatement();
String sql = "SELECT bc from t1";
// First with getCharacterStream
ResultSet rs = stmt.executeQuery(sql);
rs.next();
java.io.Reader characterStream = rs.getCharacterStream(1);
// Extract all the characters
int read = characterStream.read();
while (read != -1) {
read = characterStream.read();
numChars++;
}
assertEquals(38000, numChars);
rs.close();
assertLockCount(0);
commit();
}
/**
* Verify that getBytes does not hold locks after ResultSet is closed.
*
* @throws SQLException
*/
public void testGetBytes() throws SQLException {
// getBytes() no locks expected after retrieval
Statement stmt = createStatement();
String sql = "SELECT bincol from t1";
ResultSet rs = stmt.executeQuery(sql);
rs.next();
byte[] value = rs.getBytes(1);
assertEquals(38000, value.length);
rs.close();
assertLockCount(0);
commit();
}
/**
* Verify that getBinaryStream() does not hold locks after retrieval
*
* @throws SQLException
* @throws IOException
*/
public void testGetBinaryStream() throws SQLException, IOException {
int numBytes = 0;
getConnection().setAutoCommit(false);
Statement stmt = createStatement();
String sql = "SELECT bincol from t1";
ResultSet rs = stmt.executeQuery(sql);
rs.next();
InputStream stream = rs.getBinaryStream(1);
int read = stream.read();
while (read != -1) {
read = stream.read();
numBytes++;
}
assertEquals(38000, numBytes);
rs.close();
assertLockCount(0);
commit();
}
/**
* Test that ResultSet.getString() does not hold locks after the ResultSet
* is closed
*
* @throws SQLException
* @throws IOException
*/
public void testGetString() throws SQLException, IOException {
// getString() no locks expected after retrieval
Statement stmt = createStatement();
String sql = "SELECT bc from t1";
ResultSet rs = stmt.executeQuery(sql);
rs.next();
String value = rs.getString(1);
assertEquals(38000, value.length());
rs.close();
assertLockCount(0);
commit();
}
/**
* Assert that the lock table contains a certain number of locks. Fail and
* dump the contents of the lock table if the lock table does not contain
* the expected number of locks.
*
* @param expected the expected number of locks
*/
private void assertLockCount(int expected) throws SQLException {
// Count the locks in a new connection so that we don't accidentally
// make the default connection auto-commit and release locks.
Connection conn = openDefaultConnection();
Statement stmt = conn.createStatement();
// First wait for post-commit work to complete so that we don't count
// locks held by the background worker thread.
stmt.execute("call wait_for_post_commit()");
ResultSet rs = stmt.executeQuery("select * from syscs_diag.lock_table");
ResultSetMetaData meta = rs.getMetaData();
// Build an error message with the contents of the lock table as
// we walk through it.
StringBuffer msg = new StringBuffer(
"Unexpected lock count. Contents of lock table:\n");
int count;
for (count = 0; rs.next(); count++) {
msg.append(count + 1).append(": ");
for (int col = 1; col <= meta.getColumnCount(); col++) {
String name = meta.getColumnName(col);
Object val = rs.getObject(col);
msg.append(name).append('=').append(val).append(' ');
}
msg.append('\n');
}
rs.close();
stmt.close();
conn.close();
assertEquals(msg.toString(), expected, count);
}
public static Test baseSuite(String name) {
BaseTestSuite suite = new BaseTestSuite(name);
suite.addTestSuite(LargeDataLocksTest.class);
return new CleanDatabaseTestSetup(suite) {
/**
* Create and populate table
* @see org.apache.derbyTesting.junit.CleanDatabaseTestSetup#decorateSQL(java.sql.Statement)
*/
protected void decorateSQL(Statement s) throws SQLException {
Connection conn = getConnection();
conn.setAutoCommit(false);
PreparedStatement ps = null;
String sql;
sql = "CREATE TABLE t1 (bc CLOB(1M), bincol BLOB(1M), datalen int)";
s.executeUpdate(sql);
// Insert big and little values
sql = "INSERT into t1 values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setCharacterStream(1, new java.io.StringReader(Utilities
.repeatChar("a", 38000)), 38000);
try {
ps.setBytes(2, Utilities.repeatChar("a", 38000).getBytes("US-ASCII"));
} catch (UnsupportedEncodingException ue) {
// Shouldn't happen US-ASCII should always be supported
BaseTestCase.fail(ue.getMessage(), ue);
}
ps.setInt(3, 38000);
ps.executeUpdate();
ps.close();
// Create a procedure for use by assertLockCount() to ensure
// that the background worker thread has completed all the
// post-commit work.
s.execute("CREATE PROCEDURE WAIT_FOR_POST_COMMIT() "
+ "LANGUAGE JAVA EXTERNAL NAME "
+ "'org.apache.derbyTesting.functionTests.util."
+ "T_Access.waitForPostCommitToFinish' "
+ "PARAMETER STYLE JAVA");
conn.commit();
}
};
}
public static Test suite() {
BaseTestSuite suite = new BaseTestSuite("LargeDataLocksTest");
suite.addTest(baseSuite("LargeDataLocksTest:embedded"));
// Disable for client until DERBY-2892 is fixed
suite.addTest(TestConfiguration.clientServerDecorator(baseSuite("LargeDataLocksTest:client")));
return suite;
}
}
|
3e0b9bd27ca966bf9a60f4a6be618d3dd51f37a9 | 1,243 | java | Java | DotArt/app/src/main/java/com/mercangelsoftware/DotArt/MainActivity.java | gngable/DotArt | 9bea9251d9935de40089550c0ab554bfbcb2e3be | [
"MIT"
] | null | null | null | DotArt/app/src/main/java/com/mercangelsoftware/DotArt/MainActivity.java | gngable/DotArt | 9bea9251d9935de40089550c0ab554bfbcb2e3be | [
"MIT"
] | null | null | null | DotArt/app/src/main/java/com/mercangelsoftware/DotArt/MainActivity.java | gngable/DotArt | 9bea9251d9935de40089550c0ab554bfbcb2e3be | [
"MIT"
] | null | null | null | 28.906977 | 107 | 0.701529 | 4,904 | package com.mercangelsoftware.DotArt;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.util.*;
public class MainActivity extends Activity
{
GridLayout mainGrid;
int columnCount = 3;
int rowCount = 3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainGrid = (GridLayout)findViewById(R.id.main_grid);
mainGrid.setColumnCount(columnCount);
mainGrid.setRowCount(rowCount);
for(int i = 0; i < rowCount; i++){
for (int j = 0; j < columnCount; j++){
TextView t = new TextView(mainGrid.getContext());
t.setText("A");
GridLayout.LayoutParams param =new GridLayout.LayoutParams();
param.height = GridLayout.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.WRAP_CONTENT;
param.rightMargin = 5;
param.topMargin = 5;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(i);
param.rowSpec = GridLayout.spec(j);
//ViewGroup.LayoutParams parms = new ViewGroup.LayoutParams(mainGrid.getContext(), new AttributeSet());
mainGrid.addView(t, j + (i * columnCount), param);
}
}
}
}
|
3e0b9cffa8d9d312ab1a4a6e2ac27d561b744ce3 | 4,213 | java | Java | app/src/main/java/com/app/encontreibvrr/libraryFlycoTabLayout/activity/ui/SegmentTabActivity.java | AdrianoJPN/EncontreiBVProjeto | 3a2c187c75f683b58e7b13adeed38ed7e28a8647 | [
"Apache-2.0"
] | 1 | 2016-08-31T04:07:42.000Z | 2016-08-31T04:07:42.000Z | app/src/main/java/com/app/encontreibvrr/libraryFlycoTabLayout/activity/ui/SegmentTabActivity.java | AdrianoJPN/EncontreiBVProjeto | 3a2c187c75f683b58e7b13adeed38ed7e28a8647 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/app/encontreibvrr/libraryFlycoTabLayout/activity/ui/SegmentTabActivity.java | AdrianoJPN/EncontreiBVProjeto | 3a2c187c75f683b58e7b13adeed38ed7e28a8647 | [
"Apache-2.0"
] | null | null | null | 33.173228 | 102 | 0.663423 | 4,905 | package com.app.encontreibvrr.libraryFlycoTabLayout.activity.ui;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.app.encontreibvrr.R;
import com.app.encontreibvrr.libraryFlycoTabLayout.SegmentTabLayout;
import com.app.encontreibvrr.libraryFlycoTabLayout.activity.utils.ViewFindUtils;
import com.app.encontreibvrr.libraryFlycoTabLayout.listener.OnTabSelectListener;
import com.app.encontreibvrr.libraryFlycoTabLayout.widget.MsgView;
import java.util.ArrayList;
public class SegmentTabActivity extends AppCompatActivity {
private ArrayList<Fragment> mFragments = new ArrayList<>();
private ArrayList<Fragment> mFragments2 = new ArrayList<>();
private String[] mTitles = {"首页", "消息"};
private String[] mTitles_2 = {"首页", "消息", "联系人"};
private String[] mTitles_3 = {"首页", "消息", "联系人", "更多"};
private View mDecorView;
private SegmentTabLayout mTabLayout_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_flycoa_ctivity_segment_tab);
for (String title : mTitles_3) {
mFragments.add(SimpleCardFragment.getInstance("Switch ViewPager " + title));
}
for (String title : mTitles_2) {
mFragments2.add(SimpleCardFragment.getInstance("Switch Fragment " + title));
}
mDecorView = getWindow().getDecorView();
SegmentTabLayout tabLayout_1 = ViewFindUtils.find(mDecorView, R.id.tl_1);
SegmentTabLayout tabLayout_2 = ViewFindUtils.find(mDecorView, R.id.tl_2);
mTabLayout_3 = ViewFindUtils.find(mDecorView, R.id.tl_3);
SegmentTabLayout tabLayout_4 = ViewFindUtils.find(mDecorView, R.id.tl_4);
SegmentTabLayout tabLayout_5 = ViewFindUtils.find(mDecorView, R.id.tl_5);
tabLayout_1.setTabData(mTitles);
tabLayout_2.setTabData(mTitles_2);
tl_3();
tabLayout_4.setTabData(mTitles_2, this, R.id.fl_change, mFragments2);
tabLayout_5.setTabData(mTitles_3);
//显示未读红点
tabLayout_1.showDot(2);
tabLayout_2.showDot(2);
mTabLayout_3.showDot(1);
tabLayout_4.showDot(1);
//设置未读消息红点
mTabLayout_3.showDot(2);
MsgView rtv_3_2 = mTabLayout_3.getMsgView(2);
if (rtv_3_2 != null) {
rtv_3_2.setBackgroundColor(Color.parseColor("#6D8FB0"));
}
}
private void tl_3() {
final ViewPager vp_3 = ViewFindUtils.find(mDecorView, R.id.vp_2);
vp_3.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabLayout_3.setTabData(mTitles_3);
mTabLayout_3.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelect(int position) {
vp_3.setCurrentItem(position);
}
@Override
public void onTabReselect(int position) {
}
});
vp_3.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mTabLayout_3.setCurrentTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
vp_3.setCurrentItem(1);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles_3[position];
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
}
|
3e0b9e57df5118b5a8426a5ed512b464ffc7ff04 | 2,058 | java | Java | service/src/main/java/se/jsquad/component/jpa/JpaConfiguration.java | andyholst/openbank-spring | 576ab1aee1ca90b146efff8b8e32e48446f723ac | [
"Apache-2.0"
] | null | null | null | service/src/main/java/se/jsquad/component/jpa/JpaConfiguration.java | andyholst/openbank-spring | 576ab1aee1ca90b146efff8b8e32e48446f723ac | [
"Apache-2.0"
] | 4 | 2020-04-13T11:45:18.000Z | 2021-01-19T07:38:57.000Z | service/src/main/java/se/jsquad/component/jpa/JpaConfiguration.java | andyholst/openbank-spring | 576ab1aee1ca90b146efff8b8e32e48446f723ac | [
"Apache-2.0"
] | 2 | 2020-05-09T15:08:46.000Z | 2022-03-19T15:54:08.000Z | 26.050633 | 75 | 0.724976 | 4,906 | /*
* Copyright 2021 JSquad AB
*
* 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 se.jsquad.component.jpa;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Validated
public class JpaConfiguration {
@NotNull
@NotEmpty
private String databasePlatform;
@NotNull
private String entityAction;
private String databaseAction;
private String secondaryLevelCache;
private String cacheRegionFactory;
public String getDatabasePlatform() {
return databasePlatform;
}
public void setDatabasePlatform(String databasePlatform) {
this.databasePlatform = databasePlatform;
}
public String getEntityAction() {
return entityAction;
}
public void setEntityAction(String entityAction) {
this.entityAction = entityAction;
}
public String getDatabaseAction() {
return databaseAction;
}
public void setDatabaseAction(String databaseAction) {
this.databaseAction = databaseAction;
}
public String getSecondaryLevelCache() {
return secondaryLevelCache;
}
public void setSecondaryLevelCache(String secondaryLevelCache) {
this.secondaryLevelCache = secondaryLevelCache;
}
public String getCacheRegionFactory() {
return cacheRegionFactory;
}
public void setCacheRegionFactory(String cacheRegionFactory) {
this.cacheRegionFactory = cacheRegionFactory;
}
}
|
3e0b9e8f135c59eabd8a99f74acc2fd754a1041e | 334 | java | Java | src/main/java/com/madisp/stupid/StupidTimeExeededException.java | s4s0l/stupid | e654a5f6f44dbf36db28d0fc43f109c7dcdccea6 | [
"MIT"
] | null | null | null | src/main/java/com/madisp/stupid/StupidTimeExeededException.java | s4s0l/stupid | e654a5f6f44dbf36db28d0fc43f109c7dcdccea6 | [
"MIT"
] | null | null | null | src/main/java/com/madisp/stupid/StupidTimeExeededException.java | s4s0l/stupid | e654a5f6f44dbf36db28d0fc43f109c7dcdccea6 | [
"MIT"
] | null | null | null | 22.266667 | 72 | 0.718563 | 4,907 | package com.madisp.stupid;
/**
* @author Marcin Wielgus
*/
public class StupidTimeExeededException extends StupidRuntimeException {
public StupidTimeExeededException(String message) {
super(message);
}
public StupidTimeExeededException(String message, Throwable cause) {
super(message, cause);
}
}
|
3e0b9ee7d2259c0296a0969087bc622e83c2ecc0 | 1,004 | java | Java | app/src/main/java/top/biduo/exchange/adapter/BorrowRecordHistoryAdapter.java | coin-exchange/ZTuoExchange_android-1 | 6b6af54fad923ce7ca7334eb33087ae0e51ebf33 | [
"Apache-2.0"
] | 32 | 2019-08-04T14:09:53.000Z | 2022-02-26T09:44:59.000Z | app/src/main/java/top/biduo/exchange/adapter/BorrowRecordHistoryAdapter.java | Theo1016/ZTuoExchange_android | 6b6af54fad923ce7ca7334eb33087ae0e51ebf33 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/top/biduo/exchange/adapter/BorrowRecordHistoryAdapter.java | Theo1016/ZTuoExchange_android | 6b6af54fad923ce7ca7334eb33087ae0e51ebf33 | [
"Apache-2.0"
] | 91 | 2019-08-05T02:13:35.000Z | 2022-02-25T09:07:58.000Z | 35.857143 | 102 | 0.749004 | 4,908 | package top.biduo.exchange.adapter;
import android.support.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import java.util.List;
import top.biduo.exchange.R;
import top.biduo.exchange.entity.BorrowRecordBean;
import top.biduo.exchange.entity.GiveBackRecordBean;
public class BorrowRecordHistoryAdapter extends BaseQuickAdapter<GiveBackRecordBean, BaseViewHolder> {
public BorrowRecordHistoryAdapter(int layoutResId, @Nullable List<GiveBackRecordBean> data) {
super(layoutResId, data);
}
@Override
protected void convert(BaseViewHolder helper, GiveBackRecordBean item) {
helper.setText(R.id.tv_borrow_record_coin, item.getCoin().getUnit())
.setText(R.id.tv_borrow_record_amount, item.getAmount() + "")
.setText(R.id.tv_borrow_record_time, item.getCreateTime())
.setText(R.id.tv_borrow_record_interest, item.getInterest() + "");
}
}
|
3e0b9f10eaeca5a35a4e592bea0512ffeea3e706 | 356 | java | Java | roth-lib-java/src/main/java/roth/lib/java/xml/tag/CloseTag.java | roth-source/roth-lib | 3bef6134cd7374cb807725de6acceae7d3c77ecb | [
"MIT"
] | null | null | null | roth-lib-java/src/main/java/roth/lib/java/xml/tag/CloseTag.java | roth-source/roth-lib | 3bef6134cd7374cb807725de6acceae7d3c77ecb | [
"MIT"
] | null | null | null | roth-lib-java/src/main/java/roth/lib/java/xml/tag/CloseTag.java | roth-source/roth-lib | 3bef6134cd7374cb807725de6acceae7d3c77ecb | [
"MIT"
] | 1 | 2018-11-05T18:02:25.000Z | 2018-11-05T18:02:25.000Z | 11.866667 | 37 | 0.640449 | 4,909 | package roth.lib.java.xml.tag;
public class CloseTag extends Tag
{
protected String name;
public CloseTag(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public CloseTag setName(String name)
{
this.name = name;
return this;
}
@Override
public String toString()
{
return "</" + name + ">";
}
}
|
3e0b9fb36ac3c63cf76b470434fd7265957bc48f | 272 | java | Java | xiyan-parent/system-base-service/src/main/java/com/xiyan/mapper/DictionaryMapper.java | 694475668/xiyan-blog | 35f0b21e9fd53bcdaba47638f97d94863d1a67fd | [
"Apache-2.0"
] | 27 | 2020-12-29T14:05:29.000Z | 2022-03-02T05:53:14.000Z | xiyan-parent/system-base-service/src/main/java/com/xiyan/mapper/DictionaryMapper.java | baiguang10/xiyan-blog | 35f0b21e9fd53bcdaba47638f97d94863d1a67fd | [
"Apache-2.0"
] | null | null | null | xiyan-parent/system-base-service/src/main/java/com/xiyan/mapper/DictionaryMapper.java | baiguang10/xiyan-blog | 35f0b21e9fd53bcdaba47638f97d94863d1a67fd | [
"Apache-2.0"
] | 10 | 2020-12-30T02:48:01.000Z | 2022-03-19T13:32:29.000Z | 19.428571 | 68 | 0.753676 | 4,910 | package com.xiyan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiyan.domain.DictionaryDO;
/**
* @author: bright
* @date:Created in 2020/11/8 14:37
* @describe :
*/
public interface DictionaryMapper extends BaseMapper<DictionaryDO> {
}
|
3e0b9fe409e7535b51633ff1a0b28c3f5027a688 | 2,903 | java | Java | src/main/java/com/student_assessment/controller/LoginController.java | wumingxm/student_assessment | e3c7afafbb0c06ad3f263d8d8b7afd04c9fe3ae1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/student_assessment/controller/LoginController.java | wumingxm/student_assessment | e3c7afafbb0c06ad3f263d8d8b7afd04c9fe3ae1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/student_assessment/controller/LoginController.java | wumingxm/student_assessment | e3c7afafbb0c06ad3f263d8d8b7afd04c9fe3ae1 | [
"Apache-2.0"
] | null | null | null | 36.2875 | 84 | 0.743024 | 4,911 | // Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name: LoginController.java
package com.student_assessment.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.student_assessment.pojo.Student;
import com.student_assessment.pojo.Teacher;
import com.student_assessment.pojo.User;
import com.student_assessment.service.StudentService;
import com.student_assessment.service.TeacherService;
import com.student_assessment.service.UserService;
@Controller
public class LoginController
{
static{
ParserConfig.getGlobalInstance().setAsmEnable(false);
SerializeConfig.getGlobalInstance().setAsmEnable(false);
}
@Autowired
private UserService userService;
@Autowired
private StudentService studentService;
@Autowired
private TeacherService teacherService;
@RequestMapping("/checkForm")
public String checkForm(String verifyCode,User user, HttpServletRequest request){
request.setAttribute("userName",user.getUserName());
request.setAttribute("passWord",user.getPassWord());
request.setAttribute("verifyCode",verifyCode);
Map map=new HashMap();
//已经登录不能重复登录
if(request.getSession().getAttribute("user")!=null){
return "index";
}
//根据用户名查询验证用户名是否存在
User user2=userService.selectUserByUserName(user.getUserName());
if(user2!=null) {
String passWord=user2.getPassWord();
if(null!=passWord&&passWord.equals(user.getPassWord())) {
String verifyCode2=(String)request.getSession().getAttribute("verifyCode");
if(verifyCode2!=null&&verifyCode2.equals(verifyCode)) {
System.out.println(user2.getUserTypeId());
if(user2.getUserTypeId()==1) {
Student s=studentService.selectStudentBySNo(user2.getUserName());
request.getSession().setAttribute("student",s);
}else{
Teacher t=new Teacher();
t=teacherService.selectTeacherByTNo(user.getUserName());
request.getSession().setAttribute("teacher",t);
}
request.getSession().setAttribute("user",user2);
return "index";
}
request.setAttribute("verifyCodeError","验证码错误");
return "forward:/login.jsp";
}
request.setAttribute("passWordError","密码错误");
return "forward:/login.jsp";
}
request.setAttribute("userNameError","用户名不存在");
return "forward:/login.jsp";
}
}
|
3e0b9ff862cf3cd51e2f9c75e9af378c01a4fc08 | 1,145 | java | Java | api/api-pipelines-as-code-internal-v1/src/main/java/com/thoughtworks/go/apiv1/pipelinesascodeinternal/representers/ConfigFileListRepresenter.java | newbloke82/gocd | cbe7b4374f5833443e03eadbdbce64960fdaa06b | [
"Apache-2.0"
] | 2 | 2015-12-06T01:40:12.000Z | 2016-12-01T22:19:28.000Z | api/api-pipelines-as-code-internal-v1/src/main/java/com/thoughtworks/go/apiv1/pipelinesascodeinternal/representers/ConfigFileListRepresenter.java | newbloke82/gocd | cbe7b4374f5833443e03eadbdbce64960fdaa06b | [
"Apache-2.0"
] | 154 | 2016-07-08T15:02:12.000Z | 2019-09-23T17:37:38.000Z | api/api-pipelines-as-code-internal-v1/src/main/java/com/thoughtworks/go/apiv1/pipelinesascodeinternal/representers/ConfigFileListRepresenter.java | newbloke82/gocd | cbe7b4374f5833443e03eadbdbce64960fdaa06b | [
"Apache-2.0"
] | 2 | 2016-05-20T23:20:43.000Z | 2017-05-25T12:13:47.000Z | 39.482759 | 104 | 0.757205 | 4,912 | /*
* Copyright 2020 ThoughtWorks, 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.thoughtworks.go.apiv1.pipelinesascodeinternal.representers;
import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.plugin.access.configrepo.ConfigFileList;
public class ConfigFileListRepresenter {
public static void toJSON(OutputWriter jsonWriter, String pluginId, ConfigFileList configFileList) {
jsonWriter.add("plugin_id", pluginId);
jsonWriter.addChildList("files", configFileList.getFiles());
jsonWriter.add("errors", configFileList.getErrors().getErrorsAsText());
}
}
|
3e0ba070c4f83bced3fc5aa66e9468a4785b68ff | 226 | java | Java | src/main/java/curso/apirest/repository/TelefoneRepository.java | gerlingabriel/Api-Rest | 1aaa43d2e2885808cf73b8d771455c6f8ff4e80c | [
"MIT"
] | 2 | 2021-06-07T23:44:21.000Z | 2021-06-19T18:42:26.000Z | src/main/java/curso/apirest/repository/TelefoneRepository.java | gerlingabriel/Api-Rest | 1aaa43d2e2885808cf73b8d771455c6f8ff4e80c | [
"MIT"
] | null | null | null | src/main/java/curso/apirest/repository/TelefoneRepository.java | gerlingabriel/Api-Rest | 1aaa43d2e2885808cf73b8d771455c6f8ff4e80c | [
"MIT"
] | null | null | null | 20.545455 | 76 | 0.800885 | 4,913 | package curso.apirest.repository;
import curso.apirest.model.Telefones;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TelefoneRepository extends JpaRepository<Telefones, Long> {
}
|
3e0ba0a1bca43e479d03418a2dab2a0a25de502a | 711 | java | Java | generator/src/main/java/org/corfudb/generator/operations/SleepOperation.java | lixinchengdu/CorfuDB | fb268e97221f6e94e27477d35578bdc0677616e5 | [
"Apache-2.0"
] | null | null | null | generator/src/main/java/org/corfudb/generator/operations/SleepOperation.java | lixinchengdu/CorfuDB | fb268e97221f6e94e27477d35578bdc0677616e5 | [
"Apache-2.0"
] | null | null | null | generator/src/main/java/org/corfudb/generator/operations/SleepOperation.java | lixinchengdu/CorfuDB | fb268e97221f6e94e27477d35578bdc0677616e5 | [
"Apache-2.0"
] | null | null | null | 20.911765 | 47 | 0.625879 | 4,914 | package org.corfudb.generator.operations;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.corfudb.generator.State;
/**
* Created by maithem on 7/14/17.
*/
@Slf4j
public class SleepOperation extends Operation {
public SleepOperation(State state) {
super(state);
shortName = "Sleep";
}
@Override
@SuppressWarnings("checkstyle:ThreadSleep")
public void execute() {
Random rand = new Random();
int sleepTime = rand.nextInt(50);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
|
3e0ba0c6afde8f54f21c8141578d70b0fac089b1 | 5,565 | java | Java | examples/src/test/java/org/apache/mahout/ga/watchmaker/cd/CDRuleTest.java | VertiPub/mahout | da10c26f8fbf3edfc7f7ab26568a5a19bfbc39a3 | [
"Apache-2.0"
] | 15 | 2015-02-27T17:14:52.000Z | 2018-03-27T10:13:24.000Z | examples/src/test/java/org/apache/mahout/ga/watchmaker/cd/CDRuleTest.java | VertiPub/mahout | da10c26f8fbf3edfc7f7ab26568a5a19bfbc39a3 | [
"Apache-2.0"
] | 8 | 2018-11-12T11:44:53.000Z | 2022-02-01T01:13:42.000Z | examples/src/test/java/org/apache/mahout/ga/watchmaker/cd/CDRuleTest.java | iotashan/mahout | eb7b2cd1ec58e399d5cdae3cc548b605b7620baf | [
"Apache-2.0"
] | 25 | 2015-01-07T16:00:14.000Z | 2018-02-24T15:36:48.000Z | 30.576923 | 100 | 0.645642 | 4,915 | /**
* 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.mahout.ga.watchmaker.cd;
import org.apache.mahout.examples.MahoutTestCase;
import org.apache.mahout.ga.watchmaker.cd.utils.MockDataSet;
import org.apache.mahout.common.RandomUtils;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import java.util.Random;
public final class CDRuleTest extends MahoutTestCase {
private Random rng;
private MockDataSet mock;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
rng = RandomUtils.getRandom();
mock = new MockDataSet(rng, 50);
}
/**
* Test method for
* {@link org.apache.mahout.ga.watchmaker.cd.CDFactory#generateRandomCandidate(java.util.Random)}.
*/
public void testRandomCDRule() {
DataSet dataset = DataSet.getDataSet();
double threshold = 0.0;
int n = 100;
for (int nloop = 0; nloop < n; nloop++) {
mock.randomDataset();
CDRule rule = new CDRule(threshold, rng);
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
int attrInd = CDRule.attributeIndex(condInd);
CDMutationTest.assertInRange(rule.getW(condInd), 0, 1);
if (dataset.isNumerical(attrInd)) {
CDMutationTest.assertInRange(rule.getV(condInd), dataset.getMin(attrInd), dataset
.getMax(attrInd));
} else {
CDMutationTest.assertInRange(rule.getV(condInd), 0, dataset.getNbValues(attrInd) - 1);
}
}
mock.verify();
}
}
/**
* Test the Weight part of the condition.
*
*/
@Test
public void testWCondition() {
// the dataline has all its attributes set to 0d
DataLine dl = EasyMock.createMock(DataLine.class);
EasyMock.expect(dl.getAttribute(EasyMock.anyInt())).andReturn(0.0).atLeastOnce();
EasyMock.replay(dl);
// all the conditions are : attribut < 0
int n = 100; // repeat the test n times
for (int nloop = 0; nloop < n; nloop++) {
double thr = rng.nextDouble();
mock.numericalDataset();
CDRule rule = new CDRule(thr);
for (int index = 0; index < rule.getNbConditions(); index++) {
rule.setW(index, rng.nextDouble());
rule.setO(index, false);
rule.setV(index, 0);
}
// all coditions should return false unless w < threshold
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
assertEquals(rule.getW(condInd) < thr, rule.condition(condInd, dl));
}
mock.verify();
}
EasyMock.verify(dl);
}
/**
* Test the Operator part of the condition, on numerical attributes
*
*/
@Test
public void testOConditionNumerical() {
// the dataline has all its attributes set to 1d
DataLine dl = EasyMock.createMock(DataLine.class);
EasyMock.expect(dl.getAttribute(EasyMock.anyInt())).andReturn(1.0).atLeastOnce();
EasyMock.replay(dl);
int n = 100; // repeat the test n times
for (int nloop = 0; nloop < n; nloop++) {
mock.numericalDataset();
CDRule rule = new CDRule(0.0);
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
rule.setW(condInd, 1.0); // all weights are 1 (active)
rule.setO(condInd, rng.nextBoolean());
rule.setV(condInd, 0);
}
// the condition is true if the operator is >=
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
assertEquals(rule.getO(condInd), rule.condition(condInd, dl));
}
mock.verify();
}
EasyMock.verify(dl);
}
/**
* Test the Operator part of the condition, on numerical attributes
*
*/
@Test
public void testOConditionCategorical() {
// the dataline has all its attributes set to 1d
DataLine dl = EasyMock.createMock(DataLine.class);
EasyMock.expect(dl.getAttribute(EasyMock.anyInt())).andReturn(1.0).atLeastOnce();
EasyMock.replay(dl);
int n = 100; // repeat the test n times
for (int nloop = 0; nloop < n; nloop++) {
mock.categoricalDataset();
// all weights are 1 (active)
CDRule rule = new CDRule(0.0);
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
rule.setW(condInd, 1.0);
rule.setO(condInd, rng.nextBoolean());
rule.setV(condInd, rng.nextInt(2)); // two categories
}
// the condition is true if the operator is == and the values are equal
// (value==1), or the operator is != and the values are no equal
// (value==0)
for (int condInd = 0; condInd < rule.getNbConditions(); condInd++) {
assertEquals(!(rule.getO(condInd) ^ rule.getV(condInd) == 1.0),
rule.condition(condInd, dl));
}
mock.verify();
}
EasyMock.verify(dl);
}
}
|
3e0ba100bbdaaa52a086fe51c18a433c2a840f2a | 26,644 | java | Java | output/e6cc8dc5b9df4f77ae6c85f17ed9cc48.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/e6cc8dc5b9df4f77ae6c85f17ed9cc48.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/e6cc8dc5b9df4f77ae6c85f17ed9cc48.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | 37.47398 | 291 | 0.494595 | 4,916 | class d {
public static void y6UvRbSDKx93 (String[] BgwfspHnSDz) {
int ap3bGViGwIT08k = --null.RBP() = null.B7;
CD_xmUomG[][] BBqiOttvnm;
boolean SwnvvAyMlrKUV2 = DTUgF[ -yzR1X6hqf4.bbKCHEA7qwdwnM] = -true.Mgwmph();
if ( true[ !new ZUejn().kiK3CPe1Wt]) return;
return;
return !!-( -!!-this.jHGGiuzE3()).Taw0_v3TGI;
k7NB1nrUht[][] _LcueH;
return -!--!new Wim().nwZ();
void kIy2V4rwK;
void[] EP = false[ false[ !-null.E8qSirpXMJ()]] = ( !rYC2FB().xLyu).Q6ec_snS9sOsh();
while ( !new GABbzPjKkUF().lGueJp_LfHa) {
boolean[] yt3Jjqa;
}
Qd5uf4khMM lYlgmOqUs7;
void[][] mkEakxShjlw;
if ( new void[ !CU7k8xH1r7e[ null.cDTj7Q66B5Eag]].BbMiTMKvs()) !!-null[ null.erTkP()];else while ( AJgkI_a9EX3U.FDkHGbjxH()) false.g6();
}
public kpVZa6E0md[] JCS6_Vf4 (lGnp ireMzy, void[][] G3, void[] CQcPfin, Z hdrueko608iH, Uv e5ws_mppaTtA_L, void o5EwhnZ2QYyVd) throws r2VFeiPVR {
ef5KrNu0 YNDeww2 = -false.qFs() = 444.jt1hkoiV7th;
{
void[][][][][][][][] uyHi;
cRPUu9Q NAsKXNJ86nMw;
{
return;
}
boolean k;
{
return;
}
boolean fzVIv9izPvZpuy;
{
int YGV_zl5LoEK3yq;
}
this[ -false[ !new xLTHoTBpsd().zFKKCPgu5Clfk]];
boolean[] UGzTTmW8zsmM1;
if ( -new cwg9rMBNy1g6[ AilIKsXUj.AgiUSYj5KY()].AXEb5EC6()) {
return;
}
;
!!this[ !-!!true.QO()];
void Y;
;
return;
}
while ( null[ !null[ B[ !true.XxMSU8]]]) while ( new rBj().bh7sPi) return;
while ( 801.QFBlTND7a()) while ( 22.ABqwBF8o5()) return;
MHSotGZ5sv D8uqNnq = gYsxxLX78_2l().H4Ff();
;
int[] ltl3uZB41e;
if ( false.ZA3gAo9nePill()) if ( null.DRdVnsR8q) while ( -new a()[ false.V6h0kPmq6iE]) ;else while ( OkKFRZdTGv.VH()) {
return;
}
while ( !!false.FamslLt) !--( !-129398[ LoTTPE[ !!false.oA]]).nJwaMxfhqrK();
UweTM O48 = -zk9JBU_wH.TA();
f0V1JJtTdjaHmo rOja7am;
int[][] l57_py;
if ( Exn_s().JXWDt5GhgIC) {
if ( !true.Ohoo()) return;
}else while ( !false.XpV6()) while ( !-!!-!new DJFFVPU5bi3AEc()[ -true.Q]) while ( -false.bhx) while ( 653069[ true[ !!null[ !-!5[ !( --!819.z1p5g())[ -!!dC()[ !!XnqXfwhbuA()[ null.jIjuDRMbOpG]]]]]]]) return;
void qG8IYHP0NgQtN;
}
public static void WXdHUnE (String[] DtgWeF) throws L_uM {
boolean[] xxKOK = ( -!--q0r1BtXsVks().WpKbCeC0NoWBVy).TKYEk;
while ( --!!new void[ new boolean[ !DcUBLgWhlt()[ -Xw3fA[ -this[ ---false.ixWibdBBWYNq()]]]].OcIxxx()].kt5R) ( !-!( !( ( Isj().tQeQHX08Fi)[ null.lbP2H6XJs8Y])[ false.gWPIwvDeE]).Q5ka()).DVld5FxJls6Zop;
while ( !!false.umChrp()) while ( !NdgX().Yxt4) if ( Ii8sUT[ ( -( this.apxAhdl9Mh_s()).fD6C8R_i057PHM).TQ97JNTqs9kvQV()]) --( true.UiFeniJ)[ new boolean[ !RM6t9ls_1Uo7.mrCFcwXn].e81DivuF];
boolean[] ryenhTpMwn;
while ( false[ -false[ new kuWwKsm()[ -!4534671[ !( false.nRLkcQKeBIIF8F())[ this.ehX()]]]]]) ;
vuV034s6XR4.GWk12();
}
public boolean[][] n60or (boolean[] kREeyR7RhBUpvq, z[][][] DZA) throws M {
if ( 855114.M3pGMvXu()) {
return;
}
void aQ01BRiyAX;
if ( -!592.tXYjXC) if ( !30[ false[ !261582397.TXTjhHYBmAh]]) return;
while ( true.H5QAW_) ;
K u1AUiKFW;
boolean Mxb1k4 = null[ xKpFxgwYgJz().tpArTsBzvE()] = !!xNf2u8JqIt.f5cfxYh;
Vp0N11g7oUtGT[][] Fp5_ma;
{
boolean[][] x3rtq;
;
BiDbWjAOqv _2Q;
_Xteb10Rwb_uZ nb2lcDm;
{
return;
}
while ( !-!!-!-YCDbh[ !new ivbwlc().qvf]) {
boolean x5z016;
}
int[] HjfDg;
while ( 7056374.Cu06PNyJs1Mr()) ;
}
int[] cooh3oktz7uMu = -!this.iLPE9_;
void[] Hpvv8tD8G = new boolean[ !new void[ !!false.GFT3Nq8L()][ false[ new yM_mC2utTR().mGK]]].sdXXsZp;
etcW.uVCDaescs4ES3;
boolean nLGUDHALH;
G[] nfQiqcXpHiFh_y;
!new uQ().ow;
int[] aOfU8;
( -this[ !new TsKbN()[ !-!( ( true.de4Adww).H).cH()]]).D;
if ( !null[ -null[ !BqicLZSRF0().Yajjst1q()]]) {
while ( true.hbt2()) !-!-( 91539._yEMzuR).UXpVkGymleYeU;
}else !!---!!-false[ new UAOpgnx_x35()[ new JhikmK2TLyYo().B4yR_8uB_V()]];
return -GrjH1dwQcwJ0Cs._be();
int[] PA;
}
public boolean[][][] miXDkT_fuWAT;
public boolean a7ON7tlBFUZt (GPHf xl_uGYzO9b7a, int vBrgrqYpv6, Bw[] ciuvmHNYNowCRY, int OLufWW) throws axBoUlmXRi5n {
return !( -!U9LE().y66AQz5nwGQ0).hkUN();
int[][] E3P6byvh8a;
if ( B7u.Gs()) if ( false.yt3mrFKqYQ8l()) {
void c2fkjaxsSjFQ;
}else false[ 1193640[ fMUBKwHWb3JAYC().sG()]];
return;
while ( true.UL5ynn()) ;
if ( !Sc0rwh[ this[ new boolean[ null.d][ ( !-true[ !ku4YjD()[ new boolean[ !-new d3s()[ qwnapR().v3j()]].r2UhRUwj()]])[ !!new void[ !!-new oAYA0[ !!!null.begX()].ZS1Qyw_dlc].PIwk_nIn70E()]]]]) while ( 376907632.uE8H5) if ( -37152147.Jr4) ;else while ( ---LV7IYY.lStnZICLrbM) return;
;
H[] AwEex = this.ajL8Z7xqn() = ---IJ6zqkc.KD();
boolean[][][] _vvqMD = true.ikWAHpdH1AND() = -new lnFBBBtEuSBRJp()[ false.pmJ2];
while ( !( new SOlpuzLgDd1S().wS5)[ uTh().FMWtAPDb]) {
gt0W[][] B92Ay;
}
void[] Q;
{
r_OYwDA[][][] RKHXR0yxM;
return;
if ( --!null.LUgcZLmwXdXmjZ()) ;
int kzLZM6J;
;
}
void[] Pqu;
while ( -JKsErnby2sjp6n.Zx3()) return;
yqjET6dPowoB3 w6w5HRKzOn;
while ( false[ ---( new void[ sRHK.fG3C1rB()].ENquKT())[ new ZVl()[ -null[ this.kJm()]]]]) ;
}
public void[] rBlEOYbpmXR1Y;
public void[] jFsj8Ha7D9l_og () throws gnTznGblfyp4j {
while ( !new int[ !sGT()[ !-new y().HD6j7Xeg6()]].Lw4OCWIX) if ( !-new void[ -!new boolean[ TPwEQC()[ -true.h6jn2()]].JU0Jseb()]._BN()) nOv5lqgG5yp5.foqXKkzQC;
void[][] S5JFzXIOGju = true.mk7_l3VeiH6LDQ() = true.Q;
int mbMSfrAmgxxjec;
false.OSGX5();
boolean SI;
DpTBUKeSwCb4h2[][] bUrb0o54BZzE = 7.KUy55W4GG;
int[] pKrgr9ay;
void bEjzIPV7o2Gv;
while ( kFKBPQ.f4spobtNuwuy8D()) if ( null.MkJ8g27nUyh()) -new iZzYbOMG()[ !false.B70hX0y4N];
void qgtNdGT;
int[] CMJq = -!new j8njV().SXWXMtq40wRlP = true.ldp6Ju0N();
void[][] qWI5as78 = ( s8a[ ( 449674[ --true.wHmuBV()]).G]).mWif5PJqYFtJv;
}
public int N8g2OmiL18lEx;
public boolean x9pMeSmetRN2I;
public XkarhrrE3K7fTu f7_Ri () throws L {
new void[ null.qo3W].fe();
}
public boolean sSwfDjs1zs__;
public int[][][][] dpB (boolean[][] Jm0WyV, digWtHjI6[][] Ns5, boolean FBIxLM3QQ7K, boolean bjxO, Cs6VmOF kySRCFp) {
if ( !122023.oJHNdAuZyD()) while ( !-!Fod9()._1t6IKTYNeZA) if ( ( !null[ this[ --!--false[ -new cbl[ !-this[ !-!-null[ ( !new h6dDLE5qMDy().XWEOju).VccXh]]].Pz6()]]]).eLsjaWwIg()) return;
-new o4gHgA[ eZ_iX3vy()[ -true[ -null.hbVVqEAx]]].MKnwd_;
void[][] hwexE = new DxkISt_9kwCX5().ALlKYgGGsemQ();
;
}
}
class xQzsBkfYaS1ci {
}
class qd {
public void PHY;
}
class s8wAulr5Cr {
}
class x3iJTOYl {
}
class D9b {
public int[][][] lI6MOZW (int fIU5, E[][] Cd, int khve7tgZ8z) throws jsC {
int rtzd66Mi;
!663.JS5Re();
void[][][] C4o4edJ5bqjF = C._PbrGCXDW() = ( !-true[ new zdmS().dqGRs])[ !-!new wYHnG().makqEQ()];
--new int[ !( BKnoUGiVZxy.i2qA4OUgy)[ --!-!!!this[ false[ --kVNjsY66IAu.gNN9gpv]]]].hPzoZiZt4();
int qBO;
void c3U6D = 04162852[ true[ !!PkzNI8nVnl[ !--qn9pMZ3.qhDPsqzn()]]] = -81272[ !-!-!true.z7QNYlkZ0tk()];
boolean ubC7FRqRjQOYxZ;
}
public int[] NLvZX97BgD (int hacF9Qn0puCy) {
{
new int[ ( new Sv()[ -null[ !true[ null.z]]]).Gr4C()].lek1t();
boolean[] Lx;
int lY6Lo;
while ( -!-false.TPaiB()) ;
int ZT;
return;
new void[ !( new boolean[ 654.jBitKtvH].Y3Kw98daldu7qi())[ ( true[ !false.H()]).ShcGz7pZRyX]].Bo9LPadAXv();
boolean[][][] ddSQ_nPTNjjzG;
void[] G8NLVbIGklgRj1;
;
int E;
{
return;
}
}
A0TNkqFHyX5N[] mjhINSbI1 = EYvR7n().ROlbd15EvGQgb2();
oL2XAV.FPMUSb2AxCYxU;
{
if ( -59238965[ !!-( !null[ !502.m()]).pAJ2bV()]) -new void[ !( !-!( -true.nndQjhcHpnRj)[ !( false.xvEjqPvx1qgre).GFVPz]).ZvVgG5cCmfX0P].wDH3;
true.o_9dAinB8tmDa();
null.g7Q();
void[][][] m2W;
int JOp;
if ( new boolean[ !!null.rV1X81j9][ !GpUCrki6MuF().stmzpV_jEiLwo]) while ( !-!!new LYlG().p2iaeSac8BOat) while ( lAlbR6CV.yvh()) ;
;
;
int vWbo;
while ( -!fYhuOuZhNXb().QFywUmSL()) ;
;
int FZ;
J8Qq[] hyxS5wodwoOn;
Nyryie3JXeXAbx[] EucR3olkSth;
return;
void qWo3pmi1p;
{
int xxDL;
}
{
while ( 57052.Kj4sIQuQeks4()) ;
}
boolean[][] vb4SBPAhvj;
}
dOLZgluUmMDw().tDB8ol();
lM1r YtcatYZc;
void[] ywn_M72IEALH2N;
return;
return;
}
public static void LW_tjTXXzuAT (String[] nzp_j) throws joSHASsWVyi8 {
{
return;
return;
--!--ux5FUl[ -( !Rfo8gCr[ this.C8OzIwQA()])[ 223554.uVy7I7gk12fvp()]];
;
M0eea9xk[] oqfZs9khjy;
VqiAE7[] bRcqXX4mf6;
if ( new OI9gIt31qKLNZf().xNyzg) while ( 597903427[ ReG.vu4VdblUJg1YMz]) {
wRUB2ld().hG7rt6d();
}
while ( !!!true.zatkiTK4Iso6()) null.Fx6szDoMJ();
void grLC;
}
boolean W35 = !-( -!--!J[ -new zm11m4oQJoEB1C().dXGt]).lGITf48yPjj9();
int FTJ7 = -!new te_gUyXlykF[ true.Jcqy3msdGZVTrw()].JpwuBlp;
boolean[][] vFgQyQ;
boolean TKUksye;
return new PHoGasCm().fu8jpPWPg8O();
if ( !true.v()) {
{
;
}
}
int[] iblbxXabz;
int[] RStffwjMNUiV;
;
;
new nLt_Dkl().Kic_HGUvB;
}
public static void F (String[] zwfPQNBdmQW476) throws m5xmtH5X {
MB7Ax pI5R64;
void[] cAg;
;
if ( false.wrPM()) {
if ( -!GOp8.z7_QuEd27_8) if ( !this.ehkeWGj7bfcS()) if ( -!this.Pa_Iu1BSXaM1()) {
int IE8dx5L;
}
}else return;
return;
null[ this.U7Rno()];
if ( false[ --new void[ new int[ -new nSjJmB().NITXO4M()].PMO5j6DR].hqCWV()]) while ( L2Twh5zaMVcNj.WP7ueKt) {
int[] on;
}else while ( ( 204[ !!7.XfHmvJ]).XH) return;
void[][] kFKEIalDk;
FjoO_[] npnPhb;
int[][] IItdbVwbq;
;
}
public boolean[] oY52daa21NQUpe (int[] jimzCcXcoK, void[][][] ld, int[][][] bcRwpPK_6O7ry7, void s5o1f2G) {
{
void[][] aT7DSzm1;
boolean tjHcQ3;
while ( -pHx8xI.bcuNBxY40) return;
fIjAmL3[][] rdDGE7TCr3NP;
if ( new int[ new boolean[ -!!!-( !!Np.TPm04nhn3lGTlK)[ !false.wVnARj1QJ()]][ new w().eHdTwXDzUz]][ ----!EYdRE().w4MdHxGHBS2]) ;
boolean oSGWSa;
;
{
wXE940b6197a[][] c1;
}
boolean P9jxv66sTb1;
boolean[][][] hAuMwaxb3Tnlf;
}
Mdl7bE55RvWF QicR3e = this[ -new int[ !( 9489[ ( -!73488711.etLLp7)[ 3360.httD_bulb8F]])[ true.sNZKKaLMtHp2f]][ !-!vkNz5c6GPFJNO5[ --new HWw[ new boolean[ -!new o7().Tf48hajh].napYd9JMU3].E()]]] = 47582.TbzYEm();
int cUi = !false.AkfOTC4v_ScmtH = !null.iOkRFPi5();
return;
{
int[][][] iasIocCqyJK1o;
if ( null.a5()) {
return;
}
void[] VKDV5B;
boolean myHQCbU69He1;
{
return;
}
pIycVICDFAO[] WTQ3;
}
;
while ( new omqTQTovnBF()[ 195728894[ false.oUKSbRFW()]]) ;
while ( this.QtZhX4W7jqz5E) while ( !null[ !!new sRnpCc45VPcS().LTkIbhU]) {
if ( -false.LR8Hh2WQKvid) if ( ( !-new d3bj6CDDflKHeD[ -wa()[ zGN6_cqaIaI.uc]].Q).XNO0PteMhSL0Zs) return;
}
boolean[] NMTOzr3Fuz5LuV = !( !!--!( !LPugA().RHG4ClQ)._rrkrnnzRiIO).NcocMxBWPysfM5 = true.dmDzQS();
while ( !null[ vA1o[ new boolean[ !true.VuH].Dsgb1DkJ7_6()]]) return;
return 0.RA3Jwpnlk;
;
this.J6Xze4LwX();
boolean gRAxLamz3nY9 = JgYfQeJbd4wn0W[ ( XSNtH.DV).nNNn29Dv] = d2m3().NE9BwLl5Q;
aWYIf[][][][] D7o_;
void[][] oR4ZyoYv8_;
int[][] ppmK;
GnQY5CPILMSfb3 NWCtmAkkVFl4 = false[ new tI_hFEkJOiP()[ !Qg1k6JIYsSwI().kIJXwh7]];
-false.e;
return new boolean[ new j8MkV1yNFeT5().jz6pW0o()].awp1F9jWnqA;
}
public int UpvE () throws fmwBee4qupmg {
void IbB3m;
while ( -----false.WI8VjeIW) while ( this.KNGbO()) {
if ( IFhMhzZKg().hZYxaf) ;
}
int NnGGKmtY;
}
public za Yy;
public dGfIcObP JlZhzxpyh (boolean thQwuz, int[][][] B_UwzwB, boolean[][] ZAtDSHBiAFv) throws bVq2qUuOw {
UYx5WdD IfHh79gMB;
return -null.Fr;
void pbYNIt8qm3i;
while ( new boolean[ mqSu2().dSDEBm5()].Q2dEGNh()) return;
!null.x_IY1ZFDS3zOt6;
boolean[][] zi;
}
public boolean[] _YZbdaj;
public static void Kf3h (String[] ZH723OSB) throws vg_YLeLWQ2ZtHu {
;
!this.nC();
boolean[] wlHu;
if ( !null[ --71[ --!-this[ null[ !-!!jm48RL()[ f2bN().dG()]]]]]) return;
while ( --!-!!!new T6ecEePTdKX8x()[ -false.VFNEhIk5kCD]) while ( !!-J8fmvhaH().zyWWamJpzV7()) ;
void[][][] bv6DRHgE_Uq = true[ new umfBJY7KiH().V4if1m7NYCIMM] = -false[ new int[ -!!--null.jl6].DqeGH3nMnpUcxG()];
return;
int[] F = !new int[ false.p0Kw2Y0esB39E][ 0587175[ -EIQNJ2OQ8().v0ZjunNn()]] = new sgADARAXIV4ma().xy1El;
return new void[ OK.l9mX][ -false.DA7];
{
return;
while ( ugMu1eCo().cQUqwepLSO_n4) {
int[][] AVJMgPG0w;
}
H0Ydtr HBf64mjXZ;
boolean yscUFyLOe;
boolean r_H;
void[] gUwLUItrLKZWnE;
void[] iRjtxp_sd;
while ( -!---!QE86G.OEQ7BtHHUk()) ;
{
return;
}
while ( -JV.DVccIcg4i()) return;
boolean no6ioP6l;
void g6REczJZ8vRY;
boolean[][] D5_N;
}
int wFweMIV = false.E1DYlj();
void[] fNO = !-true[ new boolean[ !!new void[ !28785.mQX9uwei99d7aK()].PTgIfn()].Af4F71mz()];
!-new void[ 01107537.fZbpc()].H8;
}
public BB59yPZ1tJ4mkx[][][][] BhxCwx;
public static void BLwQPlCQvqnMY (String[] x) throws h_CNNijcoVfv {
Spq ZSqxyiFJIEm02B;
boolean[] sHS8faXea;
!-new JAc9Wdq3qx()[ true.PWF];
int[] dU;
return;
int VJc = false.Po() = ----!--!-yIBLjlJIxYIDs.n65U3WVwi3;
{
boolean lIoZVWRgkc;
;
int[][][][][][][] rgq_Jytp;
;
if ( new void[ --!921.v].eyjW()) ;
boolean GJ1hI;
int wMSmRSs;
if ( -bOXs1mDDkoPJ.qUvc8icbZQy6()) return;
;
;
boolean[] zH_JjM6;
boolean yVwx6d;
int[] cy7dHxv66nIGt;
NhLyzbYuyL bJKRF;
int TT3;
}
while ( -R()[ new PR().VwjCS8F_NGK]) {
;
}
( new iEg()[ ( !new pFeN[ Yumw4jie4aFs[ new n()[ !true.Zok()]]].mC_RPMrG).aA05uR3ZOPP()]).MJnU6_zPlr();
return;
while ( !---new void[ 42545.dupyqy1fOiM()][ --true.xbSMW7LRhB]) while ( --067980531.taRUamQ) {
boolean BE;
}
while ( !!true.M6B2f1T) ( 0223930.SS1YEoRnbSK97b).WUK36cnD0;
return;
int LR9Xu3qq4tOm5X;
{
int[] F89BhYO9ykVg;
int D1hhMiEuP78E;
while ( null._tw6kPLC()) ( -63549.OG)[ !ts3XNMVJLX().D2HYOtUXqnG9];
while ( this.NW6()) return;
boolean[] Q9on0_;
while ( -UTdGtERpQM28s().KEdk) while ( -( !( !true[ !UIXf3()[ -!new void[ !new Tw()[ -new Hrvz3m()[ null[ new tk2iB4v90Sle7().DzXKP2RfLnFV()]]]].JQE()]]).CLU19UlNOQI).x()) if ( new MwDCPyAFB_T1a().HNHBE1aT) while ( -true.QfYHuFz8) return;
void v4MGqI;
int XdbF5OfPn;
int[] qyrNEwX;
boolean ceyz4ewlp6S6A;
boolean[] erT3ZNgo;
;
-bw9xDDxNPk2Tmo.Qm2j4ApXp;
void XyS6_di;
int[] zPwrjBx55;
boolean[] nHCzMXnHl6MjDj;
while ( false.WDr3x) -15.Y_Nq3aN();
}
boolean bto1K9 = !!915542.z9VD();
;
}
}
class LPizReT {
}
class GO {
}
class ftobdhmS613V {
public static void kPBWUDofUVcwq (String[] JC2oZJy) throws Qv06JUxxH {
!new YL().sKJYK;
int Hy1e0Jr0xhzVfw = !!--44984414.Fr6();
while ( h8JoojL5VJ5kZN.q8wRoMsx6j) -null[ --false.v];
D2gKg[] QcYBN1PrN6huVg;
JO8YWd0Bn_e1[][] rxBTp;
while ( sKt().n74ihlFXzn1()) ;
while ( --this.oXpfoU()) 40[ new NaZ62h_MZYX()[ !false[ new void[ true.V].x_7Q]]];
{
int fCzuPb;
{
if ( !!-!qTtD6Mcn_Co[ !970747731.SNPlosOY]) -!this.nhhNYSUJ();
}
{
{
boolean[][] AV4E;
}
}
hrpOg_qC_6I[][] T;
while ( -tyvyJXICD().En()) if ( true.Wbh0JAROuVJc()) return;
this.jiE();
{
return;
}
LLioLh7QPb gc1tOixH59B;
void[] jbcMFl;
CPFp9to[] VNuV;
{
-false[ ( null.jQ9HDlf7).fXh81LXNn];
}
void[][][][] GSr_DAwTz;
{
{
boolean[] a4;
}
}
;
return;
( !-true.or9J9Us).nCgOZY;
}
if ( -!37219.t4N) return;else if ( new Poa883Kbt()[ -false.WWpqx()]) while ( -!new void[ !( --new int[ -g.Y9M4uIqOq18bg].I).TGTJudpv7()].ebbYgx()) if ( new boolean[ -this[ null.zTZ8rkEtleW]][ null[ !-!--053439387[ new l2s3usWd5nS0()[ null.dCPv_69Oz4uY4]]]]) ;
while ( this[ this.YQX8vpH3h()]) if ( !new qoQYmYCjuL[ !ar85tOE()._qDZj1pgD7JfA].FNjmNdSMlEgAKu) -!!254468186.nTBhpA;
int[][][][][] bAdQ0 = false[ yGux_Y().Axqj3Rnanpzg()] = ( ----false[ -!-this[ false.F]]).vyH2();
{
( null.Dyrd()).jePON;
e4Se()[ --( new l16725R()[ ----false[ this.M5QANykap()]]).SoUc8Gp1Lspqy1];
UG GZZT;
if ( null.w()) return;
int txTS5qou;
return;
jftfzXecxTF[] IJhsGZ;
this.TzH0();
return;
n3 vQlpRj7f;
{
;
}
;
;
new void[ a5qjj6fvgCgK().QcC6BIZxU9][ true.F38JSPY()];
}
return ( !true._XJxNHrdq_MMk).Fq();
while ( ( -!!!-giH6M5SkSfsAC().o34X)[ null[ this.I8i6ox9VvRXWA]]) {
!!!!true[ new bpH4rUX[ this.UP5Yp0obgpBO()][ f.SuGAWyG49HrK]];
}
}
public static void M4jYzQf (String[] u) throws wV3R {
void gOU;
int[] TsyvfHITLs;
zZpivrrVS[][] ALwy = !-bD9POzazUaE3T().h2h9();
void PG38QltdFOy2T;
return;
while ( true.CnrABeX9DaqIWP) while ( -new int[ !i6tyN2().AgzvNAOI_].hT7aS()) ;
if ( !--( null[ false.WIfm6]).RO) ;
return;
if ( false.Jd3M) return;else return;
boolean mc_bpj72i;
if ( new boolean[ new TbbVgdQz4ntRW().X0Wqm3Q][ -new XKSclnsn().eUpaXPF]) ;
boolean fSxH;
boolean[] _nhZayIB;
lh1OkZb921D D = --!new tAqnk42Ky().sAym1jMP7d;
JTma3_[][] MBGm;
{
void[][] IQaQRgFo;
PIDz t;
void Q5GUpRIdM;
if ( null.j()) if ( new uVnFycT7().rm4ITcYV_()) {
boolean I9n;
}
while ( !!!!this.cPyk_5FRWOjy) while ( new int[ false.F][ !null.k_Tv27kuyqfA()]) return;
new rOG().bmz();
-!new _zspI6ejQPqdWU[ -new t1W_ZOl8W4().Tx].T3();
boolean[] lwH3YQ;
void[][] Zs2fZIdtvhTW9E;
if ( null.JMhimw6()) ;
new Rhx8K0GQmMl().tyJ_();
( -!new ZA3HS88OeSdVJ4().J()).eMFgRyzqpRj;
false.YHJh7K;
}
}
public int[][][][][][][] fgReUZdIpo () throws rla01Tz4GQP {
c4[] TNoxYB;
void w = true[ false.Py5zgaJyU9ML()];
{
{
!58054.bb_EBTa2FHKiHD;
}
aydsfy Ged11_uZJS7Gg;
void[][][][][][] u_Z;
int ZZ7MF_RkUS;
{
{
Q9 fEMZy0OUuhV;
}
}
int[][][] eFjLmXI;
}
void BQNYjl;
if ( !true.GE9g()) ;
_lABzHO6bJo QQzCF0HWYTu = null.mwTfCCnKV = -!true.H3pSS8g3uWs();
void[][][] AGaVo3d = --new HZNFlc()[ -true.yC7x1r15ccp()];
int[] NavIBJBxmOT0;
{
{
int[][] ZhepNFAvAkYpk;
}
{
if ( -!--!!-!new boolean[ ( !null[ -this.IqG2maAwhGB92g]).E()][ new void[ !--null.HwfPU].D09v()]) if ( !-!0881.YaYbbwyB()) ;
}
boolean M5t0;
UKEVEB[][] y;
!true[ !HzyT9i0uUt().XP];
void[] n5b;
}
while ( this[ 660.hXtrRe6KQsO()]) !-rTG4n5sdvBN.dBtN6Nqo;
while ( true.Opt2()) while ( !true.g()) {
boolean[][][] BAKl;
}
boolean bb = 336236.GR7lffN() = !8.Ji9t8BZNLg();
if ( this.oulGxAN40Lp6m1) ;
--!this.adjHKiKV5z();
null.etRY();
!false[ !---true.tkUQ29];
}
public static void hF (String[] JxWCgTVdeb5uy) throws Ab4r2Dhr {
boolean cmvy9VLJ1JS2;
int[] wMTkZEW5 = --uhoP9rYZCZfvp().L = ZhqMd.lMig;
;
IUv Np6deupofqP0 = 6576896.EFwR;
ow[] nbe1T = !this.Hthnrf();
;
while ( this.B6qfjm) if ( -!null.SKEM3j_SCg) {
;
}
}
public static void hwUZF (String[] i4ltb) {
int[] gbmGcG;
while ( true[ ( this[ cSSNv9ho()[ -!!54448949[ -this.Nf_]]]).HQaOUnfVH6uJ]) if ( true.l) !!new auaUDSvKMCWlIz().L2JwIafh1wuCJt;
;
return;
int u;
if ( !-null.vrPnXuw_) ;
void[] qWZ = false[ null.dxh2Oy];
jLpswTF5ZI[][] PV;
;
oeC9HWiAv r8H;
( 36695465[ false[ -new int[ new Ee2ZpzZ().PjZK8e()][ !( ----799[ 501497373[ new XO2ScjO6[ !-X1HewPw.hQN_4ehre][ new L().NQkBHN9z9D()]]])[ !new bf().qULex()]]]]).geT;
void[][][] XktJllZs9NX = false[ !gUQEQ3Mhps3mJh[ 72.bacInJLt2p()]] = !!-y8.AAC();
boolean[][][] JDkh = -false.S = new BNgKi()[ -this.ii4ylCEthvuYWL()];
void FLtqNGK5R;
return -!!--10212164.nMrt;
}
public nFnCBtZm0WpILW[] UEdIY4lhBDIjy () {
return;
;
void jUEtBF5yF4IJ;
!161961289.sVtt();
}
public static void PjhCv (String[] BGsW1ipPb4J5O) {
int[] gG = !jRzDFlwW().GtCXg = ULmB90AD.HHBY();
while ( ( true.p).Y1plU8lev) return;
!-!-!----false.c2470CkyA;
;
void[] fr46cyNC3z5r;
{
{
;
}
prM_JFzxXJqt[] i;
int IIPPtr2fF4wGRc;
boolean[] zzupAGTZGgZ;
boolean[][] oXdO_IczUtL4ds;
return;
if ( !!--vm083w4EM6aZj().Dg91fdbATFkFlK()) if ( ev69.WkDnD6S) {
wCpSWzHwWPJ[] V;
}
boolean R3;
void[] zdIse2uvh;
if ( new owKnxAt5wwNY().MnJCL()) return;
SCHU1c[] bO0D1E4rB;
void nG6zSo_wV;
if ( --!!!false[ -!new int[ false[ true[ --Lm.L9Mey9c]]].BnmOS()]) {
-!this[ -this[ new E9R7[ -new twDQMjx[ -!-!!!new kl6GvjtBDaUYV().XZW3HGMhhn()][ -!!null.jYf]].sVg1VW]];
}
YRq wwhb1Bk;
new mJU()[ -!McWVQG.N];
{
{
int bFLhUS66C;
}
}
IlnKHi6 eSlX;
}
void[] KeYwnuwiLLB;
boolean[] va = ( !false[ new int[ null.up()][ 633.w03wJHF()]]).Q8pi4uFmqU8Mr() = wDveb2pET_L0S[ !null.FZltgRD];
void[] Ofo = -R()[ -true.qXgK];
boolean[] x8cr1TUnX2Heui = false[ !new void[ new boolean[ new int[ -AsgAgAMt().DYDuJ()][ fX().O0SU2P]][ new q0wBHgKyv().gxA09tU()]].Tvn5D59()] = -new z3rMjCu()[ !!dIVJ.sRB7vJ_PeCUcM0];
boolean[][] xuP;
;
void tByCEqAJ = null[ new FlAWyB()[ 4064.sKUN()]] = !false[ --true.EV()];
return;
if ( -!null[ -!this.G4G0c6NwGSsI6]) {
{
if ( !!!89360121.MCO_zU2gE) ( !null.W32jvJ())[ --( -SKYKPvk2_Qmq[ --bt1VUcaXtBN1.g2GF]).lI1jNB];
}
}else return;
return --!TIC().ALAt;
void[] cXITK = -new jtq9jq().X7FIwg_bdJAv();
while ( this.HnyYB()) {
boolean[][] b49gx45Zw;
}
;
return wjyz.qxzUKOxFiqgl();
}
public static void L (String[] MWbJUL) throws kDbMkJxAT {
boolean Kr1 = -( -false.eA5M()).kDPZmGCw = -( null.tOW1)[ false.HzGaNAVHv49];
boolean UC;
o[][][][] dKho;
;
int[][][][] GAQaO_jVA = new RwqZuwcX_9apq().cUIT0rM = 30743.HTpn0j9HT;
c0S BIUm3gD6OYD = -coB_vk6g().mYjs() = iBi.ttINMc4olvu();
;
true.lHRC;
boolean VW6VWO;
return;
if ( vDz[ null[ new Q0VfZbTFynbGxG()[ !null[ new KiGG[ !!this[ --BZqg2vjYGmA.Ey09kgJewYt()]].bkxhW0_jP()]]]]) {
if ( !false.dLuA) ;
}
return;
}
}
|
3e0ba3e6a5c559eafedb48cb2758cde4057c0ca1 | 5,178 | java | Java | src/test/java/com/l2fprod/common/util/converter/NumberConvertersTest.java | ZenHarbinger/l2fprod | d9b15c3f0b6ac1d9a2a9d315be073d2a4a419c32 | [
"Apache-2.0"
] | 2 | 2015-06-30T14:31:44.000Z | 2016-06-09T20:36:51.000Z | src/test/java/com/l2fprod/common/util/converter/NumberConvertersTest.java | atomixnmc/l2fprod-properties-editor | 6cb8eb716c54dfcb149843ff6739d5052df2b0c8 | [
"Apache-2.0"
] | 9 | 2016-03-12T17:28:07.000Z | 2017-07-24T19:11:25.000Z | src/test/java/com/l2fprod/common/util/converter/NumberConvertersTest.java | atomixnmc/l2fprod-properties-editor | 6cb8eb716c54dfcb149843ff6739d5052df2b0c8 | [
"Apache-2.0"
] | 4 | 2016-02-27T12:31:26.000Z | 2018-12-14T07:44:07.000Z | 34.291391 | 98 | 0.621089 | 4,917 | /*
* Copyright 2016 matta.
*
* 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.l2fprod.common.util.converter;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author matta
*/
public class NumberConvertersTest {
public NumberConvertersTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of convert method, of class NumberConverters.
*/
@Test
public void testConvertInteger() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Integer.class);
for (int ii = 0; ii < 100; ii++) {
Integer integer = ii;
assertEquals(integer, lookup.convert(Integer.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Integer.class, String.class);
for (int ii = 0; ii < 100; ii++) {
Integer integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertShort() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Short.class);
for (short ii = 0; ii < 100; ii++) {
Short integer = ii;
assertEquals(integer, lookup.convert(Short.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Short.class, String.class);
for (short ii = 0; ii < 100; ii++) {
Short integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertByte() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Byte.class);
for (byte ii = 0; ii < 100; ii++) {
Byte integer = ii;
assertEquals(integer, lookup.convert(Byte.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Byte.class, String.class);
for (byte ii = 0; ii < 100; ii++) {
Byte integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertLong() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Long.class);
for (long ii = 0; ii < 100; ii++) {
Long integer = ii;
assertEquals(integer, lookup.convert(Long.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Long.class, String.class);
for (long ii = 0; ii < 100; ii++) {
Long integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertDouble() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Double.class);
for (double ii = 0.5; ii < 100; ii++) {
Double integer = ii;
assertEquals(integer, lookup.convert(Double.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Double.class, String.class);
for (double ii = 0.5; ii < 100; ii++) {
Double integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertFloat() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Float.class);
for (float ii = 0.5f; ii < 100; ii++) {
Float integer = ii;
assertEquals(integer, lookup.convert(Float.class, integer.toString()));
}
lookup = ConverterRegistry.instance().getConverter(Float.class, String.class);
for (float ii = 0.5f; ii < 100; ii++) {
Float integer = ii;
assertEquals(integer.toString(), lookup.convert(String.class, integer));
}
}
@Test
public void testConvertFail() {
Converter lookup = ConverterRegistry.instance().getConverter(String.class, Float.class);
Float integer = new Float(1);
boolean exception = false;
try {
assertEquals(integer, lookup.convert(ConverterRegistry.class, integer.toString()));
} catch (Exception ex) {
exception = true;
}
Assert.assertTrue(exception);
}
}
|
3e0ba5450775d9adfcca286d343a6c34dbc031b6 | 1,312 | java | Java | src/test/org/apache/commons/betwixt/recursion/IdBean.java | ripdajacker/commons-betwixt | dc67ac5a5b71f450a9c33e60979e9fd74d3baeee | [
"Apache-2.0"
] | 1 | 2016-02-05T03:31:10.000Z | 2016-02-05T03:31:10.000Z | src/test/org/apache/commons/betwixt/recursion/IdBean.java | ripdajacker/commons-betwixt | dc67ac5a5b71f450a9c33e60979e9fd74d3baeee | [
"Apache-2.0"
] | null | null | null | src/test/org/apache/commons/betwixt/recursion/IdBean.java | ripdajacker/commons-betwixt | dc67ac5a5b71f450a9c33e60979e9fd74d3baeee | [
"Apache-2.0"
] | null | null | null | 26.24 | 75 | 0.69436 | 4,918 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.betwixt.recursion;
/**
* Used to test mapping of id's to
*
* @author Robert Burrell Donkin
* @version $Id$
*/
public class IdBean {
private String id;
private String notId;
public IdBean(String id) {
setId(id);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNotId() {
return notId;
}
public void setNotId(String notId) {
this.notId = notId;
}
}
|
3e0ba5a4afd60726e69a935fefe7838de6f25934 | 4,576 | java | Java | app/src/main/java/lab/stem/vim/core/Graph.java | STEMLab/VIM | e455567a4540930aead4798233a5d1aeba64a11d | [
"MIT"
] | 1 | 2021-12-28T08:22:45.000Z | 2021-12-28T08:22:45.000Z | app/src/main/java/lab/stem/vim/core/Graph.java | STEMLab/VIM | e455567a4540930aead4798233a5d1aeba64a11d | [
"MIT"
] | null | null | null | app/src/main/java/lab/stem/vim/core/Graph.java | STEMLab/VIM | e455567a4540930aead4798233a5d1aeba64a11d | [
"MIT"
] | null | null | null | 27.733333 | 90 | 0.506119 | 4,919 | package lab.stem.vim.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
class Vertex implements Comparable<Vertex> {
private String id;
private Double distance;
private String type;
public Vertex(String id, double distance) {
super();
this.id = id;
this.distance = distance;
}
public Vertex(String id, double distance, String type) {
super();
this.id = id;
this.distance = distance;
this.type = type;
}
public String getId() {
return id;
}
public Double getDistance() {
return distance;
}
public void setId(String id) {
this.id = id;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((distance == null) ? 0 : distance.hashCode());
result = prime * result + ((id == null) ? 0 : id.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;
Vertex other = (Vertex) obj;
if (distance == null) {
if (other.distance != null)
return false;
} else if (!distance.equals(other.distance))
return false;
if (id == null) {
return other.id == null;
} else return id.equals(other.id);
}
@Override
public String toString() {
return "Vertex [id=" + id + ", distance=" + distance + "]";
}
@Override
public int compareTo(Vertex o) {
if (this.distance < o.distance)
return -1;
else if (this.distance > o.distance)
return 1;
else
return this.getId().compareTo(o.getId());
}
}
public class Graph {
private final Map<String, List<Vertex>> vertices;
public Graph() {
this.vertices = new HashMap<>();
}
public void addVertex(String character, List<Vertex> vertex) {
this.vertices.put(character, vertex);
}
public List<String> getShortestPath(String start, String finish, String floorType) {
final Map<String, Double> distances = new HashMap<>();
final Map<String, Vertex> previous = new HashMap<>();
PriorityQueue<Vertex> nodes = new PriorityQueue<>();
for(String vertex : vertices.keySet()) {
if (vertex.equals(start)) {
distances.put(vertex, (double) 0);
nodes.add(new Vertex(vertex, 0));
} else {
distances.put(vertex, Double.MAX_VALUE);
nodes.add(new Vertex(vertex, Double.MAX_VALUE));
}
previous.put(vertex, null);
}
while (!nodes.isEmpty()) {
Vertex smallest = nodes.poll();
if (smallest != null && smallest.getId().equals(finish)) {
final List<String> path = new ArrayList<>();
while (previous.get(smallest != null ? smallest.getId() : null) != null) {
if (smallest != null) {
path.add(smallest.getId());
smallest = previous.get(smallest.getId());
}
}
return path;
}
if (distances.get(smallest.getId()) == Double.MAX_VALUE) {
break;
}
for (Vertex neighbor : vertices.get(smallest.getId())) {
Double alt = distances.get(smallest.getId()) + neighbor.getDistance();
if (alt < distances.get(neighbor.getId())) {
distances.put(neighbor.getId(), alt);
previous.put(neighbor.getId(), smallest);
for (Vertex n : nodes) {
if (n.getId().equals(neighbor.getId())) {
nodes.remove(n);
n.setDistance(alt);
nodes.add(n);
break;
}
}
}
}
}
return new ArrayList<>(distances.keySet());
}
}
|
3e0ba5c8052dd0689ecba7275a9492d214b5e8a1 | 502 | java | Java | src/main/java/com/davidepugliese/springfood/domain/UserDAO.java | Deviad/springfood | cd6511501e3a9a960ab31310f8ab1304bc7d0de9 | [
"Apache-2.0"
] | 2 | 2017-10-16T08:29:19.000Z | 2019-07-04T03:11:05.000Z | src/main/java/com/davidepugliese/springfood/domain/UserDAO.java | Deviad/springfood | cd6511501e3a9a960ab31310f8ab1304bc7d0de9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/davidepugliese/springfood/domain/UserDAO.java | Deviad/springfood | cd6511501e3a9a960ab31310f8ab1304bc7d0de9 | [
"Apache-2.0"
] | null | null | null | 27.888889 | 53 | 0.772908 | 4,920 | package com.davidepugliese.springfood.domain;
import com.davidepugliese.springfood.models.Role;
import com.davidepugliese.springfood.models.User;
import com.davidepugliese.springfood.models.UserInfo;
public interface UserDAO {
// public User getUser();
void saveUser(User theUser);
void updateUser(User theUser);
void updateUserInfo(UserInfo userInfo);
User getUser(Integer id);
User getUserByUsername(String username);
// Set<Role> getRolesByUsername(String username);
} |
3e0ba5f3a1a8c3bcc8d121e17825c559ae4a78f2 | 372 | java | Java | command-control-model/src/main/java/io/dddbyexamples/comandcontrol/commands/SentCommands.java | michal-michaluk/command-control | fa3a51c3fcaa71a4616a01c3f91b2bb13033fb2a | [
"MIT"
] | 2 | 2019-04-26T07:23:29.000Z | 2021-01-11T19:41:57.000Z | command-control-model/src/main/java/io/dddbyexamples/comandcontrol/commands/SentCommands.java | michal-michaluk/command-control | fa3a51c3fcaa71a4616a01c3f91b2bb13033fb2a | [
"MIT"
] | null | null | null | command-control-model/src/main/java/io/dddbyexamples/comandcontrol/commands/SentCommands.java | michal-michaluk/command-control | fa3a51c3fcaa71a4616a01c3f91b2bb13033fb2a | [
"MIT"
] | 1 | 2019-06-25T22:45:53.000Z | 2019-06-25T22:45:53.000Z | 26.571429 | 75 | 0.827957 | 4,921 | package io.dddbyexamples.comandcontrol.commands;
import io.dddbyexamples.comandcontrol.leadership.takeover.HandoverAccepted;
import io.dddbyexamples.comandcontrol.leadership.takeover.HandoverStarted;
public interface SentCommands {
CommandState getStatsOf(String commandID);
void add(HandoverStarted event);
void add(HandoverAccepted handoverAccepted);
}
|
3e0ba76efedf035f6e3cd10c69614aa1ab2a6e0d | 194 | java | Java | Bitwise/power of four.java | saikiran20002102/Competetive-Coding | 651dcbca7dd1abb291a8198080dc22e8fcbe2038 | [
"MIT"
] | 6 | 2020-07-05T16:49:39.000Z | 2020-11-07T09:14:44.000Z | Bitwise/power of four.java | saikiran20002102/Competetive-Coding | 651dcbca7dd1abb291a8198080dc22e8fcbe2038 | [
"MIT"
] | null | null | null | Bitwise/power of four.java | saikiran20002102/Competetive-Coding | 651dcbca7dd1abb291a8198080dc22e8fcbe2038 | [
"MIT"
] | 5 | 2020-08-10T17:01:59.000Z | 2021-06-16T15:27:24.000Z | 38.8 | 90 | 0.603093 | 4,922 | //Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.